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