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