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