BugReporter.cpp revision 3ea09a802f973c2726b2a489ae08a4bded93410b
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/ParentMap.h"
22#include "clang/AST/StmtObjC.h"
23#include "clang/Analysis/CFG.h"
24#include "clang/Analysis/ProgramPoint.h"
25#include "clang/Basic/SourceManager.h"
26#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
27#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
28#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/IntrusiveRefCntPtr.h"
31#include "llvm/ADT/OwningPtr.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/SmallString.h"
34#include "llvm/ADT/Statistic.h"
35#include "llvm/Support/raw_ostream.h"
36#include <queue>
37
38using namespace clang;
39using namespace ento;
40
41STATISTIC(MaxBugClassSize,
42          "The maximum number of bug reports in the same equivalence class");
43STATISTIC(MaxValidBugClassSize,
44          "The maximum number of bug reports in the same equivalence class "
45          "where at least one report is valid (not suppressed)");
46
47BugReporterVisitor::~BugReporterVisitor() {}
48
49void BugReporterContext::anchor() {}
50
51//===----------------------------------------------------------------------===//
52// Helper routines for walking the ExplodedGraph and fetching statements.
53//===----------------------------------------------------------------------===//
54
55static inline const Stmt *GetStmt(const ProgramPoint &P) {
56  if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
57    return SP->getStmt();
58  if (Optional<BlockEdge> BE = P.getAs<BlockEdge>())
59    return BE->getSrc()->getTerminator();
60  if (Optional<CallEnter> CE = P.getAs<CallEnter>())
61    return CE->getCallExpr();
62  if (Optional<CallExitEnd> CEE = P.getAs<CallExitEnd>())
63    return CEE->getCalleeContext()->getCallSite();
64
65  return 0;
66}
67
68static inline const ExplodedNode*
69GetPredecessorNode(const ExplodedNode *N) {
70  return N->pred_empty() ? NULL : *(N->pred_begin());
71}
72
73static inline const ExplodedNode*
74GetSuccessorNode(const ExplodedNode *N) {
75  return N->succ_empty() ? NULL : *(N->succ_begin());
76}
77
78static const Stmt *GetPreviousStmt(const ExplodedNode *N) {
79  for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N))
80    if (const Stmt *S = GetStmt(N->getLocation()))
81      return S;
82
83  return 0;
84}
85
86static const Stmt *GetNextStmt(const ExplodedNode *N) {
87  for (N = GetSuccessorNode(N); N; N = GetSuccessorNode(N))
88    if (const Stmt *S = GetStmt(N->getLocation())) {
89      // Check if the statement is '?' or '&&'/'||'.  These are "merges",
90      // not actual statement points.
91      switch (S->getStmtClass()) {
92        case Stmt::ChooseExprClass:
93        case Stmt::BinaryConditionalOperatorClass: continue;
94        case Stmt::ConditionalOperatorClass: continue;
95        case Stmt::BinaryOperatorClass: {
96          BinaryOperatorKind Op = cast<BinaryOperator>(S)->getOpcode();
97          if (Op == BO_LAnd || Op == BO_LOr)
98            continue;
99          break;
100        }
101        default:
102          break;
103      }
104      return S;
105    }
106
107  return 0;
108}
109
110static inline const Stmt*
111GetCurrentOrPreviousStmt(const ExplodedNode *N) {
112  if (const Stmt *S = GetStmt(N->getLocation()))
113    return S;
114
115  return GetPreviousStmt(N);
116}
117
118static inline const Stmt*
119GetCurrentOrNextStmt(const ExplodedNode *N) {
120  if (const Stmt *S = GetStmt(N->getLocation()))
121    return S;
122
123  return GetNextStmt(N);
124}
125
126//===----------------------------------------------------------------------===//
127// Diagnostic cleanup.
128//===----------------------------------------------------------------------===//
129
130static PathDiagnosticEventPiece *
131eventsDescribeSameCondition(PathDiagnosticEventPiece *X,
132                            PathDiagnosticEventPiece *Y) {
133  // Prefer diagnostics that come from ConditionBRVisitor over
134  // those that came from TrackConstraintBRVisitor.
135  const void *tagPreferred = ConditionBRVisitor::getTag();
136  const void *tagLesser = TrackConstraintBRVisitor::getTag();
137
138  if (X->getLocation() != Y->getLocation())
139    return 0;
140
141  if (X->getTag() == tagPreferred && Y->getTag() == tagLesser)
142    return X;
143
144  if (Y->getTag() == tagPreferred && X->getTag() == tagLesser)
145    return Y;
146
147  return 0;
148}
149
150/// An optimization pass over PathPieces that removes redundant diagnostics
151/// generated by both ConditionBRVisitor and TrackConstraintBRVisitor.  Both
152/// BugReporterVisitors use different methods to generate diagnostics, with
153/// one capable of emitting diagnostics in some cases but not in others.  This
154/// can lead to redundant diagnostic pieces at the same point in a path.
155static void removeRedundantMsgs(PathPieces &path) {
156  unsigned N = path.size();
157  if (N < 2)
158    return;
159  // NOTE: this loop intentionally is not using an iterator.  Instead, we
160  // are streaming the path and modifying it in place.  This is done by
161  // grabbing the front, processing it, and if we decide to keep it append
162  // it to the end of the path.  The entire path is processed in this way.
163  for (unsigned i = 0; i < N; ++i) {
164    IntrusiveRefCntPtr<PathDiagnosticPiece> piece(path.front());
165    path.pop_front();
166
167    switch (piece->getKind()) {
168      case clang::ento::PathDiagnosticPiece::Call:
169        removeRedundantMsgs(cast<PathDiagnosticCallPiece>(piece)->path);
170        break;
171      case clang::ento::PathDiagnosticPiece::Macro:
172        removeRedundantMsgs(cast<PathDiagnosticMacroPiece>(piece)->subPieces);
173        break;
174      case clang::ento::PathDiagnosticPiece::ControlFlow:
175        break;
176      case clang::ento::PathDiagnosticPiece::Event: {
177        if (i == N-1)
178          break;
179
180        if (PathDiagnosticEventPiece *nextEvent =
181            dyn_cast<PathDiagnosticEventPiece>(path.front().getPtr())) {
182          PathDiagnosticEventPiece *event =
183            cast<PathDiagnosticEventPiece>(piece);
184          // Check to see if we should keep one of the two pieces.  If we
185          // come up with a preference, record which piece to keep, and consume
186          // another piece from the path.
187          if (PathDiagnosticEventPiece *pieceToKeep =
188              eventsDescribeSameCondition(event, nextEvent)) {
189            piece = pieceToKeep;
190            path.pop_front();
191            ++i;
192          }
193        }
194        break;
195      }
196    }
197    path.push_back(piece);
198  }
199}
200
201/// Recursively scan through a path and prune out calls and macros pieces
202/// that aren't needed.  Return true if afterwards the path contains
203/// "interesting stuff" which means it shouldn't be pruned from the parent path.
204bool BugReporter::RemoveUnneededCalls(PathPieces &pieces, BugReport *R) {
205  bool containsSomethingInteresting = false;
206  const unsigned N = pieces.size();
207
208  for (unsigned i = 0 ; i < N ; ++i) {
209    // Remove the front piece from the path.  If it is still something we
210    // want to keep once we are done, we will push it back on the end.
211    IntrusiveRefCntPtr<PathDiagnosticPiece> piece(pieces.front());
212    pieces.pop_front();
213
214    // Throw away pieces with invalid locations. Note that we can't throw away
215    // calls just yet because they might have something interesting inside them.
216    // If so, their locations will be adjusted as necessary later.
217    if (piece->getKind() != PathDiagnosticPiece::Call &&
218        piece->getLocation().asLocation().isInvalid())
219      continue;
220
221    switch (piece->getKind()) {
222      case PathDiagnosticPiece::Call: {
223        PathDiagnosticCallPiece *call = cast<PathDiagnosticCallPiece>(piece);
224        // Check if the location context is interesting.
225        assert(LocationContextMap.count(call));
226        if (R->isInteresting(LocationContextMap[call])) {
227          containsSomethingInteresting = true;
228          break;
229        }
230
231        if (!RemoveUnneededCalls(call->path, R))
232          continue;
233
234        containsSomethingInteresting = true;
235        break;
236      }
237      case PathDiagnosticPiece::Macro: {
238        PathDiagnosticMacroPiece *macro = cast<PathDiagnosticMacroPiece>(piece);
239        if (!RemoveUnneededCalls(macro->subPieces, R))
240          continue;
241        containsSomethingInteresting = true;
242        break;
243      }
244      case PathDiagnosticPiece::Event: {
245        PathDiagnosticEventPiece *event = cast<PathDiagnosticEventPiece>(piece);
246
247        // We never throw away an event, but we do throw it away wholesale
248        // as part of a path if we throw the entire path away.
249        containsSomethingInteresting |= !event->isPrunable();
250        break;
251      }
252      case PathDiagnosticPiece::ControlFlow:
253        break;
254    }
255
256    pieces.push_back(piece);
257  }
258
259  return containsSomethingInteresting;
260}
261
262/// Recursively scan through a path and make sure that all call pieces have
263/// valid locations. Note that all other pieces with invalid locations should
264/// have already been pruned out.
265static void adjustCallLocations(PathPieces &Pieces,
266                                PathDiagnosticLocation *LastCallLocation = 0) {
267  for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E; ++I) {
268    PathDiagnosticCallPiece *Call = dyn_cast<PathDiagnosticCallPiece>(*I);
269
270    if (!Call) {
271      assert((*I)->getLocation().asLocation().isValid());
272      continue;
273    }
274
275    if (LastCallLocation) {
276      if (!Call->callEnter.asLocation().isValid() ||
277          Call->getCaller()->isImplicit())
278        Call->callEnter = *LastCallLocation;
279      if (!Call->callReturn.asLocation().isValid() ||
280          Call->getCaller()->isImplicit())
281        Call->callReturn = *LastCallLocation;
282    }
283
284    // Recursively clean out the subclass.  Keep this call around if
285    // it contains any informative diagnostics.
286    PathDiagnosticLocation *ThisCallLocation;
287    if (Call->callEnterWithin.asLocation().isValid() &&
288        !Call->getCallee()->isImplicit())
289      ThisCallLocation = &Call->callEnterWithin;
290    else
291      ThisCallLocation = &Call->callEnter;
292
293    assert(ThisCallLocation && "Outermost call has an invalid location");
294    adjustCallLocations(Call->path, ThisCallLocation);
295  }
296}
297
298//===----------------------------------------------------------------------===//
299// PathDiagnosticBuilder and its associated routines and helper objects.
300//===----------------------------------------------------------------------===//
301
302namespace {
303class NodeMapClosure : public BugReport::NodeResolver {
304  InterExplodedGraphMap &M;
305public:
306  NodeMapClosure(InterExplodedGraphMap &m) : M(m) {}
307
308  const ExplodedNode *getOriginalNode(const ExplodedNode *N) {
309    return M.lookup(N);
310  }
311};
312
313class PathDiagnosticBuilder : public BugReporterContext {
314  BugReport *R;
315  PathDiagnosticConsumer *PDC;
316  NodeMapClosure NMC;
317public:
318  const LocationContext *LC;
319
320  PathDiagnosticBuilder(GRBugReporter &br,
321                        BugReport *r, InterExplodedGraphMap &Backmap,
322                        PathDiagnosticConsumer *pdc)
323    : BugReporterContext(br),
324      R(r), PDC(pdc), NMC(Backmap), LC(r->getErrorNode()->getLocationContext())
325  {}
326
327  PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N);
328
329  PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream &os,
330                                            const ExplodedNode *N);
331
332  BugReport *getBugReport() { return R; }
333
334  Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); }
335
336  ParentMap& getParentMap() { return LC->getParentMap(); }
337
338  const Stmt *getParent(const Stmt *S) {
339    return getParentMap().getParent(S);
340  }
341
342  virtual NodeMapClosure& getNodeResolver() { return NMC; }
343
344  PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
345
346  PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const {
347    return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Extensive;
348  }
349
350  bool supportsLogicalOpControlFlow() const {
351    return PDC ? PDC->supportsLogicalOpControlFlow() : true;
352  }
353};
354} // end anonymous namespace
355
356PathDiagnosticLocation
357PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) {
358  if (const Stmt *S = GetNextStmt(N))
359    return PathDiagnosticLocation(S, getSourceManager(), LC);
360
361  return PathDiagnosticLocation::createDeclEnd(N->getLocationContext(),
362                                               getSourceManager());
363}
364
365PathDiagnosticLocation
366PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream &os,
367                                          const ExplodedNode *N) {
368
369  // Slow, but probably doesn't matter.
370  if (os.str().empty())
371    os << ' ';
372
373  const PathDiagnosticLocation &Loc = ExecutionContinues(N);
374
375  if (Loc.asStmt())
376    os << "Execution continues on line "
377       << getSourceManager().getExpansionLineNumber(Loc.asLocation())
378       << '.';
379  else {
380    os << "Execution jumps to the end of the ";
381    const Decl *D = N->getLocationContext()->getDecl();
382    if (isa<ObjCMethodDecl>(D))
383      os << "method";
384    else if (isa<FunctionDecl>(D))
385      os << "function";
386    else {
387      assert(isa<BlockDecl>(D));
388      os << "anonymous block";
389    }
390    os << '.';
391  }
392
393  return Loc;
394}
395
396static bool IsNested(const Stmt *S, ParentMap &PM) {
397  if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
398    return true;
399
400  const Stmt *Parent = PM.getParentIgnoreParens(S);
401
402  if (Parent)
403    switch (Parent->getStmtClass()) {
404      case Stmt::ForStmtClass:
405      case Stmt::DoStmtClass:
406      case Stmt::WhileStmtClass:
407        return true;
408      default:
409        break;
410    }
411
412  return false;
413}
414
415PathDiagnosticLocation
416PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
417  assert(S && "Null Stmt *passed to getEnclosingStmtLocation");
418  ParentMap &P = getParentMap();
419  SourceManager &SMgr = getSourceManager();
420
421  while (IsNested(S, P)) {
422    const Stmt *Parent = P.getParentIgnoreParens(S);
423
424    if (!Parent)
425      break;
426
427    switch (Parent->getStmtClass()) {
428      case Stmt::BinaryOperatorClass: {
429        const BinaryOperator *B = cast<BinaryOperator>(Parent);
430        if (B->isLogicalOp())
431          return PathDiagnosticLocation(S, SMgr, LC);
432        break;
433      }
434      case Stmt::CompoundStmtClass:
435      case Stmt::StmtExprClass:
436        return PathDiagnosticLocation(S, SMgr, LC);
437      case Stmt::ChooseExprClass:
438        // Similar to '?' if we are referring to condition, just have the edge
439        // point to the entire choose expression.
440        if (cast<ChooseExpr>(Parent)->getCond() == S)
441          return PathDiagnosticLocation(Parent, SMgr, LC);
442        else
443          return PathDiagnosticLocation(S, SMgr, LC);
444      case Stmt::BinaryConditionalOperatorClass:
445      case Stmt::ConditionalOperatorClass:
446        // For '?', if we are referring to condition, just have the edge point
447        // to the entire '?' expression.
448        if (cast<AbstractConditionalOperator>(Parent)->getCond() == S)
449          return PathDiagnosticLocation(Parent, SMgr, LC);
450        else
451          return PathDiagnosticLocation(S, SMgr, LC);
452      case Stmt::DoStmtClass:
453          return PathDiagnosticLocation(S, SMgr, LC);
454      case Stmt::ForStmtClass:
455        if (cast<ForStmt>(Parent)->getBody() == S)
456          return PathDiagnosticLocation(S, SMgr, LC);
457        break;
458      case Stmt::IfStmtClass:
459        if (cast<IfStmt>(Parent)->getCond() != S)
460          return PathDiagnosticLocation(S, SMgr, LC);
461        break;
462      case Stmt::ObjCForCollectionStmtClass:
463        if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
464          return PathDiagnosticLocation(S, SMgr, LC);
465        break;
466      case Stmt::WhileStmtClass:
467        if (cast<WhileStmt>(Parent)->getCond() != S)
468          return PathDiagnosticLocation(S, SMgr, LC);
469        break;
470      default:
471        break;
472    }
473
474    S = Parent;
475  }
476
477  assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
478
479  // Special case: DeclStmts can appear in for statement declarations, in which
480  //  case the ForStmt is the context.
481  if (isa<DeclStmt>(S)) {
482    if (const Stmt *Parent = P.getParent(S)) {
483      switch (Parent->getStmtClass()) {
484        case Stmt::ForStmtClass:
485        case Stmt::ObjCForCollectionStmtClass:
486          return PathDiagnosticLocation(Parent, SMgr, LC);
487        default:
488          break;
489      }
490    }
491  }
492  else if (isa<BinaryOperator>(S)) {
493    // Special case: the binary operator represents the initialization
494    // code in a for statement (this can happen when the variable being
495    // initialized is an old variable.
496    if (const ForStmt *FS =
497          dyn_cast_or_null<ForStmt>(P.getParentIgnoreParens(S))) {
498      if (FS->getInit() == S)
499        return PathDiagnosticLocation(FS, SMgr, LC);
500    }
501  }
502
503  return PathDiagnosticLocation(S, SMgr, LC);
504}
505
506//===----------------------------------------------------------------------===//
507// "Visitors only" path diagnostic generation algorithm.
508//===----------------------------------------------------------------------===//
509static bool GenerateVisitorsOnlyPathDiagnostic(PathDiagnostic &PD,
510                                               PathDiagnosticBuilder &PDB,
511                                               const ExplodedNode *N,
512                                      ArrayRef<BugReporterVisitor *> visitors) {
513  // All path generation skips the very first node (the error node).
514  // This is because there is special handling for the end-of-path note.
515  N = N->getFirstPred();
516  if (!N)
517    return true;
518
519  BugReport *R = PDB.getBugReport();
520  while (const ExplodedNode *Pred = N->getFirstPred()) {
521    for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(),
522                                                  E = visitors.end();
523         I != E; ++I) {
524      // Visit all the node pairs, but throw the path pieces away.
525      PathDiagnosticPiece *Piece = (*I)->VisitNode(N, Pred, PDB, *R);
526      delete Piece;
527    }
528
529    N = Pred;
530  }
531
532  return R->isValid();
533}
534
535//===----------------------------------------------------------------------===//
536// "Minimal" path diagnostic generation algorithm.
537//===----------------------------------------------------------------------===//
538typedef std::pair<PathDiagnosticCallPiece*, const ExplodedNode*> StackDiagPair;
539typedef SmallVector<StackDiagPair, 6> StackDiagVector;
540
541static void updateStackPiecesWithMessage(PathDiagnosticPiece *P,
542                                         StackDiagVector &CallStack) {
543  // If the piece contains a special message, add it to all the call
544  // pieces on the active stack.
545  if (PathDiagnosticEventPiece *ep =
546        dyn_cast<PathDiagnosticEventPiece>(P)) {
547
548    if (ep->hasCallStackHint())
549      for (StackDiagVector::iterator I = CallStack.begin(),
550                                     E = CallStack.end(); I != E; ++I) {
551        PathDiagnosticCallPiece *CP = I->first;
552        const ExplodedNode *N = I->second;
553        std::string stackMsg = ep->getCallStackMessage(N);
554
555        // The last message on the path to final bug is the most important
556        // one. Since we traverse the path backwards, do not add the message
557        // if one has been previously added.
558        if  (!CP->hasCallStackMessage())
559          CP->setCallStackMessage(stackMsg);
560      }
561  }
562}
563
564static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM);
565
566static bool GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
567                                          PathDiagnosticBuilder &PDB,
568                                          const ExplodedNode *N,
569                                      ArrayRef<BugReporterVisitor *> visitors) {
570
571  SourceManager& SMgr = PDB.getSourceManager();
572  const LocationContext *LC = PDB.LC;
573  const ExplodedNode *NextNode = N->pred_empty()
574                                        ? NULL : *(N->pred_begin());
575
576  StackDiagVector CallStack;
577
578  while (NextNode) {
579    N = NextNode;
580    PDB.LC = N->getLocationContext();
581    NextNode = GetPredecessorNode(N);
582
583    ProgramPoint P = N->getLocation();
584
585    do {
586      if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
587        PathDiagnosticCallPiece *C =
588            PathDiagnosticCallPiece::construct(N, *CE, SMgr);
589        GRBugReporter& BR = PDB.getBugReporter();
590        BR.addCallPieceLocationContextPair(C, CE->getCalleeContext());
591        PD.getActivePath().push_front(C);
592        PD.pushActivePath(&C->path);
593        CallStack.push_back(StackDiagPair(C, N));
594        break;
595      }
596
597      if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
598        // Flush all locations, and pop the active path.
599        bool VisitedEntireCall = PD.isWithinCall();
600        PD.popActivePath();
601
602        // Either we just added a bunch of stuff to the top-level path, or
603        // we have a previous CallExitEnd.  If the former, it means that the
604        // path terminated within a function call.  We must then take the
605        // current contents of the active path and place it within
606        // a new PathDiagnosticCallPiece.
607        PathDiagnosticCallPiece *C;
608        if (VisitedEntireCall) {
609          C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
610        } else {
611          const Decl *Caller = CE->getLocationContext()->getDecl();
612          C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
613          GRBugReporter& BR = PDB.getBugReporter();
614          BR.addCallPieceLocationContextPair(C, CE->getCalleeContext());
615        }
616
617        C->setCallee(*CE, SMgr);
618        if (!CallStack.empty()) {
619          assert(CallStack.back().first == C);
620          CallStack.pop_back();
621        }
622        break;
623      }
624
625      if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
626        const CFGBlock *Src = BE->getSrc();
627        const CFGBlock *Dst = BE->getDst();
628        const Stmt *T = Src->getTerminator();
629
630        if (!T)
631          break;
632
633        PathDiagnosticLocation Start =
634            PathDiagnosticLocation::createBegin(T, SMgr,
635                N->getLocationContext());
636
637        switch (T->getStmtClass()) {
638        default:
639          break;
640
641        case Stmt::GotoStmtClass:
642        case Stmt::IndirectGotoStmtClass: {
643          const Stmt *S = GetNextStmt(N);
644
645          if (!S)
646            break;
647
648          std::string sbuf;
649          llvm::raw_string_ostream os(sbuf);
650          const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
651
652          os << "Control jumps to line "
653              << End.asLocation().getExpansionLineNumber();
654          PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
655              Start, End, os.str()));
656          break;
657        }
658
659        case Stmt::SwitchStmtClass: {
660          // Figure out what case arm we took.
661          std::string sbuf;
662          llvm::raw_string_ostream os(sbuf);
663
664          if (const Stmt *S = Dst->getLabel()) {
665            PathDiagnosticLocation End(S, SMgr, LC);
666
667            switch (S->getStmtClass()) {
668            default:
669              os << "No cases match in the switch statement. "
670              "Control jumps to line "
671              << End.asLocation().getExpansionLineNumber();
672              break;
673            case Stmt::DefaultStmtClass:
674              os << "Control jumps to the 'default' case at line "
675              << End.asLocation().getExpansionLineNumber();
676              break;
677
678            case Stmt::CaseStmtClass: {
679              os << "Control jumps to 'case ";
680              const CaseStmt *Case = cast<CaseStmt>(S);
681              const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
682
683              // Determine if it is an enum.
684              bool GetRawInt = true;
685
686              if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
687                // FIXME: Maybe this should be an assertion.  Are there cases
688                // were it is not an EnumConstantDecl?
689                const EnumConstantDecl *D =
690                    dyn_cast<EnumConstantDecl>(DR->getDecl());
691
692                if (D) {
693                  GetRawInt = false;
694                  os << *D;
695                }
696              }
697
698              if (GetRawInt)
699                os << LHS->EvaluateKnownConstInt(PDB.getASTContext());
700
701              os << ":'  at line "
702                  << End.asLocation().getExpansionLineNumber();
703              break;
704            }
705            }
706            PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
707                Start, End, os.str()));
708          }
709          else {
710            os << "'Default' branch taken. ";
711            const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
712            PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
713                Start, End, os.str()));
714          }
715
716          break;
717        }
718
719        case Stmt::BreakStmtClass:
720        case Stmt::ContinueStmtClass: {
721          std::string sbuf;
722          llvm::raw_string_ostream os(sbuf);
723          PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
724          PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
725              Start, End, os.str()));
726          break;
727        }
728
729        // Determine control-flow for ternary '?'.
730        case Stmt::BinaryConditionalOperatorClass:
731        case Stmt::ConditionalOperatorClass: {
732          std::string sbuf;
733          llvm::raw_string_ostream os(sbuf);
734          os << "'?' condition is ";
735
736          if (*(Src->succ_begin()+1) == Dst)
737            os << "false";
738          else
739            os << "true";
740
741          PathDiagnosticLocation End = PDB.ExecutionContinues(N);
742
743          if (const Stmt *S = End.asStmt())
744            End = PDB.getEnclosingStmtLocation(S);
745
746          PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
747              Start, End, os.str()));
748          break;
749        }
750
751        // Determine control-flow for short-circuited '&&' and '||'.
752        case Stmt::BinaryOperatorClass: {
753          if (!PDB.supportsLogicalOpControlFlow())
754            break;
755
756          const BinaryOperator *B = cast<BinaryOperator>(T);
757          std::string sbuf;
758          llvm::raw_string_ostream os(sbuf);
759          os << "Left side of '";
760
761          if (B->getOpcode() == BO_LAnd) {
762            os << "&&" << "' is ";
763
764            if (*(Src->succ_begin()+1) == Dst) {
765              os << "false";
766              PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
767              PathDiagnosticLocation Start =
768                  PathDiagnosticLocation::createOperatorLoc(B, SMgr);
769              PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
770                  Start, End, os.str()));
771            }
772            else {
773              os << "true";
774              PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
775              PathDiagnosticLocation End = PDB.ExecutionContinues(N);
776              PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
777                  Start, End, os.str()));
778            }
779          }
780          else {
781            assert(B->getOpcode() == BO_LOr);
782            os << "||" << "' is ";
783
784            if (*(Src->succ_begin()+1) == Dst) {
785              os << "false";
786              PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
787              PathDiagnosticLocation End = PDB.ExecutionContinues(N);
788              PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
789                  Start, End, os.str()));
790            }
791            else {
792              os << "true";
793              PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
794              PathDiagnosticLocation Start =
795                  PathDiagnosticLocation::createOperatorLoc(B, SMgr);
796              PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
797                  Start, End, os.str()));
798            }
799          }
800
801          break;
802        }
803
804        case Stmt::DoStmtClass:  {
805          if (*(Src->succ_begin()) == Dst) {
806            std::string sbuf;
807            llvm::raw_string_ostream os(sbuf);
808
809            os << "Loop condition is true. ";
810            PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
811
812            if (const Stmt *S = End.asStmt())
813              End = PDB.getEnclosingStmtLocation(S);
814
815            PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
816                Start, End, os.str()));
817          }
818          else {
819            PathDiagnosticLocation End = PDB.ExecutionContinues(N);
820
821            if (const Stmt *S = End.asStmt())
822              End = PDB.getEnclosingStmtLocation(S);
823
824            PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
825                Start, End, "Loop condition is false.  Exiting loop"));
826          }
827
828          break;
829        }
830
831        case Stmt::WhileStmtClass:
832        case Stmt::ForStmtClass: {
833          if (*(Src->succ_begin()+1) == Dst) {
834            std::string sbuf;
835            llvm::raw_string_ostream os(sbuf);
836
837            os << "Loop condition is false. ";
838            PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
839            if (const Stmt *S = End.asStmt())
840              End = PDB.getEnclosingStmtLocation(S);
841
842            PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
843                Start, End, os.str()));
844          }
845          else {
846            PathDiagnosticLocation End = PDB.ExecutionContinues(N);
847            if (const Stmt *S = End.asStmt())
848              End = PDB.getEnclosingStmtLocation(S);
849
850            PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
851                Start, End, "Loop condition is true.  Entering loop body"));
852          }
853
854          break;
855        }
856
857        case Stmt::IfStmtClass: {
858          PathDiagnosticLocation End = PDB.ExecutionContinues(N);
859
860          if (const Stmt *S = End.asStmt())
861            End = PDB.getEnclosingStmtLocation(S);
862
863          if (*(Src->succ_begin()+1) == Dst)
864            PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
865                Start, End, "Taking false branch"));
866          else
867            PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
868                Start, End, "Taking true branch"));
869
870          break;
871        }
872        }
873      }
874    } while(0);
875
876    if (NextNode) {
877      // Add diagnostic pieces from custom visitors.
878      BugReport *R = PDB.getBugReport();
879      for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(),
880                                                    E = visitors.end();
881           I != E; ++I) {
882        if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) {
883          PD.getActivePath().push_front(p);
884          updateStackPiecesWithMessage(p, CallStack);
885        }
886      }
887    }
888  }
889
890  if (!PDB.getBugReport()->isValid())
891    return false;
892
893  // After constructing the full PathDiagnostic, do a pass over it to compact
894  // PathDiagnosticPieces that occur within a macro.
895  CompactPathDiagnostic(PD.getMutablePieces(), PDB.getSourceManager());
896  return true;
897}
898
899//===----------------------------------------------------------------------===//
900// "Extensive" PathDiagnostic generation.
901//===----------------------------------------------------------------------===//
902
903static bool IsControlFlowExpr(const Stmt *S) {
904  const Expr *E = dyn_cast<Expr>(S);
905
906  if (!E)
907    return false;
908
909  E = E->IgnoreParenCasts();
910
911  if (isa<AbstractConditionalOperator>(E))
912    return true;
913
914  if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
915    if (B->isLogicalOp())
916      return true;
917
918  return false;
919}
920
921namespace {
922class ContextLocation : public PathDiagnosticLocation {
923  bool IsDead;
924public:
925  ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
926    : PathDiagnosticLocation(L), IsDead(isdead) {}
927
928  void markDead() { IsDead = true; }
929  bool isDead() const { return IsDead; }
930};
931
932class EdgeBuilder {
933  std::vector<ContextLocation> CLocs;
934  typedef std::vector<ContextLocation>::iterator iterator;
935  PathDiagnostic &PD;
936  PathDiagnosticBuilder &PDB;
937  PathDiagnosticLocation PrevLoc;
938
939  bool IsConsumedExpr(const PathDiagnosticLocation &L);
940
941  bool containsLocation(const PathDiagnosticLocation &Container,
942                        const PathDiagnosticLocation &Containee);
943
944  PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
945
946  PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
947                                         bool firstCharOnly = false) {
948    if (const Stmt *S = L.asStmt()) {
949      const Stmt *Original = S;
950      while (1) {
951        // Adjust the location for some expressions that are best referenced
952        // by one of their subexpressions.
953        switch (S->getStmtClass()) {
954          default:
955            break;
956          case Stmt::ParenExprClass:
957          case Stmt::GenericSelectionExprClass:
958            S = cast<Expr>(S)->IgnoreParens();
959            firstCharOnly = true;
960            continue;
961          case Stmt::BinaryConditionalOperatorClass:
962          case Stmt::ConditionalOperatorClass:
963            S = cast<AbstractConditionalOperator>(S)->getCond();
964            firstCharOnly = true;
965            continue;
966          case Stmt::ChooseExprClass:
967            S = cast<ChooseExpr>(S)->getCond();
968            firstCharOnly = true;
969            continue;
970          case Stmt::BinaryOperatorClass:
971            S = cast<BinaryOperator>(S)->getLHS();
972            firstCharOnly = true;
973            continue;
974        }
975
976        break;
977      }
978
979      if (S != Original)
980        L = PathDiagnosticLocation(S, L.getManager(), PDB.LC);
981    }
982
983    if (firstCharOnly)
984      L  = PathDiagnosticLocation::createSingleLocation(L);
985
986    return L;
987  }
988
989  void popLocation() {
990    if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
991      // For contexts, we only one the first character as the range.
992      rawAddEdge(cleanUpLocation(CLocs.back(), true));
993    }
994    CLocs.pop_back();
995  }
996
997public:
998  EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
999    : PD(pd), PDB(pdb) {
1000
1001      // If the PathDiagnostic already has pieces, add the enclosing statement
1002      // of the first piece as a context as well.
1003      if (!PD.path.empty()) {
1004        PrevLoc = (*PD.path.begin())->getLocation();
1005
1006        if (const Stmt *S = PrevLoc.asStmt())
1007          addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1008      }
1009  }
1010
1011  ~EdgeBuilder() {
1012    while (!CLocs.empty()) popLocation();
1013
1014    // Finally, add an initial edge from the start location of the first
1015    // statement (if it doesn't already exist).
1016    PathDiagnosticLocation L = PathDiagnosticLocation::createDeclBegin(
1017                                                       PDB.LC,
1018                                                       PDB.getSourceManager());
1019    if (L.isValid())
1020      rawAddEdge(L);
1021  }
1022
1023  void flushLocations() {
1024    while (!CLocs.empty())
1025      popLocation();
1026    PrevLoc = PathDiagnosticLocation();
1027  }
1028
1029  void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false,
1030               bool IsPostJump = false);
1031
1032  void rawAddEdge(PathDiagnosticLocation NewLoc);
1033
1034  void addContext(const Stmt *S);
1035  void addContext(const PathDiagnosticLocation &L);
1036  void addExtendedContext(const Stmt *S);
1037};
1038} // end anonymous namespace
1039
1040
1041PathDiagnosticLocation
1042EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
1043  if (const Stmt *S = L.asStmt()) {
1044    if (IsControlFlowExpr(S))
1045      return L;
1046
1047    return PDB.getEnclosingStmtLocation(S);
1048  }
1049
1050  return L;
1051}
1052
1053bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
1054                                   const PathDiagnosticLocation &Containee) {
1055
1056  if (Container == Containee)
1057    return true;
1058
1059  if (Container.asDecl())
1060    return true;
1061
1062  if (const Stmt *S = Containee.asStmt())
1063    if (const Stmt *ContainerS = Container.asStmt()) {
1064      while (S) {
1065        if (S == ContainerS)
1066          return true;
1067        S = PDB.getParent(S);
1068      }
1069      return false;
1070    }
1071
1072  // Less accurate: compare using source ranges.
1073  SourceRange ContainerR = Container.asRange();
1074  SourceRange ContaineeR = Containee.asRange();
1075
1076  SourceManager &SM = PDB.getSourceManager();
1077  SourceLocation ContainerRBeg = SM.getExpansionLoc(ContainerR.getBegin());
1078  SourceLocation ContainerREnd = SM.getExpansionLoc(ContainerR.getEnd());
1079  SourceLocation ContaineeRBeg = SM.getExpansionLoc(ContaineeR.getBegin());
1080  SourceLocation ContaineeREnd = SM.getExpansionLoc(ContaineeR.getEnd());
1081
1082  unsigned ContainerBegLine = SM.getExpansionLineNumber(ContainerRBeg);
1083  unsigned ContainerEndLine = SM.getExpansionLineNumber(ContainerREnd);
1084  unsigned ContaineeBegLine = SM.getExpansionLineNumber(ContaineeRBeg);
1085  unsigned ContaineeEndLine = SM.getExpansionLineNumber(ContaineeREnd);
1086
1087  assert(ContainerBegLine <= ContainerEndLine);
1088  assert(ContaineeBegLine <= ContaineeEndLine);
1089
1090  return (ContainerBegLine <= ContaineeBegLine &&
1091          ContainerEndLine >= ContaineeEndLine &&
1092          (ContainerBegLine != ContaineeBegLine ||
1093           SM.getExpansionColumnNumber(ContainerRBeg) <=
1094           SM.getExpansionColumnNumber(ContaineeRBeg)) &&
1095          (ContainerEndLine != ContaineeEndLine ||
1096           SM.getExpansionColumnNumber(ContainerREnd) >=
1097           SM.getExpansionColumnNumber(ContaineeREnd)));
1098}
1099
1100void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
1101  if (!PrevLoc.isValid()) {
1102    PrevLoc = NewLoc;
1103    return;
1104  }
1105
1106  const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc);
1107  const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc);
1108
1109  if (PrevLocClean.asLocation().isInvalid()) {
1110    PrevLoc = NewLoc;
1111    return;
1112  }
1113
1114  if (NewLocClean.asLocation() == PrevLocClean.asLocation())
1115    return;
1116
1117  // FIXME: Ignore intra-macro edges for now.
1118  if (NewLocClean.asLocation().getExpansionLoc() ==
1119      PrevLocClean.asLocation().getExpansionLoc())
1120    return;
1121
1122  PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
1123  PrevLoc = NewLoc;
1124}
1125
1126void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd,
1127                          bool IsPostJump) {
1128
1129  if (!alwaysAdd && NewLoc.asLocation().isMacroID())
1130    return;
1131
1132  const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
1133
1134  while (!CLocs.empty()) {
1135    ContextLocation &TopContextLoc = CLocs.back();
1136
1137    // Is the top location context the same as the one for the new location?
1138    if (TopContextLoc == CLoc) {
1139      if (alwaysAdd) {
1140        if (IsConsumedExpr(TopContextLoc))
1141          TopContextLoc.markDead();
1142
1143        rawAddEdge(NewLoc);
1144      }
1145
1146      if (IsPostJump)
1147        TopContextLoc.markDead();
1148      return;
1149    }
1150
1151    if (containsLocation(TopContextLoc, CLoc)) {
1152      if (alwaysAdd) {
1153        rawAddEdge(NewLoc);
1154
1155        if (IsConsumedExpr(CLoc)) {
1156          CLocs.push_back(ContextLocation(CLoc, /*IsDead=*/true));
1157          return;
1158        }
1159      }
1160
1161      CLocs.push_back(ContextLocation(CLoc, /*IsDead=*/IsPostJump));
1162      return;
1163    }
1164
1165    // Context does not contain the location.  Flush it.
1166    popLocation();
1167  }
1168
1169  // If we reach here, there is no enclosing context.  Just add the edge.
1170  rawAddEdge(NewLoc);
1171}
1172
1173bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
1174  if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
1175    return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
1176
1177  return false;
1178}
1179
1180void EdgeBuilder::addExtendedContext(const Stmt *S) {
1181  if (!S)
1182    return;
1183
1184  const Stmt *Parent = PDB.getParent(S);
1185  while (Parent) {
1186    if (isa<CompoundStmt>(Parent))
1187      Parent = PDB.getParent(Parent);
1188    else
1189      break;
1190  }
1191
1192  if (Parent) {
1193    switch (Parent->getStmtClass()) {
1194      case Stmt::DoStmtClass:
1195      case Stmt::ObjCAtSynchronizedStmtClass:
1196        addContext(Parent);
1197      default:
1198        break;
1199    }
1200  }
1201
1202  addContext(S);
1203}
1204
1205void EdgeBuilder::addContext(const Stmt *S) {
1206  if (!S)
1207    return;
1208
1209  PathDiagnosticLocation L(S, PDB.getSourceManager(), PDB.LC);
1210  addContext(L);
1211}
1212
1213void EdgeBuilder::addContext(const PathDiagnosticLocation &L) {
1214  while (!CLocs.empty()) {
1215    const PathDiagnosticLocation &TopContextLoc = CLocs.back();
1216
1217    // Is the top location context the same as the one for the new location?
1218    if (TopContextLoc == L)
1219      return;
1220
1221    if (containsLocation(TopContextLoc, L)) {
1222      CLocs.push_back(L);
1223      return;
1224    }
1225
1226    // Context does not contain the location.  Flush it.
1227    popLocation();
1228  }
1229
1230  CLocs.push_back(L);
1231}
1232
1233// Cone-of-influence: support the reverse propagation of "interesting" symbols
1234// and values by tracing interesting calculations backwards through evaluated
1235// expressions along a path.  This is probably overly complicated, but the idea
1236// is that if an expression computed an "interesting" value, the child
1237// expressions are are also likely to be "interesting" as well (which then
1238// propagates to the values they in turn compute).  This reverse propagation
1239// is needed to track interesting correlations across function call boundaries,
1240// where formal arguments bind to actual arguments, etc.  This is also needed
1241// because the constraint solver sometimes simplifies certain symbolic values
1242// into constants when appropriate, and this complicates reasoning about
1243// interesting values.
1244typedef llvm::DenseSet<const Expr *> InterestingExprs;
1245
1246static void reversePropagateIntererstingSymbols(BugReport &R,
1247                                                InterestingExprs &IE,
1248                                                const ProgramState *State,
1249                                                const Expr *Ex,
1250                                                const LocationContext *LCtx) {
1251  SVal V = State->getSVal(Ex, LCtx);
1252  if (!(R.isInteresting(V) || IE.count(Ex)))
1253    return;
1254
1255  switch (Ex->getStmtClass()) {
1256    default:
1257      if (!isa<CastExpr>(Ex))
1258        break;
1259      // Fall through.
1260    case Stmt::BinaryOperatorClass:
1261    case Stmt::UnaryOperatorClass: {
1262      for (Stmt::const_child_iterator CI = Ex->child_begin(),
1263            CE = Ex->child_end();
1264            CI != CE; ++CI) {
1265        if (const Expr *child = dyn_cast_or_null<Expr>(*CI)) {
1266          IE.insert(child);
1267          SVal ChildV = State->getSVal(child, LCtx);
1268          R.markInteresting(ChildV);
1269        }
1270        break;
1271      }
1272    }
1273  }
1274
1275  R.markInteresting(V);
1276}
1277
1278static void reversePropagateInterestingSymbols(BugReport &R,
1279                                               InterestingExprs &IE,
1280                                               const ProgramState *State,
1281                                               const LocationContext *CalleeCtx,
1282                                               const LocationContext *CallerCtx)
1283{
1284  // FIXME: Handle non-CallExpr-based CallEvents.
1285  const StackFrameContext *Callee = CalleeCtx->getCurrentStackFrame();
1286  const Stmt *CallSite = Callee->getCallSite();
1287  if (const CallExpr *CE = dyn_cast_or_null<CallExpr>(CallSite)) {
1288    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CalleeCtx->getDecl())) {
1289      FunctionDecl::param_const_iterator PI = FD->param_begin(),
1290                                         PE = FD->param_end();
1291      CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end();
1292      for (; AI != AE && PI != PE; ++AI, ++PI) {
1293        if (const Expr *ArgE = *AI) {
1294          if (const ParmVarDecl *PD = *PI) {
1295            Loc LV = State->getLValue(PD, CalleeCtx);
1296            if (R.isInteresting(LV) || R.isInteresting(State->getRawSVal(LV)))
1297              IE.insert(ArgE);
1298          }
1299        }
1300      }
1301    }
1302  }
1303}
1304
1305//===----------------------------------------------------------------------===//
1306// Functions for determining if a loop was executed 0 times.
1307//===----------------------------------------------------------------------===//
1308
1309/// Return true if the terminator is a loop and the destination is the
1310/// false branch.
1311static bool isLoopJumpPastBody(const Stmt *Term, const BlockEdge *BE) {
1312  switch (Term->getStmtClass()) {
1313    case Stmt::ForStmtClass:
1314    case Stmt::WhileStmtClass:
1315    case Stmt::ObjCForCollectionStmtClass:
1316      break;
1317    default:
1318      // Note that we intentionally do not include do..while here.
1319      return false;
1320  }
1321
1322  // Did we take the false branch?
1323  const CFGBlock *Src = BE->getSrc();
1324  assert(Src->succ_size() == 2);
1325  return (*(Src->succ_begin()+1) == BE->getDst());
1326}
1327
1328static bool isContainedByStmt(ParentMap &PM, const Stmt *S, const Stmt *SubS) {
1329  while (SubS) {
1330    if (SubS == S)
1331      return true;
1332    SubS = PM.getParent(SubS);
1333  }
1334  return false;
1335}
1336
1337static const Stmt *getStmtBeforeCond(ParentMap &PM, const Stmt *Term,
1338                                     const ExplodedNode *N) {
1339  while (N) {
1340    Optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>();
1341    if (SP) {
1342      const Stmt *S = SP->getStmt();
1343      if (!isContainedByStmt(PM, Term, S))
1344        return S;
1345    }
1346    N = GetPredecessorNode(N);
1347  }
1348  return 0;
1349}
1350
1351static bool isInLoopBody(ParentMap &PM, const Stmt *S, const Stmt *Term) {
1352  const Stmt *LoopBody = 0;
1353  switch (Term->getStmtClass()) {
1354    case Stmt::ForStmtClass: {
1355      const ForStmt *FS = cast<ForStmt>(Term);
1356      if (isContainedByStmt(PM, FS->getInc(), S))
1357        return true;
1358      LoopBody = FS->getBody();
1359      break;
1360    }
1361    case Stmt::ObjCForCollectionStmtClass: {
1362      const ObjCForCollectionStmt *FC = cast<ObjCForCollectionStmt>(Term);
1363      LoopBody = FC->getBody();
1364      break;
1365    }
1366    case Stmt::WhileStmtClass:
1367      LoopBody = cast<WhileStmt>(Term)->getBody();
1368      break;
1369    default:
1370      return false;
1371  }
1372  return isContainedByStmt(PM, LoopBody, S);
1373}
1374
1375//===----------------------------------------------------------------------===//
1376// Top-level logic for generating extensive path diagnostics.
1377//===----------------------------------------------------------------------===//
1378
1379static bool GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
1380                                            PathDiagnosticBuilder &PDB,
1381                                            const ExplodedNode *N,
1382                                      ArrayRef<BugReporterVisitor *> visitors) {
1383  EdgeBuilder EB(PD, PDB);
1384  const SourceManager& SM = PDB.getSourceManager();
1385  StackDiagVector CallStack;
1386  InterestingExprs IE;
1387
1388  const ExplodedNode *NextNode = N->pred_empty() ? NULL : *(N->pred_begin());
1389  while (NextNode) {
1390    N = NextNode;
1391    NextNode = GetPredecessorNode(N);
1392    ProgramPoint P = N->getLocation();
1393
1394    do {
1395      if (Optional<PostStmt> PS = P.getAs<PostStmt>()) {
1396        if (const Expr *Ex = PS->getStmtAs<Expr>())
1397          reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1398                                              N->getState().getPtr(), Ex,
1399                                              N->getLocationContext());
1400      }
1401
1402      if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
1403        const Stmt *S = CE->getCalleeContext()->getCallSite();
1404        if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) {
1405            reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1406                                                N->getState().getPtr(), Ex,
1407                                                N->getLocationContext());
1408        }
1409
1410        PathDiagnosticCallPiece *C =
1411          PathDiagnosticCallPiece::construct(N, *CE, SM);
1412        GRBugReporter& BR = PDB.getBugReporter();
1413        BR.addCallPieceLocationContextPair(C, CE->getCalleeContext());
1414
1415        EB.addEdge(C->callReturn, /*AlwaysAdd=*/true, /*IsPostJump=*/true);
1416        EB.flushLocations();
1417
1418        PD.getActivePath().push_front(C);
1419        PD.pushActivePath(&C->path);
1420        CallStack.push_back(StackDiagPair(C, N));
1421        break;
1422      }
1423
1424      // Pop the call hierarchy if we are done walking the contents
1425      // of a function call.
1426      if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
1427        // Add an edge to the start of the function.
1428        const Decl *D = CE->getCalleeContext()->getDecl();
1429        PathDiagnosticLocation pos =
1430          PathDiagnosticLocation::createBegin(D, SM);
1431        EB.addEdge(pos);
1432
1433        // Flush all locations, and pop the active path.
1434        bool VisitedEntireCall = PD.isWithinCall();
1435        EB.flushLocations();
1436        PD.popActivePath();
1437        PDB.LC = N->getLocationContext();
1438
1439        // Either we just added a bunch of stuff to the top-level path, or
1440        // we have a previous CallExitEnd.  If the former, it means that the
1441        // path terminated within a function call.  We must then take the
1442        // current contents of the active path and place it within
1443        // a new PathDiagnosticCallPiece.
1444        PathDiagnosticCallPiece *C;
1445        if (VisitedEntireCall) {
1446          C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
1447        } else {
1448          const Decl *Caller = CE->getLocationContext()->getDecl();
1449          C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
1450          GRBugReporter& BR = PDB.getBugReporter();
1451          BR.addCallPieceLocationContextPair(C, CE->getCalleeContext());
1452        }
1453
1454        C->setCallee(*CE, SM);
1455        EB.addContext(C->getLocation());
1456
1457        if (!CallStack.empty()) {
1458          assert(CallStack.back().first == C);
1459          CallStack.pop_back();
1460        }
1461        break;
1462      }
1463
1464      // Note that is important that we update the LocationContext
1465      // after looking at CallExits.  CallExit basically adds an
1466      // edge in the *caller*, so we don't want to update the LocationContext
1467      // too soon.
1468      PDB.LC = N->getLocationContext();
1469
1470      // Block edges.
1471      if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
1472        // Does this represent entering a call?  If so, look at propagating
1473        // interesting symbols across call boundaries.
1474        if (NextNode) {
1475          const LocationContext *CallerCtx = NextNode->getLocationContext();
1476          const LocationContext *CalleeCtx = PDB.LC;
1477          if (CallerCtx != CalleeCtx) {
1478            reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
1479                                               N->getState().getPtr(),
1480                                               CalleeCtx, CallerCtx);
1481          }
1482        }
1483
1484        // Are we jumping to the head of a loop?  Add a special diagnostic.
1485        if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
1486          PathDiagnosticLocation L(Loop, SM, PDB.LC);
1487          const CompoundStmt *CS = NULL;
1488
1489          if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1490            CS = dyn_cast<CompoundStmt>(FS->getBody());
1491          else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1492            CS = dyn_cast<CompoundStmt>(WS->getBody());
1493
1494          PathDiagnosticEventPiece *p =
1495            new PathDiagnosticEventPiece(L,
1496                                        "Looping back to the head of the loop");
1497          p->setPrunable(true);
1498
1499          EB.addEdge(p->getLocation(), true);
1500          PD.getActivePath().push_front(p);
1501
1502          if (CS) {
1503            PathDiagnosticLocation BL =
1504              PathDiagnosticLocation::createEndBrace(CS, SM);
1505            EB.addEdge(BL);
1506          }
1507        }
1508
1509        const CFGBlock *BSrc = BE->getSrc();
1510        ParentMap &PM = PDB.getParentMap();
1511
1512        if (const Stmt *Term = BSrc->getTerminator()) {
1513          // Are we jumping past the loop body without ever executing the
1514          // loop (because the condition was false)?
1515          if (isLoopJumpPastBody(Term, &*BE) &&
1516              !isInLoopBody(PM,
1517                            getStmtBeforeCond(PM,
1518                                              BSrc->getTerminatorCondition(),
1519                                              N),
1520                            Term)) {
1521            PathDiagnosticLocation L(Term, SM, PDB.LC);
1522            PathDiagnosticEventPiece *PE =
1523                new PathDiagnosticEventPiece(L, "Loop body executed 0 times");
1524            PE->setPrunable(true);
1525
1526            EB.addEdge(PE->getLocation(), true);
1527            PD.getActivePath().push_front(PE);
1528          }
1529
1530          // In any case, add the terminator as the current statement
1531          // context for control edges.
1532          EB.addContext(Term);
1533        }
1534
1535        break;
1536      }
1537
1538      if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) {
1539        Optional<CFGElement> First = BE->getFirstElement();
1540        if (Optional<CFGStmt> S = First ? First->getAs<CFGStmt>() : None) {
1541          const Stmt *stmt = S->getStmt();
1542          if (IsControlFlowExpr(stmt)) {
1543            // Add the proper context for '&&', '||', and '?'.
1544            EB.addContext(stmt);
1545          }
1546          else
1547            EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt());
1548        }
1549
1550        break;
1551      }
1552
1553
1554    } while (0);
1555
1556    if (!NextNode)
1557      continue;
1558
1559    // Add pieces from custom visitors.
1560    BugReport *R = PDB.getBugReport();
1561    for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(),
1562                                                  E = visitors.end();
1563         I != E; ++I) {
1564      if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) {
1565        const PathDiagnosticLocation &Loc = p->getLocation();
1566        EB.addEdge(Loc, true);
1567        PD.getActivePath().push_front(p);
1568        updateStackPiecesWithMessage(p, CallStack);
1569
1570        if (const Stmt *S = Loc.asStmt())
1571          EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1572      }
1573    }
1574  }
1575
1576  return PDB.getBugReport()->isValid();
1577}
1578
1579//===----------------------------------------------------------------------===//
1580// Methods for BugType and subclasses.
1581//===----------------------------------------------------------------------===//
1582BugType::~BugType() { }
1583
1584void BugType::FlushReports(BugReporter &BR) {}
1585
1586void BuiltinBug::anchor() {}
1587
1588//===----------------------------------------------------------------------===//
1589// Methods for BugReport and subclasses.
1590//===----------------------------------------------------------------------===//
1591
1592void BugReport::NodeResolver::anchor() {}
1593
1594void BugReport::addVisitor(BugReporterVisitor* visitor) {
1595  if (!visitor)
1596    return;
1597
1598  llvm::FoldingSetNodeID ID;
1599  visitor->Profile(ID);
1600  void *InsertPos;
1601
1602  if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
1603    delete visitor;
1604    return;
1605  }
1606
1607  CallbacksSet.InsertNode(visitor, InsertPos);
1608  Callbacks.push_back(visitor);
1609  ++ConfigurationChangeToken;
1610}
1611
1612BugReport::~BugReport() {
1613  for (visitor_iterator I = visitor_begin(), E = visitor_end(); I != E; ++I) {
1614    delete *I;
1615  }
1616  while (!interestingSymbols.empty()) {
1617    popInterestingSymbolsAndRegions();
1618  }
1619}
1620
1621const Decl *BugReport::getDeclWithIssue() const {
1622  if (DeclWithIssue)
1623    return DeclWithIssue;
1624
1625  const ExplodedNode *N = getErrorNode();
1626  if (!N)
1627    return 0;
1628
1629  const LocationContext *LC = N->getLocationContext();
1630  return LC->getCurrentStackFrame()->getDecl();
1631}
1632
1633void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
1634  hash.AddPointer(&BT);
1635  hash.AddString(Description);
1636  PathDiagnosticLocation UL = getUniqueingLocation();
1637  if (UL.isValid()) {
1638    UL.Profile(hash);
1639  } else if (Location.isValid()) {
1640    Location.Profile(hash);
1641  } else {
1642    assert(ErrorNode);
1643    hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
1644  }
1645
1646  for (SmallVectorImpl<SourceRange>::const_iterator I =
1647      Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1648    const SourceRange range = *I;
1649    if (!range.isValid())
1650      continue;
1651    hash.AddInteger(range.getBegin().getRawEncoding());
1652    hash.AddInteger(range.getEnd().getRawEncoding());
1653  }
1654}
1655
1656void BugReport::markInteresting(SymbolRef sym) {
1657  if (!sym)
1658    return;
1659
1660  // If the symbol wasn't already in our set, note a configuration change.
1661  if (getInterestingSymbols().insert(sym).second)
1662    ++ConfigurationChangeToken;
1663
1664  if (const SymbolMetadata *meta = dyn_cast<SymbolMetadata>(sym))
1665    getInterestingRegions().insert(meta->getRegion());
1666}
1667
1668void BugReport::markInteresting(const MemRegion *R) {
1669  if (!R)
1670    return;
1671
1672  // If the base region wasn't already in our set, note a configuration change.
1673  R = R->getBaseRegion();
1674  if (getInterestingRegions().insert(R).second)
1675    ++ConfigurationChangeToken;
1676
1677  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
1678    getInterestingSymbols().insert(SR->getSymbol());
1679}
1680
1681void BugReport::markInteresting(SVal V) {
1682  markInteresting(V.getAsRegion());
1683  markInteresting(V.getAsSymbol());
1684}
1685
1686void BugReport::markInteresting(const LocationContext *LC) {
1687  if (!LC)
1688    return;
1689  InterestingLocationContexts.insert(LC);
1690}
1691
1692bool BugReport::isInteresting(SVal V) {
1693  return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol());
1694}
1695
1696bool BugReport::isInteresting(SymbolRef sym) {
1697  if (!sym)
1698    return false;
1699  // We don't currently consider metadata symbols to be interesting
1700  // even if we know their region is interesting. Is that correct behavior?
1701  return getInterestingSymbols().count(sym);
1702}
1703
1704bool BugReport::isInteresting(const MemRegion *R) {
1705  if (!R)
1706    return false;
1707  R = R->getBaseRegion();
1708  bool b = getInterestingRegions().count(R);
1709  if (b)
1710    return true;
1711  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
1712    return getInterestingSymbols().count(SR->getSymbol());
1713  return false;
1714}
1715
1716bool BugReport::isInteresting(const LocationContext *LC) {
1717  if (!LC)
1718    return false;
1719  return InterestingLocationContexts.count(LC);
1720}
1721
1722void BugReport::lazyInitializeInterestingSets() {
1723  if (interestingSymbols.empty()) {
1724    interestingSymbols.push_back(new Symbols());
1725    interestingRegions.push_back(new Regions());
1726  }
1727}
1728
1729BugReport::Symbols &BugReport::getInterestingSymbols() {
1730  lazyInitializeInterestingSets();
1731  return *interestingSymbols.back();
1732}
1733
1734BugReport::Regions &BugReport::getInterestingRegions() {
1735  lazyInitializeInterestingSets();
1736  return *interestingRegions.back();
1737}
1738
1739void BugReport::pushInterestingSymbolsAndRegions() {
1740  interestingSymbols.push_back(new Symbols(getInterestingSymbols()));
1741  interestingRegions.push_back(new Regions(getInterestingRegions()));
1742}
1743
1744void BugReport::popInterestingSymbolsAndRegions() {
1745  delete interestingSymbols.back();
1746  interestingSymbols.pop_back();
1747  delete interestingRegions.back();
1748  interestingRegions.pop_back();
1749}
1750
1751const Stmt *BugReport::getStmt() const {
1752  if (!ErrorNode)
1753    return 0;
1754
1755  ProgramPoint ProgP = ErrorNode->getLocation();
1756  const Stmt *S = NULL;
1757
1758  if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
1759    CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
1760    if (BE->getBlock() == &Exit)
1761      S = GetPreviousStmt(ErrorNode);
1762  }
1763  if (!S)
1764    S = GetStmt(ProgP);
1765
1766  return S;
1767}
1768
1769std::pair<BugReport::ranges_iterator, BugReport::ranges_iterator>
1770BugReport::getRanges() {
1771    // If no custom ranges, add the range of the statement corresponding to
1772    // the error node.
1773    if (Ranges.empty()) {
1774      if (const Expr *E = dyn_cast_or_null<Expr>(getStmt()))
1775        addRange(E->getSourceRange());
1776      else
1777        return std::make_pair(ranges_iterator(), ranges_iterator());
1778    }
1779
1780    // User-specified absence of range info.
1781    if (Ranges.size() == 1 && !Ranges.begin()->isValid())
1782      return std::make_pair(ranges_iterator(), ranges_iterator());
1783
1784    return std::make_pair(Ranges.begin(), Ranges.end());
1785}
1786
1787PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
1788  if (ErrorNode) {
1789    assert(!Location.isValid() &&
1790     "Either Location or ErrorNode should be specified but not both.");
1791
1792    if (const Stmt *S = GetCurrentOrPreviousStmt(ErrorNode)) {
1793      const LocationContext *LC = ErrorNode->getLocationContext();
1794
1795      // For member expressions, return the location of the '.' or '->'.
1796      if (const MemberExpr *ME = dyn_cast<MemberExpr>(S))
1797        return PathDiagnosticLocation::createMemberLoc(ME, SM);
1798      // For binary operators, return the location of the operator.
1799      if (const BinaryOperator *B = dyn_cast<BinaryOperator>(S))
1800        return PathDiagnosticLocation::createOperatorLoc(B, SM);
1801
1802      if (ErrorNode->getLocation().getAs<PostStmtPurgeDeadSymbols>())
1803        return PathDiagnosticLocation::createEnd(S, SM, LC);
1804
1805      return PathDiagnosticLocation::createBegin(S, SM, LC);
1806    }
1807  } else {
1808    assert(Location.isValid());
1809    return Location;
1810  }
1811
1812  return PathDiagnosticLocation();
1813}
1814
1815//===----------------------------------------------------------------------===//
1816// Methods for BugReporter and subclasses.
1817//===----------------------------------------------------------------------===//
1818
1819BugReportEquivClass::~BugReportEquivClass() { }
1820GRBugReporter::~GRBugReporter() { }
1821BugReporterData::~BugReporterData() {}
1822
1823ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
1824
1825ProgramStateManager&
1826GRBugReporter::getStateManager() { return Eng.getStateManager(); }
1827
1828BugReporter::~BugReporter() {
1829  FlushReports();
1830
1831  // Free the bug reports we are tracking.
1832  typedef std::vector<BugReportEquivClass *> ContTy;
1833  for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end();
1834       I != E; ++I) {
1835    delete *I;
1836  }
1837}
1838
1839void BugReporter::FlushReports() {
1840  if (BugTypes.isEmpty())
1841    return;
1842
1843  // First flush the warnings for each BugType.  This may end up creating new
1844  // warnings and new BugTypes.
1845  // FIXME: Only NSErrorChecker needs BugType's FlushReports.
1846  // Turn NSErrorChecker into a proper checker and remove this.
1847  SmallVector<const BugType*, 16> bugTypes;
1848  for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
1849    bugTypes.push_back(*I);
1850  for (SmallVector<const BugType*, 16>::iterator
1851         I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I)
1852    const_cast<BugType*>(*I)->FlushReports(*this);
1853
1854  // We need to flush reports in deterministic order to ensure the order
1855  // of the reports is consistent between runs.
1856  typedef std::vector<BugReportEquivClass *> ContVecTy;
1857  for (ContVecTy::iterator EI=EQClassesVector.begin(), EE=EQClassesVector.end();
1858       EI != EE; ++EI){
1859    BugReportEquivClass& EQ = **EI;
1860    FlushReport(EQ);
1861  }
1862
1863  // BugReporter owns and deletes only BugTypes created implicitly through
1864  // EmitBasicReport.
1865  // FIXME: There are leaks from checkers that assume that the BugTypes they
1866  // create will be destroyed by the BugReporter.
1867  for (llvm::StringMap<BugType*>::iterator
1868         I = StrBugTypes.begin(), E = StrBugTypes.end(); I != E; ++I)
1869    delete I->second;
1870
1871  // Remove all references to the BugType objects.
1872  BugTypes = F.getEmptySet();
1873}
1874
1875//===----------------------------------------------------------------------===//
1876// PathDiagnostics generation.
1877//===----------------------------------------------------------------------===//
1878
1879namespace {
1880/// A wrapper around a report graph, which contains only a single path, and its
1881/// node maps.
1882class ReportGraph {
1883public:
1884  InterExplodedGraphMap BackMap;
1885  OwningPtr<ExplodedGraph> Graph;
1886  const ExplodedNode *ErrorNode;
1887  size_t Index;
1888};
1889
1890/// A wrapper around a trimmed graph and its node maps.
1891class TrimmedGraph {
1892  InterExplodedGraphMap InverseMap;
1893
1894  typedef llvm::DenseMap<const ExplodedNode *, unsigned> PriorityMapTy;
1895  PriorityMapTy PriorityMap;
1896
1897  typedef std::pair<const ExplodedNode *, size_t> NodeIndexPair;
1898  SmallVector<NodeIndexPair, 32> ReportNodes;
1899
1900  OwningPtr<ExplodedGraph> G;
1901
1902  /// A helper class for sorting ExplodedNodes by priority.
1903  template <bool Descending>
1904  class PriorityCompare {
1905    const PriorityMapTy &PriorityMap;
1906
1907  public:
1908    PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {}
1909
1910    bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const {
1911      PriorityMapTy::const_iterator LI = PriorityMap.find(LHS);
1912      PriorityMapTy::const_iterator RI = PriorityMap.find(RHS);
1913      PriorityMapTy::const_iterator E = PriorityMap.end();
1914
1915      if (LI == E)
1916        return Descending;
1917      if (RI == E)
1918        return !Descending;
1919
1920      return Descending ? LI->second > RI->second
1921                        : LI->second < RI->second;
1922    }
1923
1924    bool operator()(const NodeIndexPair &LHS, const NodeIndexPair &RHS) const {
1925      return (*this)(LHS.first, RHS.first);
1926    }
1927  };
1928
1929public:
1930  TrimmedGraph(const ExplodedGraph *OriginalGraph,
1931               ArrayRef<const ExplodedNode *> Nodes);
1932
1933  bool popNextReportGraph(ReportGraph &GraphWrapper);
1934};
1935}
1936
1937TrimmedGraph::TrimmedGraph(const ExplodedGraph *OriginalGraph,
1938                           ArrayRef<const ExplodedNode *> Nodes) {
1939  // The trimmed graph is created in the body of the constructor to ensure
1940  // that the DenseMaps have been initialized already.
1941  InterExplodedGraphMap ForwardMap;
1942  G.reset(OriginalGraph->trim(Nodes, &ForwardMap, &InverseMap));
1943
1944  // Find the (first) error node in the trimmed graph.  We just need to consult
1945  // the node map which maps from nodes in the original graph to nodes
1946  // in the new graph.
1947  llvm::SmallPtrSet<const ExplodedNode *, 32> RemainingNodes;
1948
1949  for (unsigned i = 0, count = Nodes.size(); i < count; ++i) {
1950    if (const ExplodedNode *NewNode = ForwardMap.lookup(Nodes[i])) {
1951      ReportNodes.push_back(std::make_pair(NewNode, i));
1952      RemainingNodes.insert(NewNode);
1953    }
1954  }
1955
1956  assert(!RemainingNodes.empty() && "No error node found in the trimmed graph");
1957
1958  // Perform a forward BFS to find all the shortest paths.
1959  std::queue<const ExplodedNode *> WS;
1960
1961  assert(G->num_roots() == 1);
1962  WS.push(*G->roots_begin());
1963  unsigned Priority = 0;
1964
1965  while (!WS.empty()) {
1966    const ExplodedNode *Node = WS.front();
1967    WS.pop();
1968
1969    PriorityMapTy::iterator PriorityEntry;
1970    bool IsNew;
1971    llvm::tie(PriorityEntry, IsNew) =
1972      PriorityMap.insert(std::make_pair(Node, Priority));
1973    ++Priority;
1974
1975    if (!IsNew) {
1976      assert(PriorityEntry->second <= Priority);
1977      continue;
1978    }
1979
1980    if (RemainingNodes.erase(Node))
1981      if (RemainingNodes.empty())
1982        break;
1983
1984    for (ExplodedNode::const_pred_iterator I = Node->succ_begin(),
1985                                           E = Node->succ_end();
1986         I != E; ++I)
1987      WS.push(*I);
1988  }
1989
1990  // Sort the error paths from longest to shortest.
1991  std::sort(ReportNodes.begin(), ReportNodes.end(),
1992            PriorityCompare<true>(PriorityMap));
1993}
1994
1995bool TrimmedGraph::popNextReportGraph(ReportGraph &GraphWrapper) {
1996  if (ReportNodes.empty())
1997    return false;
1998
1999  const ExplodedNode *OrigN;
2000  llvm::tie(OrigN, GraphWrapper.Index) = ReportNodes.pop_back_val();
2001  assert(PriorityMap.find(OrigN) != PriorityMap.end() &&
2002         "error node not accessible from root");
2003
2004  // Create a new graph with a single path.  This is the graph
2005  // that will be returned to the caller.
2006  ExplodedGraph *GNew = new ExplodedGraph();
2007  GraphWrapper.Graph.reset(GNew);
2008  GraphWrapper.BackMap.clear();
2009
2010  // Now walk from the error node up the BFS path, always taking the
2011  // predeccessor with the lowest number.
2012  ExplodedNode *Succ = 0;
2013  while (true) {
2014    // Create the equivalent node in the new graph with the same state
2015    // and location.
2016    ExplodedNode *NewN = GNew->getNode(OrigN->getLocation(), OrigN->getState(),
2017                                       OrigN->isSink());
2018
2019    // Store the mapping to the original node.
2020    InterExplodedGraphMap::const_iterator IMitr = InverseMap.find(OrigN);
2021    assert(IMitr != InverseMap.end() && "No mapping to original node.");
2022    GraphWrapper.BackMap[NewN] = IMitr->second;
2023
2024    // Link up the new node with the previous node.
2025    if (Succ)
2026      Succ->addPredecessor(NewN, *GNew);
2027    else
2028      GraphWrapper.ErrorNode = NewN;
2029
2030    Succ = NewN;
2031
2032    // Are we at the final node?
2033    if (OrigN->pred_empty()) {
2034      GNew->addRoot(NewN);
2035      break;
2036    }
2037
2038    // Find the next predeccessor node.  We choose the node that is marked
2039    // with the lowest BFS number.
2040    OrigN = *std::min_element(OrigN->pred_begin(), OrigN->pred_end(),
2041                          PriorityCompare<false>(PriorityMap));
2042  }
2043
2044  return true;
2045}
2046
2047
2048/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
2049///  and collapses PathDiagosticPieces that are expanded by macros.
2050static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM) {
2051  typedef std::vector<std::pair<IntrusiveRefCntPtr<PathDiagnosticMacroPiece>,
2052                                SourceLocation> > MacroStackTy;
2053
2054  typedef std::vector<IntrusiveRefCntPtr<PathDiagnosticPiece> >
2055          PiecesTy;
2056
2057  MacroStackTy MacroStack;
2058  PiecesTy Pieces;
2059
2060  for (PathPieces::const_iterator I = path.begin(), E = path.end();
2061       I!=E; ++I) {
2062
2063    PathDiagnosticPiece *piece = I->getPtr();
2064
2065    // Recursively compact calls.
2066    if (PathDiagnosticCallPiece *call=dyn_cast<PathDiagnosticCallPiece>(piece)){
2067      CompactPathDiagnostic(call->path, SM);
2068    }
2069
2070    // Get the location of the PathDiagnosticPiece.
2071    const FullSourceLoc Loc = piece->getLocation().asLocation();
2072
2073    // Determine the instantiation location, which is the location we group
2074    // related PathDiagnosticPieces.
2075    SourceLocation InstantiationLoc = Loc.isMacroID() ?
2076                                      SM.getExpansionLoc(Loc) :
2077                                      SourceLocation();
2078
2079    if (Loc.isFileID()) {
2080      MacroStack.clear();
2081      Pieces.push_back(piece);
2082      continue;
2083    }
2084
2085    assert(Loc.isMacroID());
2086
2087    // Is the PathDiagnosticPiece within the same macro group?
2088    if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
2089      MacroStack.back().first->subPieces.push_back(piece);
2090      continue;
2091    }
2092
2093    // We aren't in the same group.  Are we descending into a new macro
2094    // or are part of an old one?
2095    IntrusiveRefCntPtr<PathDiagnosticMacroPiece> MacroGroup;
2096
2097    SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
2098                                          SM.getExpansionLoc(Loc) :
2099                                          SourceLocation();
2100
2101    // Walk the entire macro stack.
2102    while (!MacroStack.empty()) {
2103      if (InstantiationLoc == MacroStack.back().second) {
2104        MacroGroup = MacroStack.back().first;
2105        break;
2106      }
2107
2108      if (ParentInstantiationLoc == MacroStack.back().second) {
2109        MacroGroup = MacroStack.back().first;
2110        break;
2111      }
2112
2113      MacroStack.pop_back();
2114    }
2115
2116    if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
2117      // Create a new macro group and add it to the stack.
2118      PathDiagnosticMacroPiece *NewGroup =
2119        new PathDiagnosticMacroPiece(
2120          PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
2121
2122      if (MacroGroup)
2123        MacroGroup->subPieces.push_back(NewGroup);
2124      else {
2125        assert(InstantiationLoc.isFileID());
2126        Pieces.push_back(NewGroup);
2127      }
2128
2129      MacroGroup = NewGroup;
2130      MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
2131    }
2132
2133    // Finally, add the PathDiagnosticPiece to the group.
2134    MacroGroup->subPieces.push_back(piece);
2135  }
2136
2137  // Now take the pieces and construct a new PathDiagnostic.
2138  path.clear();
2139
2140  for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I)
2141    path.push_back(*I);
2142}
2143
2144bool GRBugReporter::generatePathDiagnostic(PathDiagnostic& PD,
2145                                           PathDiagnosticConsumer &PC,
2146                                           ArrayRef<BugReport *> &bugReports) {
2147  assert(!bugReports.empty());
2148
2149  bool HasValid = false;
2150  bool HasInvalid = false;
2151  SmallVector<const ExplodedNode *, 32> errorNodes;
2152  for (ArrayRef<BugReport*>::iterator I = bugReports.begin(),
2153                                      E = bugReports.end(); I != E; ++I) {
2154    if ((*I)->isValid()) {
2155      HasValid = true;
2156      errorNodes.push_back((*I)->getErrorNode());
2157    } else {
2158      // Keep the errorNodes list in sync with the bugReports list.
2159      HasInvalid = true;
2160      errorNodes.push_back(0);
2161    }
2162  }
2163
2164  // If all the reports have been marked invalid by a previous path generation,
2165  // we're done.
2166  if (!HasValid)
2167    return false;
2168
2169  typedef PathDiagnosticConsumer::PathGenerationScheme PathGenerationScheme;
2170  PathGenerationScheme ActiveScheme = PC.getGenerationScheme();
2171
2172  TrimmedGraph TrimG(&getGraph(), errorNodes);
2173  ReportGraph ErrorGraph;
2174
2175  while (TrimG.popNextReportGraph(ErrorGraph)) {
2176    // Find the BugReport with the original location.
2177    assert(ErrorGraph.Index < bugReports.size());
2178    BugReport *R = bugReports[ErrorGraph.Index];
2179    assert(R && "No original report found for sliced graph.");
2180    assert(R->isValid() && "Report selected by trimmed graph marked invalid.");
2181
2182    // Start building the path diagnostic...
2183    PathDiagnosticBuilder PDB(*this, R, ErrorGraph.BackMap, &PC);
2184    const ExplodedNode *N = ErrorGraph.ErrorNode;
2185
2186    // Register additional node visitors.
2187    R->addVisitor(new NilReceiverBRVisitor());
2188    R->addVisitor(new ConditionBRVisitor());
2189    R->addVisitor(new LikelyFalsePositiveSuppressionBRVisitor());
2190
2191    BugReport::VisitorList visitors;
2192    unsigned origReportConfigToken, finalReportConfigToken;
2193
2194    // While generating diagnostics, it's possible the visitors will decide
2195    // new symbols and regions are interesting, or add other visitors based on
2196    // the information they find. If they do, we need to regenerate the path
2197    // based on our new report configuration.
2198    do {
2199      // Get a clean copy of all the visitors.
2200      for (BugReport::visitor_iterator I = R->visitor_begin(),
2201                                       E = R->visitor_end(); I != E; ++I)
2202        visitors.push_back((*I)->clone());
2203
2204      // Clear out the active path from any previous work.
2205      PD.resetPath();
2206      origReportConfigToken = R->getConfigurationChangeToken();
2207
2208      // Generate the very last diagnostic piece - the piece is visible before
2209      // the trace is expanded.
2210      PathDiagnosticPiece *LastPiece = 0;
2211      for (BugReport::visitor_iterator I = visitors.begin(), E = visitors.end();
2212          I != E; ++I) {
2213        if (PathDiagnosticPiece *Piece = (*I)->getEndPath(PDB, N, *R)) {
2214          assert (!LastPiece &&
2215              "There can only be one final piece in a diagnostic.");
2216          LastPiece = Piece;
2217        }
2218      }
2219
2220      if (ActiveScheme != PathDiagnosticConsumer::None) {
2221        if (!LastPiece)
2222          LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R);
2223        assert(LastPiece);
2224        PD.setEndOfPath(LastPiece);
2225      }
2226
2227      switch (ActiveScheme) {
2228      case PathDiagnosticConsumer::Extensive:
2229        GenerateExtensivePathDiagnostic(PD, PDB, N, visitors);
2230        break;
2231      case PathDiagnosticConsumer::Minimal:
2232        GenerateMinimalPathDiagnostic(PD, PDB, N, visitors);
2233        break;
2234      case PathDiagnosticConsumer::None:
2235        GenerateVisitorsOnlyPathDiagnostic(PD, PDB, N, visitors);
2236        break;
2237      }
2238
2239      // Clean up the visitors we used.
2240      llvm::DeleteContainerPointers(visitors);
2241
2242      // Did anything change while generating this path?
2243      finalReportConfigToken = R->getConfigurationChangeToken();
2244    } while (finalReportConfigToken != origReportConfigToken);
2245
2246    if (!R->isValid())
2247      continue;
2248
2249    // Finally, prune the diagnostic path of uninteresting stuff.
2250    if (!PD.path.empty()) {
2251      // Remove messages that are basically the same.
2252      removeRedundantMsgs(PD.getMutablePieces());
2253
2254      if (R->shouldPrunePath() &&
2255          getEngine().getAnalysisManager().options.shouldPrunePaths()) {
2256        bool stillHasNotes = RemoveUnneededCalls(PD.getMutablePieces(), R);
2257        assert(stillHasNotes);
2258        (void)stillHasNotes;
2259      }
2260
2261      adjustCallLocations(PD.getMutablePieces());
2262    }
2263
2264    // We found a report and didn't suppress it.
2265    return true;
2266  }
2267
2268  // We suppressed all the reports in this equivalence class.
2269  assert(!HasInvalid && "Inconsistent suppression");
2270  (void)HasInvalid;
2271  return false;
2272}
2273
2274void BugReporter::Register(BugType *BT) {
2275  BugTypes = F.add(BugTypes, BT);
2276}
2277
2278void BugReporter::emitReport(BugReport* R) {
2279  // Compute the bug report's hash to determine its equivalence class.
2280  llvm::FoldingSetNodeID ID;
2281  R->Profile(ID);
2282
2283  // Lookup the equivance class.  If there isn't one, create it.
2284  BugType& BT = R->getBugType();
2285  Register(&BT);
2286  void *InsertPos;
2287  BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
2288
2289  if (!EQ) {
2290    EQ = new BugReportEquivClass(R);
2291    EQClasses.InsertNode(EQ, InsertPos);
2292    EQClassesVector.push_back(EQ);
2293  }
2294  else
2295    EQ->AddReport(R);
2296}
2297
2298
2299//===----------------------------------------------------------------------===//
2300// Emitting reports in equivalence classes.
2301//===----------------------------------------------------------------------===//
2302
2303namespace {
2304struct FRIEC_WLItem {
2305  const ExplodedNode *N;
2306  ExplodedNode::const_succ_iterator I, E;
2307
2308  FRIEC_WLItem(const ExplodedNode *n)
2309  : N(n), I(N->succ_begin()), E(N->succ_end()) {}
2310};
2311}
2312
2313static BugReport *
2314FindReportInEquivalenceClass(BugReportEquivClass& EQ,
2315                             SmallVectorImpl<BugReport*> &bugReports) {
2316
2317  BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
2318  assert(I != E);
2319  BugType& BT = I->getBugType();
2320
2321  // If we don't need to suppress any of the nodes because they are
2322  // post-dominated by a sink, simply add all the nodes in the equivalence class
2323  // to 'Nodes'.  Any of the reports will serve as a "representative" report.
2324  if (!BT.isSuppressOnSink()) {
2325    BugReport *R = I;
2326    for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
2327      const ExplodedNode *N = I->getErrorNode();
2328      if (N) {
2329        R = I;
2330        bugReports.push_back(R);
2331      }
2332    }
2333    return R;
2334  }
2335
2336  // For bug reports that should be suppressed when all paths are post-dominated
2337  // by a sink node, iterate through the reports in the equivalence class
2338  // until we find one that isn't post-dominated (if one exists).  We use a
2339  // DFS traversal of the ExplodedGraph to find a non-sink node.  We could write
2340  // this as a recursive function, but we don't want to risk blowing out the
2341  // stack for very long paths.
2342  BugReport *exampleReport = 0;
2343
2344  for (; I != E; ++I) {
2345    const ExplodedNode *errorNode = I->getErrorNode();
2346
2347    if (!errorNode)
2348      continue;
2349    if (errorNode->isSink()) {
2350      llvm_unreachable(
2351           "BugType::isSuppressSink() should not be 'true' for sink end nodes");
2352    }
2353    // No successors?  By definition this nodes isn't post-dominated by a sink.
2354    if (errorNode->succ_empty()) {
2355      bugReports.push_back(I);
2356      if (!exampleReport)
2357        exampleReport = I;
2358      continue;
2359    }
2360
2361    // At this point we know that 'N' is not a sink and it has at least one
2362    // successor.  Use a DFS worklist to find a non-sink end-of-path node.
2363    typedef FRIEC_WLItem WLItem;
2364    typedef SmallVector<WLItem, 10> DFSWorkList;
2365    llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
2366
2367    DFSWorkList WL;
2368    WL.push_back(errorNode);
2369    Visited[errorNode] = 1;
2370
2371    while (!WL.empty()) {
2372      WLItem &WI = WL.back();
2373      assert(!WI.N->succ_empty());
2374
2375      for (; WI.I != WI.E; ++WI.I) {
2376        const ExplodedNode *Succ = *WI.I;
2377        // End-of-path node?
2378        if (Succ->succ_empty()) {
2379          // If we found an end-of-path node that is not a sink.
2380          if (!Succ->isSink()) {
2381            bugReports.push_back(I);
2382            if (!exampleReport)
2383              exampleReport = I;
2384            WL.clear();
2385            break;
2386          }
2387          // Found a sink?  Continue on to the next successor.
2388          continue;
2389        }
2390        // Mark the successor as visited.  If it hasn't been explored,
2391        // enqueue it to the DFS worklist.
2392        unsigned &mark = Visited[Succ];
2393        if (!mark) {
2394          mark = 1;
2395          WL.push_back(Succ);
2396          break;
2397        }
2398      }
2399
2400      // The worklist may have been cleared at this point.  First
2401      // check if it is empty before checking the last item.
2402      if (!WL.empty() && &WL.back() == &WI)
2403        WL.pop_back();
2404    }
2405  }
2406
2407  // ExampleReport will be NULL if all the nodes in the equivalence class
2408  // were post-dominated by sinks.
2409  return exampleReport;
2410}
2411
2412void BugReporter::FlushReport(BugReportEquivClass& EQ) {
2413  SmallVector<BugReport*, 10> bugReports;
2414  BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports);
2415  if (exampleReport) {
2416    const PathDiagnosticConsumers &C = getPathDiagnosticConsumers();
2417    for (PathDiagnosticConsumers::const_iterator I=C.begin(),
2418                                                 E=C.end(); I != E; ++I) {
2419      FlushReport(exampleReport, **I, bugReports);
2420    }
2421  }
2422}
2423
2424void BugReporter::FlushReport(BugReport *exampleReport,
2425                              PathDiagnosticConsumer &PD,
2426                              ArrayRef<BugReport*> bugReports) {
2427
2428  // FIXME: Make sure we use the 'R' for the path that was actually used.
2429  // Probably doesn't make a difference in practice.
2430  BugType& BT = exampleReport->getBugType();
2431
2432  OwningPtr<PathDiagnostic>
2433    D(new PathDiagnostic(exampleReport->getDeclWithIssue(),
2434                         exampleReport->getBugType().getName(),
2435                         exampleReport->getDescription(),
2436                         exampleReport->getShortDescription(/*Fallback=*/false),
2437                         BT.getCategory(),
2438                         exampleReport->getUniqueingLocation(),
2439                         exampleReport->getUniqueingDecl()));
2440
2441  MaxBugClassSize = std::max(bugReports.size(),
2442                             static_cast<size_t>(MaxBugClassSize));
2443
2444  // Generate the full path diagnostic, using the generation scheme
2445  // specified by the PathDiagnosticConsumer. Note that we have to generate
2446  // path diagnostics even for consumers which do not support paths, because
2447  // the BugReporterVisitors may mark this bug as a false positive.
2448  if (!bugReports.empty())
2449    if (!generatePathDiagnostic(*D.get(), PD, bugReports))
2450      return;
2451
2452  MaxValidBugClassSize = std::max(bugReports.size(),
2453                                  static_cast<size_t>(MaxValidBugClassSize));
2454
2455  // If the path is empty, generate a single step path with the location
2456  // of the issue.
2457  if (D->path.empty()) {
2458    PathDiagnosticLocation L = exampleReport->getLocation(getSourceManager());
2459    PathDiagnosticPiece *piece =
2460      new PathDiagnosticEventPiece(L, exampleReport->getDescription());
2461    BugReport::ranges_iterator Beg, End;
2462    llvm::tie(Beg, End) = exampleReport->getRanges();
2463    for ( ; Beg != End; ++Beg)
2464      piece->addRange(*Beg);
2465    D->setEndOfPath(piece);
2466  }
2467
2468  // Get the meta data.
2469  const BugReport::ExtraTextList &Meta = exampleReport->getExtraText();
2470  for (BugReport::ExtraTextList::const_iterator i = Meta.begin(),
2471                                                e = Meta.end(); i != e; ++i) {
2472    D->addMeta(*i);
2473  }
2474
2475  PD.HandlePathDiagnostic(D.take());
2476}
2477
2478void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
2479                                  StringRef name,
2480                                  StringRef category,
2481                                  StringRef str, PathDiagnosticLocation Loc,
2482                                  SourceRange* RBeg, unsigned NumRanges) {
2483
2484  // 'BT' is owned by BugReporter.
2485  BugType *BT = getBugTypeForName(name, category);
2486  BugReport *R = new BugReport(*BT, str, Loc);
2487  R->setDeclWithIssue(DeclWithIssue);
2488  for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
2489  emitReport(R);
2490}
2491
2492BugType *BugReporter::getBugTypeForName(StringRef name,
2493                                        StringRef category) {
2494  SmallString<136> fullDesc;
2495  llvm::raw_svector_ostream(fullDesc) << name << ":" << category;
2496  llvm::StringMapEntry<BugType *> &
2497      entry = StrBugTypes.GetOrCreateValue(fullDesc);
2498  BugType *BT = entry.getValue();
2499  if (!BT) {
2500    BT = new BugType(name, category);
2501    entry.setValue(BT);
2502  }
2503  return BT;
2504}
2505