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