blob: 8556089fe37330470d4af2eee2a3f508ec9d2ac2 [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
1298/// Return true if the terminator is a loop and the destination is the
1299/// false branch.
1300static bool isLoopJumpPastBody(const Stmt *Term, const BlockEdge *BE) {
1301 switch (Term->getStmtClass()) {
1302 case Stmt::ForStmtClass:
1303 case Stmt::WhileStmtClass:
1304 break;
1305 default:
1306 // Note that we intentionally do not include do..while here.
1307 return false;
1308 }
1309
1310 // Did we take the false branch?
1311 const CFGBlock *Src = BE->getSrc();
1312 assert(Src->succ_size() == 2);
1313 return (*(Src->succ_begin()+1) == BE->getDst());
1314}
1315
Jordan Rose8347d3d2012-09-22 01:24:53 +00001316static bool GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
Ted Kremenek14856d72009-04-06 23:06:54 +00001317 PathDiagnosticBuilder &PDB,
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001318 const ExplodedNode *N,
1319 ArrayRef<BugReporterVisitor *> visitors) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001320 EdgeBuilder EB(PD, PDB);
Anna Zaks0cd59482011-09-16 19:18:30 +00001321 const SourceManager& SM = PDB.getSourceManager();
Anna Zaks56a938f2012-03-16 23:24:20 +00001322 StackDiagVector CallStack;
Ted Kremenek11abcec2012-05-02 00:31:29 +00001323 InterestingExprs IE;
Ted Kremenek14856d72009-04-06 23:06:54 +00001324
Ted Kremenek81856742013-02-08 19:51:43 +00001325 // Record the last "looping back" diagnostic. This is used
1326 // for determining if we should emit a diagnostic for skipped loops.
NAKAMURA Takumif07e8152013-02-09 01:22:23 +00001327 std::pair<const Stmt *, PathDiagnosticEventPiece *>
1328 LastLoopDiagnostic((Stmt*)0, (PathDiagnosticEventPiece*)0);
Ted Kremenek81856742013-02-08 19:51:43 +00001329
Ted Kremenek9c378f72011-08-12 23:37:29 +00001330 const ExplodedNode *NextNode = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenek14856d72009-04-06 23:06:54 +00001331 while (NextNode) {
1332 N = NextNode;
1333 NextNode = GetPredecessorNode(N);
1334 ProgramPoint P = N->getLocation();
1335
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001336 do {
David Blaikie7a95de62013-02-21 22:23:56 +00001337 if (Optional<PostStmt> PS = P.getAs<PostStmt>()) {
Ted Kremenek11abcec2012-05-02 00:31:29 +00001338 if (const Expr *Ex = PS->getStmtAs<Expr>())
1339 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1340 N->getState().getPtr(), Ex,
1341 N->getLocationContext());
1342 }
1343
David Blaikie7a95de62013-02-21 22:23:56 +00001344 if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
Jordan Rose183ba8e2012-07-26 20:04:05 +00001345 const Stmt *S = CE->getCalleeContext()->getCallSite();
1346 if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001347 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1348 N->getState().getPtr(), Ex,
1349 N->getLocationContext());
Jordan Rose852aa0d2012-07-10 22:07:52 +00001350 }
Jordan Rose183ba8e2012-07-26 20:04:05 +00001351
1352 PathDiagnosticCallPiece *C =
1353 PathDiagnosticCallPiece::construct(N, *CE, SM);
Anna Zaks80de4872012-08-29 21:22:37 +00001354 GRBugReporter& BR = PDB.getBugReporter();
1355 BR.addCallPieceLocationContextPair(C, CE->getCalleeContext());
Jordan Rose183ba8e2012-07-26 20:04:05 +00001356
1357 EB.addEdge(C->callReturn, true);
1358 EB.flushLocations();
1359
1360 PD.getActivePath().push_front(C);
1361 PD.pushActivePath(&C->path);
1362 CallStack.push_back(StackDiagPair(C, N));
Ted Kremenek5de4fdb2012-02-07 02:26:17 +00001363 break;
1364 }
Ted Kremenek4ba86bc2012-03-02 21:16:22 +00001365
Ted Kremenek2042fc12012-02-24 06:00:00 +00001366 // Pop the call hierarchy if we are done walking the contents
1367 // of a function call.
David Blaikie7a95de62013-02-21 22:23:56 +00001368 if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
Ted Kremenek097ebb32012-03-06 01:25:01 +00001369 // Add an edge to the start of the function.
1370 const Decl *D = CE->getCalleeContext()->getDecl();
1371 PathDiagnosticLocation pos =
1372 PathDiagnosticLocation::createBegin(D, SM);
1373 EB.addEdge(pos);
1374
1375 // Flush all locations, and pop the active path.
Jordan Rose183ba8e2012-07-26 20:04:05 +00001376 bool VisitedEntireCall = PD.isWithinCall();
Ted Kremenek4ba86bc2012-03-02 21:16:22 +00001377 EB.flushLocations();
Ted Kremenek2042fc12012-02-24 06:00:00 +00001378 PD.popActivePath();
Ted Kremenek4ba86bc2012-03-02 21:16:22 +00001379 PDB.LC = N->getLocationContext();
Ted Kremenek097ebb32012-03-06 01:25:01 +00001380
Jordan Rose183ba8e2012-07-26 20:04:05 +00001381 // Either we just added a bunch of stuff to the top-level path, or
1382 // we have a previous CallExitEnd. If the former, it means that the
Ted Kremenek2042fc12012-02-24 06:00:00 +00001383 // path terminated within a function call. We must then take the
1384 // current contents of the active path and place it within
1385 // a new PathDiagnosticCallPiece.
Jordan Rose183ba8e2012-07-26 20:04:05 +00001386 PathDiagnosticCallPiece *C;
1387 if (VisitedEntireCall) {
1388 C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
1389 } else {
1390 const Decl *Caller = CE->getLocationContext()->getDecl();
Anna Zaks93739372012-03-14 18:58:28 +00001391 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
Anna Zaks80de4872012-08-29 21:22:37 +00001392 GRBugReporter& BR = PDB.getBugReporter();
1393 BR.addCallPieceLocationContextPair(C, CE->getCalleeContext());
Anna Zaks93739372012-03-14 18:58:28 +00001394 }
Jordan Rose852aa0d2012-07-10 22:07:52 +00001395
Jordan Rose183ba8e2012-07-26 20:04:05 +00001396 C->setCallee(*CE, SM);
1397 EB.addContext(C->getLocation());
Anna Zaks368a0d52012-03-15 21:13:02 +00001398
1399 if (!CallStack.empty()) {
Anna Zaks56a938f2012-03-16 23:24:20 +00001400 assert(CallStack.back().first == C);
Anna Zaks368a0d52012-03-15 21:13:02 +00001401 CallStack.pop_back();
1402 }
Ted Kremenek2042fc12012-02-24 06:00:00 +00001403 break;
1404 }
Ted Kremenek4ba86bc2012-03-02 21:16:22 +00001405
1406 // Note that is important that we update the LocationContext
1407 // after looking at CallExits. CallExit basically adds an
1408 // edge in the *caller*, so we don't want to update the LocationContext
1409 // too soon.
1410 PDB.LC = N->getLocationContext();
Ted Kremenek5de4fdb2012-02-07 02:26:17 +00001411
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001412 // Block edges.
David Blaikie7a95de62013-02-21 22:23:56 +00001413 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
Ted Kremenek11abcec2012-05-02 00:31:29 +00001414 // Does this represent entering a call? If so, look at propagating
1415 // interesting symbols across call boundaries.
1416 if (NextNode) {
1417 const LocationContext *CallerCtx = NextNode->getLocationContext();
1418 const LocationContext *CalleeCtx = PDB.LC;
1419 if (CallerCtx != CalleeCtx) {
1420 reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
1421 N->getState().getPtr(),
1422 CalleeCtx, CallerCtx);
1423 }
1424 }
1425
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001426 // Are we jumping to the head of a loop? Add a special diagnostic.
Ted Kremenekf57a2aa2012-09-12 06:22:18 +00001427 if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
Ted Kremenek59950d32012-02-24 07:12:52 +00001428 PathDiagnosticLocation L(Loop, SM, PDB.LC);
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001429 const CompoundStmt *CS = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001430
Ted Kremenekf57a2aa2012-09-12 06:22:18 +00001431 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1432 CS = dyn_cast<CompoundStmt>(FS->getBody());
1433 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1434 CS = dyn_cast<CompoundStmt>(WS->getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001436 PathDiagnosticEventPiece *p =
1437 new PathDiagnosticEventPiece(L,
Ted Kremenek07c015c2009-05-15 02:46:13 +00001438 "Looping back to the head of the loop");
Ted Kremenek2dd17ab2012-03-06 01:00:36 +00001439 p->setPrunable(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001440
Ted Kremenek81856742013-02-08 19:51:43 +00001441 // Record the loop diagnostic for later consultation. We can
1442 // use this to determine whether or not to emit a "skipped loop"
1443 // event.
1444 LastLoopDiagnostic.first = Loop;
1445 LastLoopDiagnostic.second = p;
1446
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001447 EB.addEdge(p->getLocation(), true);
Ted Kremenek2042fc12012-02-24 06:00:00 +00001448 PD.getActivePath().push_front(p);
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001450 if (CS) {
Anna Zaks0cd59482011-09-16 19:18:30 +00001451 PathDiagnosticLocation BL =
1452 PathDiagnosticLocation::createEndBrace(CS, SM);
Ted Kremenek07c015c2009-05-15 02:46:13 +00001453 EB.addEdge(BL);
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001454 }
Ted Kremenek8bd4d032009-04-28 04:23:15 +00001455 }
Ted Kremenek81856742013-02-08 19:51:43 +00001456
1457 if (const Stmt *Term = BE->getSrc()->getTerminator()) {
1458 // Are we jumping past the loop body without ever executing the
1459 // loop (because the condition was false)?
David Blaikie7a95de62013-02-21 22:23:56 +00001460 if (isLoopJumpPastBody(Term, &*BE) &&
Ted Kremenek81856742013-02-08 19:51:43 +00001461 !PD.getActivePath().empty() &&
1462 PD.getActivePath().front() != LastLoopDiagnostic.second &&
1463 Term != LastLoopDiagnostic.first)
1464 {
1465 PathDiagnosticLocation L(Term, SM, PDB.LC);
1466 PathDiagnosticEventPiece *PE =
1467 new PathDiagnosticEventPiece(L,
1468 "Loop body executed 0 times");
1469 PE->setPrunable(true);
1470 LastLoopDiagnostic.first = 0;
1471 LastLoopDiagnostic.second = 0;
1472
1473 EB.addEdge(PE->getLocation(), true);
1474 PD.getActivePath().push_front(PE);
1475 }
1476
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001477 EB.addContext(Term);
Ted Kremenek81856742013-02-08 19:51:43 +00001478 }
Mike Stump1eb44332009-09-09 15:08:12 +00001479
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001480 break;
Ted Kremenek14856d72009-04-06 23:06:54 +00001481 }
1482
David Blaikie7a95de62013-02-21 22:23:56 +00001483 if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) {
Jordan Rose1a7bcc42012-09-12 22:48:08 +00001484 CFGElement First = BE->getFirstElement();
David Blaikiefdf6a272013-02-21 20:58:29 +00001485 if (CFGStmt S = First.getAs<CFGStmt>()) {
1486 const Stmt *stmt = S.getStmt();
Ted Kremenek3c0349e2011-03-01 03:15:10 +00001487 if (IsControlFlowExpr(stmt)) {
Zhongxing Xub36cd3e2010-09-16 01:25:47 +00001488 // Add the proper context for '&&', '||', and '?'.
Ted Kremenek3c0349e2011-03-01 03:15:10 +00001489 EB.addContext(stmt);
Zhongxing Xub36cd3e2010-09-16 01:25:47 +00001490 }
1491 else
Ted Kremenek3c0349e2011-03-01 03:15:10 +00001492 EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt());
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001493 }
Zhongxing Xub36cd3e2010-09-16 01:25:47 +00001494
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001495 break;
1496 }
Ted Kremenek5de4fdb2012-02-07 02:26:17 +00001497
1498
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001499 } while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001501 if (!NextNode)
Ted Kremenek14856d72009-04-06 23:06:54 +00001502 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Anna Zaks8e6431a2011-08-18 22:37:56 +00001504 // Add pieces from custom visitors.
1505 BugReport *R = PDB.getBugReport();
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001506 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(),
1507 E = visitors.end();
1508 I != E; ++I) {
Anna Zaks8e6431a2011-08-18 22:37:56 +00001509 if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) {
Ted Kremenek8966bc12009-05-06 21:39:49 +00001510 const PathDiagnosticLocation &Loc = p->getLocation();
1511 EB.addEdge(Loc, true);
Ted Kremenek2042fc12012-02-24 06:00:00 +00001512 PD.getActivePath().push_front(p);
Anna Zaks368a0d52012-03-15 21:13:02 +00001513 updateStackPiecesWithMessage(p, CallStack);
1514
Ted Kremenek8966bc12009-05-06 21:39:49 +00001515 if (const Stmt *S = Loc.asStmt())
Mike Stump1eb44332009-09-09 15:08:12 +00001516 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
Ted Kremenek8966bc12009-05-06 21:39:49 +00001517 }
Mike Stump1eb44332009-09-09 15:08:12 +00001518 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001519 }
Jordan Rose8347d3d2012-09-22 01:24:53 +00001520
1521 return PDB.getBugReport()->isValid();
Ted Kremenek14856d72009-04-06 23:06:54 +00001522}
1523
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001524//===----------------------------------------------------------------------===//
Ted Kremenekcf118d42009-02-04 23:49:09 +00001525// Methods for BugType and subclasses.
1526//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00001527BugType::~BugType() { }
1528
Ted Kremenekcf118d42009-02-04 23:49:09 +00001529void BugType::FlushReports(BugReporter &BR) {}
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001530
David Blaikie99ba9e32011-12-20 02:48:34 +00001531void BuiltinBug::anchor() {}
1532
Ted Kremenekcf118d42009-02-04 23:49:09 +00001533//===----------------------------------------------------------------------===//
1534// Methods for BugReport and subclasses.
1535//===----------------------------------------------------------------------===//
Anna Zakse172e8b2011-08-17 23:00:25 +00001536
David Blaikie99ba9e32011-12-20 02:48:34 +00001537void BugReport::NodeResolver::anchor() {}
1538
Anna Zaks8e6431a2011-08-18 22:37:56 +00001539void BugReport::addVisitor(BugReporterVisitor* visitor) {
1540 if (!visitor)
1541 return;
1542
1543 llvm::FoldingSetNodeID ID;
1544 visitor->Profile(ID);
1545 void *InsertPos;
1546
1547 if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
1548 delete visitor;
1549 return;
1550 }
1551
1552 CallbacksSet.InsertNode(visitor, InsertPos);
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001553 Callbacks.push_back(visitor);
1554 ++ConfigurationChangeToken;
Anna Zaks8e6431a2011-08-18 22:37:56 +00001555}
1556
1557BugReport::~BugReport() {
1558 for (visitor_iterator I = visitor_begin(), E = visitor_end(); I != E; ++I) {
Anna Zaksdc757b02011-08-19 23:21:56 +00001559 delete *I;
Anna Zaks8e6431a2011-08-18 22:37:56 +00001560 }
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001561 while (!interestingSymbols.empty()) {
1562 popInterestingSymbolsAndRegions();
1563 }
Anna Zaks8e6431a2011-08-18 22:37:56 +00001564}
Anna Zakse172e8b2011-08-17 23:00:25 +00001565
Ted Kremenek07189522012-04-04 18:11:35 +00001566const Decl *BugReport::getDeclWithIssue() const {
1567 if (DeclWithIssue)
1568 return DeclWithIssue;
1569
1570 const ExplodedNode *N = getErrorNode();
1571 if (!N)
1572 return 0;
1573
1574 const LocationContext *LC = N->getLocationContext();
1575 return LC->getCurrentStackFrame()->getDecl();
1576}
1577
Anna Zakse172e8b2011-08-17 23:00:25 +00001578void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
1579 hash.AddPointer(&BT);
Anna Zakse172e8b2011-08-17 23:00:25 +00001580 hash.AddString(Description);
Anna Zaks97bfb552013-01-08 00:25:29 +00001581 PathDiagnosticLocation UL = getUniqueingLocation();
1582 if (UL.isValid()) {
1583 UL.Profile(hash);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001584 } else if (Location.isValid()) {
Anna Zaks590dd8e2011-09-20 21:38:35 +00001585 Location.Profile(hash);
1586 } else {
1587 assert(ErrorNode);
1588 hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
1589 }
Anna Zakse172e8b2011-08-17 23:00:25 +00001590
1591 for (SmallVectorImpl<SourceRange>::const_iterator I =
1592 Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1593 const SourceRange range = *I;
1594 if (!range.isValid())
1595 continue;
1596 hash.AddInteger(range.getBegin().getRawEncoding());
1597 hash.AddInteger(range.getEnd().getRawEncoding());
1598 }
1599}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001600
Ted Kremenek76aadc32012-03-09 01:13:14 +00001601void BugReport::markInteresting(SymbolRef sym) {
1602 if (!sym)
1603 return;
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001604
1605 // If the symbol wasn't already in our set, note a configuration change.
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001606 if (getInterestingSymbols().insert(sym).second)
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001607 ++ConfigurationChangeToken;
Jordy Rose8ec588e2012-03-15 22:45:29 +00001608
1609 if (const SymbolMetadata *meta = dyn_cast<SymbolMetadata>(sym))
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001610 getInterestingRegions().insert(meta->getRegion());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001611}
1612
1613void BugReport::markInteresting(const MemRegion *R) {
1614 if (!R)
1615 return;
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001616
1617 // If the base region wasn't already in our set, note a configuration change.
Ted Kremenek76aadc32012-03-09 01:13:14 +00001618 R = R->getBaseRegion();
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001619 if (getInterestingRegions().insert(R).second)
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001620 ++ConfigurationChangeToken;
Jordy Rose8ec588e2012-03-15 22:45:29 +00001621
Ted Kremenek76aadc32012-03-09 01:13:14 +00001622 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001623 getInterestingSymbols().insert(SR->getSymbol());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001624}
1625
1626void BugReport::markInteresting(SVal V) {
1627 markInteresting(V.getAsRegion());
1628 markInteresting(V.getAsSymbol());
1629}
1630
Anna Zaks80de4872012-08-29 21:22:37 +00001631void BugReport::markInteresting(const LocationContext *LC) {
1632 if (!LC)
1633 return;
1634 InterestingLocationContexts.insert(LC);
1635}
1636
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001637bool BugReport::isInteresting(SVal V) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00001638 return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol());
1639}
1640
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001641bool BugReport::isInteresting(SymbolRef sym) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00001642 if (!sym)
1643 return false;
Jordy Rose8ec588e2012-03-15 22:45:29 +00001644 // We don't currently consider metadata symbols to be interesting
1645 // even if we know their region is interesting. Is that correct behavior?
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001646 return getInterestingSymbols().count(sym);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001647}
1648
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001649bool BugReport::isInteresting(const MemRegion *R) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00001650 if (!R)
1651 return false;
1652 R = R->getBaseRegion();
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001653 bool b = getInterestingRegions().count(R);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001654 if (b)
1655 return true;
1656 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001657 return getInterestingSymbols().count(SR->getSymbol());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001658 return false;
1659}
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001660
Anna Zaks80de4872012-08-29 21:22:37 +00001661bool BugReport::isInteresting(const LocationContext *LC) {
1662 if (!LC)
1663 return false;
1664 return InterestingLocationContexts.count(LC);
1665}
1666
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001667void BugReport::lazyInitializeInterestingSets() {
1668 if (interestingSymbols.empty()) {
1669 interestingSymbols.push_back(new Symbols());
1670 interestingRegions.push_back(new Regions());
1671 }
1672}
1673
1674BugReport::Symbols &BugReport::getInterestingSymbols() {
1675 lazyInitializeInterestingSets();
1676 return *interestingSymbols.back();
1677}
1678
1679BugReport::Regions &BugReport::getInterestingRegions() {
1680 lazyInitializeInterestingSets();
1681 return *interestingRegions.back();
1682}
1683
1684void BugReport::pushInterestingSymbolsAndRegions() {
1685 interestingSymbols.push_back(new Symbols(getInterestingSymbols()));
1686 interestingRegions.push_back(new Regions(getInterestingRegions()));
1687}
1688
1689void BugReport::popInterestingSymbolsAndRegions() {
1690 delete interestingSymbols.back();
1691 interestingSymbols.pop_back();
1692 delete interestingRegions.back();
1693 interestingRegions.pop_back();
1694}
Ted Kremenek76aadc32012-03-09 01:13:14 +00001695
Ted Kremenek9c378f72011-08-12 23:37:29 +00001696const Stmt *BugReport::getStmt() const {
Anna Zakse172e8b2011-08-17 23:00:25 +00001697 if (!ErrorNode)
1698 return 0;
1699
Tom Care212f6d32010-09-16 03:50:38 +00001700 ProgramPoint ProgP = ErrorNode->getLocation();
Ted Kremenek5f85e172009-07-22 22:35:28 +00001701 const Stmt *S = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001702
David Blaikie7a95de62013-02-21 22:23:56 +00001703 if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
Zhongxing Xufafd3832009-08-20 01:23:34 +00001704 CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
Zhongxing Xu50d5bc42009-08-18 08:46:04 +00001705 if (BE->getBlock() == &Exit)
Tom Care212f6d32010-09-16 03:50:38 +00001706 S = GetPreviousStmt(ErrorNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001707 }
Ted Kremenek5f85e172009-07-22 22:35:28 +00001708 if (!S)
Mike Stump1eb44332009-09-09 15:08:12 +00001709 S = GetStmt(ProgP);
1710
1711 return S;
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001712}
1713
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001714std::pair<BugReport::ranges_iterator, BugReport::ranges_iterator>
Anna Zakse172e8b2011-08-17 23:00:25 +00001715BugReport::getRanges() {
1716 // If no custom ranges, add the range of the statement corresponding to
1717 // the error node.
1718 if (Ranges.empty()) {
1719 if (const Expr *E = dyn_cast_or_null<Expr>(getStmt()))
1720 addRange(E->getSourceRange());
1721 else
1722 return std::make_pair(ranges_iterator(), ranges_iterator());
1723 }
1724
Anna Zaks14924262011-08-24 20:31:06 +00001725 // User-specified absence of range info.
1726 if (Ranges.size() == 1 && !Ranges.begin()->isValid())
1727 return std::make_pair(ranges_iterator(), ranges_iterator());
1728
Anna Zakse172e8b2011-08-17 23:00:25 +00001729 return std::make_pair(Ranges.begin(), Ranges.end());
Ted Kremenekf1ae7052008-04-03 17:57:38 +00001730}
1731
Anna Zaks590dd8e2011-09-20 21:38:35 +00001732PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
Anna Zaksb7530a42011-08-17 23:21:23 +00001733 if (ErrorNode) {
Anna Zaks590dd8e2011-09-20 21:38:35 +00001734 assert(!Location.isValid() &&
Anna Zaksb7530a42011-08-17 23:21:23 +00001735 "Either Location or ErrorNode should be specified but not both.");
1736
Ted Kremenek9c378f72011-08-12 23:37:29 +00001737 if (const Stmt *S = GetCurrentOrPreviousStmt(ErrorNode)) {
Anna Zaks590dd8e2011-09-20 21:38:35 +00001738 const LocationContext *LC = ErrorNode->getLocationContext();
1739
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001740 // For member expressions, return the location of the '.' or '->'.
Ted Kremenek5b9bd212009-09-11 22:07:28 +00001741 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S))
Anna Zaks590dd8e2011-09-20 21:38:35 +00001742 return PathDiagnosticLocation::createMemberLoc(ME, SM);
Ted Kremenek5b9bd212009-09-11 22:07:28 +00001743 // For binary operators, return the location of the operator.
1744 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(S))
Anna Zaks590dd8e2011-09-20 21:38:35 +00001745 return PathDiagnosticLocation::createOperatorLoc(B, SM);
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001746
David Blaikie7a95de62013-02-21 22:23:56 +00001747 if (ErrorNode->getLocation().getAs<PostStmtPurgeDeadSymbols>())
Jordan Rose63bc1862012-11-15 19:11:43 +00001748 return PathDiagnosticLocation::createEnd(S, SM, LC);
1749
Anna Zaks590dd8e2011-09-20 21:38:35 +00001750 return PathDiagnosticLocation::createBegin(S, SM, LC);
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001751 }
Anna Zaksb7530a42011-08-17 23:21:23 +00001752 } else {
1753 assert(Location.isValid());
1754 return Location;
1755 }
1756
Anna Zaks590dd8e2011-09-20 21:38:35 +00001757 return PathDiagnosticLocation();
Ted Kremenekd2f642b2008-04-14 17:39:48 +00001758}
1759
Ted Kremenekcf118d42009-02-04 23:49:09 +00001760//===----------------------------------------------------------------------===//
1761// Methods for BugReporter and subclasses.
1762//===----------------------------------------------------------------------===//
1763
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00001764BugReportEquivClass::~BugReportEquivClass() { }
Zhongxing Xua2f4ec02009-09-05 06:06:49 +00001765GRBugReporter::~GRBugReporter() { }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001766BugReporterData::~BugReporterData() {}
1767
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001768ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001769
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001770ProgramStateManager&
Ted Kremenekcf118d42009-02-04 23:49:09 +00001771GRBugReporter::getStateManager() { return Eng.getStateManager(); }
1772
Anna Zaks3b030a22011-08-19 01:57:09 +00001773BugReporter::~BugReporter() {
1774 FlushReports();
1775
1776 // Free the bug reports we are tracking.
1777 typedef std::vector<BugReportEquivClass *> ContTy;
1778 for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end();
1779 I != E; ++I) {
1780 delete *I;
1781 }
1782}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001783
1784void BugReporter::FlushReports() {
1785 if (BugTypes.isEmpty())
1786 return;
1787
1788 // First flush the warnings for each BugType. This may end up creating new
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00001789 // warnings and new BugTypes.
1790 // FIXME: Only NSErrorChecker needs BugType's FlushReports.
1791 // Turn NSErrorChecker into a proper checker and remove this.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001792 SmallVector<const BugType*, 16> bugTypes;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001793 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00001794 bugTypes.push_back(*I);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001795 for (SmallVector<const BugType*, 16>::iterator
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00001796 I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I)
Ted Kremenekcf118d42009-02-04 23:49:09 +00001797 const_cast<BugType*>(*I)->FlushReports(*this);
1798
Anna Zaksd015f4f2012-08-02 23:41:05 +00001799 // We need to flush reports in deterministic order to ensure the order
1800 // of the reports is consistent between runs.
Anna Zaks0eb6c372012-08-02 00:41:43 +00001801 typedef std::vector<BugReportEquivClass *> ContVecTy;
1802 for (ContVecTy::iterator EI=EQClassesVector.begin(), EE=EQClassesVector.end();
1803 EI != EE; ++EI){
1804 BugReportEquivClass& EQ = **EI;
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00001805 FlushReport(EQ);
Ted Kremenek94826a72008-04-03 04:59:14 +00001806 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001807
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00001808 // BugReporter owns and deletes only BugTypes created implicitly through
1809 // EmitBasicReport.
1810 // FIXME: There are leaks from checkers that assume that the BugTypes they
1811 // create will be destroyed by the BugReporter.
1812 for (llvm::StringMap<BugType*>::iterator
1813 I = StrBugTypes.begin(), E = StrBugTypes.end(); I != E; ++I)
1814 delete I->second;
1815
Ted Kremenekcf118d42009-02-04 23:49:09 +00001816 // Remove all references to the BugType objects.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001817 BugTypes = F.getEmptySet();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001818}
1819
1820//===----------------------------------------------------------------------===//
1821// PathDiagnostics generation.
1822//===----------------------------------------------------------------------===//
1823
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001824static std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001825 std::pair<ExplodedNode*, unsigned> >
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001826MakeReportGraph(const ExplodedGraph* G,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001827 SmallVectorImpl<const ExplodedNode*> &nodes) {
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Ted Kremenekcf118d42009-02-04 23:49:09 +00001829 // Create the trimmed graph. It will contain the shortest paths from the
Mike Stump1eb44332009-09-09 15:08:12 +00001830 // error nodes to the root. In the new graph we should only have one
Ted Kremenekcf118d42009-02-04 23:49:09 +00001831 // error node unless there are two or more error nodes with the same minimum
1832 // path length.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001833 ExplodedGraph* GTrim;
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001834 InterExplodedGraphMap* NMap;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001835
1836 llvm::DenseMap<const void*, const void*> InverseMap;
Ted Kremenek40406fe2010-12-03 06:52:30 +00001837 llvm::tie(GTrim, NMap) = G->Trim(nodes.data(), nodes.data() + nodes.size(),
1838 &InverseMap);
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Ted Kremenekcf118d42009-02-04 23:49:09 +00001840 // Create owning pointers for GTrim and NMap just to ensure that they are
1841 // released when this function exists.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001842 OwningPtr<ExplodedGraph> AutoReleaseGTrim(GTrim);
1843 OwningPtr<InterExplodedGraphMap> AutoReleaseNMap(NMap);
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Ted Kremenekcf118d42009-02-04 23:49:09 +00001845 // Find the (first) error node in the trimmed graph. We just need to consult
1846 // the node map (NMap) which maps from nodes in the original graph to nodes
1847 // in the new graph.
Ted Kremenek938332c2009-05-16 01:11:58 +00001848
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001849 std::queue<const ExplodedNode*> WS;
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001850 typedef llvm::DenseMap<const ExplodedNode*, unsigned> IndexMapTy;
Ted Kremenek938332c2009-05-16 01:11:58 +00001851 IndexMapTy IndexMap;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001852
Ted Kremenek40406fe2010-12-03 06:52:30 +00001853 for (unsigned nodeIndex = 0 ; nodeIndex < nodes.size(); ++nodeIndex) {
1854 const ExplodedNode *originalNode = nodes[nodeIndex];
1855 if (const ExplodedNode *N = NMap->getMappedNode(originalNode)) {
Ted Kremenek938332c2009-05-16 01:11:58 +00001856 WS.push(N);
Ted Kremenek40406fe2010-12-03 06:52:30 +00001857 IndexMap[originalNode] = nodeIndex;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001858 }
Ted Kremenek40406fe2010-12-03 06:52:30 +00001859 }
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Ted Kremenek938332c2009-05-16 01:11:58 +00001861 assert(!WS.empty() && "No error node found in the trimmed graph.");
Ted Kremenekcf118d42009-02-04 23:49:09 +00001862
1863 // Create a new (third!) graph with a single path. This is the graph
1864 // that will be returned to the caller.
Zhongxing Xuc77a5512010-07-01 07:10:59 +00001865 ExplodedGraph *GNew = new ExplodedGraph();
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Ted Kremenek10aa5542009-03-12 23:41:59 +00001867 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001868 // to the root node, and then construct a new graph that contains only
1869 // a single path.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001870 llvm::DenseMap<const void*,unsigned> Visited;
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001872 unsigned cnt = 0;
Ted Kremenek9c378f72011-08-12 23:37:29 +00001873 const ExplodedNode *Root = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001875 while (!WS.empty()) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001876 const ExplodedNode *Node = WS.front();
Ted Kremenek10aa5542009-03-12 23:41:59 +00001877 WS.pop();
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001879 if (Visited.find(Node) != Visited.end())
1880 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001881
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001882 Visited[Node] = cnt++;
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001884 if (Node->pred_empty()) {
1885 Root = Node;
1886 break;
1887 }
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001889 for (ExplodedNode::const_pred_iterator I=Node->pred_begin(),
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001890 E=Node->pred_end(); I!=E; ++I)
Ted Kremenek10aa5542009-03-12 23:41:59 +00001891 WS.push(*I);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001892 }
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Ted Kremenek938332c2009-05-16 01:11:58 +00001894 assert(Root);
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Ted Kremenek10aa5542009-03-12 23:41:59 +00001896 // Now walk from the root down the BFS path, always taking the successor
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001897 // with the lowest number.
Mike Stump1eb44332009-09-09 15:08:12 +00001898 ExplodedNode *Last = 0, *First = 0;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001899 NodeBackMap *BM = new NodeBackMap();
Ted Kremenek938332c2009-05-16 01:11:58 +00001900 unsigned NodeIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001902 for ( const ExplodedNode *N = Root ;;) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001903 // Lookup the number associated with the current node.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001904 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
Ted Kremenek938332c2009-05-16 01:11:58 +00001905 assert(I != Visited.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001907 // Create the equivalent node in the new graph with the same state
1908 // and location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00001909 ExplodedNode *NewN = GNew->getNode(N->getLocation(), N->getState());
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001911 // Store the mapping to the original node.
1912 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1913 assert(IMitr != InverseMap.end() && "No mapping to original node.");
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001914 (*BM)[NewN] = (const ExplodedNode*) IMitr->second;
Mike Stump1eb44332009-09-09 15:08:12 +00001915
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001916 // Link up the new node with the previous node.
1917 if (Last)
Ted Kremenek5fe4d9d2009-10-07 00:42:52 +00001918 NewN->addPredecessor(Last, *GNew);
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001920 Last = NewN;
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001922 // Are we at the final node?
Ted Kremenek938332c2009-05-16 01:11:58 +00001923 IndexMapTy::iterator IMI =
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001924 IndexMap.find((const ExplodedNode*)(IMitr->second));
Ted Kremenek938332c2009-05-16 01:11:58 +00001925 if (IMI != IndexMap.end()) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001926 First = NewN;
Ted Kremenek938332c2009-05-16 01:11:58 +00001927 NodeIndex = IMI->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001928 break;
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001929 }
Mike Stump1eb44332009-09-09 15:08:12 +00001930
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001931 // Find the next successor node. We choose the node that is marked
1932 // with the lowest DFS number.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001933 ExplodedNode::const_succ_iterator SI = N->succ_begin();
1934 ExplodedNode::const_succ_iterator SE = N->succ_end();
Ted Kremenekc1da4412008-06-17 19:14:06 +00001935 N = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001937 for (unsigned MinVal = 0; SI != SE; ++SI) {
Mike Stump1eb44332009-09-09 15:08:12 +00001938
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001939 I = Visited.find(*SI);
Mike Stump1eb44332009-09-09 15:08:12 +00001940
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001941 if (I == Visited.end())
1942 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001944 if (!N || I->second < MinVal) {
1945 N = *SI;
1946 MinVal = I->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001947 }
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001948 }
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Ted Kremenek938332c2009-05-16 01:11:58 +00001950 assert(N);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001951 }
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Ted Kremenek938332c2009-05-16 01:11:58 +00001953 assert(First);
1954
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001955 return std::make_pair(std::make_pair(GNew, BM),
1956 std::make_pair(First, NodeIndex));
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001957}
1958
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001959/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
1960/// and collapses PathDiagosticPieces that are expanded by macros.
Ted Kremenek77d09442012-03-02 01:27:31 +00001961static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM) {
Ted Kremenek2042fc12012-02-24 06:00:00 +00001962 typedef std::vector<std::pair<IntrusiveRefCntPtr<PathDiagnosticMacroPiece>,
1963 SourceLocation> > MacroStackTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001965 typedef std::vector<IntrusiveRefCntPtr<PathDiagnosticPiece> >
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001966 PiecesTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001968 MacroStackTy MacroStack;
1969 PiecesTy Pieces;
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Ted Kremenek77d09442012-03-02 01:27:31 +00001971 for (PathPieces::const_iterator I = path.begin(), E = path.end();
Ted Kremenek2042fc12012-02-24 06:00:00 +00001972 I!=E; ++I) {
Ted Kremenek77d09442012-03-02 01:27:31 +00001973
1974 PathDiagnosticPiece *piece = I->getPtr();
1975
1976 // Recursively compact calls.
1977 if (PathDiagnosticCallPiece *call=dyn_cast<PathDiagnosticCallPiece>(piece)){
1978 CompactPathDiagnostic(call->path, SM);
1979 }
1980
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001981 // Get the location of the PathDiagnosticPiece.
Ted Kremenek77d09442012-03-02 01:27:31 +00001982 const FullSourceLoc Loc = piece->getLocation().asLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001984 // Determine the instantiation location, which is the location we group
1985 // related PathDiagnosticPieces.
Mike Stump1eb44332009-09-09 15:08:12 +00001986 SourceLocation InstantiationLoc = Loc.isMacroID() ?
Chandler Carruth40278532011-07-25 16:49:02 +00001987 SM.getExpansionLoc(Loc) :
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001988 SourceLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001990 if (Loc.isFileID()) {
1991 MacroStack.clear();
Ted Kremenek77d09442012-03-02 01:27:31 +00001992 Pieces.push_back(piece);
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001993 continue;
1994 }
1995
1996 assert(Loc.isMacroID());
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001998 // Is the PathDiagnosticPiece within the same macro group?
1999 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
Ted Kremenek77d09442012-03-02 01:27:31 +00002000 MacroStack.back().first->subPieces.push_back(piece);
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002001 continue;
2002 }
2003
2004 // We aren't in the same group. Are we descending into a new macro
2005 // or are part of an old one?
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002006 IntrusiveRefCntPtr<PathDiagnosticMacroPiece> MacroGroup;
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002007
2008 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
Chandler Carruth40278532011-07-25 16:49:02 +00002009 SM.getExpansionLoc(Loc) :
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002010 SourceLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002012 // Walk the entire macro stack.
2013 while (!MacroStack.empty()) {
2014 if (InstantiationLoc == MacroStack.back().second) {
2015 MacroGroup = MacroStack.back().first;
2016 break;
2017 }
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002019 if (ParentInstantiationLoc == MacroStack.back().second) {
2020 MacroGroup = MacroStack.back().first;
2021 break;
2022 }
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002024 MacroStack.pop_back();
2025 }
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002027 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
2028 // Create a new macro group and add it to the stack.
Anna Zaks590dd8e2011-09-20 21:38:35 +00002029 PathDiagnosticMacroPiece *NewGroup =
2030 new PathDiagnosticMacroPiece(
Ted Kremenek77d09442012-03-02 01:27:31 +00002031 PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002032
2033 if (MacroGroup)
Ted Kremenek802e0242012-02-08 04:32:34 +00002034 MacroGroup->subPieces.push_back(NewGroup);
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002035 else {
2036 assert(InstantiationLoc.isFileID());
2037 Pieces.push_back(NewGroup);
2038 }
Mike Stump1eb44332009-09-09 15:08:12 +00002039
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002040 MacroGroup = NewGroup;
2041 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
2042 }
2043
2044 // Finally, add the PathDiagnosticPiece to the group.
Ted Kremenek77d09442012-03-02 01:27:31 +00002045 MacroGroup->subPieces.push_back(piece);
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002046 }
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002048 // Now take the pieces and construct a new PathDiagnostic.
Ted Kremenek77d09442012-03-02 01:27:31 +00002049 path.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Ted Kremenek77d09442012-03-02 01:27:31 +00002051 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I)
2052 path.push_back(*I);
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002053}
2054
Jordan Rose8347d3d2012-09-22 01:24:53 +00002055bool GRBugReporter::generatePathDiagnostic(PathDiagnostic& PD,
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002056 PathDiagnosticConsumer &PC,
2057 ArrayRef<BugReport *> &bugReports) {
Ted Kremenek40406fe2010-12-03 06:52:30 +00002058 assert(!bugReports.empty());
Jordan Rose8347d3d2012-09-22 01:24:53 +00002059
2060 bool HasValid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002061 SmallVector<const ExplodedNode *, 10> errorNodes;
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002062 for (ArrayRef<BugReport*>::iterator I = bugReports.begin(),
2063 E = bugReports.end(); I != E; ++I) {
Jordan Rose8347d3d2012-09-22 01:24:53 +00002064 if ((*I)->isValid()) {
2065 HasValid = true;
Ted Kremenek40406fe2010-12-03 06:52:30 +00002066 errorNodes.push_back((*I)->getErrorNode());
Jordan Rose8347d3d2012-09-22 01:24:53 +00002067 } else {
2068 errorNodes.push_back(0);
2069 }
Ted Kremenek40406fe2010-12-03 06:52:30 +00002070 }
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Jordan Rose8347d3d2012-09-22 01:24:53 +00002072 // If all the reports have been marked invalid, we're done.
2073 if (!HasValid)
2074 return false;
2075
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00002076 // Construct a new graph that contains only a single path from the error
Mike Stump1eb44332009-09-09 15:08:12 +00002077 // node to a root.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00002078 const std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002079 std::pair<ExplodedNode*, unsigned> >&
Ted Kremenek40406fe2010-12-03 06:52:30 +00002080 GPair = MakeReportGraph(&getGraph(), errorNodes);
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Ted Kremenekcf118d42009-02-04 23:49:09 +00002082 // Find the BugReport with the original location.
Ted Kremenek40406fe2010-12-03 06:52:30 +00002083 assert(GPair.second.second < bugReports.size());
2084 BugReport *R = bugReports[GPair.second.second];
Ted Kremenekcf118d42009-02-04 23:49:09 +00002085 assert(R && "No original report found for sliced graph.");
Jordan Rose8347d3d2012-09-22 01:24:53 +00002086 assert(R->isValid() && "Report selected from trimmed graph marked invalid.");
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002088 OwningPtr<ExplodedGraph> ReportGraph(GPair.first.first);
2089 OwningPtr<NodeBackMap> BackMap(GPair.first.second);
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002090 const ExplodedNode *N = GPair.second.first;
Mike Stump1eb44332009-09-09 15:08:12 +00002091
2092 // Start building the path diagnostic...
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002093 PathDiagnosticBuilder PDB(*this, R, BackMap.get(), &PC);
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Anna Zaks8e6431a2011-08-18 22:37:56 +00002095 // Register additional node visitors.
Anna Zaks50bbc162011-08-19 22:33:38 +00002096 R->addVisitor(new NilReceiverBRVisitor());
2097 R->addVisitor(new ConditionBRVisitor());
Anna Zaks86ff12c2013-01-30 19:12:34 +00002098 R->addVisitor(new LikelyFalsePositiveSuppressionBRVisitor());
Mike Stump1eb44332009-09-09 15:08:12 +00002099
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002100 BugReport::VisitorList visitors;
2101 unsigned originalReportConfigToken, finalReportConfigToken;
Anna Zaks23f395e2011-08-20 01:27:22 +00002102
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002103 // While generating diagnostics, it's possible the visitors will decide
2104 // new symbols and regions are interesting, or add other visitors based on
2105 // the information they find. If they do, we need to regenerate the path
2106 // based on our new report configuration.
2107 do {
2108 // Get a clean copy of all the visitors.
2109 for (BugReport::visitor_iterator I = R->visitor_begin(),
2110 E = R->visitor_end(); I != E; ++I)
2111 visitors.push_back((*I)->clone());
2112
2113 // Clear out the active path from any previous work.
Jordan Rose3a46f5f2012-08-31 00:36:26 +00002114 PD.resetPath();
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002115 originalReportConfigToken = R->getConfigurationChangeToken();
2116
2117 // Generate the very last diagnostic piece - the piece is visible before
2118 // the trace is expanded.
Anna Zaks86ff12c2013-01-30 19:12:34 +00002119 PathDiagnosticPiece *LastPiece = 0;
2120 for (BugReport::visitor_iterator I = visitors.begin(), E = visitors.end();
2121 I != E; ++I) {
2122 if (PathDiagnosticPiece *Piece = (*I)->getEndPath(PDB, N, *R)) {
2123 assert (!LastPiece &&
2124 "There can only be one final piece in a diagnostic.");
2125 LastPiece = Piece;
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002126 }
Anna Zaks86ff12c2013-01-30 19:12:34 +00002127 }
2128
2129 if (PDB.getGenerationScheme() != PathDiagnosticConsumer::None) {
Jordan Rosed632d6f2012-09-22 01:24:56 +00002130 if (!LastPiece)
2131 LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R);
2132 if (LastPiece)
2133 PD.setEndOfPath(LastPiece);
2134 else
2135 return false;
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002136 }
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002137
2138 switch (PDB.getGenerationScheme()) {
David Blaikieef3643f2011-09-26 00:51:36 +00002139 case PathDiagnosticConsumer::Extensive:
Jordan Rose8347d3d2012-09-22 01:24:53 +00002140 if (!GenerateExtensivePathDiagnostic(PD, PDB, N, visitors)) {
2141 assert(!R->isValid() && "Failed on valid report");
2142 // Try again. We'll filter out the bad report when we trim the graph.
2143 // FIXME: It would be more efficient to use the same intermediate
2144 // trimmed graph, and just repeat the shortest-path search.
2145 return generatePathDiagnostic(PD, PC, bugReports);
2146 }
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00002147 break;
David Blaikieef3643f2011-09-26 00:51:36 +00002148 case PathDiagnosticConsumer::Minimal:
Jordan Rose8347d3d2012-09-22 01:24:53 +00002149 if (!GenerateMinimalPathDiagnostic(PD, PDB, N, visitors)) {
2150 assert(!R->isValid() && "Failed on valid report");
2151 // Try again. We'll filter out the bad report when we trim the graph.
2152 return generatePathDiagnostic(PD, PC, bugReports);
2153 }
Ted Kremenek7dc86642009-03-31 20:22:36 +00002154 break;
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002155 case PathDiagnosticConsumer::None:
Jordan Rosed632d6f2012-09-22 01:24:56 +00002156 if (!GenerateVisitorsOnlyPathDiagnostic(PD, PDB, N, visitors)) {
2157 assert(!R->isValid() && "Failed on valid report");
2158 // Try again. We'll filter out the bad report when we trim the graph.
2159 return generatePathDiagnostic(PD, PC, bugReports);
2160 }
2161 break;
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002162 }
2163
2164 // Clean up the visitors we used.
2165 llvm::DeleteContainerPointers(visitors);
2166
2167 // Did anything change while generating this path?
2168 finalReportConfigToken = R->getConfigurationChangeToken();
2169 } while(finalReportConfigToken != originalReportConfigToken);
2170
Ted Kremenekc89f4b02012-02-28 23:06:21 +00002171 // Finally, prune the diagnostic path of uninteresting stuff.
Ted Kremenekb85cce02012-10-25 22:07:10 +00002172 if (!PD.path.empty()) {
2173 // Remove messages that are basically the same.
Ted Kremenek38001652012-10-26 16:02:36 +00002174 removeRedundantMsgs(PD.getMutablePieces());
Ted Kremenekb85cce02012-10-25 22:07:10 +00002175
Jordan Roseaeca2cc2013-01-26 01:28:15 +00002176 if (R->shouldPrunePath() &&
2177 getEngine().getAnalysisManager().options.shouldPrunePaths()) {
Jordan Roseafa7cae2012-12-07 19:56:29 +00002178 bool hasSomethingInteresting = RemoveUnneededCalls(PD.getMutablePieces(),
2179 R);
Ted Kremenekb85cce02012-10-25 22:07:10 +00002180 assert(hasSomethingInteresting);
2181 (void) hasSomethingInteresting;
2182 }
Jordan Roseafa7cae2012-12-07 19:56:29 +00002183
2184 adjustCallLocations(PD.getMutablePieces());
Ted Kremeneked7948b2012-05-31 06:03:17 +00002185 }
Jordan Rose8347d3d2012-09-22 01:24:53 +00002186
2187 return true;
Ted Kremenek7dc86642009-03-31 20:22:36 +00002188}
2189
Ted Kremenekcf118d42009-02-04 23:49:09 +00002190void BugReporter::Register(BugType *BT) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00002191 BugTypes = F.add(BugTypes, BT);
Ted Kremenek76d90c82008-05-16 18:33:14 +00002192}
2193
Jordan Rose785950e2012-11-02 01:53:40 +00002194void BugReporter::emitReport(BugReport* R) {
Ted Kremenekcf118d42009-02-04 23:49:09 +00002195 // Compute the bug report's hash to determine its equivalence class.
2196 llvm::FoldingSetNodeID ID;
2197 R->Profile(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00002198
2199 // Lookup the equivance class. If there isn't one, create it.
Ted Kremenekcf118d42009-02-04 23:49:09 +00002200 BugType& BT = R->getBugType();
2201 Register(&BT);
2202 void *InsertPos;
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00002203 BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002204
Ted Kremenekcf118d42009-02-04 23:49:09 +00002205 if (!EQ) {
2206 EQ = new BugReportEquivClass(R);
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00002207 EQClasses.InsertNode(EQ, InsertPos);
Anna Zaks3b030a22011-08-19 01:57:09 +00002208 EQClassesVector.push_back(EQ);
Ted Kremenekcf118d42009-02-04 23:49:09 +00002209 }
2210 else
2211 EQ->AddReport(R);
Ted Kremenek61f3e052008-04-03 04:42:52 +00002212}
2213
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002214
2215//===----------------------------------------------------------------------===//
2216// Emitting reports in equivalence classes.
2217//===----------------------------------------------------------------------===//
2218
2219namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00002220struct FRIEC_WLItem {
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002221 const ExplodedNode *N;
2222 ExplodedNode::const_succ_iterator I, E;
2223
2224 FRIEC_WLItem(const ExplodedNode *n)
2225 : N(n), I(N->succ_begin()), E(N->succ_end()) {}
2226};
2227}
2228
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002229static BugReport *
2230FindReportInEquivalenceClass(BugReportEquivClass& EQ,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002231 SmallVectorImpl<BugReport*> &bugReports) {
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002232
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002233 BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
2234 assert(I != E);
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002235 BugType& BT = I->getBugType();
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002236
Ted Kremenek40406fe2010-12-03 06:52:30 +00002237 // If we don't need to suppress any of the nodes because they are
2238 // post-dominated by a sink, simply add all the nodes in the equivalence class
2239 // to 'Nodes'. Any of the reports will serve as a "representative" report.
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002240 if (!BT.isSuppressOnSink()) {
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002241 BugReport *R = I;
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002242 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002243 const ExplodedNode *N = I->getErrorNode();
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002244 if (N) {
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002245 R = I;
Ted Kremenek40406fe2010-12-03 06:52:30 +00002246 bugReports.push_back(R);
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002247 }
2248 }
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002249 return R;
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002250 }
2251
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002252 // For bug reports that should be suppressed when all paths are post-dominated
2253 // by a sink node, iterate through the reports in the equivalence class
2254 // until we find one that isn't post-dominated (if one exists). We use a
2255 // DFS traversal of the ExplodedGraph to find a non-sink node. We could write
2256 // this as a recursive function, but we don't want to risk blowing out the
2257 // stack for very long paths.
Ted Kremenek40406fe2010-12-03 06:52:30 +00002258 BugReport *exampleReport = 0;
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002259
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002260 for (; I != E; ++I) {
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002261 const ExplodedNode *errorNode = I->getErrorNode();
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002262
Ted Kremenek40406fe2010-12-03 06:52:30 +00002263 if (!errorNode)
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002264 continue;
Ted Kremenek40406fe2010-12-03 06:52:30 +00002265 if (errorNode->isSink()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002266 llvm_unreachable(
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002267 "BugType::isSuppressSink() should not be 'true' for sink end nodes");
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002268 }
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002269 // No successors? By definition this nodes isn't post-dominated by a sink.
Ted Kremenek40406fe2010-12-03 06:52:30 +00002270 if (errorNode->succ_empty()) {
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002271 bugReports.push_back(I);
Ted Kremenek40406fe2010-12-03 06:52:30 +00002272 if (!exampleReport)
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002273 exampleReport = I;
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002274 continue;
2275 }
2276
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002277 // At this point we know that 'N' is not a sink and it has at least one
2278 // successor. Use a DFS worklist to find a non-sink end-of-path node.
2279 typedef FRIEC_WLItem WLItem;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002280 typedef SmallVector<WLItem, 10> DFSWorkList;
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002281 llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
2282
2283 DFSWorkList WL;
Ted Kremenek40406fe2010-12-03 06:52:30 +00002284 WL.push_back(errorNode);
2285 Visited[errorNode] = 1;
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002286
2287 while (!WL.empty()) {
2288 WLItem &WI = WL.back();
2289 assert(!WI.N->succ_empty());
2290
2291 for (; WI.I != WI.E; ++WI.I) {
2292 const ExplodedNode *Succ = *WI.I;
2293 // End-of-path node?
2294 if (Succ->succ_empty()) {
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002295 // If we found an end-of-path node that is not a sink.
2296 if (!Succ->isSink()) {
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002297 bugReports.push_back(I);
Ted Kremenek40406fe2010-12-03 06:52:30 +00002298 if (!exampleReport)
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002299 exampleReport = I;
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002300 WL.clear();
2301 break;
2302 }
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002303 // Found a sink? Continue on to the next successor.
2304 continue;
2305 }
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002306 // Mark the successor as visited. If it hasn't been explored,
2307 // enqueue it to the DFS worklist.
2308 unsigned &mark = Visited[Succ];
2309 if (!mark) {
2310 mark = 1;
2311 WL.push_back(Succ);
2312 break;
2313 }
2314 }
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002315
2316 // The worklist may have been cleared at this point. First
2317 // check if it is empty before checking the last item.
2318 if (!WL.empty() && &WL.back() == &WI)
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002319 WL.pop_back();
2320 }
2321 }
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002322
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002323 // ExampleReport will be NULL if all the nodes in the equivalence class
2324 // were post-dominated by sinks.
Ted Kremenek40406fe2010-12-03 06:52:30 +00002325 return exampleReport;
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002326}
Ted Kremeneke0a58072009-09-18 22:37:37 +00002327
Ted Kremenekcf118d42009-02-04 23:49:09 +00002328void BugReporter::FlushReport(BugReportEquivClass& EQ) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002329 SmallVector<BugReport*, 10> bugReports;
Ted Kremenek40406fe2010-12-03 06:52:30 +00002330 BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports);
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002331 if (exampleReport) {
2332 const PathDiagnosticConsumers &C = getPathDiagnosticConsumers();
2333 for (PathDiagnosticConsumers::const_iterator I=C.begin(),
2334 E=C.end(); I != E; ++I) {
2335 FlushReport(exampleReport, **I, bugReports);
2336 }
2337 }
2338}
2339
2340void BugReporter::FlushReport(BugReport *exampleReport,
2341 PathDiagnosticConsumer &PD,
2342 ArrayRef<BugReport*> bugReports) {
Mike Stump1eb44332009-09-09 15:08:12 +00002343
Ted Kremenekcf118d42009-02-04 23:49:09 +00002344 // FIXME: Make sure we use the 'R' for the path that was actually used.
Mike Stump1eb44332009-09-09 15:08:12 +00002345 // Probably doesn't make a difference in practice.
Ted Kremenek40406fe2010-12-03 06:52:30 +00002346 BugType& BT = exampleReport->getBugType();
Mike Stump1eb44332009-09-09 15:08:12 +00002347
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002348 OwningPtr<PathDiagnostic>
Ted Kremenek07189522012-04-04 18:11:35 +00002349 D(new PathDiagnostic(exampleReport->getDeclWithIssue(),
2350 exampleReport->getBugType().getName(),
Jordan Rose3a46f5f2012-08-31 00:36:26 +00002351 exampleReport->getDescription(),
2352 exampleReport->getShortDescription(/*Fallback=*/false),
Anna Zaks97bfb552013-01-08 00:25:29 +00002353 BT.getCategory(),
2354 exampleReport->getUniqueingLocation(),
2355 exampleReport->getUniqueingDecl()));
Ted Kremenekd49967f2009-04-29 21:58:13 +00002356
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002357 // Generate the full path diagnostic, using the generation scheme
Jordan Rosed632d6f2012-09-22 01:24:56 +00002358 // specified by the PathDiagnosticConsumer. Note that we have to generate
2359 // path diagnostics even for consumers which do not support paths, because
2360 // the BugReporterVisitors may mark this bug as a false positive.
2361 if (!bugReports.empty())
2362 if (!generatePathDiagnostic(*D.get(), PD, bugReports))
2363 return;
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002364
2365 // If the path is empty, generate a single step path with the location
2366 // of the issue.
2367 if (D->path.empty()) {
2368 PathDiagnosticLocation L = exampleReport->getLocation(getSourceManager());
2369 PathDiagnosticPiece *piece =
2370 new PathDiagnosticEventPiece(L, exampleReport->getDescription());
2371 BugReport::ranges_iterator Beg, End;
2372 llvm::tie(Beg, End) = exampleReport->getRanges();
2373 for ( ; Beg != End; ++Beg)
2374 piece->addRange(*Beg);
Jordan Rose3a46f5f2012-08-31 00:36:26 +00002375 D->setEndOfPath(piece);
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002376 }
2377
Ted Kremenek072192b2008-04-30 23:47:44 +00002378 // Get the meta data.
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002379 const BugReport::ExtraTextList &Meta = exampleReport->getExtraText();
Anna Zaks7f2531c2011-08-22 20:31:28 +00002380 for (BugReport::ExtraTextList::const_iterator i = Meta.begin(),
2381 e = Meta.end(); i != e; ++i) {
2382 D->addMeta(*i);
2383 }
Ted Kremenek75840e12008-04-18 01:56:37 +00002384
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002385 PD.HandlePathDiagnostic(D.take());
Ted Kremenek61f3e052008-04-03 04:42:52 +00002386}
Ted Kremenek57202072008-07-14 17:40:50 +00002387
Ted Kremenek07189522012-04-04 18:11:35 +00002388void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
Ted Kremenek07189522012-04-04 18:11:35 +00002389 StringRef name,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002390 StringRef category,
Anna Zaks590dd8e2011-09-20 21:38:35 +00002391 StringRef str, PathDiagnosticLocation Loc,
Ted Kremenek8c036c72008-09-20 04:23:38 +00002392 SourceRange* RBeg, unsigned NumRanges) {
Mike Stump1eb44332009-09-09 15:08:12 +00002393
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00002394 // 'BT' is owned by BugReporter.
2395 BugType *BT = getBugTypeForName(name, category);
Anna Zaks590dd8e2011-09-20 21:38:35 +00002396 BugReport *R = new BugReport(*BT, str, Loc);
Ted Kremenek07189522012-04-04 18:11:35 +00002397 R->setDeclWithIssue(DeclWithIssue);
Ted Kremenekcf118d42009-02-04 23:49:09 +00002398 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
Jordan Rose785950e2012-11-02 01:53:40 +00002399 emitReport(R);
Ted Kremenek57202072008-07-14 17:40:50 +00002400}
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00002401
Chris Lattner5f9e2722011-07-23 10:55:15 +00002402BugType *BugReporter::getBugTypeForName(StringRef name,
2403 StringRef category) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002404 SmallString<136> fullDesc;
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00002405 llvm::raw_svector_ostream(fullDesc) << name << ":" << category;
2406 llvm::StringMapEntry<BugType *> &
2407 entry = StrBugTypes.GetOrCreateValue(fullDesc);
2408 BugType *BT = entry.getValue();
2409 if (!BT) {
2410 BT = new BugType(name, category);
2411 entry.setValue(BT);
2412 }
2413 return BT;
2414}