blob: 9191fdea2d814055c362767db9d23dccf8c6e4cd [file] [log] [blame]
Ted Kremenek61f3e052008-04-03 04:42:52 +00001// BugReporter.cpp - Generate PathDiagnostics for Bugs ------------*- C++ -*--//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines BugReporter, a utility class for generating
Ted Kremenek6c07bdb2009-06-26 00:05:51 +000011// PathDiagnostics.
Ted Kremenek61f3e052008-04-03 04:42:52 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenek9b663712011-02-10 01:03:03 +000015#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
Ted Kremenek61f3e052008-04-03 04:42:52 +000016#include "clang/AST/ASTContext.h"
Benjamin Kramerc35fb7d2012-01-28 12:06:22 +000017#include "clang/AST/DeclObjC.h"
Ted Kremenek61f3e052008-04-03 04:42:52 +000018#include "clang/AST/Expr.h"
Ted Kremenek00605e02009-03-27 20:55:39 +000019#include "clang/AST/ParentMap.h"
Chris Lattner16f00492009-04-26 01:32:48 +000020#include "clang/AST/StmtObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000021#include "clang/Analysis/CFG.h"
Ted Kremenek61f3e052008-04-03 04:42:52 +000022#include "clang/Analysis/ProgramPoint.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "clang/Basic/SourceManager.h"
24#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000025#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
Ted Kremenek331b0ac2008-06-18 05:34:07 +000027#include "llvm/ADT/DenseMap.h"
Ted Kremenek802e0242012-02-08 04:32:34 +000028#include "llvm/ADT/IntrusiveRefCntPtr.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000029#include "llvm/ADT/OwningPtr.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/SmallString.h"
32#include "llvm/Support/raw_ostream.h"
Ted Kremenek10aa5542009-03-12 23:41:59 +000033#include <queue>
Ted Kremenek61f3e052008-04-03 04:42:52 +000034
35using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000036using namespace ento;
Ted Kremenek61f3e052008-04-03 04:42:52 +000037
Ted Kremenek8966bc12009-05-06 21:39:49 +000038BugReporterVisitor::~BugReporterVisitor() {}
Ted Kremenek1b431022010-03-20 18:01:57 +000039
David Blaikie99ba9e32011-12-20 02:48:34 +000040void BugReporterContext::anchor() {}
41
Ted Kremenekcf118d42009-02-04 23:49:09 +000042//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +000043// Helper routines for walking the ExplodedGraph and fetching statements.
Ted Kremenekcf118d42009-02-04 23:49:09 +000044//===----------------------------------------------------------------------===//
Ted Kremenek61f3e052008-04-03 04:42:52 +000045
Ted Kremenek9c378f72011-08-12 23:37:29 +000046static inline const Stmt *GetStmt(const ProgramPoint &P) {
David Blaikie7a95de62013-02-21 22:23:56 +000047 if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Ted Kremenek592362b2009-08-18 01:05:30 +000048 return SP->getStmt();
David Blaikie7a95de62013-02-21 22:23:56 +000049 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>())
Ted Kremenek61f3e052008-04-03 04:42:52 +000050 return BE->getSrc()->getTerminator();
David Blaikie7a95de62013-02-21 22:23:56 +000051 if (Optional<CallEnter> CE = P.getAs<CallEnter>())
Jordan Rose852aa0d2012-07-10 22:07:52 +000052 return CE->getCallExpr();
David Blaikie7a95de62013-02-21 22:23:56 +000053 if (Optional<CallExitEnd> CEE = P.getAs<CallExitEnd>())
Jordan Rose852aa0d2012-07-10 22:07:52 +000054 return CEE->getCalleeContext()->getCallSite();
Mike Stump1eb44332009-09-09 15:08:12 +000055
Ted Kremenekb697b102009-02-23 22:44:26 +000056 return 0;
Ted Kremenek706e3cf2008-04-07 23:35:17 +000057}
58
Zhongxing Xuc5619d92009-08-06 01:32:16 +000059static inline const ExplodedNode*
Ted Kremenek9c378f72011-08-12 23:37:29 +000060GetPredecessorNode(const ExplodedNode *N) {
Ted Kremenekbd7efa82008-04-17 23:44:37 +000061 return N->pred_empty() ? NULL : *(N->pred_begin());
62}
Ted Kremenek2673c9f2008-04-25 19:01:27 +000063
Zhongxing Xuc5619d92009-08-06 01:32:16 +000064static inline const ExplodedNode*
Ted Kremenek9c378f72011-08-12 23:37:29 +000065GetSuccessorNode(const ExplodedNode *N) {
Ted Kremenekb697b102009-02-23 22:44:26 +000066 return N->succ_empty() ? NULL : *(N->succ_begin());
Ted Kremenekbd7efa82008-04-17 23:44:37 +000067}
68
Ted Kremenek9c378f72011-08-12 23:37:29 +000069static const Stmt *GetPreviousStmt(const ExplodedNode *N) {
Ted Kremenekb697b102009-02-23 22:44:26 +000070 for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N))
Ted Kremenek5f85e172009-07-22 22:35:28 +000071 if (const Stmt *S = GetStmt(N->getLocation()))
Ted Kremenekb697b102009-02-23 22:44:26 +000072 return S;
Mike Stump1eb44332009-09-09 15:08:12 +000073
Ted Kremenekb697b102009-02-23 22:44:26 +000074 return 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +000075}
76
Ted Kremenek9c378f72011-08-12 23:37:29 +000077static const Stmt *GetNextStmt(const ExplodedNode *N) {
Ted Kremenekb697b102009-02-23 22:44:26 +000078 for (N = GetSuccessorNode(N); N; N = GetSuccessorNode(N))
Ted Kremenek5f85e172009-07-22 22:35:28 +000079 if (const Stmt *S = GetStmt(N->getLocation())) {
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000080 // Check if the statement is '?' or '&&'/'||'. These are "merges",
81 // not actual statement points.
82 switch (S->getStmtClass()) {
83 case Stmt::ChooseExprClass:
John McCall56ca35d2011-02-17 10:25:35 +000084 case Stmt::BinaryConditionalOperatorClass: continue;
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000085 case Stmt::ConditionalOperatorClass: continue;
86 case Stmt::BinaryOperatorClass: {
John McCall2de56d12010-08-25 11:45:40 +000087 BinaryOperatorKind Op = cast<BinaryOperator>(S)->getOpcode();
88 if (Op == BO_LAnd || Op == BO_LOr)
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000089 continue;
90 break;
91 }
92 default:
93 break;
94 }
Ted Kremenekb697b102009-02-23 22:44:26 +000095 return S;
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000096 }
Mike Stump1eb44332009-09-09 15:08:12 +000097
Ted Kremenekb697b102009-02-23 22:44:26 +000098 return 0;
99}
100
Ted Kremenek5f85e172009-07-22 22:35:28 +0000101static inline const Stmt*
Ted Kremenek9c378f72011-08-12 23:37:29 +0000102GetCurrentOrPreviousStmt(const ExplodedNode *N) {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000103 if (const Stmt *S = GetStmt(N->getLocation()))
Ted Kremenekb697b102009-02-23 22:44:26 +0000104 return S;
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Ted Kremenekb697b102009-02-23 22:44:26 +0000106 return GetPreviousStmt(N);
107}
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Ted Kremenek5f85e172009-07-22 22:35:28 +0000109static inline const Stmt*
Ted Kremenek9c378f72011-08-12 23:37:29 +0000110GetCurrentOrNextStmt(const ExplodedNode *N) {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000111 if (const Stmt *S = GetStmt(N->getLocation()))
Ted Kremenekb697b102009-02-23 22:44:26 +0000112 return S;
Mike Stump1eb44332009-09-09 15:08:12 +0000113
Ted Kremenekb697b102009-02-23 22:44:26 +0000114 return GetNextStmt(N);
115}
116
117//===----------------------------------------------------------------------===//
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000118// Diagnostic cleanup.
119//===----------------------------------------------------------------------===//
120
Ted Kremenekb85cce02012-10-25 22:07:10 +0000121static PathDiagnosticEventPiece *
122eventsDescribeSameCondition(PathDiagnosticEventPiece *X,
123 PathDiagnosticEventPiece *Y) {
124 // Prefer diagnostics that come from ConditionBRVisitor over
125 // those that came from TrackConstraintBRVisitor.
126 const void *tagPreferred = ConditionBRVisitor::getTag();
127 const void *tagLesser = TrackConstraintBRVisitor::getTag();
128
129 if (X->getLocation() != Y->getLocation())
130 return 0;
131
132 if (X->getTag() == tagPreferred && Y->getTag() == tagLesser)
133 return X;
134
135 if (Y->getTag() == tagPreferred && X->getTag() == tagLesser)
136 return Y;
137
138 return 0;
139}
140
Ted Kremenek38001652012-10-26 16:02:36 +0000141/// An optimization pass over PathPieces that removes redundant diagnostics
142/// generated by both ConditionBRVisitor and TrackConstraintBRVisitor. Both
143/// BugReporterVisitors use different methods to generate diagnostics, with
144/// one capable of emitting diagnostics in some cases but not in others. This
145/// can lead to redundant diagnostic pieces at the same point in a path.
146static void removeRedundantMsgs(PathPieces &path) {
Ted Kremenekb85cce02012-10-25 22:07:10 +0000147 unsigned N = path.size();
148 if (N < 2)
149 return;
Ted Kremenek38001652012-10-26 16:02:36 +0000150 // NOTE: this loop intentionally is not using an iterator. Instead, we
151 // are streaming the path and modifying it in place. This is done by
152 // grabbing the front, processing it, and if we decide to keep it append
153 // it to the end of the path. The entire path is processed in this way.
Ted Kremenekb85cce02012-10-25 22:07:10 +0000154 for (unsigned i = 0; i < N; ++i) {
155 IntrusiveRefCntPtr<PathDiagnosticPiece> piece(path.front());
156 path.pop_front();
157
158 switch (piece->getKind()) {
159 case clang::ento::PathDiagnosticPiece::Call:
Ted Kremenek38001652012-10-26 16:02:36 +0000160 removeRedundantMsgs(cast<PathDiagnosticCallPiece>(piece)->path);
Ted Kremenekb85cce02012-10-25 22:07:10 +0000161 break;
162 case clang::ento::PathDiagnosticPiece::Macro:
Ted Kremenek38001652012-10-26 16:02:36 +0000163 removeRedundantMsgs(cast<PathDiagnosticMacroPiece>(piece)->subPieces);
Ted Kremenekb85cce02012-10-25 22:07:10 +0000164 break;
165 case clang::ento::PathDiagnosticPiece::ControlFlow:
166 break;
167 case clang::ento::PathDiagnosticPiece::Event: {
168 if (i == N-1)
169 break;
170
171 if (PathDiagnosticEventPiece *nextEvent =
172 dyn_cast<PathDiagnosticEventPiece>(path.front().getPtr())) {
173 PathDiagnosticEventPiece *event =
174 cast<PathDiagnosticEventPiece>(piece);
175 // Check to see if we should keep one of the two pieces. If we
176 // come up with a preference, record which piece to keep, and consume
177 // another piece from the path.
178 if (PathDiagnosticEventPiece *pieceToKeep =
179 eventsDescribeSameCondition(event, nextEvent)) {
180 piece = pieceToKeep;
181 path.pop_front();
182 ++i;
183 }
184 }
185 break;
186 }
187 }
188 path.push_back(piece);
189 }
190}
191
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000192/// Recursively scan through a path and prune out calls and macros pieces
193/// that aren't needed. Return true if afterwards the path contains
Jordan Roseafa7cae2012-12-07 19:56:29 +0000194/// "interesting stuff" which means it shouldn't be pruned from the parent path.
195bool BugReporter::RemoveUnneededCalls(PathPieces &pieces, BugReport *R) {
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000196 bool containsSomethingInteresting = false;
197 const unsigned N = pieces.size();
198
199 for (unsigned i = 0 ; i < N ; ++i) {
200 // Remove the front piece from the path. If it is still something we
201 // want to keep once we are done, we will push it back on the end.
202 IntrusiveRefCntPtr<PathDiagnosticPiece> piece(pieces.front());
203 pieces.pop_front();
204
Jordan Roseafa7cae2012-12-07 19:56:29 +0000205 // Throw away pieces with invalid locations. Note that we can't throw away
206 // calls just yet because they might have something interesting inside them.
207 // If so, their locations will be adjusted as necessary later.
Ted Kremeneka43df952012-09-21 00:09:11 +0000208 if (piece->getKind() != PathDiagnosticPiece::Call &&
209 piece->getLocation().asLocation().isInvalid())
210 continue;
211
Ted Kremenek72516742012-03-01 00:05:06 +0000212 switch (piece->getKind()) {
213 case PathDiagnosticPiece::Call: {
214 PathDiagnosticCallPiece *call = cast<PathDiagnosticCallPiece>(piece);
Anna Zaks80de4872012-08-29 21:22:37 +0000215 // Check if the location context is interesting.
216 assert(LocationContextMap.count(call));
217 if (R->isInteresting(LocationContextMap[call])) {
218 containsSomethingInteresting = true;
219 break;
220 }
Jordan Rose368f3b02012-11-15 02:07:23 +0000221
Jordan Roseafa7cae2012-12-07 19:56:29 +0000222 if (!RemoveUnneededCalls(call->path, R))
Jordan Rose368f3b02012-11-15 02:07:23 +0000223 continue;
Ted Kremeneka43df952012-09-21 00:09:11 +0000224
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000225 containsSomethingInteresting = true;
Ted Kremenek72516742012-03-01 00:05:06 +0000226 break;
227 }
228 case PathDiagnosticPiece::Macro: {
229 PathDiagnosticMacroPiece *macro = cast<PathDiagnosticMacroPiece>(piece);
Jordan Roseafa7cae2012-12-07 19:56:29 +0000230 if (!RemoveUnneededCalls(macro->subPieces, R))
Ted Kremenek72516742012-03-01 00:05:06 +0000231 continue;
232 containsSomethingInteresting = true;
233 break;
234 }
235 case PathDiagnosticPiece::Event: {
236 PathDiagnosticEventPiece *event = cast<PathDiagnosticEventPiece>(piece);
Ted Kremeneka43df952012-09-21 00:09:11 +0000237
Ted Kremenek72516742012-03-01 00:05:06 +0000238 // We never throw away an event, but we do throw it away wholesale
239 // as part of a path if we throw the entire path away.
Ted Kremenek22505ef2012-09-08 07:18:18 +0000240 containsSomethingInteresting |= !event->isPrunable();
Ted Kremenek72516742012-03-01 00:05:06 +0000241 break;
242 }
243 case PathDiagnosticPiece::ControlFlow:
244 break;
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000245 }
246
247 pieces.push_back(piece);
248 }
249
250 return containsSomethingInteresting;
251}
252
Jordan Roseafa7cae2012-12-07 19:56:29 +0000253/// Recursively scan through a path and make sure that all call pieces have
254/// valid locations. Note that all other pieces with invalid locations should
255/// have already been pruned out.
256static void adjustCallLocations(PathPieces &Pieces,
257 PathDiagnosticLocation *LastCallLocation = 0) {
258 for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E; ++I) {
259 PathDiagnosticCallPiece *Call = dyn_cast<PathDiagnosticCallPiece>(*I);
260
261 if (!Call) {
262 assert((*I)->getLocation().asLocation().isValid());
263 continue;
264 }
265
266 if (LastCallLocation) {
Jordan Rose187f8bd2013-01-21 18:28:30 +0000267 if (!Call->callEnter.asLocation().isValid() ||
268 Call->getCaller()->isImplicit())
Jordan Roseafa7cae2012-12-07 19:56:29 +0000269 Call->callEnter = *LastCallLocation;
Jordan Rose187f8bd2013-01-21 18:28:30 +0000270 if (!Call->callReturn.asLocation().isValid() ||
271 Call->getCaller()->isImplicit())
Jordan Roseafa7cae2012-12-07 19:56:29 +0000272 Call->callReturn = *LastCallLocation;
273 }
274
275 // Recursively clean out the subclass. Keep this call around if
276 // it contains any informative diagnostics.
277 PathDiagnosticLocation *ThisCallLocation;
Jordan Rose187f8bd2013-01-21 18:28:30 +0000278 if (Call->callEnterWithin.asLocation().isValid() &&
279 !Call->getCallee()->isImplicit())
Jordan Roseafa7cae2012-12-07 19:56:29 +0000280 ThisCallLocation = &Call->callEnterWithin;
281 else
282 ThisCallLocation = &Call->callEnter;
283
284 assert(ThisCallLocation && "Outermost call has an invalid location");
285 adjustCallLocations(Call->path, ThisCallLocation);
286 }
287}
288
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000289//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000290// PathDiagnosticBuilder and its associated routines and helper objects.
Ted Kremenekb697b102009-02-23 22:44:26 +0000291//===----------------------------------------------------------------------===//
Ted Kremenekb479dad2009-02-23 23:13:51 +0000292
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000293typedef llvm::DenseMap<const ExplodedNode*,
294const ExplodedNode*> NodeBackMap;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000295
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000296namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000297class NodeMapClosure : public BugReport::NodeResolver {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000298 NodeBackMap& M;
299public:
300 NodeMapClosure(NodeBackMap *m) : M(*m) {}
301 ~NodeMapClosure() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Ted Kremenek9c378f72011-08-12 23:37:29 +0000303 const ExplodedNode *getOriginalNode(const ExplodedNode *N) {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000304 NodeBackMap::iterator I = M.find(N);
305 return I == M.end() ? 0 : I->second;
306 }
307};
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000309class PathDiagnosticBuilder : public BugReporterContext {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000310 BugReport *R;
David Blaikieef3643f2011-09-26 00:51:36 +0000311 PathDiagnosticConsumer *PDC;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000312 NodeMapClosure NMC;
Mike Stump1eb44332009-09-09 15:08:12 +0000313public:
Ted Kremenek59950d32012-02-24 07:12:52 +0000314 const LocationContext *LC;
315
Ted Kremenek8966bc12009-05-06 21:39:49 +0000316 PathDiagnosticBuilder(GRBugReporter &br,
Mike Stump1eb44332009-09-09 15:08:12 +0000317 BugReport *r, NodeBackMap *Backmap,
David Blaikieef3643f2011-09-26 00:51:36 +0000318 PathDiagnosticConsumer *pdc)
Ted Kremenek8966bc12009-05-06 21:39:49 +0000319 : BugReporterContext(br),
Ted Kremenek59950d32012-02-24 07:12:52 +0000320 R(r), PDC(pdc), NMC(Backmap), LC(r->getErrorNode()->getLocationContext())
321 {}
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Ted Kremenek9c378f72011-08-12 23:37:29 +0000323 PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N);
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Ted Kremenek9c378f72011-08-12 23:37:29 +0000325 PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream &os,
326 const ExplodedNode *N);
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Anna Zaks8e6431a2011-08-18 22:37:56 +0000328 BugReport *getBugReport() { return R; }
329
Tom Care212f6d32010-09-16 03:50:38 +0000330 Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); }
Ted Kremenek59950d32012-02-24 07:12:52 +0000331
332 ParentMap& getParentMap() { return LC->getParentMap(); }
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000334 const Stmt *getParent(const Stmt *S) {
335 return getParentMap().getParent(S);
336 }
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Ted Kremenek8966bc12009-05-06 21:39:49 +0000338 virtual NodeMapClosure& getNodeResolver() { return NMC; }
Douglas Gregor72971342009-04-18 00:02:19 +0000339
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000340 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000341
David Blaikieef3643f2011-09-26 00:51:36 +0000342 PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const {
343 return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Extensive;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000344 }
345
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000346 bool supportsLogicalOpControlFlow() const {
347 return PDC ? PDC->supportsLogicalOpControlFlow() : true;
Mike Stump1eb44332009-09-09 15:08:12 +0000348 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000349};
350} // end anonymous namespace
351
Ted Kremenek00605e02009-03-27 20:55:39 +0000352PathDiagnosticLocation
Ted Kremenek9c378f72011-08-12 23:37:29 +0000353PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000354 if (const Stmt *S = GetNextStmt(N))
Ted Kremenek59950d32012-02-24 07:12:52 +0000355 return PathDiagnosticLocation(S, getSourceManager(), LC);
Ted Kremenek00605e02009-03-27 20:55:39 +0000356
Anna Zaks0cd59482011-09-16 19:18:30 +0000357 return PathDiagnosticLocation::createDeclEnd(N->getLocationContext(),
358 getSourceManager());
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000359}
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Ted Kremenek00605e02009-03-27 20:55:39 +0000361PathDiagnosticLocation
Ted Kremenek9c378f72011-08-12 23:37:29 +0000362PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream &os,
363 const ExplodedNode *N) {
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000364
Ted Kremenek143ca222008-05-06 18:11:09 +0000365 // Slow, but probably doesn't matter.
Ted Kremenekb697b102009-02-23 22:44:26 +0000366 if (os.str().empty())
367 os << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Ted Kremenek00605e02009-03-27 20:55:39 +0000369 const PathDiagnosticLocation &Loc = ExecutionContinues(N);
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Ted Kremenek00605e02009-03-27 20:55:39 +0000371 if (Loc.asStmt())
Ted Kremenekb697b102009-02-23 22:44:26 +0000372 os << "Execution continues on line "
Chandler Carruth64211622011-07-25 21:09:52 +0000373 << getSourceManager().getExpansionLineNumber(Loc.asLocation())
Ted Kremenek8966bc12009-05-06 21:39:49 +0000374 << '.';
Ted Kremenek4f1db532009-12-04 20:34:31 +0000375 else {
376 os << "Execution jumps to the end of the ";
377 const Decl *D = N->getLocationContext()->getDecl();
378 if (isa<ObjCMethodDecl>(D))
379 os << "method";
380 else if (isa<FunctionDecl>(D))
381 os << "function";
382 else {
383 assert(isa<BlockDecl>(D));
384 os << "anonymous block";
385 }
386 os << '.';
387 }
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000389 return Loc;
Ted Kremenek143ca222008-05-06 18:11:09 +0000390}
391
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000392static bool IsNested(const Stmt *S, ParentMap &PM) {
393 if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
394 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000396 const Stmt *Parent = PM.getParentIgnoreParens(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000398 if (Parent)
399 switch (Parent->getStmtClass()) {
400 case Stmt::ForStmtClass:
401 case Stmt::DoStmtClass:
402 case Stmt::WhileStmtClass:
403 return true;
404 default:
405 break;
406 }
Mike Stump1eb44332009-09-09 15:08:12 +0000407
408 return false;
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000409}
410
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000411PathDiagnosticLocation
412PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
Ted Kremenek9c378f72011-08-12 23:37:29 +0000413 assert(S && "Null Stmt *passed to getEnclosingStmtLocation");
Mike Stump1eb44332009-09-09 15:08:12 +0000414 ParentMap &P = getParentMap();
Ted Kremenek8966bc12009-05-06 21:39:49 +0000415 SourceManager &SMgr = getSourceManager();
Ted Kremeneke88a1702009-05-11 22:19:32 +0000416
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000417 while (IsNested(S, P)) {
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000418 const Stmt *Parent = P.getParentIgnoreParens(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000420 if (!Parent)
421 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000423 switch (Parent->getStmtClass()) {
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000424 case Stmt::BinaryOperatorClass: {
425 const BinaryOperator *B = cast<BinaryOperator>(Parent);
426 if (B->isLogicalOp())
Anna Zaks220ac8c2011-09-15 01:08:34 +0000427 return PathDiagnosticLocation(S, SMgr, LC);
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000428 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000429 }
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000430 case Stmt::CompoundStmtClass:
431 case Stmt::StmtExprClass:
Anna Zaks220ac8c2011-09-15 01:08:34 +0000432 return PathDiagnosticLocation(S, SMgr, LC);
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000433 case Stmt::ChooseExprClass:
434 // Similar to '?' if we are referring to condition, just have the edge
435 // point to the entire choose expression.
436 if (cast<ChooseExpr>(Parent)->getCond() == S)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000437 return PathDiagnosticLocation(Parent, SMgr, LC);
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000438 else
Anna Zaks220ac8c2011-09-15 01:08:34 +0000439 return PathDiagnosticLocation(S, SMgr, LC);
John McCall56ca35d2011-02-17 10:25:35 +0000440 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000441 case Stmt::ConditionalOperatorClass:
442 // For '?', if we are referring to condition, just have the edge point
443 // to the entire '?' expression.
John McCall56ca35d2011-02-17 10:25:35 +0000444 if (cast<AbstractConditionalOperator>(Parent)->getCond() == S)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000445 return PathDiagnosticLocation(Parent, SMgr, LC);
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000446 else
Anna Zaks220ac8c2011-09-15 01:08:34 +0000447 return PathDiagnosticLocation(S, SMgr, LC);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000448 case Stmt::DoStmtClass:
Anna Zaks220ac8c2011-09-15 01:08:34 +0000449 return PathDiagnosticLocation(S, SMgr, LC);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000450 case Stmt::ForStmtClass:
451 if (cast<ForStmt>(Parent)->getBody() == S)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000452 return PathDiagnosticLocation(S, SMgr, LC);
Mike Stump1eb44332009-09-09 15:08:12 +0000453 break;
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000454 case Stmt::IfStmtClass:
455 if (cast<IfStmt>(Parent)->getCond() != S)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000456 return PathDiagnosticLocation(S, SMgr, LC);
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000457 break;
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000458 case Stmt::ObjCForCollectionStmtClass:
459 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000460 return PathDiagnosticLocation(S, SMgr, LC);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000461 break;
462 case Stmt::WhileStmtClass:
463 if (cast<WhileStmt>(Parent)->getCond() != S)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000464 return PathDiagnosticLocation(S, SMgr, LC);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000465 break;
466 default:
467 break;
468 }
469
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000470 S = Parent;
471 }
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000473 assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
Ted Kremeneke88a1702009-05-11 22:19:32 +0000474
475 // Special case: DeclStmts can appear in for statement declarations, in which
476 // case the ForStmt is the context.
477 if (isa<DeclStmt>(S)) {
478 if (const Stmt *Parent = P.getParent(S)) {
479 switch (Parent->getStmtClass()) {
480 case Stmt::ForStmtClass:
481 case Stmt::ObjCForCollectionStmtClass:
Anna Zaks220ac8c2011-09-15 01:08:34 +0000482 return PathDiagnosticLocation(Parent, SMgr, LC);
Ted Kremeneke88a1702009-05-11 22:19:32 +0000483 default:
484 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000485 }
486 }
Ted Kremeneke88a1702009-05-11 22:19:32 +0000487 }
488 else if (isa<BinaryOperator>(S)) {
489 // Special case: the binary operator represents the initialization
490 // code in a for statement (this can happen when the variable being
491 // initialized is an old variable.
492 if (const ForStmt *FS =
493 dyn_cast_or_null<ForStmt>(P.getParentIgnoreParens(S))) {
494 if (FS->getInit() == S)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000495 return PathDiagnosticLocation(FS, SMgr, LC);
Ted Kremeneke88a1702009-05-11 22:19:32 +0000496 }
497 }
498
Anna Zaks220ac8c2011-09-15 01:08:34 +0000499 return PathDiagnosticLocation(S, SMgr, LC);
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000500}
501
Ted Kremenekcf118d42009-02-04 23:49:09 +0000502//===----------------------------------------------------------------------===//
Jordan Rosed632d6f2012-09-22 01:24:56 +0000503// "Visitors only" path diagnostic generation algorithm.
504//===----------------------------------------------------------------------===//
505static bool GenerateVisitorsOnlyPathDiagnostic(PathDiagnostic &PD,
506 PathDiagnosticBuilder &PDB,
507 const ExplodedNode *N,
508 ArrayRef<BugReporterVisitor *> visitors) {
509 // All path generation skips the very first node (the error node).
510 // This is because there is special handling for the end-of-path note.
511 N = N->getFirstPred();
512 if (!N)
513 return true;
514
515 BugReport *R = PDB.getBugReport();
516 while (const ExplodedNode *Pred = N->getFirstPred()) {
517 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(),
518 E = visitors.end();
519 I != E; ++I) {
520 // Visit all the node pairs, but throw the path pieces away.
521 PathDiagnosticPiece *Piece = (*I)->VisitNode(N, Pred, PDB, *R);
522 delete Piece;
523 }
524
525 N = Pred;
526 }
527
528 return R->isValid();
529}
530
531//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000532// "Minimal" path diagnostic generation algorithm.
533//===----------------------------------------------------------------------===//
Anna Zaks56a938f2012-03-16 23:24:20 +0000534typedef std::pair<PathDiagnosticCallPiece*, const ExplodedNode*> StackDiagPair;
535typedef SmallVector<StackDiagPair, 6> StackDiagVector;
536
Anna Zaks368a0d52012-03-15 21:13:02 +0000537static void updateStackPiecesWithMessage(PathDiagnosticPiece *P,
Anna Zaks56a938f2012-03-16 23:24:20 +0000538 StackDiagVector &CallStack) {
Anna Zaks368a0d52012-03-15 21:13:02 +0000539 // If the piece contains a special message, add it to all the call
540 // pieces on the active stack.
541 if (PathDiagnosticEventPiece *ep =
542 dyn_cast<PathDiagnosticEventPiece>(P)) {
Anna Zaks368a0d52012-03-15 21:13:02 +0000543
Anna Zaks56a938f2012-03-16 23:24:20 +0000544 if (ep->hasCallStackHint())
545 for (StackDiagVector::iterator I = CallStack.begin(),
546 E = CallStack.end(); I != E; ++I) {
547 PathDiagnosticCallPiece *CP = I->first;
548 const ExplodedNode *N = I->second;
NAKAMURA Takumi8fe45252012-03-17 13:06:05 +0000549 std::string stackMsg = ep->getCallStackMessage(N);
Anna Zaks56a938f2012-03-16 23:24:20 +0000550
Anna Zaks368a0d52012-03-15 21:13:02 +0000551 // The last message on the path to final bug is the most important
552 // one. Since we traverse the path backwards, do not add the message
553 // if one has been previously added.
Anna Zaks56a938f2012-03-16 23:24:20 +0000554 if (!CP->hasCallStackMessage())
555 CP->setCallStackMessage(stackMsg);
556 }
Anna Zaks368a0d52012-03-15 21:13:02 +0000557 }
558}
Ted Kremenek31061982009-03-31 23:00:32 +0000559
Ted Kremenek77d09442012-03-02 01:27:31 +0000560static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM);
Ted Kremenek14856d72009-04-06 23:06:54 +0000561
Jordan Rose8347d3d2012-09-22 01:24:53 +0000562static bool GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
Ted Kremenek31061982009-03-31 23:00:32 +0000563 PathDiagnosticBuilder &PDB,
Jordy Rose3bc75ca2012-03-24 03:03:29 +0000564 const ExplodedNode *N,
565 ArrayRef<BugReporterVisitor *> visitors) {
Ted Kremenek8966bc12009-05-06 21:39:49 +0000566
Ted Kremenek31061982009-03-31 23:00:32 +0000567 SourceManager& SMgr = PDB.getSourceManager();
Ted Kremenek59950d32012-02-24 07:12:52 +0000568 const LocationContext *LC = PDB.LC;
Ted Kremenek9c378f72011-08-12 23:37:29 +0000569 const ExplodedNode *NextNode = N->pred_empty()
Ted Kremenek31061982009-03-31 23:00:32 +0000570 ? NULL : *(N->pred_begin());
Anna Zaks368a0d52012-03-15 21:13:02 +0000571
Anna Zaks56a938f2012-03-16 23:24:20 +0000572 StackDiagVector CallStack;
Anna Zaks368a0d52012-03-15 21:13:02 +0000573
Ted Kremenek31061982009-03-31 23:00:32 +0000574 while (NextNode) {
Mike Stump1eb44332009-09-09 15:08:12 +0000575 N = NextNode;
Ted Kremenek59950d32012-02-24 07:12:52 +0000576 PDB.LC = N->getLocationContext();
Ted Kremenek31061982009-03-31 23:00:32 +0000577 NextNode = GetPredecessorNode(N);
Mike Stump1eb44332009-09-09 15:08:12 +0000578
Ted Kremenek31061982009-03-31 23:00:32 +0000579 ProgramPoint P = N->getLocation();
Jordan Rose183ba8e2012-07-26 20:04:05 +0000580
Anna Zaks80de4872012-08-29 21:22:37 +0000581 do {
David Blaikie7a95de62013-02-21 22:23:56 +0000582 if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
Anna Zaks80de4872012-08-29 21:22:37 +0000583 PathDiagnosticCallPiece *C =
584 PathDiagnosticCallPiece::construct(N, *CE, SMgr);
585 GRBugReporter& BR = PDB.getBugReporter();
586 BR.addCallPieceLocationContextPair(C, CE->getCalleeContext());
587 PD.getActivePath().push_front(C);
588 PD.pushActivePath(&C->path);
589 CallStack.push_back(StackDiagPair(C, N));
590 break;
Anna Zaks93739372012-03-14 18:58:28 +0000591 }
Jordan Rose183ba8e2012-07-26 20:04:05 +0000592
David Blaikie7a95de62013-02-21 22:23:56 +0000593 if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
Anna Zaks80de4872012-08-29 21:22:37 +0000594 // Flush all locations, and pop the active path.
595 bool VisitedEntireCall = PD.isWithinCall();
596 PD.popActivePath();
597
598 // Either we just added a bunch of stuff to the top-level path, or
599 // we have a previous CallExitEnd. If the former, it means that the
600 // path terminated within a function call. We must then take the
601 // current contents of the active path and place it within
602 // a new PathDiagnosticCallPiece.
603 PathDiagnosticCallPiece *C;
604 if (VisitedEntireCall) {
605 C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
606 } else {
607 const Decl *Caller = CE->getLocationContext()->getDecl();
608 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
609 GRBugReporter& BR = PDB.getBugReporter();
610 BR.addCallPieceLocationContextPair(C, CE->getCalleeContext());
611 }
612
613 C->setCallee(*CE, SMgr);
614 if (!CallStack.empty()) {
615 assert(CallStack.back().first == C);
616 CallStack.pop_back();
617 }
618 break;
Anna Zaks368a0d52012-03-15 21:13:02 +0000619 }
Mike Stump1eb44332009-09-09 15:08:12 +0000620
David Blaikie7a95de62013-02-21 22:23:56 +0000621 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
Anna Zaks80de4872012-08-29 21:22:37 +0000622 const CFGBlock *Src = BE->getSrc();
623 const CFGBlock *Dst = BE->getDst();
624 const Stmt *T = Src->getTerminator();
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Anna Zaks80de4872012-08-29 21:22:37 +0000626 if (!T)
627 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Anna Zaks80de4872012-08-29 21:22:37 +0000629 PathDiagnosticLocation Start =
630 PathDiagnosticLocation::createBegin(T, SMgr,
631 N->getLocationContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Anna Zaks80de4872012-08-29 21:22:37 +0000633 switch (T->getStmtClass()) {
Ted Kremenek31061982009-03-31 23:00:32 +0000634 default:
635 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Ted Kremenek31061982009-03-31 23:00:32 +0000637 case Stmt::GotoStmtClass:
Mike Stump1eb44332009-09-09 15:08:12 +0000638 case Stmt::IndirectGotoStmtClass: {
Ted Kremenek9c378f72011-08-12 23:37:29 +0000639 const Stmt *S = GetNextStmt(N);
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Ted Kremenek31061982009-03-31 23:00:32 +0000641 if (!S)
Anna Zaks80de4872012-08-29 21:22:37 +0000642 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000643
Ted Kremenek31061982009-03-31 23:00:32 +0000644 std::string sbuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000645 llvm::raw_string_ostream os(sbuf);
Ted Kremenek31061982009-03-31 23:00:32 +0000646 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000647
Ted Kremenek31061982009-03-31 23:00:32 +0000648 os << "Control jumps to line "
Anna Zaks80de4872012-08-29 21:22:37 +0000649 << End.asLocation().getExpansionLineNumber();
650 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
651 Start, End, os.str()));
Ted Kremenek31061982009-03-31 23:00:32 +0000652 break;
653 }
Mike Stump1eb44332009-09-09 15:08:12 +0000654
655 case Stmt::SwitchStmtClass: {
Ted Kremenek31061982009-03-31 23:00:32 +0000656 // Figure out what case arm we took.
657 std::string sbuf;
658 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000659
Ted Kremenek9c378f72011-08-12 23:37:29 +0000660 if (const Stmt *S = Dst->getLabel()) {
Anna Zaks220ac8c2011-09-15 01:08:34 +0000661 PathDiagnosticLocation End(S, SMgr, LC);
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Ted Kremenek31061982009-03-31 23:00:32 +0000663 switch (S->getStmtClass()) {
Anna Zaks80de4872012-08-29 21:22:37 +0000664 default:
665 os << "No cases match in the switch statement. "
666 "Control jumps to line "
667 << End.asLocation().getExpansionLineNumber();
668 break;
669 case Stmt::DefaultStmtClass:
670 os << "Control jumps to the 'default' case at line "
671 << End.asLocation().getExpansionLineNumber();
672 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000673
Anna Zaks80de4872012-08-29 21:22:37 +0000674 case Stmt::CaseStmtClass: {
675 os << "Control jumps to 'case ";
676 const CaseStmt *Case = cast<CaseStmt>(S);
677 const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Anna Zaks80de4872012-08-29 21:22:37 +0000679 // Determine if it is an enum.
680 bool GetRawInt = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000681
Anna Zaks80de4872012-08-29 21:22:37 +0000682 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
683 // FIXME: Maybe this should be an assertion. Are there cases
684 // were it is not an EnumConstantDecl?
685 const EnumConstantDecl *D =
Zhongxing Xu03509ae2010-07-20 06:22:24 +0000686 dyn_cast<EnumConstantDecl>(DR->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000687
Anna Zaks80de4872012-08-29 21:22:37 +0000688 if (D) {
689 GetRawInt = false;
690 os << *D;
Ted Kremenek31061982009-03-31 23:00:32 +0000691 }
Ted Kremenek31061982009-03-31 23:00:32 +0000692 }
Anna Zaks80de4872012-08-29 21:22:37 +0000693
694 if (GetRawInt)
695 os << LHS->EvaluateKnownConstInt(PDB.getASTContext());
696
697 os << ":' at line "
698 << End.asLocation().getExpansionLineNumber();
699 break;
Ted Kremenek31061982009-03-31 23:00:32 +0000700 }
Anna Zaks80de4872012-08-29 21:22:37 +0000701 }
702 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
703 Start, End, os.str()));
Ted Kremenek31061982009-03-31 23:00:32 +0000704 }
705 else {
706 os << "'Default' branch taken. ";
Mike Stump1eb44332009-09-09 15:08:12 +0000707 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
Anna Zaks80de4872012-08-29 21:22:37 +0000708 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
709 Start, End, os.str()));
Ted Kremenek31061982009-03-31 23:00:32 +0000710 }
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Ted Kremenek31061982009-03-31 23:00:32 +0000712 break;
713 }
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Ted Kremenek31061982009-03-31 23:00:32 +0000715 case Stmt::BreakStmtClass:
716 case Stmt::ContinueStmtClass: {
717 std::string sbuf;
718 llvm::raw_string_ostream os(sbuf);
719 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
Anna Zaks80de4872012-08-29 21:22:37 +0000720 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
721 Start, End, os.str()));
Ted Kremenek31061982009-03-31 23:00:32 +0000722 break;
723 }
Mike Stump1eb44332009-09-09 15:08:12 +0000724
Anna Zaks80de4872012-08-29 21:22:37 +0000725 // Determine control-flow for ternary '?'.
John McCall56ca35d2011-02-17 10:25:35 +0000726 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek31061982009-03-31 23:00:32 +0000727 case Stmt::ConditionalOperatorClass: {
728 std::string sbuf;
729 llvm::raw_string_ostream os(sbuf);
730 os << "'?' condition is ";
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Ted Kremenek31061982009-03-31 23:00:32 +0000732 if (*(Src->succ_begin()+1) == Dst)
733 os << "false";
734 else
735 os << "true";
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Ted Kremenek31061982009-03-31 23:00:32 +0000737 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Ted Kremenek31061982009-03-31 23:00:32 +0000739 if (const Stmt *S = End.asStmt())
740 End = PDB.getEnclosingStmtLocation(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Anna Zaks80de4872012-08-29 21:22:37 +0000742 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
743 Start, End, os.str()));
Ted Kremenek31061982009-03-31 23:00:32 +0000744 break;
745 }
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Anna Zaks80de4872012-08-29 21:22:37 +0000747 // Determine control-flow for short-circuited '&&' and '||'.
Ted Kremenek31061982009-03-31 23:00:32 +0000748 case Stmt::BinaryOperatorClass: {
749 if (!PDB.supportsLogicalOpControlFlow())
750 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Zhongxing Xu03509ae2010-07-20 06:22:24 +0000752 const BinaryOperator *B = cast<BinaryOperator>(T);
Ted Kremenek31061982009-03-31 23:00:32 +0000753 std::string sbuf;
754 llvm::raw_string_ostream os(sbuf);
755 os << "Left side of '";
Mike Stump1eb44332009-09-09 15:08:12 +0000756
John McCall2de56d12010-08-25 11:45:40 +0000757 if (B->getOpcode() == BO_LAnd) {
Ted Kremenek31061982009-03-31 23:00:32 +0000758 os << "&&" << "' is ";
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Ted Kremenek31061982009-03-31 23:00:32 +0000760 if (*(Src->succ_begin()+1) == Dst) {
761 os << "false";
Anna Zaks220ac8c2011-09-15 01:08:34 +0000762 PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
Anna Zaks0cd59482011-09-16 19:18:30 +0000763 PathDiagnosticLocation Start =
Anna Zaks80de4872012-08-29 21:22:37 +0000764 PathDiagnosticLocation::createOperatorLoc(B, SMgr);
765 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
766 Start, End, os.str()));
Mike Stump1eb44332009-09-09 15:08:12 +0000767 }
Ted Kremenek31061982009-03-31 23:00:32 +0000768 else {
769 os << "true";
Anna Zaks220ac8c2011-09-15 01:08:34 +0000770 PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
Ted Kremenek31061982009-03-31 23:00:32 +0000771 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
Anna Zaks80de4872012-08-29 21:22:37 +0000772 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
773 Start, End, os.str()));
Mike Stump1eb44332009-09-09 15:08:12 +0000774 }
Ted Kremenek31061982009-03-31 23:00:32 +0000775 }
776 else {
John McCall2de56d12010-08-25 11:45:40 +0000777 assert(B->getOpcode() == BO_LOr);
Ted Kremenek31061982009-03-31 23:00:32 +0000778 os << "||" << "' is ";
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Ted Kremenek31061982009-03-31 23:00:32 +0000780 if (*(Src->succ_begin()+1) == Dst) {
781 os << "false";
Anna Zaks220ac8c2011-09-15 01:08:34 +0000782 PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
Ted Kremenek31061982009-03-31 23:00:32 +0000783 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
Anna Zaks80de4872012-08-29 21:22:37 +0000784 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
785 Start, End, os.str()));
Ted Kremenek31061982009-03-31 23:00:32 +0000786 }
787 else {
788 os << "true";
Anna Zaks220ac8c2011-09-15 01:08:34 +0000789 PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
Anna Zaks0cd59482011-09-16 19:18:30 +0000790 PathDiagnosticLocation Start =
Anna Zaks80de4872012-08-29 21:22:37 +0000791 PathDiagnosticLocation::createOperatorLoc(B, SMgr);
792 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
793 Start, End, os.str()));
Ted Kremenek31061982009-03-31 23:00:32 +0000794 }
795 }
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Ted Kremenek31061982009-03-31 23:00:32 +0000797 break;
798 }
Mike Stump1eb44332009-09-09 15:08:12 +0000799
800 case Stmt::DoStmtClass: {
Ted Kremenek31061982009-03-31 23:00:32 +0000801 if (*(Src->succ_begin()) == Dst) {
802 std::string sbuf;
803 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Ted Kremenek31061982009-03-31 23:00:32 +0000805 os << "Loop condition is true. ";
806 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Ted Kremenek31061982009-03-31 23:00:32 +0000808 if (const Stmt *S = End.asStmt())
809 End = PDB.getEnclosingStmtLocation(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Anna Zaks80de4872012-08-29 21:22:37 +0000811 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
812 Start, End, os.str()));
Ted Kremenek31061982009-03-31 23:00:32 +0000813 }
814 else {
815 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Ted Kremenek31061982009-03-31 23:00:32 +0000817 if (const Stmt *S = End.asStmt())
818 End = PDB.getEnclosingStmtLocation(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Anna Zaks80de4872012-08-29 21:22:37 +0000820 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
821 Start, End, "Loop condition is false. Exiting loop"));
Ted Kremenek31061982009-03-31 23:00:32 +0000822 }
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Ted Kremenek31061982009-03-31 23:00:32 +0000824 break;
825 }
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Ted Kremenek31061982009-03-31 23:00:32 +0000827 case Stmt::WhileStmtClass:
Mike Stump1eb44332009-09-09 15:08:12 +0000828 case Stmt::ForStmtClass: {
Ted Kremenek31061982009-03-31 23:00:32 +0000829 if (*(Src->succ_begin()+1) == Dst) {
830 std::string sbuf;
831 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Ted Kremenek31061982009-03-31 23:00:32 +0000833 os << "Loop condition is false. ";
834 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
835 if (const Stmt *S = End.asStmt())
836 End = PDB.getEnclosingStmtLocation(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Anna Zaks80de4872012-08-29 21:22:37 +0000838 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
839 Start, End, os.str()));
Ted Kremenek31061982009-03-31 23:00:32 +0000840 }
841 else {
842 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
843 if (const Stmt *S = End.asStmt())
844 End = PDB.getEnclosingStmtLocation(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Anna Zaks80de4872012-08-29 21:22:37 +0000846 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
847 Start, End, "Loop condition is true. Entering loop body"));
Ted Kremenek31061982009-03-31 23:00:32 +0000848 }
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Ted Kremenek31061982009-03-31 23:00:32 +0000850 break;
851 }
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Ted Kremenek31061982009-03-31 23:00:32 +0000853 case Stmt::IfStmtClass: {
854 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
Mike Stump1eb44332009-09-09 15:08:12 +0000855
Ted Kremenek31061982009-03-31 23:00:32 +0000856 if (const Stmt *S = End.asStmt())
857 End = PDB.getEnclosingStmtLocation(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Ted Kremenek31061982009-03-31 23:00:32 +0000859 if (*(Src->succ_begin()+1) == Dst)
Anna Zaks80de4872012-08-29 21:22:37 +0000860 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
861 Start, End, "Taking false branch"));
Mike Stump1eb44332009-09-09 15:08:12 +0000862 else
Anna Zaks80de4872012-08-29 21:22:37 +0000863 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
864 Start, End, "Taking true branch"));
Mike Stump1eb44332009-09-09 15:08:12 +0000865
Ted Kremenek31061982009-03-31 23:00:32 +0000866 break;
867 }
Anna Zaks80de4872012-08-29 21:22:37 +0000868 }
Ted Kremenek31061982009-03-31 23:00:32 +0000869 }
Anna Zaks80de4872012-08-29 21:22:37 +0000870 } while(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Ted Kremenekdd986cc2009-05-07 00:45:33 +0000872 if (NextNode) {
Anna Zaks8e6431a2011-08-18 22:37:56 +0000873 // Add diagnostic pieces from custom visitors.
874 BugReport *R = PDB.getBugReport();
Jordy Rose3bc75ca2012-03-24 03:03:29 +0000875 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(),
876 E = visitors.end();
877 I != E; ++I) {
Anna Zaks368a0d52012-03-15 21:13:02 +0000878 if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) {
Ted Kremenek2042fc12012-02-24 06:00:00 +0000879 PD.getActivePath().push_front(p);
Anna Zaks368a0d52012-03-15 21:13:02 +0000880 updateStackPiecesWithMessage(p, CallStack);
881 }
Ted Kremenekdd986cc2009-05-07 00:45:33 +0000882 }
Ted Kremenek8966bc12009-05-06 21:39:49 +0000883 }
Ted Kremenek31061982009-03-31 23:00:32 +0000884 }
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Jordan Rose8347d3d2012-09-22 01:24:53 +0000886 if (!PDB.getBugReport()->isValid())
887 return false;
888
Ted Kremenek14856d72009-04-06 23:06:54 +0000889 // After constructing the full PathDiagnostic, do a pass over it to compact
890 // PathDiagnosticPieces that occur within a macro.
Ted Kremenek77d09442012-03-02 01:27:31 +0000891 CompactPathDiagnostic(PD.getMutablePieces(), PDB.getSourceManager());
Jordan Rose8347d3d2012-09-22 01:24:53 +0000892 return true;
Ted Kremenek31061982009-03-31 23:00:32 +0000893}
894
895//===----------------------------------------------------------------------===//
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000896// "Extensive" PathDiagnostic generation.
897//===----------------------------------------------------------------------===//
898
899static bool IsControlFlowExpr(const Stmt *S) {
900 const Expr *E = dyn_cast<Expr>(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000902 if (!E)
903 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000904
905 E = E->IgnoreParenCasts();
906
John McCall56ca35d2011-02-17 10:25:35 +0000907 if (isa<AbstractConditionalOperator>(E))
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000908 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000910 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
911 if (B->isLogicalOp())
912 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000913
914 return false;
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000915}
916
Ted Kremenek14856d72009-04-06 23:06:54 +0000917namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000918class ContextLocation : public PathDiagnosticLocation {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000919 bool IsDead;
920public:
921 ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
922 : PathDiagnosticLocation(L), IsDead(isdead) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000923
924 void markDead() { IsDead = true; }
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000925 bool isDead() const { return IsDead; }
926};
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000928class EdgeBuilder {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000929 std::vector<ContextLocation> CLocs;
930 typedef std::vector<ContextLocation>::iterator iterator;
Ted Kremenek14856d72009-04-06 23:06:54 +0000931 PathDiagnostic &PD;
932 PathDiagnosticBuilder &PDB;
933 PathDiagnosticLocation PrevLoc;
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000935 bool IsConsumedExpr(const PathDiagnosticLocation &L);
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Ted Kremenek14856d72009-04-06 23:06:54 +0000937 bool containsLocation(const PathDiagnosticLocation &Container,
938 const PathDiagnosticLocation &Containee);
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Ted Kremenek14856d72009-04-06 23:06:54 +0000940 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Ted Kremenek9650cf32009-05-11 21:42:34 +0000942 PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
943 bool firstCharOnly = false) {
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000944 if (const Stmt *S = L.asStmt()) {
Ted Kremenek9650cf32009-05-11 21:42:34 +0000945 const Stmt *Original = S;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000946 while (1) {
947 // Adjust the location for some expressions that are best referenced
948 // by one of their subexpressions.
Ted Kremenek9650cf32009-05-11 21:42:34 +0000949 switch (S->getStmtClass()) {
950 default:
951 break;
952 case Stmt::ParenExprClass:
Peter Collingbournef111d932011-04-15 00:35:48 +0000953 case Stmt::GenericSelectionExprClass:
954 S = cast<Expr>(S)->IgnoreParens();
Ted Kremenek9650cf32009-05-11 21:42:34 +0000955 firstCharOnly = true;
956 continue;
John McCall56ca35d2011-02-17 10:25:35 +0000957 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek9650cf32009-05-11 21:42:34 +0000958 case Stmt::ConditionalOperatorClass:
John McCall56ca35d2011-02-17 10:25:35 +0000959 S = cast<AbstractConditionalOperator>(S)->getCond();
Ted Kremenek9650cf32009-05-11 21:42:34 +0000960 firstCharOnly = true;
961 continue;
962 case Stmt::ChooseExprClass:
963 S = cast<ChooseExpr>(S)->getCond();
964 firstCharOnly = true;
965 continue;
966 case Stmt::BinaryOperatorClass:
967 S = cast<BinaryOperator>(S)->getLHS();
968 firstCharOnly = true;
969 continue;
970 }
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Ted Kremenek9650cf32009-05-11 21:42:34 +0000972 break;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000973 }
Mike Stump1eb44332009-09-09 15:08:12 +0000974
Ted Kremenek9650cf32009-05-11 21:42:34 +0000975 if (S != Original)
Ted Kremenek59950d32012-02-24 07:12:52 +0000976 L = PathDiagnosticLocation(S, L.getManager(), PDB.LC);
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000977 }
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Ted Kremenek9650cf32009-05-11 21:42:34 +0000979 if (firstCharOnly)
Anna Zaks1531bb02011-09-20 01:38:47 +0000980 L = PathDiagnosticLocation::createSingleLocation(L);
Ted Kremenek9650cf32009-05-11 21:42:34 +0000981
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000982 return L;
983 }
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Ted Kremenek14856d72009-04-06 23:06:54 +0000985 void popLocation() {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000986 if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000987 // For contexts, we only one the first character as the range.
Ted Kremenek07c015c2009-05-15 02:46:13 +0000988 rawAddEdge(cleanUpLocation(CLocs.back(), true));
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000989 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000990 CLocs.pop_back();
991 }
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Ted Kremenek14856d72009-04-06 23:06:54 +0000993public:
994 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
995 : PD(pd), PDB(pdb) {
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Ted Kremeneka301a672009-04-22 18:16:20 +0000997 // If the PathDiagnostic already has pieces, add the enclosing statement
998 // of the first piece as a context as well.
Ted Kremenek802e0242012-02-08 04:32:34 +0000999 if (!PD.path.empty()) {
1000 PrevLoc = (*PD.path.begin())->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Ted Kremenek14856d72009-04-06 23:06:54 +00001002 if (const Stmt *S = PrevLoc.asStmt())
Ted Kremeneke1baed32009-05-05 23:13:38 +00001003 addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
Ted Kremenek14856d72009-04-06 23:06:54 +00001004 }
1005 }
1006
1007 ~EdgeBuilder() {
1008 while (!CLocs.empty()) popLocation();
Anna Zaks0cd59482011-09-16 19:18:30 +00001009
Ted Kremeneka301a672009-04-22 18:16:20 +00001010 // Finally, add an initial edge from the start location of the first
1011 // statement (if it doesn't already exist).
Anna Zaks0cd59482011-09-16 19:18:30 +00001012 PathDiagnosticLocation L = PathDiagnosticLocation::createDeclBegin(
Ted Kremenek59950d32012-02-24 07:12:52 +00001013 PDB.LC,
Anna Zaks0cd59482011-09-16 19:18:30 +00001014 PDB.getSourceManager());
1015 if (L.isValid())
1016 rawAddEdge(L);
Ted Kremenek14856d72009-04-06 23:06:54 +00001017 }
1018
Ted Kremenek5de4fdb2012-02-07 02:26:17 +00001019 void flushLocations() {
1020 while (!CLocs.empty())
1021 popLocation();
1022 PrevLoc = PathDiagnosticLocation();
1023 }
1024
Ted Kremenek14856d72009-04-06 23:06:54 +00001025 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false);
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Ted Kremenek8bd4d032009-04-28 04:23:15 +00001027 void rawAddEdge(PathDiagnosticLocation NewLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Ted Kremenek14856d72009-04-06 23:06:54 +00001029 void addContext(const Stmt *S);
Jordan Rose183ba8e2012-07-26 20:04:05 +00001030 void addContext(const PathDiagnosticLocation &L);
Ted Kremeneke1baed32009-05-05 23:13:38 +00001031 void addExtendedContext(const Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +00001032};
Ted Kremenek14856d72009-04-06 23:06:54 +00001033} // end anonymous namespace
1034
1035
1036PathDiagnosticLocation
1037EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
1038 if (const Stmt *S = L.asStmt()) {
1039 if (IsControlFlowExpr(S))
1040 return L;
Mike Stump1eb44332009-09-09 15:08:12 +00001041
1042 return PDB.getEnclosingStmtLocation(S);
Ted Kremenek14856d72009-04-06 23:06:54 +00001043 }
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Ted Kremenek14856d72009-04-06 23:06:54 +00001045 return L;
1046}
1047
1048bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
1049 const PathDiagnosticLocation &Containee) {
1050
1051 if (Container == Containee)
1052 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Ted Kremenek14856d72009-04-06 23:06:54 +00001054 if (Container.asDecl())
1055 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001056
Ted Kremenek14856d72009-04-06 23:06:54 +00001057 if (const Stmt *S = Containee.asStmt())
1058 if (const Stmt *ContainerS = Container.asStmt()) {
1059 while (S) {
1060 if (S == ContainerS)
1061 return true;
1062 S = PDB.getParent(S);
1063 }
1064 return false;
1065 }
1066
1067 // Less accurate: compare using source ranges.
1068 SourceRange ContainerR = Container.asRange();
1069 SourceRange ContaineeR = Containee.asRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Ted Kremenek14856d72009-04-06 23:06:54 +00001071 SourceManager &SM = PDB.getSourceManager();
Chandler Carruth40278532011-07-25 16:49:02 +00001072 SourceLocation ContainerRBeg = SM.getExpansionLoc(ContainerR.getBegin());
1073 SourceLocation ContainerREnd = SM.getExpansionLoc(ContainerR.getEnd());
1074 SourceLocation ContaineeRBeg = SM.getExpansionLoc(ContaineeR.getBegin());
1075 SourceLocation ContaineeREnd = SM.getExpansionLoc(ContaineeR.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001076
Chandler Carruth64211622011-07-25 21:09:52 +00001077 unsigned ContainerBegLine = SM.getExpansionLineNumber(ContainerRBeg);
1078 unsigned ContainerEndLine = SM.getExpansionLineNumber(ContainerREnd);
1079 unsigned ContaineeBegLine = SM.getExpansionLineNumber(ContaineeRBeg);
1080 unsigned ContaineeEndLine = SM.getExpansionLineNumber(ContaineeREnd);
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Ted Kremenek14856d72009-04-06 23:06:54 +00001082 assert(ContainerBegLine <= ContainerEndLine);
Mike Stump1eb44332009-09-09 15:08:12 +00001083 assert(ContaineeBegLine <= ContaineeEndLine);
1084
Ted Kremenek14856d72009-04-06 23:06:54 +00001085 return (ContainerBegLine <= ContaineeBegLine &&
1086 ContainerEndLine >= ContaineeEndLine &&
1087 (ContainerBegLine != ContaineeBegLine ||
Chandler Carrutha77c0312011-07-25 20:57:57 +00001088 SM.getExpansionColumnNumber(ContainerRBeg) <=
1089 SM.getExpansionColumnNumber(ContaineeRBeg)) &&
Ted Kremenek14856d72009-04-06 23:06:54 +00001090 (ContainerEndLine != ContaineeEndLine ||
Chandler Carrutha77c0312011-07-25 20:57:57 +00001091 SM.getExpansionColumnNumber(ContainerREnd) >=
Ted Kremenek6488dc32012-03-28 05:24:50 +00001092 SM.getExpansionColumnNumber(ContaineeREnd)));
Ted Kremenek14856d72009-04-06 23:06:54 +00001093}
1094
Ted Kremenek14856d72009-04-06 23:06:54 +00001095void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
1096 if (!PrevLoc.isValid()) {
1097 PrevLoc = NewLoc;
1098 return;
1099 }
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +00001101 const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc);
1102 const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001103
Ted Kremeneka43df952012-09-21 00:09:11 +00001104 if (PrevLocClean.asLocation().isInvalid()) {
1105 PrevLoc = NewLoc;
1106 return;
1107 }
1108
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +00001109 if (NewLocClean.asLocation() == PrevLocClean.asLocation())
Ted Kremenek14856d72009-04-06 23:06:54 +00001110 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Ted Kremenek14856d72009-04-06 23:06:54 +00001112 // FIXME: Ignore intra-macro edges for now.
Chandler Carruth40278532011-07-25 16:49:02 +00001113 if (NewLocClean.asLocation().getExpansionLoc() ==
1114 PrevLocClean.asLocation().getExpansionLoc())
Ted Kremenek14856d72009-04-06 23:06:54 +00001115 return;
1116
Ted Kremenek2042fc12012-02-24 06:00:00 +00001117 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +00001118 PrevLoc = NewLoc;
Ted Kremenek14856d72009-04-06 23:06:54 +00001119}
1120
1121void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) {
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Ted Kremeneka301a672009-04-22 18:16:20 +00001123 if (!alwaysAdd && NewLoc.asLocation().isMacroID())
1124 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001125
Ted Kremenek14856d72009-04-06 23:06:54 +00001126 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
1127
1128 while (!CLocs.empty()) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001129 ContextLocation &TopContextLoc = CLocs.back();
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Ted Kremenek14856d72009-04-06 23:06:54 +00001131 // Is the top location context the same as the one for the new location?
1132 if (TopContextLoc == CLoc) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001133 if (alwaysAdd) {
Ted Kremenek4c6f8d32009-05-04 18:15:17 +00001134 if (IsConsumedExpr(TopContextLoc) &&
1135 !IsControlFlowExpr(TopContextLoc.asStmt()))
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001136 TopContextLoc.markDead();
1137
Ted Kremenek14856d72009-04-06 23:06:54 +00001138 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001139 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001140
1141 return;
1142 }
1143
1144 if (containsLocation(TopContextLoc, CLoc)) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001145 if (alwaysAdd) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001146 rawAddEdge(NewLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Ted Kremenek4c6f8d32009-05-04 18:15:17 +00001148 if (IsConsumedExpr(CLoc) && !IsControlFlowExpr(CLoc.asStmt())) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001149 CLocs.push_back(ContextLocation(CLoc, true));
1150 return;
1151 }
1152 }
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Ted Kremenek14856d72009-04-06 23:06:54 +00001154 CLocs.push_back(CLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001155 return;
Ted Kremenek14856d72009-04-06 23:06:54 +00001156 }
1157
1158 // Context does not contain the location. Flush it.
1159 popLocation();
1160 }
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Ted Kremenek5c7168c2009-04-22 20:36:26 +00001162 // If we reach here, there is no enclosing context. Just add the edge.
1163 rawAddEdge(NewLoc);
Ted Kremenek14856d72009-04-06 23:06:54 +00001164}
1165
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001166bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
1167 if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
1168 return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001170 return false;
1171}
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Ted Kremeneke1baed32009-05-05 23:13:38 +00001173void EdgeBuilder::addExtendedContext(const Stmt *S) {
1174 if (!S)
1175 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001176
1177 const Stmt *Parent = PDB.getParent(S);
Ted Kremeneke1baed32009-05-05 23:13:38 +00001178 while (Parent) {
1179 if (isa<CompoundStmt>(Parent))
1180 Parent = PDB.getParent(Parent);
1181 else
1182 break;
1183 }
1184
1185 if (Parent) {
1186 switch (Parent->getStmtClass()) {
1187 case Stmt::DoStmtClass:
1188 case Stmt::ObjCAtSynchronizedStmtClass:
1189 addContext(Parent);
1190 default:
1191 break;
1192 }
1193 }
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Ted Kremeneke1baed32009-05-05 23:13:38 +00001195 addContext(S);
1196}
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Ted Kremenek14856d72009-04-06 23:06:54 +00001198void EdgeBuilder::addContext(const Stmt *S) {
1199 if (!S)
1200 return;
1201
Ted Kremenek59950d32012-02-24 07:12:52 +00001202 PathDiagnosticLocation L(S, PDB.getSourceManager(), PDB.LC);
Jordan Rose183ba8e2012-07-26 20:04:05 +00001203 addContext(L);
1204}
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Jordan Rose183ba8e2012-07-26 20:04:05 +00001206void EdgeBuilder::addContext(const PathDiagnosticLocation &L) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001207 while (!CLocs.empty()) {
1208 const PathDiagnosticLocation &TopContextLoc = CLocs.back();
1209
1210 // Is the top location context the same as the one for the new location?
1211 if (TopContextLoc == L)
1212 return;
1213
1214 if (containsLocation(TopContextLoc, L)) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001215 CLocs.push_back(L);
Mike Stump1eb44332009-09-09 15:08:12 +00001216 return;
Ted Kremenek14856d72009-04-06 23:06:54 +00001217 }
1218
1219 // Context does not contain the location. Flush it.
1220 popLocation();
1221 }
1222
1223 CLocs.push_back(L);
1224}
1225
Ted Kremenek11abcec2012-05-02 00:31:29 +00001226// Cone-of-influence: support the reverse propagation of "interesting" symbols
1227// and values by tracing interesting calculations backwards through evaluated
1228// expressions along a path. This is probably overly complicated, but the idea
1229// is that if an expression computed an "interesting" value, the child
1230// expressions are are also likely to be "interesting" as well (which then
1231// propagates to the values they in turn compute). This reverse propagation
1232// is needed to track interesting correlations across function call boundaries,
1233// where formal arguments bind to actual arguments, etc. This is also needed
1234// because the constraint solver sometimes simplifies certain symbolic values
1235// into constants when appropriate, and this complicates reasoning about
1236// interesting values.
1237typedef llvm::DenseSet<const Expr *> InterestingExprs;
1238
1239static void reversePropagateIntererstingSymbols(BugReport &R,
1240 InterestingExprs &IE,
1241 const ProgramState *State,
1242 const Expr *Ex,
1243 const LocationContext *LCtx) {
1244 SVal V = State->getSVal(Ex, LCtx);
1245 if (!(R.isInteresting(V) || IE.count(Ex)))
1246 return;
1247
1248 switch (Ex->getStmtClass()) {
1249 default:
1250 if (!isa<CastExpr>(Ex))
1251 break;
1252 // Fall through.
1253 case Stmt::BinaryOperatorClass:
1254 case Stmt::UnaryOperatorClass: {
1255 for (Stmt::const_child_iterator CI = Ex->child_begin(),
1256 CE = Ex->child_end();
1257 CI != CE; ++CI) {
1258 if (const Expr *child = dyn_cast_or_null<Expr>(*CI)) {
1259 IE.insert(child);
1260 SVal ChildV = State->getSVal(child, LCtx);
1261 R.markInteresting(ChildV);
1262 }
1263 break;
1264 }
1265 }
1266 }
1267
1268 R.markInteresting(V);
1269}
1270
1271static void reversePropagateInterestingSymbols(BugReport &R,
1272 InterestingExprs &IE,
1273 const ProgramState *State,
1274 const LocationContext *CalleeCtx,
1275 const LocationContext *CallerCtx)
1276{
Jordan Rose852aa0d2012-07-10 22:07:52 +00001277 // FIXME: Handle non-CallExpr-based CallEvents.
Ted Kremenek11abcec2012-05-02 00:31:29 +00001278 const StackFrameContext *Callee = CalleeCtx->getCurrentStackFrame();
1279 const Stmt *CallSite = Callee->getCallSite();
Jordan Rose852aa0d2012-07-10 22:07:52 +00001280 if (const CallExpr *CE = dyn_cast_or_null<CallExpr>(CallSite)) {
Ted Kremenek11abcec2012-05-02 00:31:29 +00001281 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CalleeCtx->getDecl())) {
1282 FunctionDecl::param_const_iterator PI = FD->param_begin(),
1283 PE = FD->param_end();
1284 CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end();
1285 for (; AI != AE && PI != PE; ++AI, ++PI) {
1286 if (const Expr *ArgE = *AI) {
1287 if (const ParmVarDecl *PD = *PI) {
1288 Loc LV = State->getLValue(PD, CalleeCtx);
1289 if (R.isInteresting(LV) || R.isInteresting(State->getRawSVal(LV)))
1290 IE.insert(ArgE);
1291 }
1292 }
1293 }
1294 }
1295 }
1296}
Ted Kremenek81856742013-02-08 19:51:43 +00001297
Ted Kremenekb04a2382013-02-22 05:45:33 +00001298//===----------------------------------------------------------------------===//
1299// Functions for determining if a loop was executed 0 times.
1300//===----------------------------------------------------------------------===//
1301
Ted Kremenek81856742013-02-08 19:51:43 +00001302/// Return true if the terminator is a loop and the destination is the
1303/// false branch.
1304static bool isLoopJumpPastBody(const Stmt *Term, const BlockEdge *BE) {
1305 switch (Term->getStmtClass()) {
1306 case Stmt::ForStmtClass:
1307 case Stmt::WhileStmtClass:
1308 break;
1309 default:
1310 // Note that we intentionally do not include do..while here.
1311 return false;
1312 }
1313
1314 // Did we take the false branch?
1315 const CFGBlock *Src = BE->getSrc();
1316 assert(Src->succ_size() == 2);
1317 return (*(Src->succ_begin()+1) == BE->getDst());
1318}
1319
Ted Kremenekb04a2382013-02-22 05:45:33 +00001320static bool isContainedByStmt(ParentMap &PM, const Stmt *S, const Stmt *SubS) {
1321 while (SubS) {
1322 if (SubS == S)
1323 return true;
1324 SubS = PM.getParent(SubS);
1325 }
1326 return false;
1327}
1328
1329static const Stmt *getStmtBeforeCond(ParentMap &PM, const Stmt *Term,
1330 const ExplodedNode *N) {
1331 while (N) {
1332 Optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>();
1333 if (SP) {
1334 const Stmt *S = SP->getStmt();
1335 if (!isContainedByStmt(PM, Term, S))
1336 return S;
1337 }
1338 N = GetPredecessorNode(N);
1339 }
1340 return 0;
1341}
1342
1343static bool isInLoopBody(ParentMap &PM, const Stmt *S, const Stmt *Term) {
1344 const Stmt *LoopBody = 0;
1345 switch (Term->getStmtClass()) {
1346 case Stmt::ForStmtClass: {
1347 const ForStmt *FS = cast<ForStmt>(Term);
1348 if (isContainedByStmt(PM, FS->getInc(), S))
1349 return true;
1350 LoopBody = FS->getBody();
1351 break;
1352 }
1353 case Stmt::WhileStmtClass:
1354 LoopBody = cast<WhileStmt>(Term)->getBody();
1355 break;
1356 default:
1357 return false;
1358 }
1359 return isContainedByStmt(PM, LoopBody, S);
1360}
1361
1362//===----------------------------------------------------------------------===//
1363// Top-level logic for generating extensive path diagnostics.
1364//===----------------------------------------------------------------------===//
1365
Jordan Rose8347d3d2012-09-22 01:24:53 +00001366static bool GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
Ted Kremenek14856d72009-04-06 23:06:54 +00001367 PathDiagnosticBuilder &PDB,
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001368 const ExplodedNode *N,
1369 ArrayRef<BugReporterVisitor *> visitors) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001370 EdgeBuilder EB(PD, PDB);
Anna Zaks0cd59482011-09-16 19:18:30 +00001371 const SourceManager& SM = PDB.getSourceManager();
Anna Zaks56a938f2012-03-16 23:24:20 +00001372 StackDiagVector CallStack;
Ted Kremenek11abcec2012-05-02 00:31:29 +00001373 InterestingExprs IE;
Ted Kremenek14856d72009-04-06 23:06:54 +00001374
Ted Kremenek9c378f72011-08-12 23:37:29 +00001375 const ExplodedNode *NextNode = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenek14856d72009-04-06 23:06:54 +00001376 while (NextNode) {
1377 N = NextNode;
1378 NextNode = GetPredecessorNode(N);
1379 ProgramPoint P = N->getLocation();
1380
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001381 do {
David Blaikie7a95de62013-02-21 22:23:56 +00001382 if (Optional<PostStmt> PS = P.getAs<PostStmt>()) {
Ted Kremenek11abcec2012-05-02 00:31:29 +00001383 if (const Expr *Ex = PS->getStmtAs<Expr>())
1384 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1385 N->getState().getPtr(), Ex,
1386 N->getLocationContext());
1387 }
1388
David Blaikie7a95de62013-02-21 22:23:56 +00001389 if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
Jordan Rose183ba8e2012-07-26 20:04:05 +00001390 const Stmt *S = CE->getCalleeContext()->getCallSite();
1391 if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001392 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1393 N->getState().getPtr(), Ex,
1394 N->getLocationContext());
Jordan Rose852aa0d2012-07-10 22:07:52 +00001395 }
Jordan Rose183ba8e2012-07-26 20:04:05 +00001396
1397 PathDiagnosticCallPiece *C =
1398 PathDiagnosticCallPiece::construct(N, *CE, SM);
Anna Zaks80de4872012-08-29 21:22:37 +00001399 GRBugReporter& BR = PDB.getBugReporter();
1400 BR.addCallPieceLocationContextPair(C, CE->getCalleeContext());
Jordan Rose183ba8e2012-07-26 20:04:05 +00001401
1402 EB.addEdge(C->callReturn, true);
1403 EB.flushLocations();
1404
1405 PD.getActivePath().push_front(C);
1406 PD.pushActivePath(&C->path);
1407 CallStack.push_back(StackDiagPair(C, N));
Ted Kremenek5de4fdb2012-02-07 02:26:17 +00001408 break;
1409 }
Ted Kremenek4ba86bc2012-03-02 21:16:22 +00001410
Ted Kremenek2042fc12012-02-24 06:00:00 +00001411 // Pop the call hierarchy if we are done walking the contents
1412 // of a function call.
David Blaikie7a95de62013-02-21 22:23:56 +00001413 if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
Ted Kremenek097ebb32012-03-06 01:25:01 +00001414 // Add an edge to the start of the function.
1415 const Decl *D = CE->getCalleeContext()->getDecl();
1416 PathDiagnosticLocation pos =
1417 PathDiagnosticLocation::createBegin(D, SM);
1418 EB.addEdge(pos);
1419
1420 // Flush all locations, and pop the active path.
Jordan Rose183ba8e2012-07-26 20:04:05 +00001421 bool VisitedEntireCall = PD.isWithinCall();
Ted Kremenek4ba86bc2012-03-02 21:16:22 +00001422 EB.flushLocations();
Ted Kremenek2042fc12012-02-24 06:00:00 +00001423 PD.popActivePath();
Ted Kremenek4ba86bc2012-03-02 21:16:22 +00001424 PDB.LC = N->getLocationContext();
Ted Kremenek097ebb32012-03-06 01:25:01 +00001425
Jordan Rose183ba8e2012-07-26 20:04:05 +00001426 // Either we just added a bunch of stuff to the top-level path, or
1427 // we have a previous CallExitEnd. If the former, it means that the
Ted Kremenek2042fc12012-02-24 06:00:00 +00001428 // path terminated within a function call. We must then take the
1429 // current contents of the active path and place it within
1430 // a new PathDiagnosticCallPiece.
Jordan Rose183ba8e2012-07-26 20:04:05 +00001431 PathDiagnosticCallPiece *C;
1432 if (VisitedEntireCall) {
1433 C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
1434 } else {
1435 const Decl *Caller = CE->getLocationContext()->getDecl();
Anna Zaks93739372012-03-14 18:58:28 +00001436 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
Anna Zaks80de4872012-08-29 21:22:37 +00001437 GRBugReporter& BR = PDB.getBugReporter();
1438 BR.addCallPieceLocationContextPair(C, CE->getCalleeContext());
Anna Zaks93739372012-03-14 18:58:28 +00001439 }
Jordan Rose852aa0d2012-07-10 22:07:52 +00001440
Jordan Rose183ba8e2012-07-26 20:04:05 +00001441 C->setCallee(*CE, SM);
1442 EB.addContext(C->getLocation());
Anna Zaks368a0d52012-03-15 21:13:02 +00001443
1444 if (!CallStack.empty()) {
Anna Zaks56a938f2012-03-16 23:24:20 +00001445 assert(CallStack.back().first == C);
Anna Zaks368a0d52012-03-15 21:13:02 +00001446 CallStack.pop_back();
1447 }
Ted Kremenek2042fc12012-02-24 06:00:00 +00001448 break;
1449 }
Ted Kremenek4ba86bc2012-03-02 21:16:22 +00001450
1451 // Note that is important that we update the LocationContext
1452 // after looking at CallExits. CallExit basically adds an
1453 // edge in the *caller*, so we don't want to update the LocationContext
1454 // too soon.
1455 PDB.LC = N->getLocationContext();
Ted Kremenek5de4fdb2012-02-07 02:26:17 +00001456
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001457 // Block edges.
David Blaikie7a95de62013-02-21 22:23:56 +00001458 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
Ted Kremenek11abcec2012-05-02 00:31:29 +00001459 // Does this represent entering a call? If so, look at propagating
1460 // interesting symbols across call boundaries.
1461 if (NextNode) {
1462 const LocationContext *CallerCtx = NextNode->getLocationContext();
1463 const LocationContext *CalleeCtx = PDB.LC;
1464 if (CallerCtx != CalleeCtx) {
1465 reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
1466 N->getState().getPtr(),
1467 CalleeCtx, CallerCtx);
1468 }
1469 }
1470
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001471 // Are we jumping to the head of a loop? Add a special diagnostic.
Ted Kremenekf57a2aa2012-09-12 06:22:18 +00001472 if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
Ted Kremenek59950d32012-02-24 07:12:52 +00001473 PathDiagnosticLocation L(Loop, SM, PDB.LC);
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001474 const CompoundStmt *CS = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001475
Ted Kremenekf57a2aa2012-09-12 06:22:18 +00001476 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1477 CS = dyn_cast<CompoundStmt>(FS->getBody());
1478 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1479 CS = dyn_cast<CompoundStmt>(WS->getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001481 PathDiagnosticEventPiece *p =
1482 new PathDiagnosticEventPiece(L,
Ted Kremenek07c015c2009-05-15 02:46:13 +00001483 "Looping back to the head of the loop");
Ted Kremenek2dd17ab2012-03-06 01:00:36 +00001484 p->setPrunable(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001486 EB.addEdge(p->getLocation(), true);
Ted Kremenek2042fc12012-02-24 06:00:00 +00001487 PD.getActivePath().push_front(p);
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001489 if (CS) {
Anna Zaks0cd59482011-09-16 19:18:30 +00001490 PathDiagnosticLocation BL =
1491 PathDiagnosticLocation::createEndBrace(CS, SM);
Ted Kremenek07c015c2009-05-15 02:46:13 +00001492 EB.addEdge(BL);
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001493 }
Ted Kremenek8bd4d032009-04-28 04:23:15 +00001494 }
Ted Kremenek81856742013-02-08 19:51:43 +00001495
Ted Kremenekb04a2382013-02-22 05:45:33 +00001496 const CFGBlock *BSrc = BE->getSrc();
1497 ParentMap &PM = PDB.getParentMap();
1498
1499 if (const Stmt *Term = BSrc->getTerminator()) {
Ted Kremenek81856742013-02-08 19:51:43 +00001500 // Are we jumping past the loop body without ever executing the
1501 // loop (because the condition was false)?
David Blaikie7a95de62013-02-21 22:23:56 +00001502 if (isLoopJumpPastBody(Term, &*BE) &&
Ted Kremenekb04a2382013-02-22 05:45:33 +00001503 !isInLoopBody(PM,
1504 getStmtBeforeCond(PM,
1505 BSrc->getTerminatorCondition(),
1506 N),
1507 Term)) {
Ted Kremenek81856742013-02-08 19:51:43 +00001508 PathDiagnosticLocation L(Term, SM, PDB.LC);
1509 PathDiagnosticEventPiece *PE =
Ted Kremenekb04a2382013-02-22 05:45:33 +00001510 new PathDiagnosticEventPiece(L, "Loop body executed 0 times");
Ted Kremenek81856742013-02-08 19:51:43 +00001511 PE->setPrunable(true);
Ted Kremenek81856742013-02-08 19:51:43 +00001512
1513 EB.addEdge(PE->getLocation(), true);
1514 PD.getActivePath().push_front(PE);
1515 }
1516
Ted Kremenekb04a2382013-02-22 05:45:33 +00001517 // In any case, add the terminator as the current statement
1518 // context for control edges.
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001519 EB.addContext(Term);
Ted Kremenek81856742013-02-08 19:51:43 +00001520 }
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001522 break;
Ted Kremenek14856d72009-04-06 23:06:54 +00001523 }
1524
David Blaikie7a95de62013-02-21 22:23:56 +00001525 if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) {
Jordan Rose1a7bcc42012-09-12 22:48:08 +00001526 CFGElement First = BE->getFirstElement();
David Blaikiefdf6a272013-02-21 20:58:29 +00001527 if (CFGStmt S = First.getAs<CFGStmt>()) {
1528 const Stmt *stmt = S.getStmt();
Ted Kremenek3c0349e2011-03-01 03:15:10 +00001529 if (IsControlFlowExpr(stmt)) {
Zhongxing Xub36cd3e2010-09-16 01:25:47 +00001530 // Add the proper context for '&&', '||', and '?'.
Ted Kremenek3c0349e2011-03-01 03:15:10 +00001531 EB.addContext(stmt);
Zhongxing Xub36cd3e2010-09-16 01:25:47 +00001532 }
1533 else
Ted Kremenek3c0349e2011-03-01 03:15:10 +00001534 EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt());
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001535 }
Zhongxing Xub36cd3e2010-09-16 01:25:47 +00001536
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001537 break;
1538 }
Ted Kremenek5de4fdb2012-02-07 02:26:17 +00001539
1540
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001541 } while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001543 if (!NextNode)
Ted Kremenek14856d72009-04-06 23:06:54 +00001544 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Anna Zaks8e6431a2011-08-18 22:37:56 +00001546 // Add pieces from custom visitors.
1547 BugReport *R = PDB.getBugReport();
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001548 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(),
1549 E = visitors.end();
1550 I != E; ++I) {
Anna Zaks8e6431a2011-08-18 22:37:56 +00001551 if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) {
Ted Kremenek8966bc12009-05-06 21:39:49 +00001552 const PathDiagnosticLocation &Loc = p->getLocation();
1553 EB.addEdge(Loc, true);
Ted Kremenek2042fc12012-02-24 06:00:00 +00001554 PD.getActivePath().push_front(p);
Anna Zaks368a0d52012-03-15 21:13:02 +00001555 updateStackPiecesWithMessage(p, CallStack);
1556
Ted Kremenek8966bc12009-05-06 21:39:49 +00001557 if (const Stmt *S = Loc.asStmt())
Mike Stump1eb44332009-09-09 15:08:12 +00001558 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
Ted Kremenek8966bc12009-05-06 21:39:49 +00001559 }
Mike Stump1eb44332009-09-09 15:08:12 +00001560 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001561 }
Jordan Rose8347d3d2012-09-22 01:24:53 +00001562
1563 return PDB.getBugReport()->isValid();
Ted Kremenek14856d72009-04-06 23:06:54 +00001564}
1565
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001566//===----------------------------------------------------------------------===//
Ted Kremenekcf118d42009-02-04 23:49:09 +00001567// Methods for BugType and subclasses.
1568//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00001569BugType::~BugType() { }
1570
Ted Kremenekcf118d42009-02-04 23:49:09 +00001571void BugType::FlushReports(BugReporter &BR) {}
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001572
David Blaikie99ba9e32011-12-20 02:48:34 +00001573void BuiltinBug::anchor() {}
1574
Ted Kremenekcf118d42009-02-04 23:49:09 +00001575//===----------------------------------------------------------------------===//
1576// Methods for BugReport and subclasses.
1577//===----------------------------------------------------------------------===//
Anna Zakse172e8b2011-08-17 23:00:25 +00001578
David Blaikie99ba9e32011-12-20 02:48:34 +00001579void BugReport::NodeResolver::anchor() {}
1580
Anna Zaks8e6431a2011-08-18 22:37:56 +00001581void BugReport::addVisitor(BugReporterVisitor* visitor) {
1582 if (!visitor)
1583 return;
1584
1585 llvm::FoldingSetNodeID ID;
1586 visitor->Profile(ID);
1587 void *InsertPos;
1588
1589 if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
1590 delete visitor;
1591 return;
1592 }
1593
1594 CallbacksSet.InsertNode(visitor, InsertPos);
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001595 Callbacks.push_back(visitor);
1596 ++ConfigurationChangeToken;
Anna Zaks8e6431a2011-08-18 22:37:56 +00001597}
1598
1599BugReport::~BugReport() {
1600 for (visitor_iterator I = visitor_begin(), E = visitor_end(); I != E; ++I) {
Anna Zaksdc757b02011-08-19 23:21:56 +00001601 delete *I;
Anna Zaks8e6431a2011-08-18 22:37:56 +00001602 }
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001603 while (!interestingSymbols.empty()) {
1604 popInterestingSymbolsAndRegions();
1605 }
Anna Zaks8e6431a2011-08-18 22:37:56 +00001606}
Anna Zakse172e8b2011-08-17 23:00:25 +00001607
Ted Kremenek07189522012-04-04 18:11:35 +00001608const Decl *BugReport::getDeclWithIssue() const {
1609 if (DeclWithIssue)
1610 return DeclWithIssue;
1611
1612 const ExplodedNode *N = getErrorNode();
1613 if (!N)
1614 return 0;
1615
1616 const LocationContext *LC = N->getLocationContext();
1617 return LC->getCurrentStackFrame()->getDecl();
1618}
1619
Anna Zakse172e8b2011-08-17 23:00:25 +00001620void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
1621 hash.AddPointer(&BT);
Anna Zakse172e8b2011-08-17 23:00:25 +00001622 hash.AddString(Description);
Anna Zaks97bfb552013-01-08 00:25:29 +00001623 PathDiagnosticLocation UL = getUniqueingLocation();
1624 if (UL.isValid()) {
1625 UL.Profile(hash);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001626 } else if (Location.isValid()) {
Anna Zaks590dd8e2011-09-20 21:38:35 +00001627 Location.Profile(hash);
1628 } else {
1629 assert(ErrorNode);
1630 hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
1631 }
Anna Zakse172e8b2011-08-17 23:00:25 +00001632
1633 for (SmallVectorImpl<SourceRange>::const_iterator I =
1634 Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1635 const SourceRange range = *I;
1636 if (!range.isValid())
1637 continue;
1638 hash.AddInteger(range.getBegin().getRawEncoding());
1639 hash.AddInteger(range.getEnd().getRawEncoding());
1640 }
1641}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001642
Ted Kremenek76aadc32012-03-09 01:13:14 +00001643void BugReport::markInteresting(SymbolRef sym) {
1644 if (!sym)
1645 return;
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001646
1647 // If the symbol wasn't already in our set, note a configuration change.
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001648 if (getInterestingSymbols().insert(sym).second)
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001649 ++ConfigurationChangeToken;
Jordy Rose8ec588e2012-03-15 22:45:29 +00001650
1651 if (const SymbolMetadata *meta = dyn_cast<SymbolMetadata>(sym))
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001652 getInterestingRegions().insert(meta->getRegion());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001653}
1654
1655void BugReport::markInteresting(const MemRegion *R) {
1656 if (!R)
1657 return;
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001658
1659 // If the base region wasn't already in our set, note a configuration change.
Ted Kremenek76aadc32012-03-09 01:13:14 +00001660 R = R->getBaseRegion();
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001661 if (getInterestingRegions().insert(R).second)
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001662 ++ConfigurationChangeToken;
Jordy Rose8ec588e2012-03-15 22:45:29 +00001663
Ted Kremenek76aadc32012-03-09 01:13:14 +00001664 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001665 getInterestingSymbols().insert(SR->getSymbol());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001666}
1667
1668void BugReport::markInteresting(SVal V) {
1669 markInteresting(V.getAsRegion());
1670 markInteresting(V.getAsSymbol());
1671}
1672
Anna Zaks80de4872012-08-29 21:22:37 +00001673void BugReport::markInteresting(const LocationContext *LC) {
1674 if (!LC)
1675 return;
1676 InterestingLocationContexts.insert(LC);
1677}
1678
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001679bool BugReport::isInteresting(SVal V) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00001680 return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol());
1681}
1682
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001683bool BugReport::isInteresting(SymbolRef sym) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00001684 if (!sym)
1685 return false;
Jordy Rose8ec588e2012-03-15 22:45:29 +00001686 // We don't currently consider metadata symbols to be interesting
1687 // even if we know their region is interesting. Is that correct behavior?
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001688 return getInterestingSymbols().count(sym);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001689}
1690
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001691bool BugReport::isInteresting(const MemRegion *R) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00001692 if (!R)
1693 return false;
1694 R = R->getBaseRegion();
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001695 bool b = getInterestingRegions().count(R);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001696 if (b)
1697 return true;
1698 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001699 return getInterestingSymbols().count(SR->getSymbol());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001700 return false;
1701}
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001702
Anna Zaks80de4872012-08-29 21:22:37 +00001703bool BugReport::isInteresting(const LocationContext *LC) {
1704 if (!LC)
1705 return false;
1706 return InterestingLocationContexts.count(LC);
1707}
1708
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001709void BugReport::lazyInitializeInterestingSets() {
1710 if (interestingSymbols.empty()) {
1711 interestingSymbols.push_back(new Symbols());
1712 interestingRegions.push_back(new Regions());
1713 }
1714}
1715
1716BugReport::Symbols &BugReport::getInterestingSymbols() {
1717 lazyInitializeInterestingSets();
1718 return *interestingSymbols.back();
1719}
1720
1721BugReport::Regions &BugReport::getInterestingRegions() {
1722 lazyInitializeInterestingSets();
1723 return *interestingRegions.back();
1724}
1725
1726void BugReport::pushInterestingSymbolsAndRegions() {
1727 interestingSymbols.push_back(new Symbols(getInterestingSymbols()));
1728 interestingRegions.push_back(new Regions(getInterestingRegions()));
1729}
1730
1731void BugReport::popInterestingSymbolsAndRegions() {
1732 delete interestingSymbols.back();
1733 interestingSymbols.pop_back();
1734 delete interestingRegions.back();
1735 interestingRegions.pop_back();
1736}
Ted Kremenek76aadc32012-03-09 01:13:14 +00001737
Ted Kremenek9c378f72011-08-12 23:37:29 +00001738const Stmt *BugReport::getStmt() const {
Anna Zakse172e8b2011-08-17 23:00:25 +00001739 if (!ErrorNode)
1740 return 0;
1741
Tom Care212f6d32010-09-16 03:50:38 +00001742 ProgramPoint ProgP = ErrorNode->getLocation();
Ted Kremenek5f85e172009-07-22 22:35:28 +00001743 const Stmt *S = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001744
David Blaikie7a95de62013-02-21 22:23:56 +00001745 if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
Zhongxing Xufafd3832009-08-20 01:23:34 +00001746 CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
Zhongxing Xu50d5bc42009-08-18 08:46:04 +00001747 if (BE->getBlock() == &Exit)
Tom Care212f6d32010-09-16 03:50:38 +00001748 S = GetPreviousStmt(ErrorNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001749 }
Ted Kremenek5f85e172009-07-22 22:35:28 +00001750 if (!S)
Mike Stump1eb44332009-09-09 15:08:12 +00001751 S = GetStmt(ProgP);
1752
1753 return S;
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001754}
1755
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001756std::pair<BugReport::ranges_iterator, BugReport::ranges_iterator>
Anna Zakse172e8b2011-08-17 23:00:25 +00001757BugReport::getRanges() {
1758 // If no custom ranges, add the range of the statement corresponding to
1759 // the error node.
1760 if (Ranges.empty()) {
1761 if (const Expr *E = dyn_cast_or_null<Expr>(getStmt()))
1762 addRange(E->getSourceRange());
1763 else
1764 return std::make_pair(ranges_iterator(), ranges_iterator());
1765 }
1766
Anna Zaks14924262011-08-24 20:31:06 +00001767 // User-specified absence of range info.
1768 if (Ranges.size() == 1 && !Ranges.begin()->isValid())
1769 return std::make_pair(ranges_iterator(), ranges_iterator());
1770
Anna Zakse172e8b2011-08-17 23:00:25 +00001771 return std::make_pair(Ranges.begin(), Ranges.end());
Ted Kremenekf1ae7052008-04-03 17:57:38 +00001772}
1773
Anna Zaks590dd8e2011-09-20 21:38:35 +00001774PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
Anna Zaksb7530a42011-08-17 23:21:23 +00001775 if (ErrorNode) {
Anna Zaks590dd8e2011-09-20 21:38:35 +00001776 assert(!Location.isValid() &&
Anna Zaksb7530a42011-08-17 23:21:23 +00001777 "Either Location or ErrorNode should be specified but not both.");
1778
Ted Kremenek9c378f72011-08-12 23:37:29 +00001779 if (const Stmt *S = GetCurrentOrPreviousStmt(ErrorNode)) {
Anna Zaks590dd8e2011-09-20 21:38:35 +00001780 const LocationContext *LC = ErrorNode->getLocationContext();
1781
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001782 // For member expressions, return the location of the '.' or '->'.
Ted Kremenek5b9bd212009-09-11 22:07:28 +00001783 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S))
Anna Zaks590dd8e2011-09-20 21:38:35 +00001784 return PathDiagnosticLocation::createMemberLoc(ME, SM);
Ted Kremenek5b9bd212009-09-11 22:07:28 +00001785 // For binary operators, return the location of the operator.
1786 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(S))
Anna Zaks590dd8e2011-09-20 21:38:35 +00001787 return PathDiagnosticLocation::createOperatorLoc(B, SM);
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001788
David Blaikie7a95de62013-02-21 22:23:56 +00001789 if (ErrorNode->getLocation().getAs<PostStmtPurgeDeadSymbols>())
Jordan Rose63bc1862012-11-15 19:11:43 +00001790 return PathDiagnosticLocation::createEnd(S, SM, LC);
1791
Anna Zaks590dd8e2011-09-20 21:38:35 +00001792 return PathDiagnosticLocation::createBegin(S, SM, LC);
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001793 }
Anna Zaksb7530a42011-08-17 23:21:23 +00001794 } else {
1795 assert(Location.isValid());
1796 return Location;
1797 }
1798
Anna Zaks590dd8e2011-09-20 21:38:35 +00001799 return PathDiagnosticLocation();
Ted Kremenekd2f642b2008-04-14 17:39:48 +00001800}
1801
Ted Kremenekcf118d42009-02-04 23:49:09 +00001802//===----------------------------------------------------------------------===//
1803// Methods for BugReporter and subclasses.
1804//===----------------------------------------------------------------------===//
1805
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00001806BugReportEquivClass::~BugReportEquivClass() { }
Zhongxing Xua2f4ec02009-09-05 06:06:49 +00001807GRBugReporter::~GRBugReporter() { }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001808BugReporterData::~BugReporterData() {}
1809
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001810ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001811
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001812ProgramStateManager&
Ted Kremenekcf118d42009-02-04 23:49:09 +00001813GRBugReporter::getStateManager() { return Eng.getStateManager(); }
1814
Anna Zaks3b030a22011-08-19 01:57:09 +00001815BugReporter::~BugReporter() {
1816 FlushReports();
1817
1818 // Free the bug reports we are tracking.
1819 typedef std::vector<BugReportEquivClass *> ContTy;
1820 for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end();
1821 I != E; ++I) {
1822 delete *I;
1823 }
1824}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001825
1826void BugReporter::FlushReports() {
1827 if (BugTypes.isEmpty())
1828 return;
1829
1830 // First flush the warnings for each BugType. This may end up creating new
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00001831 // warnings and new BugTypes.
1832 // FIXME: Only NSErrorChecker needs BugType's FlushReports.
1833 // Turn NSErrorChecker into a proper checker and remove this.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001834 SmallVector<const BugType*, 16> bugTypes;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001835 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00001836 bugTypes.push_back(*I);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001837 for (SmallVector<const BugType*, 16>::iterator
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00001838 I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I)
Ted Kremenekcf118d42009-02-04 23:49:09 +00001839 const_cast<BugType*>(*I)->FlushReports(*this);
1840
Anna Zaksd015f4f2012-08-02 23:41:05 +00001841 // We need to flush reports in deterministic order to ensure the order
1842 // of the reports is consistent between runs.
Anna Zaks0eb6c372012-08-02 00:41:43 +00001843 typedef std::vector<BugReportEquivClass *> ContVecTy;
1844 for (ContVecTy::iterator EI=EQClassesVector.begin(), EE=EQClassesVector.end();
1845 EI != EE; ++EI){
1846 BugReportEquivClass& EQ = **EI;
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00001847 FlushReport(EQ);
Ted Kremenek94826a72008-04-03 04:59:14 +00001848 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001849
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00001850 // BugReporter owns and deletes only BugTypes created implicitly through
1851 // EmitBasicReport.
1852 // FIXME: There are leaks from checkers that assume that the BugTypes they
1853 // create will be destroyed by the BugReporter.
1854 for (llvm::StringMap<BugType*>::iterator
1855 I = StrBugTypes.begin(), E = StrBugTypes.end(); I != E; ++I)
1856 delete I->second;
1857
Ted Kremenekcf118d42009-02-04 23:49:09 +00001858 // Remove all references to the BugType objects.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001859 BugTypes = F.getEmptySet();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001860}
1861
1862//===----------------------------------------------------------------------===//
1863// PathDiagnostics generation.
1864//===----------------------------------------------------------------------===//
1865
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001866static std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001867 std::pair<ExplodedNode*, unsigned> >
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001868MakeReportGraph(const ExplodedGraph* G,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001869 SmallVectorImpl<const ExplodedNode*> &nodes) {
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Ted Kremenekcf118d42009-02-04 23:49:09 +00001871 // Create the trimmed graph. It will contain the shortest paths from the
Mike Stump1eb44332009-09-09 15:08:12 +00001872 // error nodes to the root. In the new graph we should only have one
Ted Kremenekcf118d42009-02-04 23:49:09 +00001873 // error node unless there are two or more error nodes with the same minimum
1874 // path length.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001875 ExplodedGraph* GTrim;
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001876 InterExplodedGraphMap* NMap;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001877
1878 llvm::DenseMap<const void*, const void*> InverseMap;
Ted Kremenek40406fe2010-12-03 06:52:30 +00001879 llvm::tie(GTrim, NMap) = G->Trim(nodes.data(), nodes.data() + nodes.size(),
1880 &InverseMap);
Mike Stump1eb44332009-09-09 15:08:12 +00001881
Ted Kremenekcf118d42009-02-04 23:49:09 +00001882 // Create owning pointers for GTrim and NMap just to ensure that they are
1883 // released when this function exists.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001884 OwningPtr<ExplodedGraph> AutoReleaseGTrim(GTrim);
1885 OwningPtr<InterExplodedGraphMap> AutoReleaseNMap(NMap);
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Ted Kremenekcf118d42009-02-04 23:49:09 +00001887 // Find the (first) error node in the trimmed graph. We just need to consult
1888 // the node map (NMap) which maps from nodes in the original graph to nodes
1889 // in the new graph.
Ted Kremenek938332c2009-05-16 01:11:58 +00001890
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001891 std::queue<const ExplodedNode*> WS;
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001892 typedef llvm::DenseMap<const ExplodedNode*, unsigned> IndexMapTy;
Ted Kremenek938332c2009-05-16 01:11:58 +00001893 IndexMapTy IndexMap;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001894
Ted Kremenek40406fe2010-12-03 06:52:30 +00001895 for (unsigned nodeIndex = 0 ; nodeIndex < nodes.size(); ++nodeIndex) {
1896 const ExplodedNode *originalNode = nodes[nodeIndex];
1897 if (const ExplodedNode *N = NMap->getMappedNode(originalNode)) {
Ted Kremenek938332c2009-05-16 01:11:58 +00001898 WS.push(N);
Ted Kremenek40406fe2010-12-03 06:52:30 +00001899 IndexMap[originalNode] = nodeIndex;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001900 }
Ted Kremenek40406fe2010-12-03 06:52:30 +00001901 }
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Ted Kremenek938332c2009-05-16 01:11:58 +00001903 assert(!WS.empty() && "No error node found in the trimmed graph.");
Ted Kremenekcf118d42009-02-04 23:49:09 +00001904
1905 // Create a new (third!) graph with a single path. This is the graph
1906 // that will be returned to the caller.
Zhongxing Xuc77a5512010-07-01 07:10:59 +00001907 ExplodedGraph *GNew = new ExplodedGraph();
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Ted Kremenek10aa5542009-03-12 23:41:59 +00001909 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001910 // to the root node, and then construct a new graph that contains only
1911 // a single path.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001912 llvm::DenseMap<const void*,unsigned> Visited;
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001914 unsigned cnt = 0;
Ted Kremenek9c378f72011-08-12 23:37:29 +00001915 const ExplodedNode *Root = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001917 while (!WS.empty()) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001918 const ExplodedNode *Node = WS.front();
Ted Kremenek10aa5542009-03-12 23:41:59 +00001919 WS.pop();
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001921 if (Visited.find(Node) != Visited.end())
1922 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001924 Visited[Node] = cnt++;
Mike Stump1eb44332009-09-09 15:08:12 +00001925
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001926 if (Node->pred_empty()) {
1927 Root = Node;
1928 break;
1929 }
Mike Stump1eb44332009-09-09 15:08:12 +00001930
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001931 for (ExplodedNode::const_pred_iterator I=Node->pred_begin(),
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001932 E=Node->pred_end(); I!=E; ++I)
Ted Kremenek10aa5542009-03-12 23:41:59 +00001933 WS.push(*I);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001934 }
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Ted Kremenek938332c2009-05-16 01:11:58 +00001936 assert(Root);
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Ted Kremenek10aa5542009-03-12 23:41:59 +00001938 // Now walk from the root down the BFS path, always taking the successor
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001939 // with the lowest number.
Mike Stump1eb44332009-09-09 15:08:12 +00001940 ExplodedNode *Last = 0, *First = 0;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001941 NodeBackMap *BM = new NodeBackMap();
Ted Kremenek938332c2009-05-16 01:11:58 +00001942 unsigned NodeIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001944 for ( const ExplodedNode *N = Root ;;) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001945 // Lookup the number associated with the current node.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001946 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
Ted Kremenek938332c2009-05-16 01:11:58 +00001947 assert(I != Visited.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001948
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001949 // Create the equivalent node in the new graph with the same state
1950 // and location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00001951 ExplodedNode *NewN = GNew->getNode(N->getLocation(), N->getState());
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001953 // Store the mapping to the original node.
1954 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1955 assert(IMitr != InverseMap.end() && "No mapping to original node.");
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001956 (*BM)[NewN] = (const ExplodedNode*) IMitr->second;
Mike Stump1eb44332009-09-09 15:08:12 +00001957
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001958 // Link up the new node with the previous node.
1959 if (Last)
Ted Kremenek5fe4d9d2009-10-07 00:42:52 +00001960 NewN->addPredecessor(Last, *GNew);
Mike Stump1eb44332009-09-09 15:08:12 +00001961
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001962 Last = NewN;
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001964 // Are we at the final node?
Ted Kremenek938332c2009-05-16 01:11:58 +00001965 IndexMapTy::iterator IMI =
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001966 IndexMap.find((const ExplodedNode*)(IMitr->second));
Ted Kremenek938332c2009-05-16 01:11:58 +00001967 if (IMI != IndexMap.end()) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001968 First = NewN;
Ted Kremenek938332c2009-05-16 01:11:58 +00001969 NodeIndex = IMI->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001970 break;
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001971 }
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001973 // Find the next successor node. We choose the node that is marked
1974 // with the lowest DFS number.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001975 ExplodedNode::const_succ_iterator SI = N->succ_begin();
1976 ExplodedNode::const_succ_iterator SE = N->succ_end();
Ted Kremenekc1da4412008-06-17 19:14:06 +00001977 N = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001979 for (unsigned MinVal = 0; SI != SE; ++SI) {
Mike Stump1eb44332009-09-09 15:08:12 +00001980
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001981 I = Visited.find(*SI);
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001983 if (I == Visited.end())
1984 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001986 if (!N || I->second < MinVal) {
1987 N = *SI;
1988 MinVal = I->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001989 }
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001990 }
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Ted Kremenek938332c2009-05-16 01:11:58 +00001992 assert(N);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001993 }
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Ted Kremenek938332c2009-05-16 01:11:58 +00001995 assert(First);
1996
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001997 return std::make_pair(std::make_pair(GNew, BM),
1998 std::make_pair(First, NodeIndex));
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001999}
2000
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002001/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
2002/// and collapses PathDiagosticPieces that are expanded by macros.
Ted Kremenek77d09442012-03-02 01:27:31 +00002003static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM) {
Ted Kremenek2042fc12012-02-24 06:00:00 +00002004 typedef std::vector<std::pair<IntrusiveRefCntPtr<PathDiagnosticMacroPiece>,
2005 SourceLocation> > MacroStackTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002007 typedef std::vector<IntrusiveRefCntPtr<PathDiagnosticPiece> >
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002008 PiecesTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002010 MacroStackTy MacroStack;
2011 PiecesTy Pieces;
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Ted Kremenek77d09442012-03-02 01:27:31 +00002013 for (PathPieces::const_iterator I = path.begin(), E = path.end();
Ted Kremenek2042fc12012-02-24 06:00:00 +00002014 I!=E; ++I) {
Ted Kremenek77d09442012-03-02 01:27:31 +00002015
2016 PathDiagnosticPiece *piece = I->getPtr();
2017
2018 // Recursively compact calls.
2019 if (PathDiagnosticCallPiece *call=dyn_cast<PathDiagnosticCallPiece>(piece)){
2020 CompactPathDiagnostic(call->path, SM);
2021 }
2022
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002023 // Get the location of the PathDiagnosticPiece.
Ted Kremenek77d09442012-03-02 01:27:31 +00002024 const FullSourceLoc Loc = piece->getLocation().asLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00002025
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002026 // Determine the instantiation location, which is the location we group
2027 // related PathDiagnosticPieces.
Mike Stump1eb44332009-09-09 15:08:12 +00002028 SourceLocation InstantiationLoc = Loc.isMacroID() ?
Chandler Carruth40278532011-07-25 16:49:02 +00002029 SM.getExpansionLoc(Loc) :
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002030 SourceLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00002031
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002032 if (Loc.isFileID()) {
2033 MacroStack.clear();
Ted Kremenek77d09442012-03-02 01:27:31 +00002034 Pieces.push_back(piece);
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002035 continue;
2036 }
2037
2038 assert(Loc.isMacroID());
Mike Stump1eb44332009-09-09 15:08:12 +00002039
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002040 // Is the PathDiagnosticPiece within the same macro group?
2041 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
Ted Kremenek77d09442012-03-02 01:27:31 +00002042 MacroStack.back().first->subPieces.push_back(piece);
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002043 continue;
2044 }
2045
2046 // We aren't in the same group. Are we descending into a new macro
2047 // or are part of an old one?
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002048 IntrusiveRefCntPtr<PathDiagnosticMacroPiece> MacroGroup;
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002049
2050 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
Chandler Carruth40278532011-07-25 16:49:02 +00002051 SM.getExpansionLoc(Loc) :
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002052 SourceLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002054 // Walk the entire macro stack.
2055 while (!MacroStack.empty()) {
2056 if (InstantiationLoc == MacroStack.back().second) {
2057 MacroGroup = MacroStack.back().first;
2058 break;
2059 }
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002061 if (ParentInstantiationLoc == MacroStack.back().second) {
2062 MacroGroup = MacroStack.back().first;
2063 break;
2064 }
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002066 MacroStack.pop_back();
2067 }
Mike Stump1eb44332009-09-09 15:08:12 +00002068
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002069 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
2070 // Create a new macro group and add it to the stack.
Anna Zaks590dd8e2011-09-20 21:38:35 +00002071 PathDiagnosticMacroPiece *NewGroup =
2072 new PathDiagnosticMacroPiece(
Ted Kremenek77d09442012-03-02 01:27:31 +00002073 PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002074
2075 if (MacroGroup)
Ted Kremenek802e0242012-02-08 04:32:34 +00002076 MacroGroup->subPieces.push_back(NewGroup);
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002077 else {
2078 assert(InstantiationLoc.isFileID());
2079 Pieces.push_back(NewGroup);
2080 }
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002082 MacroGroup = NewGroup;
2083 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
2084 }
2085
2086 // Finally, add the PathDiagnosticPiece to the group.
Ted Kremenek77d09442012-03-02 01:27:31 +00002087 MacroGroup->subPieces.push_back(piece);
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002088 }
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002090 // Now take the pieces and construct a new PathDiagnostic.
Ted Kremenek77d09442012-03-02 01:27:31 +00002091 path.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Ted Kremenek77d09442012-03-02 01:27:31 +00002093 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I)
2094 path.push_back(*I);
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002095}
2096
Jordan Rose8347d3d2012-09-22 01:24:53 +00002097bool GRBugReporter::generatePathDiagnostic(PathDiagnostic& PD,
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002098 PathDiagnosticConsumer &PC,
2099 ArrayRef<BugReport *> &bugReports) {
Ted Kremenek40406fe2010-12-03 06:52:30 +00002100 assert(!bugReports.empty());
Jordan Rose8347d3d2012-09-22 01:24:53 +00002101
2102 bool HasValid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002103 SmallVector<const ExplodedNode *, 10> errorNodes;
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002104 for (ArrayRef<BugReport*>::iterator I = bugReports.begin(),
2105 E = bugReports.end(); I != E; ++I) {
Jordan Rose8347d3d2012-09-22 01:24:53 +00002106 if ((*I)->isValid()) {
2107 HasValid = true;
Ted Kremenek40406fe2010-12-03 06:52:30 +00002108 errorNodes.push_back((*I)->getErrorNode());
Jordan Rose8347d3d2012-09-22 01:24:53 +00002109 } else {
2110 errorNodes.push_back(0);
2111 }
Ted Kremenek40406fe2010-12-03 06:52:30 +00002112 }
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Jordan Rose8347d3d2012-09-22 01:24:53 +00002114 // If all the reports have been marked invalid, we're done.
2115 if (!HasValid)
2116 return false;
2117
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00002118 // Construct a new graph that contains only a single path from the error
Mike Stump1eb44332009-09-09 15:08:12 +00002119 // node to a root.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00002120 const std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002121 std::pair<ExplodedNode*, unsigned> >&
Ted Kremenek40406fe2010-12-03 06:52:30 +00002122 GPair = MakeReportGraph(&getGraph(), errorNodes);
Mike Stump1eb44332009-09-09 15:08:12 +00002123
Ted Kremenekcf118d42009-02-04 23:49:09 +00002124 // Find the BugReport with the original location.
Ted Kremenek40406fe2010-12-03 06:52:30 +00002125 assert(GPair.second.second < bugReports.size());
2126 BugReport *R = bugReports[GPair.second.second];
Ted Kremenekcf118d42009-02-04 23:49:09 +00002127 assert(R && "No original report found for sliced graph.");
Jordan Rose8347d3d2012-09-22 01:24:53 +00002128 assert(R->isValid() && "Report selected from trimmed graph marked invalid.");
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002130 OwningPtr<ExplodedGraph> ReportGraph(GPair.first.first);
2131 OwningPtr<NodeBackMap> BackMap(GPair.first.second);
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002132 const ExplodedNode *N = GPair.second.first;
Mike Stump1eb44332009-09-09 15:08:12 +00002133
2134 // Start building the path diagnostic...
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002135 PathDiagnosticBuilder PDB(*this, R, BackMap.get(), &PC);
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Anna Zaks8e6431a2011-08-18 22:37:56 +00002137 // Register additional node visitors.
Anna Zaks50bbc162011-08-19 22:33:38 +00002138 R->addVisitor(new NilReceiverBRVisitor());
2139 R->addVisitor(new ConditionBRVisitor());
Anna Zaks86ff12c2013-01-30 19:12:34 +00002140 R->addVisitor(new LikelyFalsePositiveSuppressionBRVisitor());
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002142 BugReport::VisitorList visitors;
2143 unsigned originalReportConfigToken, finalReportConfigToken;
Anna Zaks23f395e2011-08-20 01:27:22 +00002144
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002145 // While generating diagnostics, it's possible the visitors will decide
2146 // new symbols and regions are interesting, or add other visitors based on
2147 // the information they find. If they do, we need to regenerate the path
2148 // based on our new report configuration.
2149 do {
2150 // Get a clean copy of all the visitors.
2151 for (BugReport::visitor_iterator I = R->visitor_begin(),
2152 E = R->visitor_end(); I != E; ++I)
2153 visitors.push_back((*I)->clone());
2154
2155 // Clear out the active path from any previous work.
Jordan Rose3a46f5f2012-08-31 00:36:26 +00002156 PD.resetPath();
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002157 originalReportConfigToken = R->getConfigurationChangeToken();
2158
2159 // Generate the very last diagnostic piece - the piece is visible before
2160 // the trace is expanded.
Anna Zaks86ff12c2013-01-30 19:12:34 +00002161 PathDiagnosticPiece *LastPiece = 0;
2162 for (BugReport::visitor_iterator I = visitors.begin(), E = visitors.end();
2163 I != E; ++I) {
2164 if (PathDiagnosticPiece *Piece = (*I)->getEndPath(PDB, N, *R)) {
2165 assert (!LastPiece &&
2166 "There can only be one final piece in a diagnostic.");
2167 LastPiece = Piece;
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002168 }
Anna Zaks86ff12c2013-01-30 19:12:34 +00002169 }
2170
2171 if (PDB.getGenerationScheme() != PathDiagnosticConsumer::None) {
Jordan Rosed632d6f2012-09-22 01:24:56 +00002172 if (!LastPiece)
2173 LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R);
2174 if (LastPiece)
2175 PD.setEndOfPath(LastPiece);
2176 else
2177 return false;
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002178 }
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002179
2180 switch (PDB.getGenerationScheme()) {
David Blaikieef3643f2011-09-26 00:51:36 +00002181 case PathDiagnosticConsumer::Extensive:
Jordan Rose8347d3d2012-09-22 01:24:53 +00002182 if (!GenerateExtensivePathDiagnostic(PD, PDB, N, visitors)) {
2183 assert(!R->isValid() && "Failed on valid report");
2184 // Try again. We'll filter out the bad report when we trim the graph.
2185 // FIXME: It would be more efficient to use the same intermediate
2186 // trimmed graph, and just repeat the shortest-path search.
2187 return generatePathDiagnostic(PD, PC, bugReports);
2188 }
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00002189 break;
David Blaikieef3643f2011-09-26 00:51:36 +00002190 case PathDiagnosticConsumer::Minimal:
Jordan Rose8347d3d2012-09-22 01:24:53 +00002191 if (!GenerateMinimalPathDiagnostic(PD, PDB, N, visitors)) {
2192 assert(!R->isValid() && "Failed on valid report");
2193 // Try again. We'll filter out the bad report when we trim the graph.
2194 return generatePathDiagnostic(PD, PC, bugReports);
2195 }
Ted Kremenek7dc86642009-03-31 20:22:36 +00002196 break;
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002197 case PathDiagnosticConsumer::None:
Jordan Rosed632d6f2012-09-22 01:24:56 +00002198 if (!GenerateVisitorsOnlyPathDiagnostic(PD, PDB, N, visitors)) {
2199 assert(!R->isValid() && "Failed on valid report");
2200 // Try again. We'll filter out the bad report when we trim the graph.
2201 return generatePathDiagnostic(PD, PC, bugReports);
2202 }
2203 break;
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002204 }
2205
2206 // Clean up the visitors we used.
2207 llvm::DeleteContainerPointers(visitors);
2208
2209 // Did anything change while generating this path?
2210 finalReportConfigToken = R->getConfigurationChangeToken();
2211 } while(finalReportConfigToken != originalReportConfigToken);
2212
Ted Kremenekc89f4b02012-02-28 23:06:21 +00002213 // Finally, prune the diagnostic path of uninteresting stuff.
Ted Kremenekb85cce02012-10-25 22:07:10 +00002214 if (!PD.path.empty()) {
2215 // Remove messages that are basically the same.
Ted Kremenek38001652012-10-26 16:02:36 +00002216 removeRedundantMsgs(PD.getMutablePieces());
Ted Kremenekb85cce02012-10-25 22:07:10 +00002217
Jordan Roseaeca2cc2013-01-26 01:28:15 +00002218 if (R->shouldPrunePath() &&
2219 getEngine().getAnalysisManager().options.shouldPrunePaths()) {
Jordan Roseafa7cae2012-12-07 19:56:29 +00002220 bool hasSomethingInteresting = RemoveUnneededCalls(PD.getMutablePieces(),
2221 R);
Ted Kremenekb85cce02012-10-25 22:07:10 +00002222 assert(hasSomethingInteresting);
2223 (void) hasSomethingInteresting;
2224 }
Jordan Roseafa7cae2012-12-07 19:56:29 +00002225
2226 adjustCallLocations(PD.getMutablePieces());
Ted Kremeneked7948b2012-05-31 06:03:17 +00002227 }
Jordan Rose8347d3d2012-09-22 01:24:53 +00002228
2229 return true;
Ted Kremenek7dc86642009-03-31 20:22:36 +00002230}
2231
Ted Kremenekcf118d42009-02-04 23:49:09 +00002232void BugReporter::Register(BugType *BT) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00002233 BugTypes = F.add(BugTypes, BT);
Ted Kremenek76d90c82008-05-16 18:33:14 +00002234}
2235
Jordan Rose785950e2012-11-02 01:53:40 +00002236void BugReporter::emitReport(BugReport* R) {
Ted Kremenekcf118d42009-02-04 23:49:09 +00002237 // Compute the bug report's hash to determine its equivalence class.
2238 llvm::FoldingSetNodeID ID;
2239 R->Profile(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00002240
2241 // Lookup the equivance class. If there isn't one, create it.
Ted Kremenekcf118d42009-02-04 23:49:09 +00002242 BugType& BT = R->getBugType();
2243 Register(&BT);
2244 void *InsertPos;
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00002245 BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Ted Kremenekcf118d42009-02-04 23:49:09 +00002247 if (!EQ) {
2248 EQ = new BugReportEquivClass(R);
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00002249 EQClasses.InsertNode(EQ, InsertPos);
Anna Zaks3b030a22011-08-19 01:57:09 +00002250 EQClassesVector.push_back(EQ);
Ted Kremenekcf118d42009-02-04 23:49:09 +00002251 }
2252 else
2253 EQ->AddReport(R);
Ted Kremenek61f3e052008-04-03 04:42:52 +00002254}
2255
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002256
2257//===----------------------------------------------------------------------===//
2258// Emitting reports in equivalence classes.
2259//===----------------------------------------------------------------------===//
2260
2261namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00002262struct FRIEC_WLItem {
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002263 const ExplodedNode *N;
2264 ExplodedNode::const_succ_iterator I, E;
2265
2266 FRIEC_WLItem(const ExplodedNode *n)
2267 : N(n), I(N->succ_begin()), E(N->succ_end()) {}
2268};
2269}
2270
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002271static BugReport *
2272FindReportInEquivalenceClass(BugReportEquivClass& EQ,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002273 SmallVectorImpl<BugReport*> &bugReports) {
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002274
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002275 BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
2276 assert(I != E);
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002277 BugType& BT = I->getBugType();
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002278
Ted Kremenek40406fe2010-12-03 06:52:30 +00002279 // If we don't need to suppress any of the nodes because they are
2280 // post-dominated by a sink, simply add all the nodes in the equivalence class
2281 // to 'Nodes'. Any of the reports will serve as a "representative" report.
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002282 if (!BT.isSuppressOnSink()) {
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002283 BugReport *R = I;
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002284 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002285 const ExplodedNode *N = I->getErrorNode();
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002286 if (N) {
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002287 R = I;
Ted Kremenek40406fe2010-12-03 06:52:30 +00002288 bugReports.push_back(R);
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002289 }
2290 }
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002291 return R;
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002292 }
2293
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002294 // For bug reports that should be suppressed when all paths are post-dominated
2295 // by a sink node, iterate through the reports in the equivalence class
2296 // until we find one that isn't post-dominated (if one exists). We use a
2297 // DFS traversal of the ExplodedGraph to find a non-sink node. We could write
2298 // this as a recursive function, but we don't want to risk blowing out the
2299 // stack for very long paths.
Ted Kremenek40406fe2010-12-03 06:52:30 +00002300 BugReport *exampleReport = 0;
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002301
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002302 for (; I != E; ++I) {
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002303 const ExplodedNode *errorNode = I->getErrorNode();
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002304
Ted Kremenek40406fe2010-12-03 06:52:30 +00002305 if (!errorNode)
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002306 continue;
Ted Kremenek40406fe2010-12-03 06:52:30 +00002307 if (errorNode->isSink()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002308 llvm_unreachable(
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002309 "BugType::isSuppressSink() should not be 'true' for sink end nodes");
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002310 }
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002311 // No successors? By definition this nodes isn't post-dominated by a sink.
Ted Kremenek40406fe2010-12-03 06:52:30 +00002312 if (errorNode->succ_empty()) {
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002313 bugReports.push_back(I);
Ted Kremenek40406fe2010-12-03 06:52:30 +00002314 if (!exampleReport)
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002315 exampleReport = I;
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002316 continue;
2317 }
2318
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002319 // At this point we know that 'N' is not a sink and it has at least one
2320 // successor. Use a DFS worklist to find a non-sink end-of-path node.
2321 typedef FRIEC_WLItem WLItem;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002322 typedef SmallVector<WLItem, 10> DFSWorkList;
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002323 llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
2324
2325 DFSWorkList WL;
Ted Kremenek40406fe2010-12-03 06:52:30 +00002326 WL.push_back(errorNode);
2327 Visited[errorNode] = 1;
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002328
2329 while (!WL.empty()) {
2330 WLItem &WI = WL.back();
2331 assert(!WI.N->succ_empty());
2332
2333 for (; WI.I != WI.E; ++WI.I) {
2334 const ExplodedNode *Succ = *WI.I;
2335 // End-of-path node?
2336 if (Succ->succ_empty()) {
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002337 // If we found an end-of-path node that is not a sink.
2338 if (!Succ->isSink()) {
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002339 bugReports.push_back(I);
Ted Kremenek40406fe2010-12-03 06:52:30 +00002340 if (!exampleReport)
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002341 exampleReport = I;
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002342 WL.clear();
2343 break;
2344 }
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002345 // Found a sink? Continue on to the next successor.
2346 continue;
2347 }
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002348 // Mark the successor as visited. If it hasn't been explored,
2349 // enqueue it to the DFS worklist.
2350 unsigned &mark = Visited[Succ];
2351 if (!mark) {
2352 mark = 1;
2353 WL.push_back(Succ);
2354 break;
2355 }
2356 }
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002357
2358 // The worklist may have been cleared at this point. First
2359 // check if it is empty before checking the last item.
2360 if (!WL.empty() && &WL.back() == &WI)
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002361 WL.pop_back();
2362 }
2363 }
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002364
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002365 // ExampleReport will be NULL if all the nodes in the equivalence class
2366 // were post-dominated by sinks.
Ted Kremenek40406fe2010-12-03 06:52:30 +00002367 return exampleReport;
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002368}
Ted Kremeneke0a58072009-09-18 22:37:37 +00002369
Ted Kremenekcf118d42009-02-04 23:49:09 +00002370void BugReporter::FlushReport(BugReportEquivClass& EQ) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002371 SmallVector<BugReport*, 10> bugReports;
Ted Kremenek40406fe2010-12-03 06:52:30 +00002372 BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports);
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002373 if (exampleReport) {
2374 const PathDiagnosticConsumers &C = getPathDiagnosticConsumers();
2375 for (PathDiagnosticConsumers::const_iterator I=C.begin(),
2376 E=C.end(); I != E; ++I) {
2377 FlushReport(exampleReport, **I, bugReports);
2378 }
2379 }
2380}
2381
2382void BugReporter::FlushReport(BugReport *exampleReport,
2383 PathDiagnosticConsumer &PD,
2384 ArrayRef<BugReport*> bugReports) {
Mike Stump1eb44332009-09-09 15:08:12 +00002385
Ted Kremenekcf118d42009-02-04 23:49:09 +00002386 // FIXME: Make sure we use the 'R' for the path that was actually used.
Mike Stump1eb44332009-09-09 15:08:12 +00002387 // Probably doesn't make a difference in practice.
Ted Kremenek40406fe2010-12-03 06:52:30 +00002388 BugType& BT = exampleReport->getBugType();
Mike Stump1eb44332009-09-09 15:08:12 +00002389
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002390 OwningPtr<PathDiagnostic>
Ted Kremenek07189522012-04-04 18:11:35 +00002391 D(new PathDiagnostic(exampleReport->getDeclWithIssue(),
2392 exampleReport->getBugType().getName(),
Jordan Rose3a46f5f2012-08-31 00:36:26 +00002393 exampleReport->getDescription(),
2394 exampleReport->getShortDescription(/*Fallback=*/false),
Anna Zaks97bfb552013-01-08 00:25:29 +00002395 BT.getCategory(),
2396 exampleReport->getUniqueingLocation(),
2397 exampleReport->getUniqueingDecl()));
Ted Kremenekd49967f2009-04-29 21:58:13 +00002398
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002399 // Generate the full path diagnostic, using the generation scheme
Jordan Rosed632d6f2012-09-22 01:24:56 +00002400 // specified by the PathDiagnosticConsumer. Note that we have to generate
2401 // path diagnostics even for consumers which do not support paths, because
2402 // the BugReporterVisitors may mark this bug as a false positive.
2403 if (!bugReports.empty())
2404 if (!generatePathDiagnostic(*D.get(), PD, bugReports))
2405 return;
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002406
2407 // If the path is empty, generate a single step path with the location
2408 // of the issue.
2409 if (D->path.empty()) {
2410 PathDiagnosticLocation L = exampleReport->getLocation(getSourceManager());
2411 PathDiagnosticPiece *piece =
2412 new PathDiagnosticEventPiece(L, exampleReport->getDescription());
2413 BugReport::ranges_iterator Beg, End;
2414 llvm::tie(Beg, End) = exampleReport->getRanges();
2415 for ( ; Beg != End; ++Beg)
2416 piece->addRange(*Beg);
Jordan Rose3a46f5f2012-08-31 00:36:26 +00002417 D->setEndOfPath(piece);
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002418 }
2419
Ted Kremenek072192b2008-04-30 23:47:44 +00002420 // Get the meta data.
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002421 const BugReport::ExtraTextList &Meta = exampleReport->getExtraText();
Anna Zaks7f2531c2011-08-22 20:31:28 +00002422 for (BugReport::ExtraTextList::const_iterator i = Meta.begin(),
2423 e = Meta.end(); i != e; ++i) {
2424 D->addMeta(*i);
2425 }
Ted Kremenek75840e12008-04-18 01:56:37 +00002426
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002427 PD.HandlePathDiagnostic(D.take());
Ted Kremenek61f3e052008-04-03 04:42:52 +00002428}
Ted Kremenek57202072008-07-14 17:40:50 +00002429
Ted Kremenek07189522012-04-04 18:11:35 +00002430void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
Ted Kremenek07189522012-04-04 18:11:35 +00002431 StringRef name,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002432 StringRef category,
Anna Zaks590dd8e2011-09-20 21:38:35 +00002433 StringRef str, PathDiagnosticLocation Loc,
Ted Kremenek8c036c72008-09-20 04:23:38 +00002434 SourceRange* RBeg, unsigned NumRanges) {
Mike Stump1eb44332009-09-09 15:08:12 +00002435
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00002436 // 'BT' is owned by BugReporter.
2437 BugType *BT = getBugTypeForName(name, category);
Anna Zaks590dd8e2011-09-20 21:38:35 +00002438 BugReport *R = new BugReport(*BT, str, Loc);
Ted Kremenek07189522012-04-04 18:11:35 +00002439 R->setDeclWithIssue(DeclWithIssue);
Ted Kremenekcf118d42009-02-04 23:49:09 +00002440 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
Jordan Rose785950e2012-11-02 01:53:40 +00002441 emitReport(R);
Ted Kremenek57202072008-07-14 17:40:50 +00002442}
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00002443
Chris Lattner5f9e2722011-07-23 10:55:15 +00002444BugType *BugReporter::getBugTypeForName(StringRef name,
2445 StringRef category) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002446 SmallString<136> fullDesc;
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00002447 llvm::raw_svector_ostream(fullDesc) << name << ":" << category;
2448 llvm::StringMapEntry<BugType *> &
2449 entry = StrBugTypes.GetOrCreateValue(fullDesc);
2450 BugType *BT = entry.getValue();
2451 if (!BT) {
2452 BT = new BugType(name, category);
2453 entry.setValue(BT);
2454 }
2455 return BT;
2456}