BugReporter.cpp revision c5b9c8bc6d77175f6d41d898511b1e7b1e2f86f8
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 (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
48    return SP->getStmt();
49  if (Optional<BlockEdge> BE = P.getAs<BlockEdge>())
50    return BE->getSrc()->getTerminator();
51  if (Optional<CallEnter> CE = P.getAs<CallEnter>())
52    return CE->getCallExpr();
53  if (Optional<CallExitEnd> CEE = P.getAs<CallExitEnd>())
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 (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
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 (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
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 (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
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//===----------------------------------------------------------------------===//
1299// Functions for determining if a loop was executed 0 times.
1300//===----------------------------------------------------------------------===//
1301
1302/// Return true if the terminator is a loop and the destination is the
1303/// false branch.
1304static bool isLoopJumpPastBody(const Stmt *Term, const BlockEdge *BE) {
1305  switch (Term->getStmtClass()) {
1306    case Stmt::ForStmtClass:
1307    case Stmt::WhileStmtClass:
1308    case Stmt::ObjCForCollectionStmtClass:
1309      break;
1310    default:
1311      // Note that we intentionally do not include do..while here.
1312      return false;
1313  }
1314
1315  // Did we take the false branch?
1316  const CFGBlock *Src = BE->getSrc();
1317  assert(Src->succ_size() == 2);
1318  return (*(Src->succ_begin()+1) == BE->getDst());
1319}
1320
1321static bool isContainedByStmt(ParentMap &PM, const Stmt *S, const Stmt *SubS) {
1322  while (SubS) {
1323    if (SubS == S)
1324      return true;
1325    SubS = PM.getParent(SubS);
1326  }
1327  return false;
1328}
1329
1330static const Stmt *getStmtBeforeCond(ParentMap &PM, const Stmt *Term,
1331                                     const ExplodedNode *N) {
1332  while (N) {
1333    Optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>();
1334    if (SP) {
1335      const Stmt *S = SP->getStmt();
1336      if (!isContainedByStmt(PM, Term, S))
1337        return S;
1338    }
1339    N = GetPredecessorNode(N);
1340  }
1341  return 0;
1342}
1343
1344static bool isInLoopBody(ParentMap &PM, const Stmt *S, const Stmt *Term) {
1345  const Stmt *LoopBody = 0;
1346  switch (Term->getStmtClass()) {
1347    case Stmt::ForStmtClass: {
1348      const ForStmt *FS = cast<ForStmt>(Term);
1349      if (isContainedByStmt(PM, FS->getInc(), S))
1350        return true;
1351      LoopBody = FS->getBody();
1352      break;
1353    }
1354    case Stmt::ObjCForCollectionStmtClass: {
1355      const ObjCForCollectionStmt *FC = cast<ObjCForCollectionStmt>(Term);
1356      LoopBody = FC->getBody();
1357      break;
1358
1359    }
1360    case Stmt::WhileStmtClass:
1361      LoopBody = cast<WhileStmt>(Term)->getBody();
1362      break;
1363    default:
1364      return false;
1365  }
1366  return isContainedByStmt(PM, LoopBody, S);
1367}
1368
1369//===----------------------------------------------------------------------===//
1370// Top-level logic for generating extensive path diagnostics.
1371//===----------------------------------------------------------------------===//
1372
1373static bool GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
1374                                            PathDiagnosticBuilder &PDB,
1375                                            const ExplodedNode *N,
1376                                      ArrayRef<BugReporterVisitor *> visitors) {
1377  EdgeBuilder EB(PD, PDB);
1378  const SourceManager& SM = PDB.getSourceManager();
1379  StackDiagVector CallStack;
1380  InterestingExprs IE;
1381
1382  const ExplodedNode *NextNode = N->pred_empty() ? NULL : *(N->pred_begin());
1383  while (NextNode) {
1384    N = NextNode;
1385    NextNode = GetPredecessorNode(N);
1386    ProgramPoint P = N->getLocation();
1387
1388    do {
1389      if (Optional<PostStmt> PS = P.getAs<PostStmt>()) {
1390        if (const Expr *Ex = PS->getStmtAs<Expr>())
1391          reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1392                                              N->getState().getPtr(), Ex,
1393                                              N->getLocationContext());
1394      }
1395
1396      if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
1397        const Stmt *S = CE->getCalleeContext()->getCallSite();
1398        if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) {
1399            reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1400                                                N->getState().getPtr(), Ex,
1401                                                N->getLocationContext());
1402        }
1403
1404        PathDiagnosticCallPiece *C =
1405          PathDiagnosticCallPiece::construct(N, *CE, SM);
1406        GRBugReporter& BR = PDB.getBugReporter();
1407        BR.addCallPieceLocationContextPair(C, CE->getCalleeContext());
1408
1409        EB.addEdge(C->callReturn, true);
1410        EB.flushLocations();
1411
1412        PD.getActivePath().push_front(C);
1413        PD.pushActivePath(&C->path);
1414        CallStack.push_back(StackDiagPair(C, N));
1415        break;
1416      }
1417
1418      // Pop the call hierarchy if we are done walking the contents
1419      // of a function call.
1420      if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
1421        // Add an edge to the start of the function.
1422        const Decl *D = CE->getCalleeContext()->getDecl();
1423        PathDiagnosticLocation pos =
1424          PathDiagnosticLocation::createBegin(D, SM);
1425        EB.addEdge(pos);
1426
1427        // Flush all locations, and pop the active path.
1428        bool VisitedEntireCall = PD.isWithinCall();
1429        EB.flushLocations();
1430        PD.popActivePath();
1431        PDB.LC = N->getLocationContext();
1432
1433        // Either we just added a bunch of stuff to the top-level path, or
1434        // we have a previous CallExitEnd.  If the former, it means that the
1435        // path terminated within a function call.  We must then take the
1436        // current contents of the active path and place it within
1437        // a new PathDiagnosticCallPiece.
1438        PathDiagnosticCallPiece *C;
1439        if (VisitedEntireCall) {
1440          C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
1441        } else {
1442          const Decl *Caller = CE->getLocationContext()->getDecl();
1443          C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
1444          GRBugReporter& BR = PDB.getBugReporter();
1445          BR.addCallPieceLocationContextPair(C, CE->getCalleeContext());
1446        }
1447
1448        C->setCallee(*CE, SM);
1449        EB.addContext(C->getLocation());
1450
1451        if (!CallStack.empty()) {
1452          assert(CallStack.back().first == C);
1453          CallStack.pop_back();
1454        }
1455        break;
1456      }
1457
1458      // Note that is important that we update the LocationContext
1459      // after looking at CallExits.  CallExit basically adds an
1460      // edge in the *caller*, so we don't want to update the LocationContext
1461      // too soon.
1462      PDB.LC = N->getLocationContext();
1463
1464      // Block edges.
1465      if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
1466        // Does this represent entering a call?  If so, look at propagating
1467        // interesting symbols across call boundaries.
1468        if (NextNode) {
1469          const LocationContext *CallerCtx = NextNode->getLocationContext();
1470          const LocationContext *CalleeCtx = PDB.LC;
1471          if (CallerCtx != CalleeCtx) {
1472            reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
1473                                               N->getState().getPtr(),
1474                                               CalleeCtx, CallerCtx);
1475          }
1476        }
1477
1478        // Are we jumping to the head of a loop?  Add a special diagnostic.
1479        if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
1480          PathDiagnosticLocation L(Loop, SM, PDB.LC);
1481          const CompoundStmt *CS = NULL;
1482
1483          if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1484            CS = dyn_cast<CompoundStmt>(FS->getBody());
1485          else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1486            CS = dyn_cast<CompoundStmt>(WS->getBody());
1487
1488          PathDiagnosticEventPiece *p =
1489            new PathDiagnosticEventPiece(L,
1490                                        "Looping back to the head of the loop");
1491          p->setPrunable(true);
1492
1493          EB.addEdge(p->getLocation(), true);
1494          PD.getActivePath().push_front(p);
1495
1496          if (CS) {
1497            PathDiagnosticLocation BL =
1498              PathDiagnosticLocation::createEndBrace(CS, SM);
1499            EB.addEdge(BL);
1500          }
1501        }
1502
1503        const CFGBlock *BSrc = BE->getSrc();
1504        ParentMap &PM = PDB.getParentMap();
1505
1506        if (const Stmt *Term = BSrc->getTerminator()) {
1507          // Are we jumping past the loop body without ever executing the
1508          // loop (because the condition was false)?
1509          if (isLoopJumpPastBody(Term, &*BE) &&
1510              !isInLoopBody(PM,
1511                            getStmtBeforeCond(PM,
1512                                              BSrc->getTerminatorCondition(),
1513                                              N),
1514                            Term)) {
1515            PathDiagnosticLocation L(Term, SM, PDB.LC);
1516            PathDiagnosticEventPiece *PE =
1517                new PathDiagnosticEventPiece(L, "Loop body executed 0 times");
1518            PE->setPrunable(true);
1519
1520            EB.addEdge(PE->getLocation(), true);
1521            PD.getActivePath().push_front(PE);
1522          }
1523
1524          // In any case, add the terminator as the current statement
1525          // context for control edges.
1526          EB.addContext(Term);
1527        }
1528
1529        break;
1530      }
1531
1532      if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) {
1533        Optional<CFGElement> First = BE->getFirstElement();
1534        if (Optional<CFGStmt> S = First ? First->getAs<CFGStmt>() : None) {
1535          const Stmt *stmt = S->getStmt();
1536          if (IsControlFlowExpr(stmt)) {
1537            // Add the proper context for '&&', '||', and '?'.
1538            EB.addContext(stmt);
1539          }
1540          else
1541            EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt());
1542        }
1543
1544        break;
1545      }
1546
1547
1548    } while (0);
1549
1550    if (!NextNode)
1551      continue;
1552
1553    // Add pieces from custom visitors.
1554    BugReport *R = PDB.getBugReport();
1555    for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(),
1556                                                  E = visitors.end();
1557         I != E; ++I) {
1558      if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) {
1559        const PathDiagnosticLocation &Loc = p->getLocation();
1560        EB.addEdge(Loc, true);
1561        PD.getActivePath().push_front(p);
1562        updateStackPiecesWithMessage(p, CallStack);
1563
1564        if (const Stmt *S = Loc.asStmt())
1565          EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1566      }
1567    }
1568  }
1569
1570  return PDB.getBugReport()->isValid();
1571}
1572
1573//===----------------------------------------------------------------------===//
1574// Methods for BugType and subclasses.
1575//===----------------------------------------------------------------------===//
1576BugType::~BugType() { }
1577
1578void BugType::FlushReports(BugReporter &BR) {}
1579
1580void BuiltinBug::anchor() {}
1581
1582//===----------------------------------------------------------------------===//
1583// Methods for BugReport and subclasses.
1584//===----------------------------------------------------------------------===//
1585
1586void BugReport::NodeResolver::anchor() {}
1587
1588void BugReport::addVisitor(BugReporterVisitor* visitor) {
1589  if (!visitor)
1590    return;
1591
1592  llvm::FoldingSetNodeID ID;
1593  visitor->Profile(ID);
1594  void *InsertPos;
1595
1596  if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
1597    delete visitor;
1598    return;
1599  }
1600
1601  CallbacksSet.InsertNode(visitor, InsertPos);
1602  Callbacks.push_back(visitor);
1603  ++ConfigurationChangeToken;
1604}
1605
1606BugReport::~BugReport() {
1607  for (visitor_iterator I = visitor_begin(), E = visitor_end(); I != E; ++I) {
1608    delete *I;
1609  }
1610  while (!interestingSymbols.empty()) {
1611    popInterestingSymbolsAndRegions();
1612  }
1613}
1614
1615const Decl *BugReport::getDeclWithIssue() const {
1616  if (DeclWithIssue)
1617    return DeclWithIssue;
1618
1619  const ExplodedNode *N = getErrorNode();
1620  if (!N)
1621    return 0;
1622
1623  const LocationContext *LC = N->getLocationContext();
1624  return LC->getCurrentStackFrame()->getDecl();
1625}
1626
1627void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
1628  hash.AddPointer(&BT);
1629  hash.AddString(Description);
1630  PathDiagnosticLocation UL = getUniqueingLocation();
1631  if (UL.isValid()) {
1632    UL.Profile(hash);
1633  } else if (Location.isValid()) {
1634    Location.Profile(hash);
1635  } else {
1636    assert(ErrorNode);
1637    hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
1638  }
1639
1640  for (SmallVectorImpl<SourceRange>::const_iterator I =
1641      Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1642    const SourceRange range = *I;
1643    if (!range.isValid())
1644      continue;
1645    hash.AddInteger(range.getBegin().getRawEncoding());
1646    hash.AddInteger(range.getEnd().getRawEncoding());
1647  }
1648}
1649
1650void BugReport::markInteresting(SymbolRef sym) {
1651  if (!sym)
1652    return;
1653
1654  // If the symbol wasn't already in our set, note a configuration change.
1655  if (getInterestingSymbols().insert(sym).second)
1656    ++ConfigurationChangeToken;
1657
1658  if (const SymbolMetadata *meta = dyn_cast<SymbolMetadata>(sym))
1659    getInterestingRegions().insert(meta->getRegion());
1660}
1661
1662void BugReport::markInteresting(const MemRegion *R) {
1663  if (!R)
1664    return;
1665
1666  // If the base region wasn't already in our set, note a configuration change.
1667  R = R->getBaseRegion();
1668  if (getInterestingRegions().insert(R).second)
1669    ++ConfigurationChangeToken;
1670
1671  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
1672    getInterestingSymbols().insert(SR->getSymbol());
1673}
1674
1675void BugReport::markInteresting(SVal V) {
1676  markInteresting(V.getAsRegion());
1677  markInteresting(V.getAsSymbol());
1678}
1679
1680void BugReport::markInteresting(const LocationContext *LC) {
1681  if (!LC)
1682    return;
1683  InterestingLocationContexts.insert(LC);
1684}
1685
1686bool BugReport::isInteresting(SVal V) {
1687  return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol());
1688}
1689
1690bool BugReport::isInteresting(SymbolRef sym) {
1691  if (!sym)
1692    return false;
1693  // We don't currently consider metadata symbols to be interesting
1694  // even if we know their region is interesting. Is that correct behavior?
1695  return getInterestingSymbols().count(sym);
1696}
1697
1698bool BugReport::isInteresting(const MemRegion *R) {
1699  if (!R)
1700    return false;
1701  R = R->getBaseRegion();
1702  bool b = getInterestingRegions().count(R);
1703  if (b)
1704    return true;
1705  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
1706    return getInterestingSymbols().count(SR->getSymbol());
1707  return false;
1708}
1709
1710bool BugReport::isInteresting(const LocationContext *LC) {
1711  if (!LC)
1712    return false;
1713  return InterestingLocationContexts.count(LC);
1714}
1715
1716void BugReport::lazyInitializeInterestingSets() {
1717  if (interestingSymbols.empty()) {
1718    interestingSymbols.push_back(new Symbols());
1719    interestingRegions.push_back(new Regions());
1720  }
1721}
1722
1723BugReport::Symbols &BugReport::getInterestingSymbols() {
1724  lazyInitializeInterestingSets();
1725  return *interestingSymbols.back();
1726}
1727
1728BugReport::Regions &BugReport::getInterestingRegions() {
1729  lazyInitializeInterestingSets();
1730  return *interestingRegions.back();
1731}
1732
1733void BugReport::pushInterestingSymbolsAndRegions() {
1734  interestingSymbols.push_back(new Symbols(getInterestingSymbols()));
1735  interestingRegions.push_back(new Regions(getInterestingRegions()));
1736}
1737
1738void BugReport::popInterestingSymbolsAndRegions() {
1739  delete interestingSymbols.back();
1740  interestingSymbols.pop_back();
1741  delete interestingRegions.back();
1742  interestingRegions.pop_back();
1743}
1744
1745const Stmt *BugReport::getStmt() const {
1746  if (!ErrorNode)
1747    return 0;
1748
1749  ProgramPoint ProgP = ErrorNode->getLocation();
1750  const Stmt *S = NULL;
1751
1752  if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
1753    CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
1754    if (BE->getBlock() == &Exit)
1755      S = GetPreviousStmt(ErrorNode);
1756  }
1757  if (!S)
1758    S = GetStmt(ProgP);
1759
1760  return S;
1761}
1762
1763std::pair<BugReport::ranges_iterator, BugReport::ranges_iterator>
1764BugReport::getRanges() {
1765    // If no custom ranges, add the range of the statement corresponding to
1766    // the error node.
1767    if (Ranges.empty()) {
1768      if (const Expr *E = dyn_cast_or_null<Expr>(getStmt()))
1769        addRange(E->getSourceRange());
1770      else
1771        return std::make_pair(ranges_iterator(), ranges_iterator());
1772    }
1773
1774    // User-specified absence of range info.
1775    if (Ranges.size() == 1 && !Ranges.begin()->isValid())
1776      return std::make_pair(ranges_iterator(), ranges_iterator());
1777
1778    return std::make_pair(Ranges.begin(), Ranges.end());
1779}
1780
1781PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
1782  if (ErrorNode) {
1783    assert(!Location.isValid() &&
1784     "Either Location or ErrorNode should be specified but not both.");
1785
1786    if (const Stmt *S = GetCurrentOrPreviousStmt(ErrorNode)) {
1787      const LocationContext *LC = ErrorNode->getLocationContext();
1788
1789      // For member expressions, return the location of the '.' or '->'.
1790      if (const MemberExpr *ME = dyn_cast<MemberExpr>(S))
1791        return PathDiagnosticLocation::createMemberLoc(ME, SM);
1792      // For binary operators, return the location of the operator.
1793      if (const BinaryOperator *B = dyn_cast<BinaryOperator>(S))
1794        return PathDiagnosticLocation::createOperatorLoc(B, SM);
1795
1796      if (ErrorNode->getLocation().getAs<PostStmtPurgeDeadSymbols>())
1797        return PathDiagnosticLocation::createEnd(S, SM, LC);
1798
1799      return PathDiagnosticLocation::createBegin(S, SM, LC);
1800    }
1801  } else {
1802    assert(Location.isValid());
1803    return Location;
1804  }
1805
1806  return PathDiagnosticLocation();
1807}
1808
1809//===----------------------------------------------------------------------===//
1810// Methods for BugReporter and subclasses.
1811//===----------------------------------------------------------------------===//
1812
1813BugReportEquivClass::~BugReportEquivClass() { }
1814GRBugReporter::~GRBugReporter() { }
1815BugReporterData::~BugReporterData() {}
1816
1817ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
1818
1819ProgramStateManager&
1820GRBugReporter::getStateManager() { return Eng.getStateManager(); }
1821
1822BugReporter::~BugReporter() {
1823  FlushReports();
1824
1825  // Free the bug reports we are tracking.
1826  typedef std::vector<BugReportEquivClass *> ContTy;
1827  for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end();
1828       I != E; ++I) {
1829    delete *I;
1830  }
1831}
1832
1833void BugReporter::FlushReports() {
1834  if (BugTypes.isEmpty())
1835    return;
1836
1837  // First flush the warnings for each BugType.  This may end up creating new
1838  // warnings and new BugTypes.
1839  // FIXME: Only NSErrorChecker needs BugType's FlushReports.
1840  // Turn NSErrorChecker into a proper checker and remove this.
1841  SmallVector<const BugType*, 16> bugTypes;
1842  for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
1843    bugTypes.push_back(*I);
1844  for (SmallVector<const BugType*, 16>::iterator
1845         I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I)
1846    const_cast<BugType*>(*I)->FlushReports(*this);
1847
1848  // We need to flush reports in deterministic order to ensure the order
1849  // of the reports is consistent between runs.
1850  typedef std::vector<BugReportEquivClass *> ContVecTy;
1851  for (ContVecTy::iterator EI=EQClassesVector.begin(), EE=EQClassesVector.end();
1852       EI != EE; ++EI){
1853    BugReportEquivClass& EQ = **EI;
1854    FlushReport(EQ);
1855  }
1856
1857  // BugReporter owns and deletes only BugTypes created implicitly through
1858  // EmitBasicReport.
1859  // FIXME: There are leaks from checkers that assume that the BugTypes they
1860  // create will be destroyed by the BugReporter.
1861  for (llvm::StringMap<BugType*>::iterator
1862         I = StrBugTypes.begin(), E = StrBugTypes.end(); I != E; ++I)
1863    delete I->second;
1864
1865  // Remove all references to the BugType objects.
1866  BugTypes = F.getEmptySet();
1867}
1868
1869//===----------------------------------------------------------------------===//
1870// PathDiagnostics generation.
1871//===----------------------------------------------------------------------===//
1872
1873static std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
1874                 std::pair<ExplodedNode*, unsigned> >
1875MakeReportGraph(const ExplodedGraph* G,
1876                SmallVectorImpl<const ExplodedNode*> &nodes) {
1877
1878  // Create the trimmed graph.  It will contain the shortest paths from the
1879  // error nodes to the root.  In the new graph we should only have one
1880  // error node unless there are two or more error nodes with the same minimum
1881  // path length.
1882  ExplodedGraph* GTrim;
1883  InterExplodedGraphMap* NMap;
1884
1885  llvm::DenseMap<const void*, const void*> InverseMap;
1886  llvm::tie(GTrim, NMap) = G->Trim(nodes.data(), nodes.data() + nodes.size(),
1887                                   &InverseMap);
1888
1889  // Create owning pointers for GTrim and NMap just to ensure that they are
1890  // released when this function exists.
1891  OwningPtr<ExplodedGraph> AutoReleaseGTrim(GTrim);
1892  OwningPtr<InterExplodedGraphMap> AutoReleaseNMap(NMap);
1893
1894  // Find the (first) error node in the trimmed graph.  We just need to consult
1895  // the node map (NMap) which maps from nodes in the original graph to nodes
1896  // in the new graph.
1897
1898  std::queue<const ExplodedNode*> WS;
1899  typedef llvm::DenseMap<const ExplodedNode*, unsigned> IndexMapTy;
1900  IndexMapTy IndexMap;
1901
1902  for (unsigned nodeIndex = 0 ; nodeIndex < nodes.size(); ++nodeIndex) {
1903    const ExplodedNode *originalNode = nodes[nodeIndex];
1904    if (const ExplodedNode *N = NMap->getMappedNode(originalNode)) {
1905      WS.push(N);
1906      IndexMap[originalNode] = nodeIndex;
1907    }
1908  }
1909
1910  assert(!WS.empty() && "No error node found in the trimmed graph.");
1911
1912  // Create a new (third!) graph with a single path.  This is the graph
1913  // that will be returned to the caller.
1914  ExplodedGraph *GNew = new ExplodedGraph();
1915
1916  // Sometimes the trimmed graph can contain a cycle.  Perform a reverse BFS
1917  // to the root node, and then construct a new graph that contains only
1918  // a single path.
1919  llvm::DenseMap<const void*,unsigned> Visited;
1920
1921  unsigned cnt = 0;
1922  const ExplodedNode *Root = 0;
1923
1924  while (!WS.empty()) {
1925    const ExplodedNode *Node = WS.front();
1926    WS.pop();
1927
1928    if (Visited.find(Node) != Visited.end())
1929      continue;
1930
1931    Visited[Node] = cnt++;
1932
1933    if (Node->pred_empty()) {
1934      Root = Node;
1935      break;
1936    }
1937
1938    for (ExplodedNode::const_pred_iterator I=Node->pred_begin(),
1939         E=Node->pred_end(); I!=E; ++I)
1940      WS.push(*I);
1941  }
1942
1943  assert(Root);
1944
1945  // Now walk from the root down the BFS path, always taking the successor
1946  // with the lowest number.
1947  ExplodedNode *Last = 0, *First = 0;
1948  NodeBackMap *BM = new NodeBackMap();
1949  unsigned NodeIndex = 0;
1950
1951  for ( const ExplodedNode *N = Root ;;) {
1952    // Lookup the number associated with the current node.
1953    llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
1954    assert(I != Visited.end());
1955
1956    // Create the equivalent node in the new graph with the same state
1957    // and location.
1958    ExplodedNode *NewN = GNew->getNode(N->getLocation(), N->getState());
1959
1960    // Store the mapping to the original node.
1961    llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1962    assert(IMitr != InverseMap.end() && "No mapping to original node.");
1963    (*BM)[NewN] = (const ExplodedNode*) IMitr->second;
1964
1965    // Link up the new node with the previous node.
1966    if (Last)
1967      NewN->addPredecessor(Last, *GNew);
1968
1969    Last = NewN;
1970
1971    // Are we at the final node?
1972    IndexMapTy::iterator IMI =
1973      IndexMap.find((const ExplodedNode*)(IMitr->second));
1974    if (IMI != IndexMap.end()) {
1975      First = NewN;
1976      NodeIndex = IMI->second;
1977      break;
1978    }
1979
1980    // Find the next successor node.  We choose the node that is marked
1981    // with the lowest DFS number.
1982    ExplodedNode::const_succ_iterator SI = N->succ_begin();
1983    ExplodedNode::const_succ_iterator SE = N->succ_end();
1984    N = 0;
1985
1986    for (unsigned MinVal = 0; SI != SE; ++SI) {
1987
1988      I = Visited.find(*SI);
1989
1990      if (I == Visited.end())
1991        continue;
1992
1993      if (!N || I->second < MinVal) {
1994        N = *SI;
1995        MinVal = I->second;
1996      }
1997    }
1998
1999    assert(N);
2000  }
2001
2002  assert(First);
2003
2004  return std::make_pair(std::make_pair(GNew, BM),
2005                        std::make_pair(First, NodeIndex));
2006}
2007
2008/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
2009///  and collapses PathDiagosticPieces that are expanded by macros.
2010static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM) {
2011  typedef std::vector<std::pair<IntrusiveRefCntPtr<PathDiagnosticMacroPiece>,
2012                                SourceLocation> > MacroStackTy;
2013
2014  typedef std::vector<IntrusiveRefCntPtr<PathDiagnosticPiece> >
2015          PiecesTy;
2016
2017  MacroStackTy MacroStack;
2018  PiecesTy Pieces;
2019
2020  for (PathPieces::const_iterator I = path.begin(), E = path.end();
2021       I!=E; ++I) {
2022
2023    PathDiagnosticPiece *piece = I->getPtr();
2024
2025    // Recursively compact calls.
2026    if (PathDiagnosticCallPiece *call=dyn_cast<PathDiagnosticCallPiece>(piece)){
2027      CompactPathDiagnostic(call->path, SM);
2028    }
2029
2030    // Get the location of the PathDiagnosticPiece.
2031    const FullSourceLoc Loc = piece->getLocation().asLocation();
2032
2033    // Determine the instantiation location, which is the location we group
2034    // related PathDiagnosticPieces.
2035    SourceLocation InstantiationLoc = Loc.isMacroID() ?
2036                                      SM.getExpansionLoc(Loc) :
2037                                      SourceLocation();
2038
2039    if (Loc.isFileID()) {
2040      MacroStack.clear();
2041      Pieces.push_back(piece);
2042      continue;
2043    }
2044
2045    assert(Loc.isMacroID());
2046
2047    // Is the PathDiagnosticPiece within the same macro group?
2048    if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
2049      MacroStack.back().first->subPieces.push_back(piece);
2050      continue;
2051    }
2052
2053    // We aren't in the same group.  Are we descending into a new macro
2054    // or are part of an old one?
2055    IntrusiveRefCntPtr<PathDiagnosticMacroPiece> MacroGroup;
2056
2057    SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
2058                                          SM.getExpansionLoc(Loc) :
2059                                          SourceLocation();
2060
2061    // Walk the entire macro stack.
2062    while (!MacroStack.empty()) {
2063      if (InstantiationLoc == MacroStack.back().second) {
2064        MacroGroup = MacroStack.back().first;
2065        break;
2066      }
2067
2068      if (ParentInstantiationLoc == MacroStack.back().second) {
2069        MacroGroup = MacroStack.back().first;
2070        break;
2071      }
2072
2073      MacroStack.pop_back();
2074    }
2075
2076    if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
2077      // Create a new macro group and add it to the stack.
2078      PathDiagnosticMacroPiece *NewGroup =
2079        new PathDiagnosticMacroPiece(
2080          PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
2081
2082      if (MacroGroup)
2083        MacroGroup->subPieces.push_back(NewGroup);
2084      else {
2085        assert(InstantiationLoc.isFileID());
2086        Pieces.push_back(NewGroup);
2087      }
2088
2089      MacroGroup = NewGroup;
2090      MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
2091    }
2092
2093    // Finally, add the PathDiagnosticPiece to the group.
2094    MacroGroup->subPieces.push_back(piece);
2095  }
2096
2097  // Now take the pieces and construct a new PathDiagnostic.
2098  path.clear();
2099
2100  for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I)
2101    path.push_back(*I);
2102}
2103
2104bool GRBugReporter::generatePathDiagnostic(PathDiagnostic& PD,
2105                                           PathDiagnosticConsumer &PC,
2106                                           ArrayRef<BugReport *> &bugReports) {
2107  assert(!bugReports.empty());
2108
2109  bool HasValid = false;
2110  SmallVector<const ExplodedNode *, 10> errorNodes;
2111  for (ArrayRef<BugReport*>::iterator I = bugReports.begin(),
2112                                      E = bugReports.end(); I != E; ++I) {
2113    if ((*I)->isValid()) {
2114      HasValid = true;
2115      errorNodes.push_back((*I)->getErrorNode());
2116    } else {
2117      errorNodes.push_back(0);
2118    }
2119  }
2120
2121  // If all the reports have been marked invalid, we're done.
2122  if (!HasValid)
2123    return false;
2124
2125  // Construct a new graph that contains only a single path from the error
2126  // node to a root.
2127  const std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
2128  std::pair<ExplodedNode*, unsigned> >&
2129    GPair = MakeReportGraph(&getGraph(), errorNodes);
2130
2131  // Find the BugReport with the original location.
2132  assert(GPair.second.second < bugReports.size());
2133  BugReport *R = bugReports[GPair.second.second];
2134  assert(R && "No original report found for sliced graph.");
2135  assert(R->isValid() && "Report selected from trimmed graph marked invalid.");
2136
2137  OwningPtr<ExplodedGraph> ReportGraph(GPair.first.first);
2138  OwningPtr<NodeBackMap> BackMap(GPair.first.second);
2139  const ExplodedNode *N = GPair.second.first;
2140
2141  // Start building the path diagnostic...
2142  PathDiagnosticBuilder PDB(*this, R, BackMap.get(), &PC);
2143
2144  // Register additional node visitors.
2145  R->addVisitor(new NilReceiverBRVisitor());
2146  R->addVisitor(new ConditionBRVisitor());
2147  R->addVisitor(new LikelyFalsePositiveSuppressionBRVisitor());
2148
2149  BugReport::VisitorList visitors;
2150  unsigned originalReportConfigToken, finalReportConfigToken;
2151
2152  // While generating diagnostics, it's possible the visitors will decide
2153  // new symbols and regions are interesting, or add other visitors based on
2154  // the information they find. If they do, we need to regenerate the path
2155  // based on our new report configuration.
2156  do {
2157    // Get a clean copy of all the visitors.
2158    for (BugReport::visitor_iterator I = R->visitor_begin(),
2159                                     E = R->visitor_end(); I != E; ++I)
2160       visitors.push_back((*I)->clone());
2161
2162    // Clear out the active path from any previous work.
2163    PD.resetPath();
2164    originalReportConfigToken = R->getConfigurationChangeToken();
2165
2166    // Generate the very last diagnostic piece - the piece is visible before
2167    // the trace is expanded.
2168    PathDiagnosticPiece *LastPiece = 0;
2169    for (BugReport::visitor_iterator I = visitors.begin(), E = visitors.end();
2170        I != E; ++I) {
2171      if (PathDiagnosticPiece *Piece = (*I)->getEndPath(PDB, N, *R)) {
2172        assert (!LastPiece &&
2173            "There can only be one final piece in a diagnostic.");
2174        LastPiece = Piece;
2175      }
2176    }
2177
2178    if (PDB.getGenerationScheme() != PathDiagnosticConsumer::None) {
2179      if (!LastPiece)
2180        LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R);
2181      if (LastPiece)
2182        PD.setEndOfPath(LastPiece);
2183      else
2184        return false;
2185    }
2186
2187    switch (PDB.getGenerationScheme()) {
2188    case PathDiagnosticConsumer::Extensive:
2189      if (!GenerateExtensivePathDiagnostic(PD, PDB, N, visitors)) {
2190        assert(!R->isValid() && "Failed on valid report");
2191        // Try again. We'll filter out the bad report when we trim the graph.
2192        // FIXME: It would be more efficient to use the same intermediate
2193        // trimmed graph, and just repeat the shortest-path search.
2194        return generatePathDiagnostic(PD, PC, bugReports);
2195      }
2196      break;
2197    case PathDiagnosticConsumer::Minimal:
2198      if (!GenerateMinimalPathDiagnostic(PD, PDB, N, visitors)) {
2199        assert(!R->isValid() && "Failed on valid report");
2200        // Try again. We'll filter out the bad report when we trim the graph.
2201        return generatePathDiagnostic(PD, PC, bugReports);
2202      }
2203      break;
2204    case PathDiagnosticConsumer::None:
2205      if (!GenerateVisitorsOnlyPathDiagnostic(PD, PDB, N, visitors)) {
2206        assert(!R->isValid() && "Failed on valid report");
2207        // Try again. We'll filter out the bad report when we trim the graph.
2208        return generatePathDiagnostic(PD, PC, bugReports);
2209      }
2210      break;
2211    }
2212
2213    // Clean up the visitors we used.
2214    llvm::DeleteContainerPointers(visitors);
2215
2216    // Did anything change while generating this path?
2217    finalReportConfigToken = R->getConfigurationChangeToken();
2218  } while(finalReportConfigToken != originalReportConfigToken);
2219
2220  // Finally, prune the diagnostic path of uninteresting stuff.
2221  if (!PD.path.empty()) {
2222    // Remove messages that are basically the same.
2223    removeRedundantMsgs(PD.getMutablePieces());
2224
2225    if (R->shouldPrunePath() &&
2226        getEngine().getAnalysisManager().options.shouldPrunePaths()) {
2227      bool hasSomethingInteresting = RemoveUnneededCalls(PD.getMutablePieces(),
2228                                                         R);
2229      assert(hasSomethingInteresting);
2230      (void) hasSomethingInteresting;
2231    }
2232
2233    adjustCallLocations(PD.getMutablePieces());
2234  }
2235
2236  return true;
2237}
2238
2239void BugReporter::Register(BugType *BT) {
2240  BugTypes = F.add(BugTypes, BT);
2241}
2242
2243void BugReporter::emitReport(BugReport* R) {
2244  // Compute the bug report's hash to determine its equivalence class.
2245  llvm::FoldingSetNodeID ID;
2246  R->Profile(ID);
2247
2248  // Lookup the equivance class.  If there isn't one, create it.
2249  BugType& BT = R->getBugType();
2250  Register(&BT);
2251  void *InsertPos;
2252  BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
2253
2254  if (!EQ) {
2255    EQ = new BugReportEquivClass(R);
2256    EQClasses.InsertNode(EQ, InsertPos);
2257    EQClassesVector.push_back(EQ);
2258  }
2259  else
2260    EQ->AddReport(R);
2261}
2262
2263
2264//===----------------------------------------------------------------------===//
2265// Emitting reports in equivalence classes.
2266//===----------------------------------------------------------------------===//
2267
2268namespace {
2269struct FRIEC_WLItem {
2270  const ExplodedNode *N;
2271  ExplodedNode::const_succ_iterator I, E;
2272
2273  FRIEC_WLItem(const ExplodedNode *n)
2274  : N(n), I(N->succ_begin()), E(N->succ_end()) {}
2275};
2276}
2277
2278static BugReport *
2279FindReportInEquivalenceClass(BugReportEquivClass& EQ,
2280                             SmallVectorImpl<BugReport*> &bugReports) {
2281
2282  BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
2283  assert(I != E);
2284  BugType& BT = I->getBugType();
2285
2286  // If we don't need to suppress any of the nodes because they are
2287  // post-dominated by a sink, simply add all the nodes in the equivalence class
2288  // to 'Nodes'.  Any of the reports will serve as a "representative" report.
2289  if (!BT.isSuppressOnSink()) {
2290    BugReport *R = I;
2291    for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
2292      const ExplodedNode *N = I->getErrorNode();
2293      if (N) {
2294        R = I;
2295        bugReports.push_back(R);
2296      }
2297    }
2298    return R;
2299  }
2300
2301  // For bug reports that should be suppressed when all paths are post-dominated
2302  // by a sink node, iterate through the reports in the equivalence class
2303  // until we find one that isn't post-dominated (if one exists).  We use a
2304  // DFS traversal of the ExplodedGraph to find a non-sink node.  We could write
2305  // this as a recursive function, but we don't want to risk blowing out the
2306  // stack for very long paths.
2307  BugReport *exampleReport = 0;
2308
2309  for (; I != E; ++I) {
2310    const ExplodedNode *errorNode = I->getErrorNode();
2311
2312    if (!errorNode)
2313      continue;
2314    if (errorNode->isSink()) {
2315      llvm_unreachable(
2316           "BugType::isSuppressSink() should not be 'true' for sink end nodes");
2317    }
2318    // No successors?  By definition this nodes isn't post-dominated by a sink.
2319    if (errorNode->succ_empty()) {
2320      bugReports.push_back(I);
2321      if (!exampleReport)
2322        exampleReport = I;
2323      continue;
2324    }
2325
2326    // At this point we know that 'N' is not a sink and it has at least one
2327    // successor.  Use a DFS worklist to find a non-sink end-of-path node.
2328    typedef FRIEC_WLItem WLItem;
2329    typedef SmallVector<WLItem, 10> DFSWorkList;
2330    llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
2331
2332    DFSWorkList WL;
2333    WL.push_back(errorNode);
2334    Visited[errorNode] = 1;
2335
2336    while (!WL.empty()) {
2337      WLItem &WI = WL.back();
2338      assert(!WI.N->succ_empty());
2339
2340      for (; WI.I != WI.E; ++WI.I) {
2341        const ExplodedNode *Succ = *WI.I;
2342        // End-of-path node?
2343        if (Succ->succ_empty()) {
2344          // If we found an end-of-path node that is not a sink.
2345          if (!Succ->isSink()) {
2346            bugReports.push_back(I);
2347            if (!exampleReport)
2348              exampleReport = I;
2349            WL.clear();
2350            break;
2351          }
2352          // Found a sink?  Continue on to the next successor.
2353          continue;
2354        }
2355        // Mark the successor as visited.  If it hasn't been explored,
2356        // enqueue it to the DFS worklist.
2357        unsigned &mark = Visited[Succ];
2358        if (!mark) {
2359          mark = 1;
2360          WL.push_back(Succ);
2361          break;
2362        }
2363      }
2364
2365      // The worklist may have been cleared at this point.  First
2366      // check if it is empty before checking the last item.
2367      if (!WL.empty() && &WL.back() == &WI)
2368        WL.pop_back();
2369    }
2370  }
2371
2372  // ExampleReport will be NULL if all the nodes in the equivalence class
2373  // were post-dominated by sinks.
2374  return exampleReport;
2375}
2376
2377void BugReporter::FlushReport(BugReportEquivClass& EQ) {
2378  SmallVector<BugReport*, 10> bugReports;
2379  BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports);
2380  if (exampleReport) {
2381    const PathDiagnosticConsumers &C = getPathDiagnosticConsumers();
2382    for (PathDiagnosticConsumers::const_iterator I=C.begin(),
2383                                                 E=C.end(); I != E; ++I) {
2384      FlushReport(exampleReport, **I, bugReports);
2385    }
2386  }
2387}
2388
2389void BugReporter::FlushReport(BugReport *exampleReport,
2390                              PathDiagnosticConsumer &PD,
2391                              ArrayRef<BugReport*> bugReports) {
2392
2393  // FIXME: Make sure we use the 'R' for the path that was actually used.
2394  // Probably doesn't make a difference in practice.
2395  BugType& BT = exampleReport->getBugType();
2396
2397  OwningPtr<PathDiagnostic>
2398    D(new PathDiagnostic(exampleReport->getDeclWithIssue(),
2399                         exampleReport->getBugType().getName(),
2400                         exampleReport->getDescription(),
2401                         exampleReport->getShortDescription(/*Fallback=*/false),
2402                         BT.getCategory(),
2403                         exampleReport->getUniqueingLocation(),
2404                         exampleReport->getUniqueingDecl()));
2405
2406  // Generate the full path diagnostic, using the generation scheme
2407  // specified by the PathDiagnosticConsumer. Note that we have to generate
2408  // path diagnostics even for consumers which do not support paths, because
2409  // the BugReporterVisitors may mark this bug as a false positive.
2410  if (!bugReports.empty())
2411    if (!generatePathDiagnostic(*D.get(), PD, bugReports))
2412      return;
2413
2414  // If the path is empty, generate a single step path with the location
2415  // of the issue.
2416  if (D->path.empty()) {
2417    PathDiagnosticLocation L = exampleReport->getLocation(getSourceManager());
2418    PathDiagnosticPiece *piece =
2419      new PathDiagnosticEventPiece(L, exampleReport->getDescription());
2420    BugReport::ranges_iterator Beg, End;
2421    llvm::tie(Beg, End) = exampleReport->getRanges();
2422    for ( ; Beg != End; ++Beg)
2423      piece->addRange(*Beg);
2424    D->setEndOfPath(piece);
2425  }
2426
2427  // Get the meta data.
2428  const BugReport::ExtraTextList &Meta = exampleReport->getExtraText();
2429  for (BugReport::ExtraTextList::const_iterator i = Meta.begin(),
2430                                                e = Meta.end(); i != e; ++i) {
2431    D->addMeta(*i);
2432  }
2433
2434  PD.HandlePathDiagnostic(D.take());
2435}
2436
2437void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
2438                                  StringRef name,
2439                                  StringRef category,
2440                                  StringRef str, PathDiagnosticLocation Loc,
2441                                  SourceRange* RBeg, unsigned NumRanges) {
2442
2443  // 'BT' is owned by BugReporter.
2444  BugType *BT = getBugTypeForName(name, category);
2445  BugReport *R = new BugReport(*BT, str, Loc);
2446  R->setDeclWithIssue(DeclWithIssue);
2447  for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
2448  emitReport(R);
2449}
2450
2451BugType *BugReporter::getBugTypeForName(StringRef name,
2452                                        StringRef category) {
2453  SmallString<136> fullDesc;
2454  llvm::raw_svector_ostream(fullDesc) << name << ":" << category;
2455  llvm::StringMapEntry<BugType *> &
2456      entry = StrBugTypes.GetOrCreateValue(fullDesc);
2457  BugType *BT = entry.getValue();
2458  if (!BT) {
2459    BT = new BugType(name, category);
2460    entry.setValue(BT);
2461  }
2462  return BT;
2463}
2464