BugReporter.cpp revision de7bc0d997cc69bd5c337ab82665c2f7ed989138
118cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien// BugReporter.cpp - Generate PathDiagnostics for Bugs ------------*- C++ -*--//
218cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien//
318cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien//                     The LLVM Compiler Infrastructure
418cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien//
518cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien// This file is distributed under the University of Illinois Open Source
618cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien// License. See LICENSE.TXT for details.
718cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien//
818cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien//===----------------------------------------------------------------------===//
918cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien//
1018cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien//  This file defines BugReporter, a utility class for generating
1118cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien//  PathDiagnostics.
1218cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien//
1318cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien//===----------------------------------------------------------------------===//
1418cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
1518cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#define DEBUG_TYPE "BugReporter"
1618cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
1718cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
1818cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "clang/AST/ASTContext.h"
1918cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "clang/AST/DeclObjC.h"
2018cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "clang/AST/Expr.h"
2118cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "clang/AST/ParentMap.h"
2218cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "clang/AST/StmtObjC.h"
2318cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "clang/Analysis/CFG.h"
2418cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "clang/Analysis/ProgramPoint.h"
2518cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "clang/Basic/SourceManager.h"
2618cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
2718cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
2818cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
2918cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "llvm/ADT/DenseMap.h"
3018cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "llvm/ADT/IntrusiveRefCntPtr.h"
3118cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "llvm/ADT/OwningPtr.h"
3218cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "llvm/ADT/STLExtras.h"
3318cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "llvm/ADT/SmallString.h"
3418cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "llvm/ADT/Statistic.h"
3518cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include "llvm/Support/raw_ostream.h"
3618cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien#include <queue>
3718cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
3818cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chienusing namespace clang;
3918cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chienusing namespace ento;
4018cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
4118cba562c8016f8095643b5dd8c4b34b294b62ddLogan ChienSTATISTIC(MaxBugClassSize,
4218cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien          "The maximum number of bug reports in the same equivalence class");
4318cba562c8016f8095643b5dd8c4b34b294b62ddLogan ChienSTATISTIC(MaxValidBugClassSize,
4418cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien          "The maximum number of bug reports in the same equivalence class "
4518cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien          "where at least one report is valid (not suppressed)");
4618cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
4718cba562c8016f8095643b5dd8c4b34b294b62ddLogan ChienBugReporterVisitor::~BugReporterVisitor() {}
4818cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
4918cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chienvoid BugReporterContext::anchor() {}
5018cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
5118cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien//===----------------------------------------------------------------------===//
5218cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien// Helper routines for walking the ExplodedGraph and fetching statements.
5318cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien//===----------------------------------------------------------------------===//
5418cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
5518cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chienstatic const Stmt *GetPreviousStmt(const ExplodedNode *N) {
5618cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  for (N = N->getFirstPred(); N; N = N->getFirstPred())
5718cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
5818cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien      return S;
5918cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
6018cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  return 0;
6118cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien}
6218cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
6318cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chienstatic inline const Stmt*
6418cba562c8016f8095643b5dd8c4b34b294b62ddLogan ChienGetCurrentOrPreviousStmt(const ExplodedNode *N) {
6518cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
6618cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    return S;
6718cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
6818cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  return GetPreviousStmt(N);
6918cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien}
7018cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
7118cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien//===----------------------------------------------------------------------===//
7218cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien// Diagnostic cleanup.
7318cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien//===----------------------------------------------------------------------===//
7418cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
7518cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chienstatic PathDiagnosticEventPiece *
7618cba562c8016f8095643b5dd8c4b34b294b62ddLogan ChieneventsDescribeSameCondition(PathDiagnosticEventPiece *X,
7718cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien                            PathDiagnosticEventPiece *Y) {
7818cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  // Prefer diagnostics that come from ConditionBRVisitor over
7918cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  // those that came from TrackConstraintBRVisitor.
8018cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  const void *tagPreferred = ConditionBRVisitor::getTag();
8118cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  const void *tagLesser = TrackConstraintBRVisitor::getTag();
8218cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
8318cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  if (X->getLocation() != Y->getLocation())
8418cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    return 0;
8518cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
8618cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  if (X->getTag() == tagPreferred && Y->getTag() == tagLesser)
8718cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    return X;
8818cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
8918cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  if (Y->getTag() == tagPreferred && X->getTag() == tagLesser)
9018cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    return Y;
9118cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
9218cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  return 0;
9318cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien}
9418cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
9518cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien/// An optimization pass over PathPieces that removes redundant diagnostics
9618cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien/// generated by both ConditionBRVisitor and TrackConstraintBRVisitor.  Both
9718cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien/// BugReporterVisitors use different methods to generate diagnostics, with
9818cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien/// one capable of emitting diagnostics in some cases but not in others.  This
9918cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien/// can lead to redundant diagnostic pieces at the same point in a path.
10018cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chienstatic void removeRedundantMsgs(PathPieces &path) {
10118cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  unsigned N = path.size();
10218cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  if (N < 2)
10318cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    return;
10418cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  // NOTE: this loop intentionally is not using an iterator.  Instead, we
10518cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  // are streaming the path and modifying it in place.  This is done by
10618cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  // grabbing the front, processing it, and if we decide to keep it append
10718cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  // it to the end of the path.  The entire path is processed in this way.
10818cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  for (unsigned i = 0; i < N; ++i) {
10918cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    IntrusiveRefCntPtr<PathDiagnosticPiece> piece(path.front());
11018cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    path.pop_front();
11118cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
11218cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    switch (piece->getKind()) {
11318cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien      case clang::ento::PathDiagnosticPiece::Call:
11418cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien        removeRedundantMsgs(cast<PathDiagnosticCallPiece>(piece)->path);
11518cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien        break;
11618cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien      case clang::ento::PathDiagnosticPiece::Macro:
11718cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien        removeRedundantMsgs(cast<PathDiagnosticMacroPiece>(piece)->subPieces);
11818cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien        break;
11918cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien      case clang::ento::PathDiagnosticPiece::ControlFlow:
12018cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien        break;
12118cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien      case clang::ento::PathDiagnosticPiece::Event: {
12218cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien        if (i == N-1)
12318cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien          break;
12418cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
12518cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien        if (PathDiagnosticEventPiece *nextEvent =
12618cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien            dyn_cast<PathDiagnosticEventPiece>(path.front().getPtr())) {
12718cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien          PathDiagnosticEventPiece *event =
12818cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien            cast<PathDiagnosticEventPiece>(piece);
12918cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien          // Check to see if we should keep one of the two pieces.  If we
13018cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien          // come up with a preference, record which piece to keep, and consume
13118cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien          // another piece from the path.
13218cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien          if (PathDiagnosticEventPiece *pieceToKeep =
13318cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien              eventsDescribeSameCondition(event, nextEvent)) {
13418cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien            piece = pieceToKeep;
13518cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien            path.pop_front();
13618cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien            ++i;
13718cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien          }
13818cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien        }
13918cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien        break;
14018cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien      }
14118cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    }
14218cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    path.push_back(piece);
14318cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  }
14418cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien}
14518cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
14618cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien/// A map from PathDiagnosticPiece to the LocationContext of the inlined
14718cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien/// function call it represents.
14818cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chientypedef llvm::DenseMap<const PathPieces *, const LocationContext *>
14918cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien        LocationContextMap;
15018cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
15118cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien/// Recursively scan through a path and prune out calls and macros pieces
15218cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien/// that aren't needed.  Return true if afterwards the path contains
15318cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien/// "interesting stuff" which means it shouldn't be pruned from the parent path.
15418cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chienstatic bool removeUnneededCalls(PathPieces &pieces, BugReport *R,
15518cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien                                LocationContextMap &LCM) {
15618cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  bool containsSomethingInteresting = false;
15718cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  const unsigned N = pieces.size();
15818cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
15918cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien  for (unsigned i = 0 ; i < N ; ++i) {
16018cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    // Remove the front piece from the path.  If it is still something we
16118cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    // want to keep once we are done, we will push it back on the end.
16218cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    IntrusiveRefCntPtr<PathDiagnosticPiece> piece(pieces.front());
16318cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    pieces.pop_front();
16418cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien
16518cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    // Throw away pieces with invalid locations. Note that we can't throw away
16618cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    // calls just yet because they might have something interesting inside them.
16718cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    // If so, their locations will be adjusted as necessary later.
16818cba562c8016f8095643b5dd8c4b34b294b62ddLogan Chien    if (piece->getKind() != PathDiagnosticPiece::Call &&
169        piece->getLocation().asLocation().isInvalid())
170      continue;
171
172    switch (piece->getKind()) {
173      case PathDiagnosticPiece::Call: {
174        PathDiagnosticCallPiece *call = cast<PathDiagnosticCallPiece>(piece);
175        // Check if the location context is interesting.
176        assert(LCM.count(&call->path));
177        if (R->isInteresting(LCM[&call->path])) {
178          containsSomethingInteresting = true;
179          break;
180        }
181
182        if (!removeUnneededCalls(call->path, R, LCM))
183          continue;
184
185        containsSomethingInteresting = true;
186        break;
187      }
188      case PathDiagnosticPiece::Macro: {
189        PathDiagnosticMacroPiece *macro = cast<PathDiagnosticMacroPiece>(piece);
190        if (!removeUnneededCalls(macro->subPieces, R, LCM))
191          continue;
192        containsSomethingInteresting = true;
193        break;
194      }
195      case PathDiagnosticPiece::Event: {
196        PathDiagnosticEventPiece *event = cast<PathDiagnosticEventPiece>(piece);
197
198        // We never throw away an event, but we do throw it away wholesale
199        // as part of a path if we throw the entire path away.
200        containsSomethingInteresting |= !event->isPrunable();
201        break;
202      }
203      case PathDiagnosticPiece::ControlFlow:
204        break;
205    }
206
207    pieces.push_back(piece);
208  }
209
210  return containsSomethingInteresting;
211}
212
213/// Recursively scan through a path and make sure that all call pieces have
214/// valid locations. Note that all other pieces with invalid locations should
215/// have already been pruned out.
216static void adjustCallLocations(PathPieces &Pieces,
217                                PathDiagnosticLocation *LastCallLocation = 0) {
218  for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E; ++I) {
219    PathDiagnosticCallPiece *Call = dyn_cast<PathDiagnosticCallPiece>(*I);
220
221    if (!Call) {
222      assert((*I)->getLocation().asLocation().isValid());
223      continue;
224    }
225
226    if (LastCallLocation) {
227      if (!Call->callEnter.asLocation().isValid() ||
228          Call->getCaller()->isImplicit())
229        Call->callEnter = *LastCallLocation;
230      if (!Call->callReturn.asLocation().isValid() ||
231          Call->getCaller()->isImplicit())
232        Call->callReturn = *LastCallLocation;
233    }
234
235    // Recursively clean out the subclass.  Keep this call around if
236    // it contains any informative diagnostics.
237    PathDiagnosticLocation *ThisCallLocation;
238    if (Call->callEnterWithin.asLocation().isValid() &&
239        !Call->getCallee()->isImplicit())
240      ThisCallLocation = &Call->callEnterWithin;
241    else
242      ThisCallLocation = &Call->callEnter;
243
244    assert(ThisCallLocation && "Outermost call has an invalid location");
245    adjustCallLocations(Call->path, ThisCallLocation);
246  }
247}
248
249//===----------------------------------------------------------------------===//
250// PathDiagnosticBuilder and its associated routines and helper objects.
251//===----------------------------------------------------------------------===//
252
253namespace {
254class NodeMapClosure : public BugReport::NodeResolver {
255  InterExplodedGraphMap &M;
256public:
257  NodeMapClosure(InterExplodedGraphMap &m) : M(m) {}
258
259  const ExplodedNode *getOriginalNode(const ExplodedNode *N) {
260    return M.lookup(N);
261  }
262};
263
264class PathDiagnosticBuilder : public BugReporterContext {
265  BugReport *R;
266  PathDiagnosticConsumer *PDC;
267  NodeMapClosure NMC;
268public:
269  const LocationContext *LC;
270
271  PathDiagnosticBuilder(GRBugReporter &br,
272                        BugReport *r, InterExplodedGraphMap &Backmap,
273                        PathDiagnosticConsumer *pdc)
274    : BugReporterContext(br),
275      R(r), PDC(pdc), NMC(Backmap), LC(r->getErrorNode()->getLocationContext())
276  {}
277
278  PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N);
279
280  PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream &os,
281                                            const ExplodedNode *N);
282
283  BugReport *getBugReport() { return R; }
284
285  Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); }
286
287  ParentMap& getParentMap() { return LC->getParentMap(); }
288
289  const Stmt *getParent(const Stmt *S) {
290    return getParentMap().getParent(S);
291  }
292
293  virtual NodeMapClosure& getNodeResolver() { return NMC; }
294
295  PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
296
297  PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const {
298    return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Extensive;
299  }
300
301  bool supportsLogicalOpControlFlow() const {
302    return PDC ? PDC->supportsLogicalOpControlFlow() : true;
303  }
304};
305} // end anonymous namespace
306
307PathDiagnosticLocation
308PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) {
309  if (const Stmt *S = PathDiagnosticLocation::getNextStmt(N))
310    return PathDiagnosticLocation(S, getSourceManager(), LC);
311
312  return PathDiagnosticLocation::createDeclEnd(N->getLocationContext(),
313                                               getSourceManager());
314}
315
316PathDiagnosticLocation
317PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream &os,
318                                          const ExplodedNode *N) {
319
320  // Slow, but probably doesn't matter.
321  if (os.str().empty())
322    os << ' ';
323
324  const PathDiagnosticLocation &Loc = ExecutionContinues(N);
325
326  if (Loc.asStmt())
327    os << "Execution continues on line "
328       << getSourceManager().getExpansionLineNumber(Loc.asLocation())
329       << '.';
330  else {
331    os << "Execution jumps to the end of the ";
332    const Decl *D = N->getLocationContext()->getDecl();
333    if (isa<ObjCMethodDecl>(D))
334      os << "method";
335    else if (isa<FunctionDecl>(D))
336      os << "function";
337    else {
338      assert(isa<BlockDecl>(D));
339      os << "anonymous block";
340    }
341    os << '.';
342  }
343
344  return Loc;
345}
346
347static bool IsNested(const Stmt *S, ParentMap &PM) {
348  if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
349    return true;
350
351  const Stmt *Parent = PM.getParentIgnoreParens(S);
352
353  if (Parent)
354    switch (Parent->getStmtClass()) {
355      case Stmt::ForStmtClass:
356      case Stmt::DoStmtClass:
357      case Stmt::WhileStmtClass:
358        return true;
359      default:
360        break;
361    }
362
363  return false;
364}
365
366PathDiagnosticLocation
367PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
368  assert(S && "Null Stmt *passed to getEnclosingStmtLocation");
369  ParentMap &P = getParentMap();
370  SourceManager &SMgr = getSourceManager();
371
372  while (IsNested(S, P)) {
373    const Stmt *Parent = P.getParentIgnoreParens(S);
374
375    if (!Parent)
376      break;
377
378    switch (Parent->getStmtClass()) {
379      case Stmt::BinaryOperatorClass: {
380        const BinaryOperator *B = cast<BinaryOperator>(Parent);
381        if (B->isLogicalOp())
382          return PathDiagnosticLocation(S, SMgr, LC);
383        break;
384      }
385      case Stmt::CompoundStmtClass:
386      case Stmt::StmtExprClass:
387        return PathDiagnosticLocation(S, SMgr, LC);
388      case Stmt::ChooseExprClass:
389        // Similar to '?' if we are referring to condition, just have the edge
390        // point to the entire choose expression.
391        if (cast<ChooseExpr>(Parent)->getCond() == S)
392          return PathDiagnosticLocation(Parent, SMgr, LC);
393        else
394          return PathDiagnosticLocation(S, SMgr, LC);
395      case Stmt::BinaryConditionalOperatorClass:
396      case Stmt::ConditionalOperatorClass:
397        // For '?', if we are referring to condition, just have the edge point
398        // to the entire '?' expression.
399        if (cast<AbstractConditionalOperator>(Parent)->getCond() == S)
400          return PathDiagnosticLocation(Parent, SMgr, LC);
401        else
402          return PathDiagnosticLocation(S, SMgr, LC);
403      case Stmt::DoStmtClass:
404          return PathDiagnosticLocation(S, SMgr, LC);
405      case Stmt::ForStmtClass:
406        if (cast<ForStmt>(Parent)->getBody() == S)
407          return PathDiagnosticLocation(S, SMgr, LC);
408        break;
409      case Stmt::IfStmtClass:
410        if (cast<IfStmt>(Parent)->getCond() != S)
411          return PathDiagnosticLocation(S, SMgr, LC);
412        break;
413      case Stmt::ObjCForCollectionStmtClass:
414        if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
415          return PathDiagnosticLocation(S, SMgr, LC);
416        break;
417      case Stmt::WhileStmtClass:
418        if (cast<WhileStmt>(Parent)->getCond() != S)
419          return PathDiagnosticLocation(S, SMgr, LC);
420        break;
421      default:
422        break;
423    }
424
425    S = Parent;
426  }
427
428  assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
429
430  // Special case: DeclStmts can appear in for statement declarations, in which
431  //  case the ForStmt is the context.
432  if (isa<DeclStmt>(S)) {
433    if (const Stmt *Parent = P.getParent(S)) {
434      switch (Parent->getStmtClass()) {
435        case Stmt::ForStmtClass:
436        case Stmt::ObjCForCollectionStmtClass:
437          return PathDiagnosticLocation(Parent, SMgr, LC);
438        default:
439          break;
440      }
441    }
442  }
443  else if (isa<BinaryOperator>(S)) {
444    // Special case: the binary operator represents the initialization
445    // code in a for statement (this can happen when the variable being
446    // initialized is an old variable.
447    if (const ForStmt *FS =
448          dyn_cast_or_null<ForStmt>(P.getParentIgnoreParens(S))) {
449      if (FS->getInit() == S)
450        return PathDiagnosticLocation(FS, SMgr, LC);
451    }
452  }
453
454  return PathDiagnosticLocation(S, SMgr, LC);
455}
456
457//===----------------------------------------------------------------------===//
458// "Visitors only" path diagnostic generation algorithm.
459//===----------------------------------------------------------------------===//
460static bool GenerateVisitorsOnlyPathDiagnostic(PathDiagnostic &PD,
461                                               PathDiagnosticBuilder &PDB,
462                                               const ExplodedNode *N,
463                                      ArrayRef<BugReporterVisitor *> visitors) {
464  // All path generation skips the very first node (the error node).
465  // This is because there is special handling for the end-of-path note.
466  N = N->getFirstPred();
467  if (!N)
468    return true;
469
470  BugReport *R = PDB.getBugReport();
471  while (const ExplodedNode *Pred = N->getFirstPred()) {
472    for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(),
473                                                  E = visitors.end();
474         I != E; ++I) {
475      // Visit all the node pairs, but throw the path pieces away.
476      PathDiagnosticPiece *Piece = (*I)->VisitNode(N, Pred, PDB, *R);
477      delete Piece;
478    }
479
480    N = Pred;
481  }
482
483  return R->isValid();
484}
485
486//===----------------------------------------------------------------------===//
487// "Minimal" path diagnostic generation algorithm.
488//===----------------------------------------------------------------------===//
489typedef std::pair<PathDiagnosticCallPiece*, const ExplodedNode*> StackDiagPair;
490typedef SmallVector<StackDiagPair, 6> StackDiagVector;
491
492static void updateStackPiecesWithMessage(PathDiagnosticPiece *P,
493                                         StackDiagVector &CallStack) {
494  // If the piece contains a special message, add it to all the call
495  // pieces on the active stack.
496  if (PathDiagnosticEventPiece *ep =
497        dyn_cast<PathDiagnosticEventPiece>(P)) {
498
499    if (ep->hasCallStackHint())
500      for (StackDiagVector::iterator I = CallStack.begin(),
501                                     E = CallStack.end(); I != E; ++I) {
502        PathDiagnosticCallPiece *CP = I->first;
503        const ExplodedNode *N = I->second;
504        std::string stackMsg = ep->getCallStackMessage(N);
505
506        // The last message on the path to final bug is the most important
507        // one. Since we traverse the path backwards, do not add the message
508        // if one has been previously added.
509        if  (!CP->hasCallStackMessage())
510          CP->setCallStackMessage(stackMsg);
511      }
512  }
513}
514
515static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM);
516
517static bool GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
518                                          PathDiagnosticBuilder &PDB,
519                                          const ExplodedNode *N,
520                                          LocationContextMap &LCM,
521                                      ArrayRef<BugReporterVisitor *> visitors) {
522
523  SourceManager& SMgr = PDB.getSourceManager();
524  const LocationContext *LC = PDB.LC;
525  const ExplodedNode *NextNode = N->pred_empty()
526                                        ? NULL : *(N->pred_begin());
527
528  StackDiagVector CallStack;
529
530  while (NextNode) {
531    N = NextNode;
532    PDB.LC = N->getLocationContext();
533    NextNode = N->getFirstPred();
534
535    ProgramPoint P = N->getLocation();
536
537    do {
538      if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
539        PathDiagnosticCallPiece *C =
540            PathDiagnosticCallPiece::construct(N, *CE, SMgr);
541        // Record the mapping from call piece to LocationContext.
542        LCM[&C->path] = CE->getCalleeContext();
543        PD.getActivePath().push_front(C);
544        PD.pushActivePath(&C->path);
545        CallStack.push_back(StackDiagPair(C, N));
546        break;
547      }
548
549      if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
550        // Flush all locations, and pop the active path.
551        bool VisitedEntireCall = PD.isWithinCall();
552        PD.popActivePath();
553
554        // Either we just added a bunch of stuff to the top-level path, or
555        // we have a previous CallExitEnd.  If the former, it means that the
556        // path terminated within a function call.  We must then take the
557        // current contents of the active path and place it within
558        // a new PathDiagnosticCallPiece.
559        PathDiagnosticCallPiece *C;
560        if (VisitedEntireCall) {
561          C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
562        } else {
563          const Decl *Caller = CE->getLocationContext()->getDecl();
564          C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
565          // Record the mapping from call piece to LocationContext.
566          LCM[&C->path] = CE->getCalleeContext();
567        }
568
569        C->setCallee(*CE, SMgr);
570        if (!CallStack.empty()) {
571          assert(CallStack.back().first == C);
572          CallStack.pop_back();
573        }
574        break;
575      }
576
577      if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
578        const CFGBlock *Src = BE->getSrc();
579        const CFGBlock *Dst = BE->getDst();
580        const Stmt *T = Src->getTerminator();
581
582        if (!T)
583          break;
584
585        PathDiagnosticLocation Start =
586            PathDiagnosticLocation::createBegin(T, SMgr,
587                N->getLocationContext());
588
589        switch (T->getStmtClass()) {
590        default:
591          break;
592
593        case Stmt::GotoStmtClass:
594        case Stmt::IndirectGotoStmtClass: {
595          const Stmt *S = PathDiagnosticLocation::getNextStmt(N);
596
597          if (!S)
598            break;
599
600          std::string sbuf;
601          llvm::raw_string_ostream os(sbuf);
602          const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
603
604          os << "Control jumps to line "
605              << End.asLocation().getExpansionLineNumber();
606          PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
607              Start, End, os.str()));
608          break;
609        }
610
611        case Stmt::SwitchStmtClass: {
612          // Figure out what case arm we took.
613          std::string sbuf;
614          llvm::raw_string_ostream os(sbuf);
615
616          if (const Stmt *S = Dst->getLabel()) {
617            PathDiagnosticLocation End(S, SMgr, LC);
618
619            switch (S->getStmtClass()) {
620            default:
621              os << "No cases match in the switch statement. "
622              "Control jumps to line "
623              << End.asLocation().getExpansionLineNumber();
624              break;
625            case Stmt::DefaultStmtClass:
626              os << "Control jumps to the 'default' case at line "
627              << End.asLocation().getExpansionLineNumber();
628              break;
629
630            case Stmt::CaseStmtClass: {
631              os << "Control jumps to 'case ";
632              const CaseStmt *Case = cast<CaseStmt>(S);
633              const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
634
635              // Determine if it is an enum.
636              bool GetRawInt = true;
637
638              if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
639                // FIXME: Maybe this should be an assertion.  Are there cases
640                // were it is not an EnumConstantDecl?
641                const EnumConstantDecl *D =
642                    dyn_cast<EnumConstantDecl>(DR->getDecl());
643
644                if (D) {
645                  GetRawInt = false;
646                  os << *D;
647                }
648              }
649
650              if (GetRawInt)
651                os << LHS->EvaluateKnownConstInt(PDB.getASTContext());
652
653              os << ":'  at line "
654                  << End.asLocation().getExpansionLineNumber();
655              break;
656            }
657            }
658            PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
659                Start, End, os.str()));
660          }
661          else {
662            os << "'Default' branch taken. ";
663            const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
664            PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
665                Start, End, os.str()));
666          }
667
668          break;
669        }
670
671        case Stmt::BreakStmtClass:
672        case Stmt::ContinueStmtClass: {
673          std::string sbuf;
674          llvm::raw_string_ostream os(sbuf);
675          PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
676          PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
677              Start, End, os.str()));
678          break;
679        }
680
681        // Determine control-flow for ternary '?'.
682        case Stmt::BinaryConditionalOperatorClass:
683        case Stmt::ConditionalOperatorClass: {
684          std::string sbuf;
685          llvm::raw_string_ostream os(sbuf);
686          os << "'?' condition is ";
687
688          if (*(Src->succ_begin()+1) == Dst)
689            os << "false";
690          else
691            os << "true";
692
693          PathDiagnosticLocation End = PDB.ExecutionContinues(N);
694
695          if (const Stmt *S = End.asStmt())
696            End = PDB.getEnclosingStmtLocation(S);
697
698          PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
699              Start, End, os.str()));
700          break;
701        }
702
703        // Determine control-flow for short-circuited '&&' and '||'.
704        case Stmt::BinaryOperatorClass: {
705          if (!PDB.supportsLogicalOpControlFlow())
706            break;
707
708          const BinaryOperator *B = cast<BinaryOperator>(T);
709          std::string sbuf;
710          llvm::raw_string_ostream os(sbuf);
711          os << "Left side of '";
712
713          if (B->getOpcode() == BO_LAnd) {
714            os << "&&" << "' is ";
715
716            if (*(Src->succ_begin()+1) == Dst) {
717              os << "false";
718              PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
719              PathDiagnosticLocation Start =
720                  PathDiagnosticLocation::createOperatorLoc(B, SMgr);
721              PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
722                  Start, End, os.str()));
723            }
724            else {
725              os << "true";
726              PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
727              PathDiagnosticLocation End = PDB.ExecutionContinues(N);
728              PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
729                  Start, End, os.str()));
730            }
731          }
732          else {
733            assert(B->getOpcode() == BO_LOr);
734            os << "||" << "' is ";
735
736            if (*(Src->succ_begin()+1) == Dst) {
737              os << "false";
738              PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
739              PathDiagnosticLocation End = PDB.ExecutionContinues(N);
740              PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
741                  Start, End, os.str()));
742            }
743            else {
744              os << "true";
745              PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
746              PathDiagnosticLocation Start =
747                  PathDiagnosticLocation::createOperatorLoc(B, SMgr);
748              PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
749                  Start, End, os.str()));
750            }
751          }
752
753          break;
754        }
755
756        case Stmt::DoStmtClass:  {
757          if (*(Src->succ_begin()) == Dst) {
758            std::string sbuf;
759            llvm::raw_string_ostream os(sbuf);
760
761            os << "Loop condition is true. ";
762            PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
763
764            if (const Stmt *S = End.asStmt())
765              End = PDB.getEnclosingStmtLocation(S);
766
767            PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
768                Start, End, os.str()));
769          }
770          else {
771            PathDiagnosticLocation End = PDB.ExecutionContinues(N);
772
773            if (const Stmt *S = End.asStmt())
774              End = PDB.getEnclosingStmtLocation(S);
775
776            PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
777                Start, End, "Loop condition is false.  Exiting loop"));
778          }
779
780          break;
781        }
782
783        case Stmt::WhileStmtClass:
784        case Stmt::ForStmtClass: {
785          if (*(Src->succ_begin()+1) == Dst) {
786            std::string sbuf;
787            llvm::raw_string_ostream os(sbuf);
788
789            os << "Loop condition is false. ";
790            PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
791            if (const Stmt *S = End.asStmt())
792              End = PDB.getEnclosingStmtLocation(S);
793
794            PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
795                Start, End, os.str()));
796          }
797          else {
798            PathDiagnosticLocation End = PDB.ExecutionContinues(N);
799            if (const Stmt *S = End.asStmt())
800              End = PDB.getEnclosingStmtLocation(S);
801
802            PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
803                Start, End, "Loop condition is true.  Entering loop body"));
804          }
805
806          break;
807        }
808
809        case Stmt::IfStmtClass: {
810          PathDiagnosticLocation End = PDB.ExecutionContinues(N);
811
812          if (const Stmt *S = End.asStmt())
813            End = PDB.getEnclosingStmtLocation(S);
814
815          if (*(Src->succ_begin()+1) == Dst)
816            PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
817                Start, End, "Taking false branch"));
818          else
819            PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
820                Start, End, "Taking true branch"));
821
822          break;
823        }
824        }
825      }
826    } while(0);
827
828    if (NextNode) {
829      // Add diagnostic pieces from custom visitors.
830      BugReport *R = PDB.getBugReport();
831      for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(),
832                                                    E = visitors.end();
833           I != E; ++I) {
834        if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) {
835          PD.getActivePath().push_front(p);
836          updateStackPiecesWithMessage(p, CallStack);
837        }
838      }
839    }
840  }
841
842  if (!PDB.getBugReport()->isValid())
843    return false;
844
845  // After constructing the full PathDiagnostic, do a pass over it to compact
846  // PathDiagnosticPieces that occur within a macro.
847  CompactPathDiagnostic(PD.getMutablePieces(), PDB.getSourceManager());
848  return true;
849}
850
851//===----------------------------------------------------------------------===//
852// "Extensive" PathDiagnostic generation.
853//===----------------------------------------------------------------------===//
854
855static bool IsControlFlowExpr(const Stmt *S) {
856  const Expr *E = dyn_cast<Expr>(S);
857
858  if (!E)
859    return false;
860
861  E = E->IgnoreParenCasts();
862
863  if (isa<AbstractConditionalOperator>(E))
864    return true;
865
866  if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
867    if (B->isLogicalOp())
868      return true;
869
870  return false;
871}
872
873namespace {
874class ContextLocation : public PathDiagnosticLocation {
875  bool IsDead;
876public:
877  ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
878    : PathDiagnosticLocation(L), IsDead(isdead) {}
879
880  void markDead() { IsDead = true; }
881  bool isDead() const { return IsDead; }
882};
883
884static PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
885                                              const LocationContext *LC,
886                                              bool firstCharOnly = false) {
887  if (const Stmt *S = L.asStmt()) {
888    const Stmt *Original = S;
889    while (1) {
890      // Adjust the location for some expressions that are best referenced
891      // by one of their subexpressions.
892      switch (S->getStmtClass()) {
893        default:
894          break;
895        case Stmt::ParenExprClass:
896        case Stmt::GenericSelectionExprClass:
897          S = cast<Expr>(S)->IgnoreParens();
898          firstCharOnly = true;
899          continue;
900        case Stmt::BinaryConditionalOperatorClass:
901        case Stmt::ConditionalOperatorClass:
902          S = cast<AbstractConditionalOperator>(S)->getCond();
903          firstCharOnly = true;
904          continue;
905        case Stmt::ChooseExprClass:
906          S = cast<ChooseExpr>(S)->getCond();
907          firstCharOnly = true;
908          continue;
909        case Stmt::BinaryOperatorClass:
910          S = cast<BinaryOperator>(S)->getLHS();
911          firstCharOnly = true;
912          continue;
913      }
914
915      break;
916    }
917
918    if (S != Original)
919      L = PathDiagnosticLocation(S, L.getManager(), LC);
920  }
921
922  if (firstCharOnly)
923    L  = PathDiagnosticLocation::createSingleLocation(L);
924
925  return L;
926}
927
928class EdgeBuilder {
929  std::vector<ContextLocation> CLocs;
930  typedef std::vector<ContextLocation>::iterator iterator;
931  PathDiagnostic &PD;
932  PathDiagnosticBuilder &PDB;
933  PathDiagnosticLocation PrevLoc;
934
935  bool IsConsumedExpr(const PathDiagnosticLocation &L);
936
937  bool containsLocation(const PathDiagnosticLocation &Container,
938                        const PathDiagnosticLocation &Containee);
939
940  PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
941
942
943
944  void popLocation() {
945    if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
946      // For contexts, we only one the first character as the range.
947      rawAddEdge(cleanUpLocation(CLocs.back(), PDB.LC, true));
948    }
949    CLocs.pop_back();
950  }
951
952public:
953  EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
954    : PD(pd), PDB(pdb) {
955
956      // If the PathDiagnostic already has pieces, add the enclosing statement
957      // of the first piece as a context as well.
958      if (!PD.path.empty()) {
959        PrevLoc = (*PD.path.begin())->getLocation();
960
961        if (const Stmt *S = PrevLoc.asStmt())
962          addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
963      }
964  }
965
966  ~EdgeBuilder() {
967    while (!CLocs.empty()) popLocation();
968
969    // Finally, add an initial edge from the start location of the first
970    // statement (if it doesn't already exist).
971    PathDiagnosticLocation L = PathDiagnosticLocation::createDeclBegin(
972                                                       PDB.LC,
973                                                       PDB.getSourceManager());
974    if (L.isValid())
975      rawAddEdge(L);
976  }
977
978  void flushLocations() {
979    while (!CLocs.empty())
980      popLocation();
981    PrevLoc = PathDiagnosticLocation();
982  }
983
984  void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false,
985               bool IsPostJump = false);
986
987  void rawAddEdge(PathDiagnosticLocation NewLoc);
988
989  void addContext(const Stmt *S);
990  void addContext(const PathDiagnosticLocation &L);
991  void addExtendedContext(const Stmt *S);
992};
993} // end anonymous namespace
994
995
996PathDiagnosticLocation
997EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
998  if (const Stmt *S = L.asStmt()) {
999    if (IsControlFlowExpr(S))
1000      return L;
1001
1002    return PDB.getEnclosingStmtLocation(S);
1003  }
1004
1005  return L;
1006}
1007
1008bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
1009                                   const PathDiagnosticLocation &Containee) {
1010
1011  if (Container == Containee)
1012    return true;
1013
1014  if (Container.asDecl())
1015    return true;
1016
1017  if (const Stmt *S = Containee.asStmt())
1018    if (const Stmt *ContainerS = Container.asStmt()) {
1019      while (S) {
1020        if (S == ContainerS)
1021          return true;
1022        S = PDB.getParent(S);
1023      }
1024      return false;
1025    }
1026
1027  // Less accurate: compare using source ranges.
1028  SourceRange ContainerR = Container.asRange();
1029  SourceRange ContaineeR = Containee.asRange();
1030
1031  SourceManager &SM = PDB.getSourceManager();
1032  SourceLocation ContainerRBeg = SM.getExpansionLoc(ContainerR.getBegin());
1033  SourceLocation ContainerREnd = SM.getExpansionLoc(ContainerR.getEnd());
1034  SourceLocation ContaineeRBeg = SM.getExpansionLoc(ContaineeR.getBegin());
1035  SourceLocation ContaineeREnd = SM.getExpansionLoc(ContaineeR.getEnd());
1036
1037  unsigned ContainerBegLine = SM.getExpansionLineNumber(ContainerRBeg);
1038  unsigned ContainerEndLine = SM.getExpansionLineNumber(ContainerREnd);
1039  unsigned ContaineeBegLine = SM.getExpansionLineNumber(ContaineeRBeg);
1040  unsigned ContaineeEndLine = SM.getExpansionLineNumber(ContaineeREnd);
1041
1042  assert(ContainerBegLine <= ContainerEndLine);
1043  assert(ContaineeBegLine <= ContaineeEndLine);
1044
1045  return (ContainerBegLine <= ContaineeBegLine &&
1046          ContainerEndLine >= ContaineeEndLine &&
1047          (ContainerBegLine != ContaineeBegLine ||
1048           SM.getExpansionColumnNumber(ContainerRBeg) <=
1049           SM.getExpansionColumnNumber(ContaineeRBeg)) &&
1050          (ContainerEndLine != ContaineeEndLine ||
1051           SM.getExpansionColumnNumber(ContainerREnd) >=
1052           SM.getExpansionColumnNumber(ContaineeREnd)));
1053}
1054
1055void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
1056  if (!PrevLoc.isValid()) {
1057    PrevLoc = NewLoc;
1058    return;
1059  }
1060
1061  const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc, PDB.LC);
1062  const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc, PDB.LC);
1063
1064  if (PrevLocClean.asLocation().isInvalid()) {
1065    PrevLoc = NewLoc;
1066    return;
1067  }
1068
1069  if (NewLocClean.asLocation() == PrevLocClean.asLocation())
1070    return;
1071
1072  // FIXME: Ignore intra-macro edges for now.
1073  if (NewLocClean.asLocation().getExpansionLoc() ==
1074      PrevLocClean.asLocation().getExpansionLoc())
1075    return;
1076
1077  PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
1078  PrevLoc = NewLoc;
1079}
1080
1081void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd,
1082                          bool IsPostJump) {
1083
1084  if (!alwaysAdd && NewLoc.asLocation().isMacroID())
1085    return;
1086
1087  const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
1088
1089  while (!CLocs.empty()) {
1090    ContextLocation &TopContextLoc = CLocs.back();
1091
1092    // Is the top location context the same as the one for the new location?
1093    if (TopContextLoc == CLoc) {
1094      if (alwaysAdd) {
1095        if (IsConsumedExpr(TopContextLoc))
1096          TopContextLoc.markDead();
1097
1098        rawAddEdge(NewLoc);
1099      }
1100
1101      if (IsPostJump)
1102        TopContextLoc.markDead();
1103      return;
1104    }
1105
1106    if (containsLocation(TopContextLoc, CLoc)) {
1107      if (alwaysAdd) {
1108        rawAddEdge(NewLoc);
1109
1110        if (IsConsumedExpr(CLoc)) {
1111          CLocs.push_back(ContextLocation(CLoc, /*IsDead=*/true));
1112          return;
1113        }
1114      }
1115
1116      CLocs.push_back(ContextLocation(CLoc, /*IsDead=*/IsPostJump));
1117      return;
1118    }
1119
1120    // Context does not contain the location.  Flush it.
1121    popLocation();
1122  }
1123
1124  // If we reach here, there is no enclosing context.  Just add the edge.
1125  rawAddEdge(NewLoc);
1126}
1127
1128bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
1129  if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
1130    return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
1131
1132  return false;
1133}
1134
1135void EdgeBuilder::addExtendedContext(const Stmt *S) {
1136  if (!S)
1137    return;
1138
1139  const Stmt *Parent = PDB.getParent(S);
1140  while (Parent) {
1141    if (isa<CompoundStmt>(Parent))
1142      Parent = PDB.getParent(Parent);
1143    else
1144      break;
1145  }
1146
1147  if (Parent) {
1148    switch (Parent->getStmtClass()) {
1149      case Stmt::DoStmtClass:
1150      case Stmt::ObjCAtSynchronizedStmtClass:
1151        addContext(Parent);
1152      default:
1153        break;
1154    }
1155  }
1156
1157  addContext(S);
1158}
1159
1160void EdgeBuilder::addContext(const Stmt *S) {
1161  if (!S)
1162    return;
1163
1164  PathDiagnosticLocation L(S, PDB.getSourceManager(), PDB.LC);
1165  addContext(L);
1166}
1167
1168void EdgeBuilder::addContext(const PathDiagnosticLocation &L) {
1169  while (!CLocs.empty()) {
1170    const PathDiagnosticLocation &TopContextLoc = CLocs.back();
1171
1172    // Is the top location context the same as the one for the new location?
1173    if (TopContextLoc == L)
1174      return;
1175
1176    if (containsLocation(TopContextLoc, L)) {
1177      CLocs.push_back(L);
1178      return;
1179    }
1180
1181    // Context does not contain the location.  Flush it.
1182    popLocation();
1183  }
1184
1185  CLocs.push_back(L);
1186}
1187
1188// Cone-of-influence: support the reverse propagation of "interesting" symbols
1189// and values by tracing interesting calculations backwards through evaluated
1190// expressions along a path.  This is probably overly complicated, but the idea
1191// is that if an expression computed an "interesting" value, the child
1192// expressions are are also likely to be "interesting" as well (which then
1193// propagates to the values they in turn compute).  This reverse propagation
1194// is needed to track interesting correlations across function call boundaries,
1195// where formal arguments bind to actual arguments, etc.  This is also needed
1196// because the constraint solver sometimes simplifies certain symbolic values
1197// into constants when appropriate, and this complicates reasoning about
1198// interesting values.
1199typedef llvm::DenseSet<const Expr *> InterestingExprs;
1200
1201static void reversePropagateIntererstingSymbols(BugReport &R,
1202                                                InterestingExprs &IE,
1203                                                const ProgramState *State,
1204                                                const Expr *Ex,
1205                                                const LocationContext *LCtx) {
1206  SVal V = State->getSVal(Ex, LCtx);
1207  if (!(R.isInteresting(V) || IE.count(Ex)))
1208    return;
1209
1210  switch (Ex->getStmtClass()) {
1211    default:
1212      if (!isa<CastExpr>(Ex))
1213        break;
1214      // Fall through.
1215    case Stmt::BinaryOperatorClass:
1216    case Stmt::UnaryOperatorClass: {
1217      for (Stmt::const_child_iterator CI = Ex->child_begin(),
1218            CE = Ex->child_end();
1219            CI != CE; ++CI) {
1220        if (const Expr *child = dyn_cast_or_null<Expr>(*CI)) {
1221          IE.insert(child);
1222          SVal ChildV = State->getSVal(child, LCtx);
1223          R.markInteresting(ChildV);
1224        }
1225        break;
1226      }
1227    }
1228  }
1229
1230  R.markInteresting(V);
1231}
1232
1233static void reversePropagateInterestingSymbols(BugReport &R,
1234                                               InterestingExprs &IE,
1235                                               const ProgramState *State,
1236                                               const LocationContext *CalleeCtx,
1237                                               const LocationContext *CallerCtx)
1238{
1239  // FIXME: Handle non-CallExpr-based CallEvents.
1240  const StackFrameContext *Callee = CalleeCtx->getCurrentStackFrame();
1241  const Stmt *CallSite = Callee->getCallSite();
1242  if (const CallExpr *CE = dyn_cast_or_null<CallExpr>(CallSite)) {
1243    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CalleeCtx->getDecl())) {
1244      FunctionDecl::param_const_iterator PI = FD->param_begin(),
1245                                         PE = FD->param_end();
1246      CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end();
1247      for (; AI != AE && PI != PE; ++AI, ++PI) {
1248        if (const Expr *ArgE = *AI) {
1249          if (const ParmVarDecl *PD = *PI) {
1250            Loc LV = State->getLValue(PD, CalleeCtx);
1251            if (R.isInteresting(LV) || R.isInteresting(State->getRawSVal(LV)))
1252              IE.insert(ArgE);
1253          }
1254        }
1255      }
1256    }
1257  }
1258}
1259
1260//===----------------------------------------------------------------------===//
1261// Functions for determining if a loop was executed 0 times.
1262//===----------------------------------------------------------------------===//
1263
1264static bool isLoop(const Stmt *Term) {
1265  switch (Term->getStmtClass()) {
1266    case Stmt::ForStmtClass:
1267    case Stmt::WhileStmtClass:
1268    case Stmt::ObjCForCollectionStmtClass:
1269      return true;
1270    default:
1271      // Note that we intentionally do not include do..while here.
1272      return false;
1273  }
1274}
1275
1276static bool isJumpToFalseBranch(const BlockEdge *BE) {
1277  const CFGBlock *Src = BE->getSrc();
1278  assert(Src->succ_size() == 2);
1279  return (*(Src->succ_begin()+1) == BE->getDst());
1280}
1281
1282/// Return true if the terminator is a loop and the destination is the
1283/// false branch.
1284static bool isLoopJumpPastBody(const Stmt *Term, const BlockEdge *BE) {
1285  if (!isLoop(Term))
1286    return false;
1287
1288  // Did we take the false branch?
1289  return isJumpToFalseBranch(BE);
1290}
1291
1292static bool isContainedByStmt(ParentMap &PM, const Stmt *S, const Stmt *SubS) {
1293  while (SubS) {
1294    if (SubS == S)
1295      return true;
1296    SubS = PM.getParent(SubS);
1297  }
1298  return false;
1299}
1300
1301static const Stmt *getStmtBeforeCond(ParentMap &PM, const Stmt *Term,
1302                                     const ExplodedNode *N) {
1303  while (N) {
1304    Optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>();
1305    if (SP) {
1306      const Stmt *S = SP->getStmt();
1307      if (!isContainedByStmt(PM, Term, S))
1308        return S;
1309    }
1310    N = N->getFirstPred();
1311  }
1312  return 0;
1313}
1314
1315static bool isInLoopBody(ParentMap &PM, const Stmt *S, const Stmt *Term) {
1316  const Stmt *LoopBody = 0;
1317  switch (Term->getStmtClass()) {
1318    case Stmt::ForStmtClass: {
1319      const ForStmt *FS = cast<ForStmt>(Term);
1320      if (isContainedByStmt(PM, FS->getInc(), S))
1321        return true;
1322      LoopBody = FS->getBody();
1323      break;
1324    }
1325    case Stmt::ObjCForCollectionStmtClass: {
1326      const ObjCForCollectionStmt *FC = cast<ObjCForCollectionStmt>(Term);
1327      LoopBody = FC->getBody();
1328      break;
1329    }
1330    case Stmt::WhileStmtClass:
1331      LoopBody = cast<WhileStmt>(Term)->getBody();
1332      break;
1333    default:
1334      return false;
1335  }
1336  return isContainedByStmt(PM, LoopBody, S);
1337}
1338
1339//===----------------------------------------------------------------------===//
1340// Top-level logic for generating extensive path diagnostics.
1341//===----------------------------------------------------------------------===//
1342
1343static bool GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
1344                                            PathDiagnosticBuilder &PDB,
1345                                            const ExplodedNode *N,
1346                                            LocationContextMap &LCM,
1347                                      ArrayRef<BugReporterVisitor *> visitors) {
1348  EdgeBuilder EB(PD, PDB);
1349  const SourceManager& SM = PDB.getSourceManager();
1350  StackDiagVector CallStack;
1351  InterestingExprs IE;
1352
1353  const ExplodedNode *NextNode = N->pred_empty() ? NULL : *(N->pred_begin());
1354  while (NextNode) {
1355    N = NextNode;
1356    NextNode = N->getFirstPred();
1357    ProgramPoint P = N->getLocation();
1358
1359    do {
1360      if (Optional<PostStmt> PS = P.getAs<PostStmt>()) {
1361        if (const Expr *Ex = PS->getStmtAs<Expr>())
1362          reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1363                                              N->getState().getPtr(), Ex,
1364                                              N->getLocationContext());
1365      }
1366
1367      if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
1368        const Stmt *S = CE->getCalleeContext()->getCallSite();
1369        if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) {
1370            reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1371                                                N->getState().getPtr(), Ex,
1372                                                N->getLocationContext());
1373        }
1374
1375        PathDiagnosticCallPiece *C =
1376          PathDiagnosticCallPiece::construct(N, *CE, SM);
1377        LCM[&C->path] = CE->getCalleeContext();
1378
1379        EB.addEdge(C->callReturn, /*AlwaysAdd=*/true, /*IsPostJump=*/true);
1380        EB.flushLocations();
1381
1382        PD.getActivePath().push_front(C);
1383        PD.pushActivePath(&C->path);
1384        CallStack.push_back(StackDiagPair(C, N));
1385        break;
1386      }
1387
1388      // Pop the call hierarchy if we are done walking the contents
1389      // of a function call.
1390      if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
1391        // Add an edge to the start of the function.
1392        const Decl *D = CE->getCalleeContext()->getDecl();
1393        PathDiagnosticLocation pos =
1394          PathDiagnosticLocation::createBegin(D, SM);
1395        EB.addEdge(pos);
1396
1397        // Flush all locations, and pop the active path.
1398        bool VisitedEntireCall = PD.isWithinCall();
1399        EB.flushLocations();
1400        PD.popActivePath();
1401        PDB.LC = N->getLocationContext();
1402
1403        // Either we just added a bunch of stuff to the top-level path, or
1404        // we have a previous CallExitEnd.  If the former, it means that the
1405        // path terminated within a function call.  We must then take the
1406        // current contents of the active path and place it within
1407        // a new PathDiagnosticCallPiece.
1408        PathDiagnosticCallPiece *C;
1409        if (VisitedEntireCall) {
1410          C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
1411        } else {
1412          const Decl *Caller = CE->getLocationContext()->getDecl();
1413          C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
1414          LCM[&C->path] = CE->getCalleeContext();
1415        }
1416
1417        C->setCallee(*CE, SM);
1418        EB.addContext(C->getLocation());
1419
1420        if (!CallStack.empty()) {
1421          assert(CallStack.back().first == C);
1422          CallStack.pop_back();
1423        }
1424        break;
1425      }
1426
1427      // Note that is important that we update the LocationContext
1428      // after looking at CallExits.  CallExit basically adds an
1429      // edge in the *caller*, so we don't want to update the LocationContext
1430      // too soon.
1431      PDB.LC = N->getLocationContext();
1432
1433      // Block edges.
1434      if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
1435        // Does this represent entering a call?  If so, look at propagating
1436        // interesting symbols across call boundaries.
1437        if (NextNode) {
1438          const LocationContext *CallerCtx = NextNode->getLocationContext();
1439          const LocationContext *CalleeCtx = PDB.LC;
1440          if (CallerCtx != CalleeCtx) {
1441            reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
1442                                               N->getState().getPtr(),
1443                                               CalleeCtx, CallerCtx);
1444          }
1445        }
1446
1447        // Are we jumping to the head of a loop?  Add a special diagnostic.
1448        if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
1449          PathDiagnosticLocation L(Loop, SM, PDB.LC);
1450          const CompoundStmt *CS = NULL;
1451
1452          if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1453            CS = dyn_cast<CompoundStmt>(FS->getBody());
1454          else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1455            CS = dyn_cast<CompoundStmt>(WS->getBody());
1456
1457          PathDiagnosticEventPiece *p =
1458            new PathDiagnosticEventPiece(L,
1459                                        "Looping back to the head of the loop");
1460          p->setPrunable(true);
1461
1462          EB.addEdge(p->getLocation(), true);
1463          PD.getActivePath().push_front(p);
1464
1465          if (CS) {
1466            PathDiagnosticLocation BL =
1467              PathDiagnosticLocation::createEndBrace(CS, SM);
1468            EB.addEdge(BL);
1469          }
1470        }
1471
1472        const CFGBlock *BSrc = BE->getSrc();
1473        ParentMap &PM = PDB.getParentMap();
1474
1475        if (const Stmt *Term = BSrc->getTerminator()) {
1476          // Are we jumping past the loop body without ever executing the
1477          // loop (because the condition was false)?
1478          if (isLoopJumpPastBody(Term, &*BE) &&
1479              !isInLoopBody(PM,
1480                            getStmtBeforeCond(PM,
1481                                              BSrc->getTerminatorCondition(),
1482                                              N),
1483                            Term)) {
1484            PathDiagnosticLocation L(Term, SM, PDB.LC);
1485            PathDiagnosticEventPiece *PE =
1486                new PathDiagnosticEventPiece(L, "Loop body executed 0 times");
1487            PE->setPrunable(true);
1488
1489            EB.addEdge(PE->getLocation(), true);
1490            PD.getActivePath().push_front(PE);
1491          }
1492
1493          // In any case, add the terminator as the current statement
1494          // context for control edges.
1495          EB.addContext(Term);
1496        }
1497
1498        break;
1499      }
1500
1501      if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) {
1502        Optional<CFGElement> First = BE->getFirstElement();
1503        if (Optional<CFGStmt> S = First ? First->getAs<CFGStmt>() : None) {
1504          const Stmt *stmt = S->getStmt();
1505          if (IsControlFlowExpr(stmt)) {
1506            // Add the proper context for '&&', '||', and '?'.
1507            EB.addContext(stmt);
1508          }
1509          else
1510            EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt());
1511        }
1512
1513        break;
1514      }
1515
1516
1517    } while (0);
1518
1519    if (!NextNode)
1520      continue;
1521
1522    // Add pieces from custom visitors.
1523    BugReport *R = PDB.getBugReport();
1524    for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(),
1525                                                  E = visitors.end();
1526         I != E; ++I) {
1527      if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) {
1528        const PathDiagnosticLocation &Loc = p->getLocation();
1529        EB.addEdge(Loc, true);
1530        PD.getActivePath().push_front(p);
1531        updateStackPiecesWithMessage(p, CallStack);
1532
1533        if (const Stmt *S = Loc.asStmt())
1534          EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1535      }
1536    }
1537  }
1538
1539  return PDB.getBugReport()->isValid();
1540}
1541
1542/// \brief Adds a sanitized control-flow diagnostic edge to a path.
1543static void addEdgeToPath(PathPieces &path,
1544                          PathDiagnosticLocation &PrevLoc,
1545                          PathDiagnosticLocation NewLoc,
1546                          const LocationContext *LC) {
1547  if (!NewLoc.isValid())
1548    return;
1549
1550  SourceLocation NewLocL = NewLoc.asLocation();
1551  if (NewLocL.isInvalid() || NewLocL.isMacroID())
1552    return;
1553
1554  if (!PrevLoc.isValid()) {
1555    PrevLoc = NewLoc;
1556    return;
1557  }
1558
1559  // FIXME: ignore intra-macro edges for now.
1560  if (NewLoc.asLocation().getExpansionLoc() ==
1561      PrevLoc.asLocation().getExpansionLoc())
1562    return;
1563
1564  path.push_front(new PathDiagnosticControlFlowPiece(NewLoc,
1565                                                     PrevLoc));
1566  PrevLoc = NewLoc;
1567}
1568
1569/// A customized wrapper for CFGBlock::getTerminatorCondition()
1570/// which returns the element for ObjCForCollectionStmts.
1571static const Stmt *getTerminatorCondition(const CFGBlock *B) {
1572  const Stmt *S = B->getTerminatorCondition();
1573  if (const ObjCForCollectionStmt *FS =
1574      dyn_cast_or_null<ObjCForCollectionStmt>(S))
1575    return FS->getElement();
1576  return S;
1577}
1578
1579static bool
1580GenerateAlternateExtensivePathDiagnostic(PathDiagnostic& PD,
1581                                         PathDiagnosticBuilder &PDB,
1582                                         const ExplodedNode *N,
1583                                         LocationContextMap &LCM,
1584                                      ArrayRef<BugReporterVisitor *> visitors) {
1585
1586  BugReport *report = PDB.getBugReport();
1587  const SourceManager& SM = PDB.getSourceManager();
1588  StackDiagVector CallStack;
1589  InterestingExprs IE;
1590
1591  // Record the last location for a given visited stack frame.
1592  llvm::DenseMap<const StackFrameContext *, PathDiagnosticLocation>
1593    PrevLocMap;
1594  PrevLocMap[N->getLocationContext()->getCurrentStackFrame()] =
1595    PD.getLocation();
1596
1597  const ExplodedNode *NextNode = N->getFirstPred();
1598  while (NextNode) {
1599    N = NextNode;
1600    NextNode = N->getFirstPred();
1601    ProgramPoint P = N->getLocation();
1602
1603    do {
1604      // Have we encountered an entrance to a call?  It may be
1605      // the case that we have not encountered a matching
1606      // call exit before this point.  This means that the path
1607      // terminated within the call itself.
1608      if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
1609        // Did we visit an entire call?
1610        bool VisitedEntireCall = PD.isWithinCall();
1611        PD.popActivePath();
1612
1613        PathDiagnosticCallPiece *C;
1614        if (VisitedEntireCall) {
1615          PathDiagnosticPiece *P = PD.getActivePath().front().getPtr();
1616          C = cast<PathDiagnosticCallPiece>(P);
1617        } else {
1618          const Decl *Caller = CE->getLocationContext()->getDecl();
1619          C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
1620
1621          // Since we just transferred the path over to the call piece,
1622          // reset the mapping from active to location context.
1623          assert(PD.getActivePath().size() == 1 &&
1624                 PD.getActivePath().front() == C);
1625          LCM[&PD.getActivePath()] = 0;
1626
1627          // Record the location context mapping for the path within
1628          // the call.
1629          assert(LCM[&C->path] == 0 ||
1630                 LCM[&C->path] == CE->getCalleeContext());
1631          LCM[&C->path] = CE->getCalleeContext();
1632
1633          // If this is the first item in the active path, record
1634          // the new mapping from active path to location context.
1635          const LocationContext *&NewLC = LCM[&PD.getActivePath()];
1636          if (!NewLC) {
1637            NewLC = N->getLocationContext();
1638          }
1639          PDB.LC = NewLC;
1640
1641          // Update the previous location in the active path
1642          // since we just created the call piece lazily.
1643          PrevLocMap[PDB.LC->getCurrentStackFrame()] = C->getLocation();
1644        }
1645        C->setCallee(*CE, SM);
1646
1647        if (!CallStack.empty()) {
1648          assert(CallStack.back().first == C);
1649          CallStack.pop_back();
1650        }
1651        break;
1652      }
1653
1654      // Query the location context here and the previous location
1655      // as processing CallEnter may change the active path.
1656      PDB.LC = N->getLocationContext();
1657
1658      // Get the previous location for the current active
1659      // location context.  All edges will be based on this
1660      // location, and it will be updated in place.
1661      PathDiagnosticLocation &PrevLoc =
1662        PrevLocMap[PDB.LC->getCurrentStackFrame()];
1663
1664      // Record the mapping from the active path to the location
1665      // context.
1666      assert(!LCM[&PD.getActivePath()] ||
1667             LCM[&PD.getActivePath()] == PDB.LC);
1668      LCM[&PD.getActivePath()] = PDB.LC;
1669
1670      // Have we encountered an exit from a function call?
1671      if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
1672        const Stmt *S = CE->getCalleeContext()->getCallSite();
1673        // Propagate the interesting symbols accordingly.
1674        if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) {
1675          reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1676                                              N->getState().getPtr(), Ex,
1677                                              N->getLocationContext());
1678        }
1679
1680        // We are descending into a call (backwards).  Construct
1681        // a new call piece to contain the path pieces for that call.
1682        PathDiagnosticCallPiece *C =
1683          PathDiagnosticCallPiece::construct(N, *CE, SM);
1684
1685        // Record the location context for this call piece.
1686        LCM[&C->path] = CE->getCalleeContext();
1687
1688        // Add the edge to the return site.
1689        addEdgeToPath(PD.getActivePath(), PrevLoc, C->callReturn, PDB.LC);
1690        PD.getActivePath().push_front(C);
1691
1692        // Make the contents of the call the active path for now.
1693        PD.pushActivePath(&C->path);
1694        CallStack.push_back(StackDiagPair(C, N));
1695        break;
1696      }
1697
1698      if (Optional<PostStmt> PS = P.getAs<PostStmt>()) {
1699        // For expressions, make sure we propagate the
1700        // interesting symbols correctly.
1701        if (const Expr *Ex = PS->getStmtAs<Expr>())
1702          reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1703                                              N->getState().getPtr(), Ex,
1704                                              N->getLocationContext());
1705
1706        // Add an edge.  If this is an ObjCForCollectionStmt do
1707        // not add an edge here as it appears in the CFG both
1708        // as a terminator and as a terminator condition.
1709        if (!isa<ObjCForCollectionStmt>(PS->getStmt())) {
1710          PathDiagnosticLocation L =
1711            PathDiagnosticLocation(PS->getStmt(), SM, PDB.LC);
1712          addEdgeToPath(PD.getActivePath(), PrevLoc, L, PDB.LC);
1713        }
1714        break;
1715      }
1716
1717      // Block edges.
1718      if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
1719        // Does this represent entering a call?  If so, look at propagating
1720        // interesting symbols across call boundaries.
1721        if (NextNode) {
1722          const LocationContext *CallerCtx = NextNode->getLocationContext();
1723          const LocationContext *CalleeCtx = PDB.LC;
1724          if (CallerCtx != CalleeCtx) {
1725            reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
1726                                               N->getState().getPtr(),
1727                                               CalleeCtx, CallerCtx);
1728          }
1729        }
1730
1731        // Are we jumping to the head of a loop?  Add a special diagnostic.
1732        if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
1733          PathDiagnosticLocation L(Loop, SM, PDB.LC);
1734          const CompoundStmt *CS = NULL;
1735
1736          if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1737            CS = dyn_cast<CompoundStmt>(FS->getBody());
1738          else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1739            CS = dyn_cast<CompoundStmt>(WS->getBody());
1740          else if (const ObjCForCollectionStmt *OFS =
1741                   dyn_cast<ObjCForCollectionStmt>(Loop)) {
1742            CS = dyn_cast<CompoundStmt>(OFS->getBody());
1743          }
1744
1745          PathDiagnosticEventPiece *p =
1746            new PathDiagnosticEventPiece(L, "Looping back to the head "
1747                                            "of the loop");
1748          p->setPrunable(true);
1749
1750          addEdgeToPath(PD.getActivePath(), PrevLoc, p->getLocation(), PDB.LC);
1751          PD.getActivePath().push_front(p);
1752
1753          if (CS) {
1754            addEdgeToPath(PD.getActivePath(), PrevLoc,
1755                          PathDiagnosticLocation::createEndBrace(CS, SM),
1756                          PDB.LC);
1757          }
1758        }
1759
1760        const CFGBlock *BSrc = BE->getSrc();
1761        ParentMap &PM = PDB.getParentMap();
1762
1763        if (const Stmt *Term = BSrc->getTerminator()) {
1764          // Are we jumping past the loop body without ever executing the
1765          // loop (because the condition was false)?
1766          if (isLoop(Term)) {
1767            const Stmt *TermCond = getTerminatorCondition(BSrc);
1768            bool IsInLoopBody =
1769              isInLoopBody(PM, getStmtBeforeCond(PM, TermCond, N), Term);
1770
1771            const char *str = 0;
1772
1773            if (isJumpToFalseBranch(&*BE)) {
1774              if (!IsInLoopBody) {
1775                str = "Loop body executed 0 times";
1776              }
1777            }
1778            else {
1779              str = "Entering loop body";
1780            }
1781
1782            if (str) {
1783              PathDiagnosticLocation L(TermCond, SM, PDB.LC);
1784              PathDiagnosticEventPiece *PE =
1785                new PathDiagnosticEventPiece(L, str);
1786              PE->setPrunable(true);
1787              addEdgeToPath(PD.getActivePath(), PrevLoc,
1788                            PE->getLocation(), PDB.LC);
1789              PD.getActivePath().push_front(PE);
1790            }
1791          }
1792          else if (isa<BreakStmt>(Term) || isa<ContinueStmt>(Term) ||
1793                   isa<GotoStmt>(Term)) {
1794            PathDiagnosticLocation L(Term, SM, PDB.LC);
1795            addEdgeToPath(PD.getActivePath(), PrevLoc, L, PDB.LC);
1796          }
1797        }
1798        break;
1799      }
1800    } while (0);
1801
1802    if (!NextNode)
1803      continue;
1804
1805    // Since the active path may have been updated prior
1806    // to this point, query the active location context now.
1807    PathDiagnosticLocation &PrevLoc =
1808      PrevLocMap[PDB.LC->getCurrentStackFrame()];
1809
1810    // Add pieces from custom visitors.
1811    for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(),
1812         E = visitors.end();
1813         I != E; ++I) {
1814      if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *report)) {
1815        addEdgeToPath(PD.getActivePath(), PrevLoc, p->getLocation(), PDB.LC);
1816        PD.getActivePath().push_front(p);
1817        updateStackPiecesWithMessage(p, CallStack);
1818      }
1819    }
1820  }
1821
1822  return report->isValid();
1823}
1824
1825const Stmt *getLocStmt(PathDiagnosticLocation L) {
1826  if (!L.isValid())
1827    return 0;
1828  return L.asStmt();
1829}
1830
1831const Stmt *getStmtParent(const Stmt *S, ParentMap &PM) {
1832  if (!S)
1833    return 0;
1834
1835  while (true) {
1836    S = PM.getParentIgnoreParens(S);
1837
1838    if (!S)
1839      break;
1840
1841    if (isa<ExprWithCleanups>(S) ||
1842        isa<CXXBindTemporaryExpr>(S) ||
1843        isa<SubstNonTypeTemplateParmExpr>(S))
1844      continue;
1845
1846    break;
1847  }
1848
1849  return S;
1850}
1851
1852static bool isConditionForTerminator(const Stmt *S, const Stmt *Cond) {
1853  switch (S->getStmtClass()) {
1854    case Stmt::BinaryOperatorClass: {
1855      const BinaryOperator *BO = cast<BinaryOperator>(S);
1856      if (!BO->isLogicalOp())
1857        return false;
1858      return BO->getLHS() == Cond || BO->getRHS() == Cond;
1859    }
1860    case Stmt::IfStmtClass:
1861      return cast<IfStmt>(S)->getCond() == Cond;
1862    case Stmt::ForStmtClass:
1863      return cast<ForStmt>(S)->getCond() == Cond;
1864    case Stmt::WhileStmtClass:
1865      return cast<WhileStmt>(S)->getCond() == Cond;
1866    case Stmt::DoStmtClass:
1867      return cast<DoStmt>(S)->getCond() == Cond;
1868    case Stmt::ChooseExprClass:
1869      return cast<ChooseExpr>(S)->getCond() == Cond;
1870    case Stmt::IndirectGotoStmtClass:
1871      return cast<IndirectGotoStmt>(S)->getTarget() == Cond;
1872    case Stmt::SwitchStmtClass:
1873      return cast<SwitchStmt>(S)->getCond() == Cond;
1874    case Stmt::BinaryConditionalOperatorClass:
1875      return cast<BinaryConditionalOperator>(S)->getCond() == Cond;
1876    case Stmt::ConditionalOperatorClass: {
1877      const ConditionalOperator *CO = cast<ConditionalOperator>(S);
1878      return CO->getCond() == Cond ||
1879             CO->getLHS() == Cond ||
1880             CO->getRHS() == Cond;
1881    }
1882    case Stmt::ObjCForCollectionStmtClass:
1883      return cast<ObjCForCollectionStmt>(S)->getElement() == Cond;
1884    default:
1885      return false;
1886  }
1887}
1888
1889static bool isIncrementOrInitInForLoop(const Stmt *S, const Stmt *FL) {
1890  const ForStmt *FS = dyn_cast<ForStmt>(FL);
1891  if (!FS)
1892    return false;
1893  return FS->getInc() == S || FS->getInit() == S;
1894}
1895
1896typedef llvm::DenseSet<const PathDiagnosticCallPiece *>
1897        OptimizedCallsSet;
1898
1899void PathPieces::dump() const {
1900  unsigned index = 0;
1901  for (PathPieces::const_iterator I = begin(), E = end(); I != E; ++I ) {
1902    llvm::errs() << "[" << index++ << "]";
1903
1904    switch ((*I)->getKind()) {
1905    case PathDiagnosticPiece::Call:
1906      llvm::errs() << "  CALL\n--------------\n";
1907
1908      if (const Stmt *SLoc = getLocStmt((*I)->getLocation())) {
1909        SLoc->dump();
1910      } else {
1911        const PathDiagnosticCallPiece *Call = cast<PathDiagnosticCallPiece>(*I);
1912        if (const NamedDecl *ND = dyn_cast<NamedDecl>(Call->getCallee()))
1913          llvm::errs() << *ND << "\n";
1914      }
1915      break;
1916    case PathDiagnosticPiece::Event:
1917      llvm::errs() << "  EVENT\n--------------\n";
1918      llvm::errs() << (*I)->getString() << "\n";
1919      if (const Stmt *SLoc = getLocStmt((*I)->getLocation())) {
1920        llvm::errs() << " ---- at ----\n";
1921        SLoc->dump();
1922      }
1923      break;
1924    case PathDiagnosticPiece::Macro:
1925      llvm::errs() << "  MACRO\n--------------\n";
1926      // FIXME: print which macro is being invoked.
1927      break;
1928    case PathDiagnosticPiece::ControlFlow: {
1929      const PathDiagnosticControlFlowPiece *CP =
1930        cast<PathDiagnosticControlFlowPiece>(*I);
1931      llvm::errs() << "  CONTROL\n--------------\n";
1932
1933      if (const Stmt *s1Start = getLocStmt(CP->getStartLocation()))
1934        s1Start->dump();
1935      else
1936        llvm::errs() << "NULL\n";
1937
1938      llvm::errs() << " ---- to ----\n";
1939
1940      if (const Stmt *s1End = getLocStmt(CP->getEndLocation()))
1941        s1End->dump();
1942      else
1943        llvm::errs() << "NULL\n";
1944
1945      break;
1946    }
1947    }
1948
1949    llvm::errs() << "\n";
1950  }
1951}
1952
1953/// \brief Return true if X is contained by Y.
1954static bool lexicalContains(ParentMap &PM,
1955                            const Stmt *X,
1956                            const Stmt *Y) {
1957  while (X) {
1958    if (X == Y)
1959      return true;
1960    X = PM.getParent(X);
1961  }
1962  return false;
1963}
1964
1965// Remove short edges on the same line less than 3 columns in difference.
1966static void removePunyEdges(PathPieces &path,
1967                            SourceManager &SM,
1968                            ParentMap &PM) {
1969
1970  bool erased = false;
1971
1972  for (PathPieces::iterator I = path.begin(), E = path.end(); I != E;
1973       erased ? I : ++I) {
1974
1975    erased = false;
1976
1977    PathDiagnosticControlFlowPiece *PieceI =
1978      dyn_cast<PathDiagnosticControlFlowPiece>(*I);
1979
1980    if (!PieceI)
1981      continue;
1982
1983    const Stmt *start = getLocStmt(PieceI->getStartLocation());
1984    const Stmt *end   = getLocStmt(PieceI->getEndLocation());
1985
1986    if (!start || !end)
1987      continue;
1988
1989    const Stmt *endParent = PM.getParent(end);
1990    if (!endParent)
1991      continue;
1992
1993    if (isConditionForTerminator(end, endParent))
1994      continue;
1995
1996    bool Invalid = false;
1997    FullSourceLoc StartL(start->getLocStart(), SM);
1998    FullSourceLoc EndL(end->getLocStart(), SM);
1999
2000    unsigned startLine = StartL.getSpellingLineNumber(&Invalid);
2001    if (Invalid)
2002      continue;
2003
2004    unsigned endLine = EndL.getSpellingLineNumber(&Invalid);
2005    if (Invalid)
2006      continue;
2007
2008    if (startLine != endLine)
2009      continue;
2010
2011    unsigned startCol = StartL.getSpellingColumnNumber(&Invalid);
2012    if (Invalid)
2013      continue;
2014
2015    unsigned endCol = EndL.getSpellingColumnNumber(&Invalid);
2016    if (Invalid)
2017      continue;
2018
2019    if (abs(startCol - endCol) <= 2) {
2020      PathPieces::iterator PieceToErase = I;
2021      ++I;
2022      erased = true;
2023      path.erase(PieceToErase);
2024      continue;
2025    }
2026  }
2027}
2028
2029static bool optimizeEdges(PathPieces &path, SourceManager &SM,
2030                          OptimizedCallsSet &OCS,
2031                          LocationContextMap &LCM) {
2032  bool hasChanges = false;
2033  const LocationContext *LC = LCM[&path];
2034  assert(LC);
2035  ParentMap &PM = LC->getParentMap();
2036  bool isFirst = true;
2037
2038  for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ) {
2039    bool wasFirst = isFirst;
2040    isFirst = false;
2041
2042    // Optimize subpaths.
2043    if (PathDiagnosticCallPiece *CallI = dyn_cast<PathDiagnosticCallPiece>(*I)){
2044      // Record the fact that a call has been optimized so we only do the
2045      // effort once.
2046      if (!OCS.count(CallI)) {
2047        while (optimizeEdges(CallI->path, SM, OCS, LCM)) {}
2048        OCS.insert(CallI);
2049      }
2050      ++I;
2051      continue;
2052    }
2053
2054    // Pattern match the current piece and its successor.
2055    PathDiagnosticControlFlowPiece *PieceI =
2056      dyn_cast<PathDiagnosticControlFlowPiece>(*I);
2057
2058    if (!PieceI) {
2059      ++I;
2060      continue;
2061    }
2062
2063    const Stmt *s1Start = getLocStmt(PieceI->getStartLocation());
2064    const Stmt *s1End   = getLocStmt(PieceI->getEndLocation());
2065    const Stmt *level1 = getStmtParent(s1Start, PM);
2066    const Stmt *level2 = getStmtParent(s1End, PM);
2067
2068    if (wasFirst) {
2069      // If the first edge (in isolation) is just a transition from
2070      // an expression to a parent expression then eliminate that edge.
2071      if (level1 && level2 && level2 == PM.getParent(level1)) {
2072        path.erase(I);
2073        // Since we are erasing the current edge at the start of the
2074        // path, just return now so we start analyzing the start of the path
2075        // again.
2076        return true;
2077      }
2078
2079      // If the first edge (in isolation) is a transition from the
2080      // initialization or increment in a for loop then remove it.
2081      if (level1 && isIncrementOrInitInForLoop(s1Start, level1)) {
2082        path.erase(I);
2083        return true;
2084      }
2085    }
2086
2087    PathPieces::iterator NextI = I; ++NextI;
2088    if (NextI == E)
2089      break;
2090
2091    PathDiagnosticControlFlowPiece *PieceNextI =
2092      dyn_cast<PathDiagnosticControlFlowPiece>(*NextI);
2093
2094    if (!PieceNextI) {
2095      ++I;
2096      continue;
2097    }
2098
2099    const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation());
2100    const Stmt *s2End   = getLocStmt(PieceNextI->getEndLocation());
2101    const Stmt *level3 = getStmtParent(s2Start, PM);
2102    const Stmt *level4 = getStmtParent(s2End, PM);
2103
2104    // Rule I.
2105    //
2106    // If we have two consecutive control edges whose end/begin locations
2107    // are at the same level (e.g. statements or top-level expressions within
2108    // a compound statement, or siblings share a single ancestor expression),
2109    // then merge them if they have no interesting intermediate event.
2110    //
2111    // For example:
2112    //
2113    // (1.1 -> 1.2) -> (1.2 -> 1.3) becomes (1.1 -> 1.3) because the common
2114    // parent is '1'.  Here 'x.y.z' represents the hierarchy of statements.
2115    //
2116    // NOTE: this will be limited later in cases where we add barriers
2117    // to prevent this optimization.
2118    //
2119    if (level1 && level1 == level2 && level1 == level3 && level1 == level4) {
2120      PieceI->setEndLocation(PieceNextI->getEndLocation());
2121      path.erase(NextI);
2122      hasChanges = true;
2123      continue;
2124    }
2125
2126    // Rule II.
2127    //
2128    // Eliminate edges between subexpressions and parent expressions
2129    // when the subexpression is consumed.
2130    //
2131    // NOTE: this will be limited later in cases where we add barriers
2132    // to prevent this optimization.
2133    //
2134    if (s1End && s1End == s2Start && level2) {
2135      bool removeEdge = false;
2136      // Remove edges into the increment or initialization of a
2137      // loop that have no interleaving event.  This means that
2138      // they aren't interesting.
2139      if (isIncrementOrInitInForLoop(s1End, level2))
2140        removeEdge = true;
2141      // Next only consider edges that are not anchored on
2142      // the condition of a terminator.  This are intermediate edges
2143      // that we might want to trim.
2144      else if (!isConditionForTerminator(level2, s1End)) {
2145        // Trim edges on expressions that are consumed by
2146        // the parent expression.
2147        if (isa<Expr>(s1End) && PM.isConsumedExpr(cast<Expr>(s1End))) {
2148          removeEdge = true;
2149        }
2150        // Trim edges where a lexical containment doesn't exist.
2151        // For example:
2152        //
2153        //  X -> Y -> Z
2154        //
2155        // If 'Z' lexically contains Y (it is an ancestor) and
2156        // 'X' does not lexically contain Y (it is a descendant OR
2157        // it has no lexical relationship at all) then trim.
2158        //
2159        // This can eliminate edges where we dive into a subexpression
2160        // and then pop back out, etc.
2161        else if (s1Start && s2End &&
2162                 lexicalContains(PM, s2Start, s2End) &&
2163                 !lexicalContains(PM, s1End, s1Start)) {
2164          removeEdge = true;
2165        }
2166      }
2167
2168      if (removeEdge) {
2169        PieceI->setEndLocation(PieceNextI->getEndLocation());
2170        path.erase(NextI);
2171        hasChanges = true;
2172        continue;
2173      }
2174    }
2175
2176    // Optimize edges for ObjC fast-enumeration loops.
2177    //
2178    // (X -> collection) -> (collection -> element)
2179    //
2180    // becomes:
2181    //
2182    // (X -> element)
2183    if (s1End == s2Start) {
2184      const ObjCForCollectionStmt *FS =
2185        dyn_cast_or_null<ObjCForCollectionStmt>(level3);
2186      if (FS && FS->getCollection()->IgnoreParens() == s2Start &&
2187          s2End == FS->getElement()) {
2188        PieceI->setEndLocation(PieceNextI->getEndLocation());
2189        path.erase(NextI);
2190        hasChanges = true;
2191        continue;
2192      }
2193    }
2194
2195    // No changes at this index?  Move to the next one.
2196    ++I;
2197  }
2198
2199  if (!hasChanges) {
2200    // Remove any puny edges left over after primary optimization pass.
2201    removePunyEdges(path, SM, PM);
2202  }
2203
2204  return hasChanges;
2205}
2206
2207static void adjustBranchEdges(PathPieces &pieces, LocationContextMap &LCM,
2208                            SourceManager &SM) {
2209  // Retrieve the parent map for this path.
2210  const LocationContext *LC = LCM[&pieces];
2211  ParentMap &PM = LC->getParentMap();
2212  PathPieces::iterator Prev = pieces.end();
2213  for (PathPieces::iterator I = pieces.begin(), E = pieces.end(); I != E;
2214       Prev = I, ++I) {
2215    // Adjust edges in subpaths.
2216    if (PathDiagnosticCallPiece *Call = dyn_cast<PathDiagnosticCallPiece>(*I)) {
2217      adjustBranchEdges(Call->path, LCM, SM);
2218      continue;
2219    }
2220
2221    PathDiagnosticControlFlowPiece *PieceI =
2222      dyn_cast<PathDiagnosticControlFlowPiece>(*I);
2223
2224    if (!PieceI)
2225      continue;
2226
2227    // We are looking at two edges.  Is the second one incident
2228    // on an expression (or subexpression) of a branch condition.
2229    const Stmt *Dst = getLocStmt(PieceI->getEndLocation());
2230    const Stmt *Src = getLocStmt(PieceI->getStartLocation());
2231
2232    if (!Dst || !Src)
2233      continue;
2234
2235    const Stmt *Branch = 0;
2236    const Stmt *S = Dst;
2237    while (const Stmt *Parent = getStmtParent(S, PM)) {
2238      if (const ForStmt *FS = dyn_cast<ForStmt>(Parent)) {
2239        if (FS->getCond()->IgnoreParens() == S)
2240          Branch = FS;
2241        break;
2242      }
2243      if (const WhileStmt *WS = dyn_cast<WhileStmt>(Parent)) {
2244        if (WS->getCond()->IgnoreParens() == S)
2245          Branch = WS;
2246        break;
2247      }
2248      if (const IfStmt *IS = dyn_cast<IfStmt>(Parent)) {
2249        if (IS->getCond()->IgnoreParens() == S)
2250          Branch = IS;
2251        break;
2252      }
2253      if (const ObjCForCollectionStmt *OFS =
2254          dyn_cast<ObjCForCollectionStmt>(Parent)) {
2255        if (OFS->getElement() == S)
2256          Branch = OFS;
2257        break;
2258      }
2259
2260      S = Parent;
2261    }
2262
2263    // If 'Branch' is non-null we have found a match where we have an edge
2264    // incident on the condition of a if/for/while statement.
2265    if (!Branch)
2266      continue;
2267
2268    // If the current source of the edge is the if/for/while, then there is
2269    // nothing left to be done.
2270    if (Src == Branch)
2271      continue;
2272
2273    // Now look at the previous edge.  We want to know if this was in the same
2274    // "level" as the for statement.
2275    const Stmt *SrcParent = getStmtParent(Src, PM);
2276    const Stmt *BranchParent = getStmtParent(Branch, PM);
2277    if (SrcParent && SrcParent == BranchParent) {
2278      PathDiagnosticLocation L(Branch, SM, LC);
2279      bool needsEdge = true;
2280
2281      if (Prev != E) {
2282        if (PathDiagnosticControlFlowPiece *P =
2283            dyn_cast<PathDiagnosticControlFlowPiece>(*Prev)) {
2284          const Stmt *PrevSrc = getLocStmt(P->getStartLocation());
2285          if (PrevSrc) {
2286            const Stmt *PrevSrcParent = getStmtParent(PrevSrc, PM);
2287            if (PrevSrcParent == BranchParent) {
2288              P->setEndLocation(L);
2289              needsEdge = false;
2290            }
2291          }
2292        }
2293      }
2294
2295      if (needsEdge) {
2296        PathDiagnosticControlFlowPiece *P =
2297          new PathDiagnosticControlFlowPiece(PieceI->getStartLocation(), L);
2298        pieces.insert(I, P);
2299      }
2300
2301      PieceI->setStartLocation(L);
2302    }
2303  }
2304}
2305
2306//===----------------------------------------------------------------------===//
2307// Methods for BugType and subclasses.
2308//===----------------------------------------------------------------------===//
2309BugType::~BugType() { }
2310
2311void BugType::FlushReports(BugReporter &BR) {}
2312
2313void BuiltinBug::anchor() {}
2314
2315//===----------------------------------------------------------------------===//
2316// Methods for BugReport and subclasses.
2317//===----------------------------------------------------------------------===//
2318
2319void BugReport::NodeResolver::anchor() {}
2320
2321void BugReport::addVisitor(BugReporterVisitor* visitor) {
2322  if (!visitor)
2323    return;
2324
2325  llvm::FoldingSetNodeID ID;
2326  visitor->Profile(ID);
2327  void *InsertPos;
2328
2329  if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
2330    delete visitor;
2331    return;
2332  }
2333
2334  CallbacksSet.InsertNode(visitor, InsertPos);
2335  Callbacks.push_back(visitor);
2336  ++ConfigurationChangeToken;
2337}
2338
2339BugReport::~BugReport() {
2340  for (visitor_iterator I = visitor_begin(), E = visitor_end(); I != E; ++I) {
2341    delete *I;
2342  }
2343  while (!interestingSymbols.empty()) {
2344    popInterestingSymbolsAndRegions();
2345  }
2346}
2347
2348const Decl *BugReport::getDeclWithIssue() const {
2349  if (DeclWithIssue)
2350    return DeclWithIssue;
2351
2352  const ExplodedNode *N = getErrorNode();
2353  if (!N)
2354    return 0;
2355
2356  const LocationContext *LC = N->getLocationContext();
2357  return LC->getCurrentStackFrame()->getDecl();
2358}
2359
2360void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
2361  hash.AddPointer(&BT);
2362  hash.AddString(Description);
2363  PathDiagnosticLocation UL = getUniqueingLocation();
2364  if (UL.isValid()) {
2365    UL.Profile(hash);
2366  } else if (Location.isValid()) {
2367    Location.Profile(hash);
2368  } else {
2369    assert(ErrorNode);
2370    hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
2371  }
2372
2373  for (SmallVectorImpl<SourceRange>::const_iterator I =
2374      Ranges.begin(), E = Ranges.end(); I != E; ++I) {
2375    const SourceRange range = *I;
2376    if (!range.isValid())
2377      continue;
2378    hash.AddInteger(range.getBegin().getRawEncoding());
2379    hash.AddInteger(range.getEnd().getRawEncoding());
2380  }
2381}
2382
2383void BugReport::markInteresting(SymbolRef sym) {
2384  if (!sym)
2385    return;
2386
2387  // If the symbol wasn't already in our set, note a configuration change.
2388  if (getInterestingSymbols().insert(sym).second)
2389    ++ConfigurationChangeToken;
2390
2391  if (const SymbolMetadata *meta = dyn_cast<SymbolMetadata>(sym))
2392    getInterestingRegions().insert(meta->getRegion());
2393}
2394
2395void BugReport::markInteresting(const MemRegion *R) {
2396  if (!R)
2397    return;
2398
2399  // If the base region wasn't already in our set, note a configuration change.
2400  R = R->getBaseRegion();
2401  if (getInterestingRegions().insert(R).second)
2402    ++ConfigurationChangeToken;
2403
2404  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
2405    getInterestingSymbols().insert(SR->getSymbol());
2406}
2407
2408void BugReport::markInteresting(SVal V) {
2409  markInteresting(V.getAsRegion());
2410  markInteresting(V.getAsSymbol());
2411}
2412
2413void BugReport::markInteresting(const LocationContext *LC) {
2414  if (!LC)
2415    return;
2416  InterestingLocationContexts.insert(LC);
2417}
2418
2419bool BugReport::isInteresting(SVal V) {
2420  return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol());
2421}
2422
2423bool BugReport::isInteresting(SymbolRef sym) {
2424  if (!sym)
2425    return false;
2426  // We don't currently consider metadata symbols to be interesting
2427  // even if we know their region is interesting. Is that correct behavior?
2428  return getInterestingSymbols().count(sym);
2429}
2430
2431bool BugReport::isInteresting(const MemRegion *R) {
2432  if (!R)
2433    return false;
2434  R = R->getBaseRegion();
2435  bool b = getInterestingRegions().count(R);
2436  if (b)
2437    return true;
2438  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
2439    return getInterestingSymbols().count(SR->getSymbol());
2440  return false;
2441}
2442
2443bool BugReport::isInteresting(const LocationContext *LC) {
2444  if (!LC)
2445    return false;
2446  return InterestingLocationContexts.count(LC);
2447}
2448
2449void BugReport::lazyInitializeInterestingSets() {
2450  if (interestingSymbols.empty()) {
2451    interestingSymbols.push_back(new Symbols());
2452    interestingRegions.push_back(new Regions());
2453  }
2454}
2455
2456BugReport::Symbols &BugReport::getInterestingSymbols() {
2457  lazyInitializeInterestingSets();
2458  return *interestingSymbols.back();
2459}
2460
2461BugReport::Regions &BugReport::getInterestingRegions() {
2462  lazyInitializeInterestingSets();
2463  return *interestingRegions.back();
2464}
2465
2466void BugReport::pushInterestingSymbolsAndRegions() {
2467  interestingSymbols.push_back(new Symbols(getInterestingSymbols()));
2468  interestingRegions.push_back(new Regions(getInterestingRegions()));
2469}
2470
2471void BugReport::popInterestingSymbolsAndRegions() {
2472  delete interestingSymbols.back();
2473  interestingSymbols.pop_back();
2474  delete interestingRegions.back();
2475  interestingRegions.pop_back();
2476}
2477
2478const Stmt *BugReport::getStmt() const {
2479  if (!ErrorNode)
2480    return 0;
2481
2482  ProgramPoint ProgP = ErrorNode->getLocation();
2483  const Stmt *S = NULL;
2484
2485  if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
2486    CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
2487    if (BE->getBlock() == &Exit)
2488      S = GetPreviousStmt(ErrorNode);
2489  }
2490  if (!S)
2491    S = PathDiagnosticLocation::getStmt(ErrorNode);
2492
2493  return S;
2494}
2495
2496std::pair<BugReport::ranges_iterator, BugReport::ranges_iterator>
2497BugReport::getRanges() {
2498    // If no custom ranges, add the range of the statement corresponding to
2499    // the error node.
2500    if (Ranges.empty()) {
2501      if (const Expr *E = dyn_cast_or_null<Expr>(getStmt()))
2502        addRange(E->getSourceRange());
2503      else
2504        return std::make_pair(ranges_iterator(), ranges_iterator());
2505    }
2506
2507    // User-specified absence of range info.
2508    if (Ranges.size() == 1 && !Ranges.begin()->isValid())
2509      return std::make_pair(ranges_iterator(), ranges_iterator());
2510
2511    return std::make_pair(Ranges.begin(), Ranges.end());
2512}
2513
2514PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
2515  if (ErrorNode) {
2516    assert(!Location.isValid() &&
2517     "Either Location or ErrorNode should be specified but not both.");
2518    return PathDiagnosticLocation::createEndOfPath(ErrorNode, SM);
2519  } else {
2520    assert(Location.isValid());
2521    return Location;
2522  }
2523
2524  return PathDiagnosticLocation();
2525}
2526
2527//===----------------------------------------------------------------------===//
2528// Methods for BugReporter and subclasses.
2529//===----------------------------------------------------------------------===//
2530
2531BugReportEquivClass::~BugReportEquivClass() { }
2532GRBugReporter::~GRBugReporter() { }
2533BugReporterData::~BugReporterData() {}
2534
2535ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
2536
2537ProgramStateManager&
2538GRBugReporter::getStateManager() { return Eng.getStateManager(); }
2539
2540BugReporter::~BugReporter() {
2541  FlushReports();
2542
2543  // Free the bug reports we are tracking.
2544  typedef std::vector<BugReportEquivClass *> ContTy;
2545  for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end();
2546       I != E; ++I) {
2547    delete *I;
2548  }
2549}
2550
2551void BugReporter::FlushReports() {
2552  if (BugTypes.isEmpty())
2553    return;
2554
2555  // First flush the warnings for each BugType.  This may end up creating new
2556  // warnings and new BugTypes.
2557  // FIXME: Only NSErrorChecker needs BugType's FlushReports.
2558  // Turn NSErrorChecker into a proper checker and remove this.
2559  SmallVector<const BugType*, 16> bugTypes;
2560  for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
2561    bugTypes.push_back(*I);
2562  for (SmallVector<const BugType*, 16>::iterator
2563         I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I)
2564    const_cast<BugType*>(*I)->FlushReports(*this);
2565
2566  // We need to flush reports in deterministic order to ensure the order
2567  // of the reports is consistent between runs.
2568  typedef std::vector<BugReportEquivClass *> ContVecTy;
2569  for (ContVecTy::iterator EI=EQClassesVector.begin(), EE=EQClassesVector.end();
2570       EI != EE; ++EI){
2571    BugReportEquivClass& EQ = **EI;
2572    FlushReport(EQ);
2573  }
2574
2575  // BugReporter owns and deletes only BugTypes created implicitly through
2576  // EmitBasicReport.
2577  // FIXME: There are leaks from checkers that assume that the BugTypes they
2578  // create will be destroyed by the BugReporter.
2579  for (llvm::StringMap<BugType*>::iterator
2580         I = StrBugTypes.begin(), E = StrBugTypes.end(); I != E; ++I)
2581    delete I->second;
2582
2583  // Remove all references to the BugType objects.
2584  BugTypes = F.getEmptySet();
2585}
2586
2587//===----------------------------------------------------------------------===//
2588// PathDiagnostics generation.
2589//===----------------------------------------------------------------------===//
2590
2591namespace {
2592/// A wrapper around a report graph, which contains only a single path, and its
2593/// node maps.
2594class ReportGraph {
2595public:
2596  InterExplodedGraphMap BackMap;
2597  OwningPtr<ExplodedGraph> Graph;
2598  const ExplodedNode *ErrorNode;
2599  size_t Index;
2600};
2601
2602/// A wrapper around a trimmed graph and its node maps.
2603class TrimmedGraph {
2604  InterExplodedGraphMap InverseMap;
2605
2606  typedef llvm::DenseMap<const ExplodedNode *, unsigned> PriorityMapTy;
2607  PriorityMapTy PriorityMap;
2608
2609  typedef std::pair<const ExplodedNode *, size_t> NodeIndexPair;
2610  SmallVector<NodeIndexPair, 32> ReportNodes;
2611
2612  OwningPtr<ExplodedGraph> G;
2613
2614  /// A helper class for sorting ExplodedNodes by priority.
2615  template <bool Descending>
2616  class PriorityCompare {
2617    const PriorityMapTy &PriorityMap;
2618
2619  public:
2620    PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {}
2621
2622    bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const {
2623      PriorityMapTy::const_iterator LI = PriorityMap.find(LHS);
2624      PriorityMapTy::const_iterator RI = PriorityMap.find(RHS);
2625      PriorityMapTy::const_iterator E = PriorityMap.end();
2626
2627      if (LI == E)
2628        return Descending;
2629      if (RI == E)
2630        return !Descending;
2631
2632      return Descending ? LI->second > RI->second
2633                        : LI->second < RI->second;
2634    }
2635
2636    bool operator()(const NodeIndexPair &LHS, const NodeIndexPair &RHS) const {
2637      return (*this)(LHS.first, RHS.first);
2638    }
2639  };
2640
2641public:
2642  TrimmedGraph(const ExplodedGraph *OriginalGraph,
2643               ArrayRef<const ExplodedNode *> Nodes);
2644
2645  bool popNextReportGraph(ReportGraph &GraphWrapper);
2646};
2647}
2648
2649TrimmedGraph::TrimmedGraph(const ExplodedGraph *OriginalGraph,
2650                           ArrayRef<const ExplodedNode *> Nodes) {
2651  // The trimmed graph is created in the body of the constructor to ensure
2652  // that the DenseMaps have been initialized already.
2653  InterExplodedGraphMap ForwardMap;
2654  G.reset(OriginalGraph->trim(Nodes, &ForwardMap, &InverseMap));
2655
2656  // Find the (first) error node in the trimmed graph.  We just need to consult
2657  // the node map which maps from nodes in the original graph to nodes
2658  // in the new graph.
2659  llvm::SmallPtrSet<const ExplodedNode *, 32> RemainingNodes;
2660
2661  for (unsigned i = 0, count = Nodes.size(); i < count; ++i) {
2662    if (const ExplodedNode *NewNode = ForwardMap.lookup(Nodes[i])) {
2663      ReportNodes.push_back(std::make_pair(NewNode, i));
2664      RemainingNodes.insert(NewNode);
2665    }
2666  }
2667
2668  assert(!RemainingNodes.empty() && "No error node found in the trimmed graph");
2669
2670  // Perform a forward BFS to find all the shortest paths.
2671  std::queue<const ExplodedNode *> WS;
2672
2673  assert(G->num_roots() == 1);
2674  WS.push(*G->roots_begin());
2675  unsigned Priority = 0;
2676
2677  while (!WS.empty()) {
2678    const ExplodedNode *Node = WS.front();
2679    WS.pop();
2680
2681    PriorityMapTy::iterator PriorityEntry;
2682    bool IsNew;
2683    llvm::tie(PriorityEntry, IsNew) =
2684      PriorityMap.insert(std::make_pair(Node, Priority));
2685    ++Priority;
2686
2687    if (!IsNew) {
2688      assert(PriorityEntry->second <= Priority);
2689      continue;
2690    }
2691
2692    if (RemainingNodes.erase(Node))
2693      if (RemainingNodes.empty())
2694        break;
2695
2696    for (ExplodedNode::const_pred_iterator I = Node->succ_begin(),
2697                                           E = Node->succ_end();
2698         I != E; ++I)
2699      WS.push(*I);
2700  }
2701
2702  // Sort the error paths from longest to shortest.
2703  std::sort(ReportNodes.begin(), ReportNodes.end(),
2704            PriorityCompare<true>(PriorityMap));
2705}
2706
2707bool TrimmedGraph::popNextReportGraph(ReportGraph &GraphWrapper) {
2708  if (ReportNodes.empty())
2709    return false;
2710
2711  const ExplodedNode *OrigN;
2712  llvm::tie(OrigN, GraphWrapper.Index) = ReportNodes.pop_back_val();
2713  assert(PriorityMap.find(OrigN) != PriorityMap.end() &&
2714         "error node not accessible from root");
2715
2716  // Create a new graph with a single path.  This is the graph
2717  // that will be returned to the caller.
2718  ExplodedGraph *GNew = new ExplodedGraph();
2719  GraphWrapper.Graph.reset(GNew);
2720  GraphWrapper.BackMap.clear();
2721
2722  // Now walk from the error node up the BFS path, always taking the
2723  // predeccessor with the lowest number.
2724  ExplodedNode *Succ = 0;
2725  while (true) {
2726    // Create the equivalent node in the new graph with the same state
2727    // and location.
2728    ExplodedNode *NewN = GNew->getNode(OrigN->getLocation(), OrigN->getState(),
2729                                       OrigN->isSink());
2730
2731    // Store the mapping to the original node.
2732    InterExplodedGraphMap::const_iterator IMitr = InverseMap.find(OrigN);
2733    assert(IMitr != InverseMap.end() && "No mapping to original node.");
2734    GraphWrapper.BackMap[NewN] = IMitr->second;
2735
2736    // Link up the new node with the previous node.
2737    if (Succ)
2738      Succ->addPredecessor(NewN, *GNew);
2739    else
2740      GraphWrapper.ErrorNode = NewN;
2741
2742    Succ = NewN;
2743
2744    // Are we at the final node?
2745    if (OrigN->pred_empty()) {
2746      GNew->addRoot(NewN);
2747      break;
2748    }
2749
2750    // Find the next predeccessor node.  We choose the node that is marked
2751    // with the lowest BFS number.
2752    OrigN = *std::min_element(OrigN->pred_begin(), OrigN->pred_end(),
2753                          PriorityCompare<false>(PriorityMap));
2754  }
2755
2756  return true;
2757}
2758
2759
2760/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
2761///  and collapses PathDiagosticPieces that are expanded by macros.
2762static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM) {
2763  typedef std::vector<std::pair<IntrusiveRefCntPtr<PathDiagnosticMacroPiece>,
2764                                SourceLocation> > MacroStackTy;
2765
2766  typedef std::vector<IntrusiveRefCntPtr<PathDiagnosticPiece> >
2767          PiecesTy;
2768
2769  MacroStackTy MacroStack;
2770  PiecesTy Pieces;
2771
2772  for (PathPieces::const_iterator I = path.begin(), E = path.end();
2773       I!=E; ++I) {
2774
2775    PathDiagnosticPiece *piece = I->getPtr();
2776
2777    // Recursively compact calls.
2778    if (PathDiagnosticCallPiece *call=dyn_cast<PathDiagnosticCallPiece>(piece)){
2779      CompactPathDiagnostic(call->path, SM);
2780    }
2781
2782    // Get the location of the PathDiagnosticPiece.
2783    const FullSourceLoc Loc = piece->getLocation().asLocation();
2784
2785    // Determine the instantiation location, which is the location we group
2786    // related PathDiagnosticPieces.
2787    SourceLocation InstantiationLoc = Loc.isMacroID() ?
2788                                      SM.getExpansionLoc(Loc) :
2789                                      SourceLocation();
2790
2791    if (Loc.isFileID()) {
2792      MacroStack.clear();
2793      Pieces.push_back(piece);
2794      continue;
2795    }
2796
2797    assert(Loc.isMacroID());
2798
2799    // Is the PathDiagnosticPiece within the same macro group?
2800    if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
2801      MacroStack.back().first->subPieces.push_back(piece);
2802      continue;
2803    }
2804
2805    // We aren't in the same group.  Are we descending into a new macro
2806    // or are part of an old one?
2807    IntrusiveRefCntPtr<PathDiagnosticMacroPiece> MacroGroup;
2808
2809    SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
2810                                          SM.getExpansionLoc(Loc) :
2811                                          SourceLocation();
2812
2813    // Walk the entire macro stack.
2814    while (!MacroStack.empty()) {
2815      if (InstantiationLoc == MacroStack.back().second) {
2816        MacroGroup = MacroStack.back().first;
2817        break;
2818      }
2819
2820      if (ParentInstantiationLoc == MacroStack.back().second) {
2821        MacroGroup = MacroStack.back().first;
2822        break;
2823      }
2824
2825      MacroStack.pop_back();
2826    }
2827
2828    if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
2829      // Create a new macro group and add it to the stack.
2830      PathDiagnosticMacroPiece *NewGroup =
2831        new PathDiagnosticMacroPiece(
2832          PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
2833
2834      if (MacroGroup)
2835        MacroGroup->subPieces.push_back(NewGroup);
2836      else {
2837        assert(InstantiationLoc.isFileID());
2838        Pieces.push_back(NewGroup);
2839      }
2840
2841      MacroGroup = NewGroup;
2842      MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
2843    }
2844
2845    // Finally, add the PathDiagnosticPiece to the group.
2846    MacroGroup->subPieces.push_back(piece);
2847  }
2848
2849  // Now take the pieces and construct a new PathDiagnostic.
2850  path.clear();
2851
2852  for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I)
2853    path.push_back(*I);
2854}
2855
2856bool GRBugReporter::generatePathDiagnostic(PathDiagnostic& PD,
2857                                           PathDiagnosticConsumer &PC,
2858                                           ArrayRef<BugReport *> &bugReports) {
2859  assert(!bugReports.empty());
2860
2861  bool HasValid = false;
2862  bool HasInvalid = false;
2863  SmallVector<const ExplodedNode *, 32> errorNodes;
2864  for (ArrayRef<BugReport*>::iterator I = bugReports.begin(),
2865                                      E = bugReports.end(); I != E; ++I) {
2866    if ((*I)->isValid()) {
2867      HasValid = true;
2868      errorNodes.push_back((*I)->getErrorNode());
2869    } else {
2870      // Keep the errorNodes list in sync with the bugReports list.
2871      HasInvalid = true;
2872      errorNodes.push_back(0);
2873    }
2874  }
2875
2876  // If all the reports have been marked invalid by a previous path generation,
2877  // we're done.
2878  if (!HasValid)
2879    return false;
2880
2881  typedef PathDiagnosticConsumer::PathGenerationScheme PathGenerationScheme;
2882  PathGenerationScheme ActiveScheme = PC.getGenerationScheme();
2883
2884  if (ActiveScheme == PathDiagnosticConsumer::Extensive) {
2885    AnalyzerOptions &options = getAnalyzerOptions();
2886    if (options.getBooleanOption("path-diagnostics-alternate", false)) {
2887      ActiveScheme = PathDiagnosticConsumer::AlternateExtensive;
2888    }
2889  }
2890
2891  TrimmedGraph TrimG(&getGraph(), errorNodes);
2892  ReportGraph ErrorGraph;
2893
2894  while (TrimG.popNextReportGraph(ErrorGraph)) {
2895    // Find the BugReport with the original location.
2896    assert(ErrorGraph.Index < bugReports.size());
2897    BugReport *R = bugReports[ErrorGraph.Index];
2898    assert(R && "No original report found for sliced graph.");
2899    assert(R->isValid() && "Report selected by trimmed graph marked invalid.");
2900
2901    // Start building the path diagnostic...
2902    PathDiagnosticBuilder PDB(*this, R, ErrorGraph.BackMap, &PC);
2903    const ExplodedNode *N = ErrorGraph.ErrorNode;
2904
2905    // Register additional node visitors.
2906    R->addVisitor(new NilReceiverBRVisitor());
2907    R->addVisitor(new ConditionBRVisitor());
2908    R->addVisitor(new LikelyFalsePositiveSuppressionBRVisitor());
2909
2910    BugReport::VisitorList visitors;
2911    unsigned origReportConfigToken, finalReportConfigToken;
2912    LocationContextMap LCM;
2913
2914    // While generating diagnostics, it's possible the visitors will decide
2915    // new symbols and regions are interesting, or add other visitors based on
2916    // the information they find. If they do, we need to regenerate the path
2917    // based on our new report configuration.
2918    do {
2919      // Get a clean copy of all the visitors.
2920      for (BugReport::visitor_iterator I = R->visitor_begin(),
2921                                       E = R->visitor_end(); I != E; ++I)
2922        visitors.push_back((*I)->clone());
2923
2924      // Clear out the active path from any previous work.
2925      PD.resetPath();
2926      origReportConfigToken = R->getConfigurationChangeToken();
2927
2928      // Generate the very last diagnostic piece - the piece is visible before
2929      // the trace is expanded.
2930      PathDiagnosticPiece *LastPiece = 0;
2931      for (BugReport::visitor_iterator I = visitors.begin(), E = visitors.end();
2932          I != E; ++I) {
2933        if (PathDiagnosticPiece *Piece = (*I)->getEndPath(PDB, N, *R)) {
2934          assert (!LastPiece &&
2935              "There can only be one final piece in a diagnostic.");
2936          LastPiece = Piece;
2937        }
2938      }
2939
2940      if (ActiveScheme != PathDiagnosticConsumer::None) {
2941        if (!LastPiece)
2942          LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R);
2943        assert(LastPiece);
2944        PD.setEndOfPath(LastPiece);
2945      }
2946
2947      // Make sure we get a clean location context map so we don't
2948      // hold onto old mappings.
2949      LCM.clear();
2950
2951      switch (ActiveScheme) {
2952      case PathDiagnosticConsumer::AlternateExtensive:
2953        GenerateAlternateExtensivePathDiagnostic(PD, PDB, N, LCM, visitors);
2954        break;
2955      case PathDiagnosticConsumer::Extensive:
2956        GenerateExtensivePathDiagnostic(PD, PDB, N, LCM, visitors);
2957        break;
2958      case PathDiagnosticConsumer::Minimal:
2959        GenerateMinimalPathDiagnostic(PD, PDB, N, LCM, visitors);
2960        break;
2961      case PathDiagnosticConsumer::None:
2962        GenerateVisitorsOnlyPathDiagnostic(PD, PDB, N, visitors);
2963        break;
2964      }
2965
2966      // Clean up the visitors we used.
2967      llvm::DeleteContainerPointers(visitors);
2968
2969      // Did anything change while generating this path?
2970      finalReportConfigToken = R->getConfigurationChangeToken();
2971    } while (finalReportConfigToken != origReportConfigToken);
2972
2973    if (!R->isValid())
2974      continue;
2975
2976    // Finally, prune the diagnostic path of uninteresting stuff.
2977    if (!PD.path.empty()) {
2978      // Remove messages that are basically the same.
2979      removeRedundantMsgs(PD.getMutablePieces());
2980
2981      if (R->shouldPrunePath() && getAnalyzerOptions().shouldPrunePaths()) {
2982        bool stillHasNotes = removeUnneededCalls(PD.getMutablePieces(), R, LCM);
2983        assert(stillHasNotes);
2984        (void)stillHasNotes;
2985      }
2986
2987      adjustCallLocations(PD.getMutablePieces());
2988
2989      if (ActiveScheme == PathDiagnosticConsumer::AlternateExtensive) {
2990        SourceManager &SM = getSourceManager();
2991
2992        // Reduce the number of edges from a very conservative set
2993        // to an aesthetically pleasing subset that conveys the
2994        // necessary information.
2995        OptimizedCallsSet OCS;
2996        while (optimizeEdges(PD.getMutablePieces(), SM, OCS, LCM)) {}
2997
2998        // Adjust edges into loop conditions to make them more uniform
2999        // and aesthetically pleasing.
3000        adjustBranchEdges(PD.getMutablePieces(), LCM, SM);
3001      }
3002    }
3003
3004    // We found a report and didn't suppress it.
3005    return true;
3006  }
3007
3008  // We suppressed all the reports in this equivalence class.
3009  assert(!HasInvalid && "Inconsistent suppression");
3010  (void)HasInvalid;
3011  return false;
3012}
3013
3014void BugReporter::Register(BugType *BT) {
3015  BugTypes = F.add(BugTypes, BT);
3016}
3017
3018void BugReporter::emitReport(BugReport* R) {
3019  // Compute the bug report's hash to determine its equivalence class.
3020  llvm::FoldingSetNodeID ID;
3021  R->Profile(ID);
3022
3023  // Lookup the equivance class.  If there isn't one, create it.
3024  BugType& BT = R->getBugType();
3025  Register(&BT);
3026  void *InsertPos;
3027  BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
3028
3029  if (!EQ) {
3030    EQ = new BugReportEquivClass(R);
3031    EQClasses.InsertNode(EQ, InsertPos);
3032    EQClassesVector.push_back(EQ);
3033  }
3034  else
3035    EQ->AddReport(R);
3036}
3037
3038
3039//===----------------------------------------------------------------------===//
3040// Emitting reports in equivalence classes.
3041//===----------------------------------------------------------------------===//
3042
3043namespace {
3044struct FRIEC_WLItem {
3045  const ExplodedNode *N;
3046  ExplodedNode::const_succ_iterator I, E;
3047
3048  FRIEC_WLItem(const ExplodedNode *n)
3049  : N(n), I(N->succ_begin()), E(N->succ_end()) {}
3050};
3051}
3052
3053static BugReport *
3054FindReportInEquivalenceClass(BugReportEquivClass& EQ,
3055                             SmallVectorImpl<BugReport*> &bugReports) {
3056
3057  BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
3058  assert(I != E);
3059  BugType& BT = I->getBugType();
3060
3061  // If we don't need to suppress any of the nodes because they are
3062  // post-dominated by a sink, simply add all the nodes in the equivalence class
3063  // to 'Nodes'.  Any of the reports will serve as a "representative" report.
3064  if (!BT.isSuppressOnSink()) {
3065    BugReport *R = I;
3066    for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
3067      const ExplodedNode *N = I->getErrorNode();
3068      if (N) {
3069        R = I;
3070        bugReports.push_back(R);
3071      }
3072    }
3073    return R;
3074  }
3075
3076  // For bug reports that should be suppressed when all paths are post-dominated
3077  // by a sink node, iterate through the reports in the equivalence class
3078  // until we find one that isn't post-dominated (if one exists).  We use a
3079  // DFS traversal of the ExplodedGraph to find a non-sink node.  We could write
3080  // this as a recursive function, but we don't want to risk blowing out the
3081  // stack for very long paths.
3082  BugReport *exampleReport = 0;
3083
3084  for (; I != E; ++I) {
3085    const ExplodedNode *errorNode = I->getErrorNode();
3086
3087    if (!errorNode)
3088      continue;
3089    if (errorNode->isSink()) {
3090      llvm_unreachable(
3091           "BugType::isSuppressSink() should not be 'true' for sink end nodes");
3092    }
3093    // No successors?  By definition this nodes isn't post-dominated by a sink.
3094    if (errorNode->succ_empty()) {
3095      bugReports.push_back(I);
3096      if (!exampleReport)
3097        exampleReport = I;
3098      continue;
3099    }
3100
3101    // At this point we know that 'N' is not a sink and it has at least one
3102    // successor.  Use a DFS worklist to find a non-sink end-of-path node.
3103    typedef FRIEC_WLItem WLItem;
3104    typedef SmallVector<WLItem, 10> DFSWorkList;
3105    llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
3106
3107    DFSWorkList WL;
3108    WL.push_back(errorNode);
3109    Visited[errorNode] = 1;
3110
3111    while (!WL.empty()) {
3112      WLItem &WI = WL.back();
3113      assert(!WI.N->succ_empty());
3114
3115      for (; WI.I != WI.E; ++WI.I) {
3116        const ExplodedNode *Succ = *WI.I;
3117        // End-of-path node?
3118        if (Succ->succ_empty()) {
3119          // If we found an end-of-path node that is not a sink.
3120          if (!Succ->isSink()) {
3121            bugReports.push_back(I);
3122            if (!exampleReport)
3123              exampleReport = I;
3124            WL.clear();
3125            break;
3126          }
3127          // Found a sink?  Continue on to the next successor.
3128          continue;
3129        }
3130        // Mark the successor as visited.  If it hasn't been explored,
3131        // enqueue it to the DFS worklist.
3132        unsigned &mark = Visited[Succ];
3133        if (!mark) {
3134          mark = 1;
3135          WL.push_back(Succ);
3136          break;
3137        }
3138      }
3139
3140      // The worklist may have been cleared at this point.  First
3141      // check if it is empty before checking the last item.
3142      if (!WL.empty() && &WL.back() == &WI)
3143        WL.pop_back();
3144    }
3145  }
3146
3147  // ExampleReport will be NULL if all the nodes in the equivalence class
3148  // were post-dominated by sinks.
3149  return exampleReport;
3150}
3151
3152void BugReporter::FlushReport(BugReportEquivClass& EQ) {
3153  SmallVector<BugReport*, 10> bugReports;
3154  BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports);
3155  if (exampleReport) {
3156    const PathDiagnosticConsumers &C = getPathDiagnosticConsumers();
3157    for (PathDiagnosticConsumers::const_iterator I=C.begin(),
3158                                                 E=C.end(); I != E; ++I) {
3159      FlushReport(exampleReport, **I, bugReports);
3160    }
3161  }
3162}
3163
3164void BugReporter::FlushReport(BugReport *exampleReport,
3165                              PathDiagnosticConsumer &PD,
3166                              ArrayRef<BugReport*> bugReports) {
3167
3168  // FIXME: Make sure we use the 'R' for the path that was actually used.
3169  // Probably doesn't make a difference in practice.
3170  BugType& BT = exampleReport->getBugType();
3171
3172  OwningPtr<PathDiagnostic>
3173    D(new PathDiagnostic(exampleReport->getDeclWithIssue(),
3174                         exampleReport->getBugType().getName(),
3175                         exampleReport->getDescription(),
3176                         exampleReport->getShortDescription(/*Fallback=*/false),
3177                         BT.getCategory(),
3178                         exampleReport->getUniqueingLocation(),
3179                         exampleReport->getUniqueingDecl()));
3180
3181  MaxBugClassSize = std::max(bugReports.size(),
3182                             static_cast<size_t>(MaxBugClassSize));
3183
3184  // Generate the full path diagnostic, using the generation scheme
3185  // specified by the PathDiagnosticConsumer. Note that we have to generate
3186  // path diagnostics even for consumers which do not support paths, because
3187  // the BugReporterVisitors may mark this bug as a false positive.
3188  if (!bugReports.empty())
3189    if (!generatePathDiagnostic(*D.get(), PD, bugReports))
3190      return;
3191
3192  MaxValidBugClassSize = std::max(bugReports.size(),
3193                                  static_cast<size_t>(MaxValidBugClassSize));
3194
3195  // Examine the report and see if the last piece is in a header. Reset the
3196  // report location to the last piece in the main source file.
3197  AnalyzerOptions& Opts = getAnalyzerOptions();
3198  if (Opts.shouldReportIssuesInMainSourceFile() && !Opts.AnalyzeAll)
3199    D->resetDiagnosticLocationToMainFile();
3200
3201  // If the path is empty, generate a single step path with the location
3202  // of the issue.
3203  if (D->path.empty()) {
3204    PathDiagnosticLocation L = exampleReport->getLocation(getSourceManager());
3205    PathDiagnosticPiece *piece =
3206      new PathDiagnosticEventPiece(L, exampleReport->getDescription());
3207    BugReport::ranges_iterator Beg, End;
3208    llvm::tie(Beg, End) = exampleReport->getRanges();
3209    for ( ; Beg != End; ++Beg)
3210      piece->addRange(*Beg);
3211    D->setEndOfPath(piece);
3212  }
3213
3214  // Get the meta data.
3215  const BugReport::ExtraTextList &Meta = exampleReport->getExtraText();
3216  for (BugReport::ExtraTextList::const_iterator i = Meta.begin(),
3217                                                e = Meta.end(); i != e; ++i) {
3218    D->addMeta(*i);
3219  }
3220
3221  PD.HandlePathDiagnostic(D.take());
3222}
3223
3224void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
3225                                  StringRef name,
3226                                  StringRef category,
3227                                  StringRef str, PathDiagnosticLocation Loc,
3228                                  SourceRange* RBeg, unsigned NumRanges) {
3229
3230  // 'BT' is owned by BugReporter.
3231  BugType *BT = getBugTypeForName(name, category);
3232  BugReport *R = new BugReport(*BT, str, Loc);
3233  R->setDeclWithIssue(DeclWithIssue);
3234  for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
3235  emitReport(R);
3236}
3237
3238BugType *BugReporter::getBugTypeForName(StringRef name,
3239                                        StringRef category) {
3240  SmallString<136> fullDesc;
3241  llvm::raw_svector_ostream(fullDesc) << name << ":" << category;
3242  llvm::StringMapEntry<BugType *> &
3243      entry = StrBugTypes.GetOrCreateValue(fullDesc);
3244  BugType *BT = entry.getValue();
3245  if (!BT) {
3246    BT = new BugType(name, category);
3247    entry.setValue(BT);
3248  }
3249  return BT;
3250}
3251