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