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