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