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