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 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
     16 #include "clang/AST/ASTContext.h"
     17 #include "clang/AST/DeclObjC.h"
     18 #include "clang/AST/Expr.h"
     19 #include "clang/AST/ExprCXX.h"
     20 #include "clang/AST/ParentMap.h"
     21 #include "clang/AST/StmtCXX.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/STLExtras.h"
     32 #include "llvm/ADT/SmallString.h"
     33 #include "llvm/ADT/Statistic.h"
     34 #include "llvm/Support/raw_ostream.h"
     35 #include <memory>
     36 #include <queue>
     37 
     38 using namespace clang;
     39 using namespace ento;
     40 
     41 #define DEBUG_TYPE "BugReporter"
     42 
     43 STATISTIC(MaxBugClassSize,
     44           "The maximum number of bug reports in the same equivalence class");
     45 STATISTIC(MaxValidBugClassSize,
     46           "The maximum number of bug reports in the same equivalence class "
     47           "where at least one report is valid (not suppressed)");
     48 
     49 BugReporterVisitor::~BugReporterVisitor() {}
     50 
     51 void BugReporterContext::anchor() {}
     52 
     53 //===----------------------------------------------------------------------===//
     54 // Helper routines for walking the ExplodedGraph and fetching statements.
     55 //===----------------------------------------------------------------------===//
     56 
     57 static const Stmt *GetPreviousStmt(const ExplodedNode *N) {
     58   for (N = N->getFirstPred(); N; N = N->getFirstPred())
     59     if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
     60       return S;
     61 
     62   return nullptr;
     63 }
     64 
     65 static inline const Stmt*
     66 GetCurrentOrPreviousStmt(const ExplodedNode *N) {
     67   if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
     68     return S;
     69 
     70   return GetPreviousStmt(N);
     71 }
     72 
     73 //===----------------------------------------------------------------------===//
     74 // Diagnostic cleanup.
     75 //===----------------------------------------------------------------------===//
     76 
     77 static PathDiagnosticEventPiece *
     78 eventsDescribeSameCondition(PathDiagnosticEventPiece *X,
     79                             PathDiagnosticEventPiece *Y) {
     80   // Prefer diagnostics that come from ConditionBRVisitor over
     81   // those that came from TrackConstraintBRVisitor.
     82   const void *tagPreferred = ConditionBRVisitor::getTag();
     83   const void *tagLesser = TrackConstraintBRVisitor::getTag();
     84 
     85   if (X->getLocation() != Y->getLocation())
     86     return nullptr;
     87 
     88   if (X->getTag() == tagPreferred && Y->getTag() == tagLesser)
     89     return X;
     90 
     91   if (Y->getTag() == tagPreferred && X->getTag() == tagLesser)
     92     return Y;
     93 
     94   return nullptr;
     95 }
     96 
     97 /// An optimization pass over PathPieces that removes redundant diagnostics
     98 /// generated by both ConditionBRVisitor and TrackConstraintBRVisitor.  Both
     99 /// BugReporterVisitors use different methods to generate diagnostics, with
    100 /// one capable of emitting diagnostics in some cases but not in others.  This
    101 /// can lead to redundant diagnostic pieces at the same point in a path.
    102 static void removeRedundantMsgs(PathPieces &path) {
    103   unsigned N = path.size();
    104   if (N < 2)
    105     return;
    106   // NOTE: this loop intentionally is not using an iterator.  Instead, we
    107   // are streaming the path and modifying it in place.  This is done by
    108   // grabbing the front, processing it, and if we decide to keep it append
    109   // it to the end of the path.  The entire path is processed in this way.
    110   for (unsigned i = 0; i < N; ++i) {
    111     IntrusiveRefCntPtr<PathDiagnosticPiece> piece(path.front());
    112     path.pop_front();
    113 
    114     switch (piece->getKind()) {
    115       case clang::ento::PathDiagnosticPiece::Call:
    116         removeRedundantMsgs(cast<PathDiagnosticCallPiece>(piece)->path);
    117         break;
    118       case clang::ento::PathDiagnosticPiece::Macro:
    119         removeRedundantMsgs(cast<PathDiagnosticMacroPiece>(piece)->subPieces);
    120         break;
    121       case clang::ento::PathDiagnosticPiece::ControlFlow:
    122         break;
    123       case clang::ento::PathDiagnosticPiece::Event: {
    124         if (i == N-1)
    125           break;
    126 
    127         if (PathDiagnosticEventPiece *nextEvent =
    128             dyn_cast<PathDiagnosticEventPiece>(path.front().get())) {
    129           PathDiagnosticEventPiece *event =
    130             cast<PathDiagnosticEventPiece>(piece);
    131           // Check to see if we should keep one of the two pieces.  If we
    132           // come up with a preference, record which piece to keep, and consume
    133           // another piece from the path.
    134           if (PathDiagnosticEventPiece *pieceToKeep =
    135               eventsDescribeSameCondition(event, nextEvent)) {
    136             piece = pieceToKeep;
    137             path.pop_front();
    138             ++i;
    139           }
    140         }
    141         break;
    142       }
    143     }
    144     path.push_back(piece);
    145   }
    146 }
    147 
    148 /// A map from PathDiagnosticPiece to the LocationContext of the inlined
    149 /// function call it represents.
    150 typedef llvm::DenseMap<const PathPieces *, const LocationContext *>
    151         LocationContextMap;
    152 
    153 /// Recursively scan through a path and prune out calls and macros pieces
    154 /// that aren't needed.  Return true if afterwards the path contains
    155 /// "interesting stuff" which means it shouldn't be pruned from the parent path.
    156 static bool removeUnneededCalls(PathPieces &pieces, BugReport *R,
    157                                 LocationContextMap &LCM) {
    158   bool containsSomethingInteresting = false;
    159   const unsigned N = pieces.size();
    160 
    161   for (unsigned i = 0 ; i < N ; ++i) {
    162     // Remove the front piece from the path.  If it is still something we
    163     // want to keep once we are done, we will push it back on the end.
    164     IntrusiveRefCntPtr<PathDiagnosticPiece> piece(pieces.front());
    165     pieces.pop_front();
    166 
    167     switch (piece->getKind()) {
    168       case PathDiagnosticPiece::Call: {
    169         PathDiagnosticCallPiece *call = cast<PathDiagnosticCallPiece>(piece);
    170         // Check if the location context is interesting.
    171         assert(LCM.count(&call->path));
    172         if (R->isInteresting(LCM[&call->path])) {
    173           containsSomethingInteresting = true;
    174           break;
    175         }
    176 
    177         if (!removeUnneededCalls(call->path, R, LCM))
    178           continue;
    179 
    180         containsSomethingInteresting = true;
    181         break;
    182       }
    183       case PathDiagnosticPiece::Macro: {
    184         PathDiagnosticMacroPiece *macro = cast<PathDiagnosticMacroPiece>(piece);
    185         if (!removeUnneededCalls(macro->subPieces, R, LCM))
    186           continue;
    187         containsSomethingInteresting = true;
    188         break;
    189       }
    190       case PathDiagnosticPiece::Event: {
    191         PathDiagnosticEventPiece *event = cast<PathDiagnosticEventPiece>(piece);
    192 
    193         // We never throw away an event, but we do throw it away wholesale
    194         // as part of a path if we throw the entire path away.
    195         containsSomethingInteresting |= !event->isPrunable();
    196         break;
    197       }
    198       case PathDiagnosticPiece::ControlFlow:
    199         break;
    200     }
    201 
    202     pieces.push_back(piece);
    203   }
    204 
    205   return containsSomethingInteresting;
    206 }
    207 
    208 /// Returns true if the given decl has been implicitly given a body, either by
    209 /// the analyzer or by the compiler proper.
    210 static bool hasImplicitBody(const Decl *D) {
    211   assert(D);
    212   return D->isImplicit() || !D->hasBody();
    213 }
    214 
    215 /// Recursively scan through a path and make sure that all call pieces have
    216 /// valid locations.
    217 static void
    218 adjustCallLocations(PathPieces &Pieces,
    219                     PathDiagnosticLocation *LastCallLocation = nullptr) {
    220   for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E; ++I) {
    221     PathDiagnosticCallPiece *Call = dyn_cast<PathDiagnosticCallPiece>(*I);
    222 
    223     if (!Call) {
    224       assert((*I)->getLocation().asLocation().isValid());
    225       continue;
    226     }
    227 
    228     if (LastCallLocation) {
    229       bool CallerIsImplicit = hasImplicitBody(Call->getCaller());
    230       if (CallerIsImplicit || !Call->callEnter.asLocation().isValid())
    231         Call->callEnter = *LastCallLocation;
    232       if (CallerIsImplicit || !Call->callReturn.asLocation().isValid())
    233         Call->callReturn = *LastCallLocation;
    234     }
    235 
    236     // Recursively clean out the subclass.  Keep this call around if
    237     // it contains any informative diagnostics.
    238     PathDiagnosticLocation *ThisCallLocation;
    239     if (Call->callEnterWithin.asLocation().isValid() &&
    240         !hasImplicitBody(Call->getCallee()))
    241       ThisCallLocation = &Call->callEnterWithin;
    242     else
    243       ThisCallLocation = &Call->callEnter;
    244 
    245     assert(ThisCallLocation && "Outermost call has an invalid location");
    246     adjustCallLocations(Call->path, ThisCallLocation);
    247   }
    248 }
    249 
    250 /// Remove edges in and out of C++ default initializer expressions. These are
    251 /// for fields that have in-class initializers, as opposed to being initialized
    252 /// explicitly in a constructor or braced list.
    253 static void removeEdgesToDefaultInitializers(PathPieces &Pieces) {
    254   for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
    255     if (PathDiagnosticCallPiece *C = dyn_cast<PathDiagnosticCallPiece>(*I))
    256       removeEdgesToDefaultInitializers(C->path);
    257 
    258     if (PathDiagnosticMacroPiece *M = dyn_cast<PathDiagnosticMacroPiece>(*I))
    259       removeEdgesToDefaultInitializers(M->subPieces);
    260 
    261     if (PathDiagnosticControlFlowPiece *CF =
    262           dyn_cast<PathDiagnosticControlFlowPiece>(*I)) {
    263       const Stmt *Start = CF->getStartLocation().asStmt();
    264       const Stmt *End = CF->getEndLocation().asStmt();
    265       if (Start && isa<CXXDefaultInitExpr>(Start)) {
    266         I = Pieces.erase(I);
    267         continue;
    268       } else if (End && isa<CXXDefaultInitExpr>(End)) {
    269         PathPieces::iterator Next = std::next(I);
    270         if (Next != E) {
    271           if (PathDiagnosticControlFlowPiece *NextCF =
    272                 dyn_cast<PathDiagnosticControlFlowPiece>(*Next)) {
    273             NextCF->setStartLocation(CF->getStartLocation());
    274           }
    275         }
    276         I = Pieces.erase(I);
    277         continue;
    278       }
    279     }
    280 
    281     I++;
    282   }
    283 }
    284 
    285 /// Remove all pieces with invalid locations as these cannot be serialized.
    286 /// We might have pieces with invalid locations as a result of inlining Body
    287 /// Farm generated functions.
    288 static void removePiecesWithInvalidLocations(PathPieces &Pieces) {
    289   for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
    290     if (PathDiagnosticCallPiece *C = dyn_cast<PathDiagnosticCallPiece>(*I))
    291       removePiecesWithInvalidLocations(C->path);
    292 
    293     if (PathDiagnosticMacroPiece *M = dyn_cast<PathDiagnosticMacroPiece>(*I))
    294       removePiecesWithInvalidLocations(M->subPieces);
    295 
    296     if (!(*I)->getLocation().isValid() ||
    297         !(*I)->getLocation().asLocation().isValid()) {
    298       I = Pieces.erase(I);
    299       continue;
    300     }
    301     I++;
    302   }
    303 }
    304 
    305 //===----------------------------------------------------------------------===//
    306 // PathDiagnosticBuilder and its associated routines and helper objects.
    307 //===----------------------------------------------------------------------===//
    308 
    309 namespace {
    310 class NodeMapClosure : public BugReport::NodeResolver {
    311   InterExplodedGraphMap &M;
    312 public:
    313   NodeMapClosure(InterExplodedGraphMap &m) : M(m) {}
    314 
    315   const ExplodedNode *getOriginalNode(const ExplodedNode *N) override {
    316     return M.lookup(N);
    317   }
    318 };
    319 
    320 class PathDiagnosticBuilder : public BugReporterContext {
    321   BugReport *R;
    322   PathDiagnosticConsumer *PDC;
    323   NodeMapClosure NMC;
    324 public:
    325   const LocationContext *LC;
    326 
    327   PathDiagnosticBuilder(GRBugReporter &br,
    328                         BugReport *r, InterExplodedGraphMap &Backmap,
    329                         PathDiagnosticConsumer *pdc)
    330     : BugReporterContext(br),
    331       R(r), PDC(pdc), NMC(Backmap), LC(r->getErrorNode()->getLocationContext())
    332   {}
    333 
    334   PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N);
    335 
    336   PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream &os,
    337                                             const ExplodedNode *N);
    338 
    339   BugReport *getBugReport() { return R; }
    340 
    341   Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); }
    342 
    343   ParentMap& getParentMap() { return LC->getParentMap(); }
    344 
    345   const Stmt *getParent(const Stmt *S) {
    346     return getParentMap().getParent(S);
    347   }
    348 
    349   NodeMapClosure& getNodeResolver() override { return NMC; }
    350 
    351   PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
    352 
    353   PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const {
    354     return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Extensive;
    355   }
    356 
    357   bool supportsLogicalOpControlFlow() const {
    358     return PDC ? PDC->supportsLogicalOpControlFlow() : true;
    359   }
    360 };
    361 } // end anonymous namespace
    362 
    363 PathDiagnosticLocation
    364 PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) {
    365   if (const Stmt *S = PathDiagnosticLocation::getNextStmt(N))
    366     return PathDiagnosticLocation(S, getSourceManager(), LC);
    367 
    368   return PathDiagnosticLocation::createDeclEnd(N->getLocationContext(),
    369                                                getSourceManager());
    370 }
    371 
    372 PathDiagnosticLocation
    373 PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream &os,
    374                                           const ExplodedNode *N) {
    375 
    376   // Slow, but probably doesn't matter.
    377   if (os.str().empty())
    378     os << ' ';
    379 
    380   const PathDiagnosticLocation &Loc = ExecutionContinues(N);
    381 
    382   if (Loc.asStmt())
    383     os << "Execution continues on line "
    384        << getSourceManager().getExpansionLineNumber(Loc.asLocation())
    385        << '.';
    386   else {
    387     os << "Execution jumps to the end of the ";
    388     const Decl *D = N->getLocationContext()->getDecl();
    389     if (isa<ObjCMethodDecl>(D))
    390       os << "method";
    391     else if (isa<FunctionDecl>(D))
    392       os << "function";
    393     else {
    394       assert(isa<BlockDecl>(D));
    395       os << "anonymous block";
    396     }
    397     os << '.';
    398   }
    399 
    400   return Loc;
    401 }
    402 
    403 static const Stmt *getEnclosingParent(const Stmt *S, const ParentMap &PM) {
    404   if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
    405     return PM.getParentIgnoreParens(S);
    406 
    407   const Stmt *Parent = PM.getParentIgnoreParens(S);
    408   if (!Parent)
    409     return nullptr;
    410 
    411   switch (Parent->getStmtClass()) {
    412   case Stmt::ForStmtClass:
    413   case Stmt::DoStmtClass:
    414   case Stmt::WhileStmtClass:
    415   case Stmt::ObjCForCollectionStmtClass:
    416   case Stmt::CXXForRangeStmtClass:
    417     return Parent;
    418   default:
    419     break;
    420   }
    421 
    422   return nullptr;
    423 }
    424 
    425 static PathDiagnosticLocation
    426 getEnclosingStmtLocation(const Stmt *S, SourceManager &SMgr, const ParentMap &P,
    427                          const LocationContext *LC, bool allowNestedContexts) {
    428   if (!S)
    429     return PathDiagnosticLocation();
    430 
    431   while (const Stmt *Parent = getEnclosingParent(S, P)) {
    432     switch (Parent->getStmtClass()) {
    433       case Stmt::BinaryOperatorClass: {
    434         const BinaryOperator *B = cast<BinaryOperator>(Parent);
    435         if (B->isLogicalOp())
    436           return PathDiagnosticLocation(allowNestedContexts ? B : S, SMgr, LC);
    437         break;
    438       }
    439       case Stmt::CompoundStmtClass:
    440       case Stmt::StmtExprClass:
    441         return PathDiagnosticLocation(S, SMgr, LC);
    442       case Stmt::ChooseExprClass:
    443         // Similar to '?' if we are referring to condition, just have the edge
    444         // point to the entire choose expression.
    445         if (allowNestedContexts || cast<ChooseExpr>(Parent)->getCond() == S)
    446           return PathDiagnosticLocation(Parent, SMgr, LC);
    447         else
    448           return PathDiagnosticLocation(S, SMgr, LC);
    449       case Stmt::BinaryConditionalOperatorClass:
    450       case Stmt::ConditionalOperatorClass:
    451         // For '?', if we are referring to condition, just have the edge point
    452         // to the entire '?' expression.
    453         if (allowNestedContexts ||
    454             cast<AbstractConditionalOperator>(Parent)->getCond() == S)
    455           return PathDiagnosticLocation(Parent, SMgr, LC);
    456         else
    457           return PathDiagnosticLocation(S, SMgr, LC);
    458       case Stmt::CXXForRangeStmtClass:
    459         if (cast<CXXForRangeStmt>(Parent)->getBody() == S)
    460           return PathDiagnosticLocation(S, SMgr, LC);
    461         break;
    462       case Stmt::DoStmtClass:
    463           return PathDiagnosticLocation(S, SMgr, LC);
    464       case Stmt::ForStmtClass:
    465         if (cast<ForStmt>(Parent)->getBody() == S)
    466           return PathDiagnosticLocation(S, SMgr, LC);
    467         break;
    468       case Stmt::IfStmtClass:
    469         if (cast<IfStmt>(Parent)->getCond() != S)
    470           return PathDiagnosticLocation(S, SMgr, LC);
    471         break;
    472       case Stmt::ObjCForCollectionStmtClass:
    473         if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
    474           return PathDiagnosticLocation(S, SMgr, LC);
    475         break;
    476       case Stmt::WhileStmtClass:
    477         if (cast<WhileStmt>(Parent)->getCond() != S)
    478           return PathDiagnosticLocation(S, SMgr, LC);
    479         break;
    480       default:
    481         break;
    482     }
    483 
    484     S = Parent;
    485   }
    486 
    487   assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
    488 
    489   return PathDiagnosticLocation(S, SMgr, LC);
    490 }
    491 
    492 PathDiagnosticLocation
    493 PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
    494   assert(S && "Null Stmt passed to getEnclosingStmtLocation");
    495   return ::getEnclosingStmtLocation(S, getSourceManager(), getParentMap(), LC,
    496                                     /*allowNestedContexts=*/false);
    497 }
    498 
    499 //===----------------------------------------------------------------------===//
    500 // "Visitors only" path diagnostic generation algorithm.
    501 //===----------------------------------------------------------------------===//
    502 static bool GenerateVisitorsOnlyPathDiagnostic(
    503     PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
    504     ArrayRef<std::unique_ptr<BugReporterVisitor>> visitors) {
    505   // All path generation skips the very first node (the error node).
    506   // This is because there is special handling for the end-of-path note.
    507   N = N->getFirstPred();
    508   if (!N)
    509     return true;
    510 
    511   BugReport *R = PDB.getBugReport();
    512   while (const ExplodedNode *Pred = N->getFirstPred()) {
    513     for (auto &V : visitors) {
    514       // Visit all the node pairs, but throw the path pieces away.
    515       PathDiagnosticPiece *Piece = V->VisitNode(N, Pred, PDB, *R);
    516       delete Piece;
    517     }
    518 
    519     N = Pred;
    520   }
    521 
    522   return R->isValid();
    523 }
    524 
    525 //===----------------------------------------------------------------------===//
    526 // "Minimal" path diagnostic generation algorithm.
    527 //===----------------------------------------------------------------------===//
    528 typedef std::pair<PathDiagnosticCallPiece*, const ExplodedNode*> StackDiagPair;
    529 typedef SmallVector<StackDiagPair, 6> StackDiagVector;
    530 
    531 static void updateStackPiecesWithMessage(PathDiagnosticPiece *P,
    532                                          StackDiagVector &CallStack) {
    533   // If the piece contains a special message, add it to all the call
    534   // pieces on the active stack.
    535   if (PathDiagnosticEventPiece *ep =
    536         dyn_cast<PathDiagnosticEventPiece>(P)) {
    537 
    538     if (ep->hasCallStackHint())
    539       for (StackDiagVector::iterator I = CallStack.begin(),
    540                                      E = CallStack.end(); I != E; ++I) {
    541         PathDiagnosticCallPiece *CP = I->first;
    542         const ExplodedNode *N = I->second;
    543         std::string stackMsg = ep->getCallStackMessage(N);
    544 
    545         // The last message on the path to final bug is the most important
    546         // one. Since we traverse the path backwards, do not add the message
    547         // if one has been previously added.
    548         if  (!CP->hasCallStackMessage())
    549           CP->setCallStackMessage(stackMsg);
    550       }
    551   }
    552 }
    553 
    554 static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM);
    555 
    556 static bool GenerateMinimalPathDiagnostic(
    557     PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
    558     LocationContextMap &LCM,
    559     ArrayRef<std::unique_ptr<BugReporterVisitor>> visitors) {
    560 
    561   SourceManager& SMgr = PDB.getSourceManager();
    562   const LocationContext *LC = PDB.LC;
    563   const ExplodedNode *NextNode = N->pred_empty()
    564                                         ? nullptr : *(N->pred_begin());
    565 
    566   StackDiagVector CallStack;
    567 
    568   while (NextNode) {
    569     N = NextNode;
    570     PDB.LC = N->getLocationContext();
    571     NextNode = N->getFirstPred();
    572 
    573     ProgramPoint P = N->getLocation();
    574 
    575     do {
    576       if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
    577         PathDiagnosticCallPiece *C =
    578             PathDiagnosticCallPiece::construct(N, *CE, SMgr);
    579         // Record the mapping from call piece to LocationContext.
    580         LCM[&C->path] = CE->getCalleeContext();
    581         PD.getActivePath().push_front(C);
    582         PD.pushActivePath(&C->path);
    583         CallStack.push_back(StackDiagPair(C, N));
    584         break;
    585       }
    586 
    587       if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
    588         // Flush all locations, and pop the active path.
    589         bool VisitedEntireCall = PD.isWithinCall();
    590         PD.popActivePath();
    591 
    592         // Either we just added a bunch of stuff to the top-level path, or
    593         // we have a previous CallExitEnd.  If the former, it means that the
    594         // path terminated within a function call.  We must then take the
    595         // current contents of the active path and place it within
    596         // a new PathDiagnosticCallPiece.
    597         PathDiagnosticCallPiece *C;
    598         if (VisitedEntireCall) {
    599           C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
    600         } else {
    601           const Decl *Caller = CE->getLocationContext()->getDecl();
    602           C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
    603           // Record the mapping from call piece to LocationContext.
    604           LCM[&C->path] = CE->getCalleeContext();
    605         }
    606 
    607         C->setCallee(*CE, SMgr);
    608         if (!CallStack.empty()) {
    609           assert(CallStack.back().first == C);
    610           CallStack.pop_back();
    611         }
    612         break;
    613       }
    614 
    615       if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
    616         const CFGBlock *Src = BE->getSrc();
    617         const CFGBlock *Dst = BE->getDst();
    618         const Stmt *T = Src->getTerminator();
    619 
    620         if (!T)
    621           break;
    622 
    623         PathDiagnosticLocation Start =
    624             PathDiagnosticLocation::createBegin(T, SMgr,
    625                 N->getLocationContext());
    626 
    627         switch (T->getStmtClass()) {
    628         default:
    629           break;
    630 
    631         case Stmt::GotoStmtClass:
    632         case Stmt::IndirectGotoStmtClass: {
    633           const Stmt *S = PathDiagnosticLocation::getNextStmt(N);
    634 
    635           if (!S)
    636             break;
    637 
    638           std::string sbuf;
    639           llvm::raw_string_ostream os(sbuf);
    640           const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
    641 
    642           os << "Control jumps to line "
    643               << End.asLocation().getExpansionLineNumber();
    644           PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
    645               Start, End, os.str()));
    646           break;
    647         }
    648 
    649         case Stmt::SwitchStmtClass: {
    650           // Figure out what case arm we took.
    651           std::string sbuf;
    652           llvm::raw_string_ostream os(sbuf);
    653 
    654           if (const Stmt *S = Dst->getLabel()) {
    655             PathDiagnosticLocation End(S, SMgr, LC);
    656 
    657             switch (S->getStmtClass()) {
    658             default:
    659               os << "No cases match in the switch statement. "
    660               "Control jumps to line "
    661               << End.asLocation().getExpansionLineNumber();
    662               break;
    663             case Stmt::DefaultStmtClass:
    664               os << "Control jumps to the 'default' case at line "
    665               << End.asLocation().getExpansionLineNumber();
    666               break;
    667 
    668             case Stmt::CaseStmtClass: {
    669               os << "Control jumps to 'case ";
    670               const CaseStmt *Case = cast<CaseStmt>(S);
    671               const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
    672 
    673               // Determine if it is an enum.
    674               bool GetRawInt = true;
    675 
    676               if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
    677                 // FIXME: Maybe this should be an assertion.  Are there cases
    678                 // were it is not an EnumConstantDecl?
    679                 const EnumConstantDecl *D =
    680                     dyn_cast<EnumConstantDecl>(DR->getDecl());
    681 
    682                 if (D) {
    683                   GetRawInt = false;
    684                   os << *D;
    685                 }
    686               }
    687 
    688               if (GetRawInt)
    689                 os << LHS->EvaluateKnownConstInt(PDB.getASTContext());
    690 
    691               os << ":'  at line "
    692                   << End.asLocation().getExpansionLineNumber();
    693               break;
    694             }
    695             }
    696             PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
    697                 Start, End, os.str()));
    698           }
    699           else {
    700             os << "'Default' branch taken. ";
    701             const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
    702             PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
    703                 Start, End, os.str()));
    704           }
    705 
    706           break;
    707         }
    708 
    709         case Stmt::BreakStmtClass:
    710         case Stmt::ContinueStmtClass: {
    711           std::string sbuf;
    712           llvm::raw_string_ostream os(sbuf);
    713           PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
    714           PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
    715               Start, End, os.str()));
    716           break;
    717         }
    718 
    719         // Determine control-flow for ternary '?'.
    720         case Stmt::BinaryConditionalOperatorClass:
    721         case Stmt::ConditionalOperatorClass: {
    722           std::string sbuf;
    723           llvm::raw_string_ostream os(sbuf);
    724           os << "'?' condition is ";
    725 
    726           if (*(Src->succ_begin()+1) == Dst)
    727             os << "false";
    728           else
    729             os << "true";
    730 
    731           PathDiagnosticLocation End = PDB.ExecutionContinues(N);
    732 
    733           if (const Stmt *S = End.asStmt())
    734             End = PDB.getEnclosingStmtLocation(S);
    735 
    736           PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
    737               Start, End, os.str()));
    738           break;
    739         }
    740 
    741         // Determine control-flow for short-circuited '&&' and '||'.
    742         case Stmt::BinaryOperatorClass: {
    743           if (!PDB.supportsLogicalOpControlFlow())
    744             break;
    745 
    746           const BinaryOperator *B = cast<BinaryOperator>(T);
    747           std::string sbuf;
    748           llvm::raw_string_ostream os(sbuf);
    749           os << "Left side of '";
    750 
    751           if (B->getOpcode() == BO_LAnd) {
    752             os << "&&" << "' is ";
    753 
    754             if (*(Src->succ_begin()+1) == Dst) {
    755               os << "false";
    756               PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
    757               PathDiagnosticLocation Start =
    758                   PathDiagnosticLocation::createOperatorLoc(B, SMgr);
    759               PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
    760                   Start, End, os.str()));
    761             }
    762             else {
    763               os << "true";
    764               PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
    765               PathDiagnosticLocation End = PDB.ExecutionContinues(N);
    766               PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
    767                   Start, End, os.str()));
    768             }
    769           }
    770           else {
    771             assert(B->getOpcode() == BO_LOr);
    772             os << "||" << "' is ";
    773 
    774             if (*(Src->succ_begin()+1) == Dst) {
    775               os << "false";
    776               PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
    777               PathDiagnosticLocation End = PDB.ExecutionContinues(N);
    778               PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
    779                   Start, End, os.str()));
    780             }
    781             else {
    782               os << "true";
    783               PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
    784               PathDiagnosticLocation Start =
    785                   PathDiagnosticLocation::createOperatorLoc(B, SMgr);
    786               PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
    787                   Start, End, os.str()));
    788             }
    789           }
    790 
    791           break;
    792         }
    793 
    794         case Stmt::DoStmtClass:  {
    795           if (*(Src->succ_begin()) == Dst) {
    796             std::string sbuf;
    797             llvm::raw_string_ostream os(sbuf);
    798 
    799             os << "Loop condition is true. ";
    800             PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
    801 
    802             if (const Stmt *S = End.asStmt())
    803               End = PDB.getEnclosingStmtLocation(S);
    804 
    805             PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
    806                 Start, End, os.str()));
    807           }
    808           else {
    809             PathDiagnosticLocation End = PDB.ExecutionContinues(N);
    810 
    811             if (const Stmt *S = End.asStmt())
    812               End = PDB.getEnclosingStmtLocation(S);
    813 
    814             PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
    815                 Start, End, "Loop condition is false.  Exiting loop"));
    816           }
    817 
    818           break;
    819         }
    820 
    821         case Stmt::WhileStmtClass:
    822         case Stmt::ForStmtClass: {
    823           if (*(Src->succ_begin()+1) == Dst) {
    824             std::string sbuf;
    825             llvm::raw_string_ostream os(sbuf);
    826 
    827             os << "Loop condition is false. ";
    828             PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
    829             if (const Stmt *S = End.asStmt())
    830               End = PDB.getEnclosingStmtLocation(S);
    831 
    832             PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
    833                 Start, End, os.str()));
    834           }
    835           else {
    836             PathDiagnosticLocation End = PDB.ExecutionContinues(N);
    837             if (const Stmt *S = End.asStmt())
    838               End = PDB.getEnclosingStmtLocation(S);
    839 
    840             PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
    841                 Start, End, "Loop condition is true.  Entering loop body"));
    842           }
    843 
    844           break;
    845         }
    846 
    847         case Stmt::IfStmtClass: {
    848           PathDiagnosticLocation End = PDB.ExecutionContinues(N);
    849 
    850           if (const Stmt *S = End.asStmt())
    851             End = PDB.getEnclosingStmtLocation(S);
    852 
    853           if (*(Src->succ_begin()+1) == Dst)
    854             PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
    855                 Start, End, "Taking false branch"));
    856           else
    857             PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
    858                 Start, End, "Taking true branch"));
    859 
    860           break;
    861         }
    862         }
    863       }
    864     } while(0);
    865 
    866     if (NextNode) {
    867       // Add diagnostic pieces from custom visitors.
    868       BugReport *R = PDB.getBugReport();
    869       for (auto &V : visitors) {
    870         if (PathDiagnosticPiece *p = V->VisitNode(N, NextNode, PDB, *R)) {
    871           PD.getActivePath().push_front(p);
    872           updateStackPiecesWithMessage(p, CallStack);
    873         }
    874       }
    875     }
    876   }
    877 
    878   if (!PDB.getBugReport()->isValid())
    879     return false;
    880 
    881   // After constructing the full PathDiagnostic, do a pass over it to compact
    882   // PathDiagnosticPieces that occur within a macro.
    883   CompactPathDiagnostic(PD.getMutablePieces(), PDB.getSourceManager());
    884   return true;
    885 }
    886 
    887 //===----------------------------------------------------------------------===//
    888 // "Extensive" PathDiagnostic generation.
    889 //===----------------------------------------------------------------------===//
    890 
    891 static bool IsControlFlowExpr(const Stmt *S) {
    892   const Expr *E = dyn_cast<Expr>(S);
    893 
    894   if (!E)
    895     return false;
    896 
    897   E = E->IgnoreParenCasts();
    898 
    899   if (isa<AbstractConditionalOperator>(E))
    900     return true;
    901 
    902   if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
    903     if (B->isLogicalOp())
    904       return true;
    905 
    906   return false;
    907 }
    908 
    909 namespace {
    910 class ContextLocation : public PathDiagnosticLocation {
    911   bool IsDead;
    912 public:
    913   ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
    914     : PathDiagnosticLocation(L), IsDead(isdead) {}
    915 
    916   void markDead() { IsDead = true; }
    917   bool isDead() const { return IsDead; }
    918 };
    919 
    920 static PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
    921                                               const LocationContext *LC,
    922                                               bool firstCharOnly = false) {
    923   if (const Stmt *S = L.asStmt()) {
    924     const Stmt *Original = S;
    925     while (1) {
    926       // Adjust the location for some expressions that are best referenced
    927       // by one of their subexpressions.
    928       switch (S->getStmtClass()) {
    929         default:
    930           break;
    931         case Stmt::ParenExprClass:
    932         case Stmt::GenericSelectionExprClass:
    933           S = cast<Expr>(S)->IgnoreParens();
    934           firstCharOnly = true;
    935           continue;
    936         case Stmt::BinaryConditionalOperatorClass:
    937         case Stmt::ConditionalOperatorClass:
    938           S = cast<AbstractConditionalOperator>(S)->getCond();
    939           firstCharOnly = true;
    940           continue;
    941         case Stmt::ChooseExprClass:
    942           S = cast<ChooseExpr>(S)->getCond();
    943           firstCharOnly = true;
    944           continue;
    945         case Stmt::BinaryOperatorClass:
    946           S = cast<BinaryOperator>(S)->getLHS();
    947           firstCharOnly = true;
    948           continue;
    949       }
    950 
    951       break;
    952     }
    953 
    954     if (S != Original)
    955       L = PathDiagnosticLocation(S, L.getManager(), LC);
    956   }
    957 
    958   if (firstCharOnly)
    959     L  = PathDiagnosticLocation::createSingleLocation(L);
    960 
    961   return L;
    962 }
    963 
    964 class EdgeBuilder {
    965   std::vector<ContextLocation> CLocs;
    966   typedef std::vector<ContextLocation>::iterator iterator;
    967   PathDiagnostic &PD;
    968   PathDiagnosticBuilder &PDB;
    969   PathDiagnosticLocation PrevLoc;
    970 
    971   bool IsConsumedExpr(const PathDiagnosticLocation &L);
    972 
    973   bool containsLocation(const PathDiagnosticLocation &Container,
    974                         const PathDiagnosticLocation &Containee);
    975 
    976   PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
    977 
    978 
    979 
    980   void popLocation() {
    981     if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
    982       // For contexts, we only one the first character as the range.
    983       rawAddEdge(cleanUpLocation(CLocs.back(), PDB.LC, true));
    984     }
    985     CLocs.pop_back();
    986   }
    987 
    988 public:
    989   EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
    990     : PD(pd), PDB(pdb) {
    991 
    992       // If the PathDiagnostic already has pieces, add the enclosing statement
    993       // of the first piece as a context as well.
    994       if (!PD.path.empty()) {
    995         PrevLoc = (*PD.path.begin())->getLocation();
    996 
    997         if (const Stmt *S = PrevLoc.asStmt())
    998           addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
    999       }
   1000   }
   1001 
   1002   ~EdgeBuilder() {
   1003     while (!CLocs.empty()) popLocation();
   1004 
   1005     // Finally, add an initial edge from the start location of the first
   1006     // statement (if it doesn't already exist).
   1007     PathDiagnosticLocation L = PathDiagnosticLocation::createDeclBegin(
   1008                                                        PDB.LC,
   1009                                                        PDB.getSourceManager());
   1010     if (L.isValid())
   1011       rawAddEdge(L);
   1012   }
   1013 
   1014   void flushLocations() {
   1015     while (!CLocs.empty())
   1016       popLocation();
   1017     PrevLoc = PathDiagnosticLocation();
   1018   }
   1019 
   1020   void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false,
   1021                bool IsPostJump = false);
   1022 
   1023   void rawAddEdge(PathDiagnosticLocation NewLoc);
   1024 
   1025   void addContext(const Stmt *S);
   1026   void addContext(const PathDiagnosticLocation &L);
   1027   void addExtendedContext(const Stmt *S);
   1028 };
   1029 } // end anonymous namespace
   1030 
   1031 
   1032 PathDiagnosticLocation
   1033 EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
   1034   if (const Stmt *S = L.asStmt()) {
   1035     if (IsControlFlowExpr(S))
   1036       return L;
   1037 
   1038     return PDB.getEnclosingStmtLocation(S);
   1039   }
   1040 
   1041   return L;
   1042 }
   1043 
   1044 bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
   1045                                    const PathDiagnosticLocation &Containee) {
   1046 
   1047   if (Container == Containee)
   1048     return true;
   1049 
   1050   if (Container.asDecl())
   1051     return true;
   1052 
   1053   if (const Stmt *S = Containee.asStmt())
   1054     if (const Stmt *ContainerS = Container.asStmt()) {
   1055       while (S) {
   1056         if (S == ContainerS)
   1057           return true;
   1058         S = PDB.getParent(S);
   1059       }
   1060       return false;
   1061     }
   1062 
   1063   // Less accurate: compare using source ranges.
   1064   SourceRange ContainerR = Container.asRange();
   1065   SourceRange ContaineeR = Containee.asRange();
   1066 
   1067   SourceManager &SM = PDB.getSourceManager();
   1068   SourceLocation ContainerRBeg = SM.getExpansionLoc(ContainerR.getBegin());
   1069   SourceLocation ContainerREnd = SM.getExpansionLoc(ContainerR.getEnd());
   1070   SourceLocation ContaineeRBeg = SM.getExpansionLoc(ContaineeR.getBegin());
   1071   SourceLocation ContaineeREnd = SM.getExpansionLoc(ContaineeR.getEnd());
   1072 
   1073   unsigned ContainerBegLine = SM.getExpansionLineNumber(ContainerRBeg);
   1074   unsigned ContainerEndLine = SM.getExpansionLineNumber(ContainerREnd);
   1075   unsigned ContaineeBegLine = SM.getExpansionLineNumber(ContaineeRBeg);
   1076   unsigned ContaineeEndLine = SM.getExpansionLineNumber(ContaineeREnd);
   1077 
   1078   assert(ContainerBegLine <= ContainerEndLine);
   1079   assert(ContaineeBegLine <= ContaineeEndLine);
   1080 
   1081   return (ContainerBegLine <= ContaineeBegLine &&
   1082           ContainerEndLine >= ContaineeEndLine &&
   1083           (ContainerBegLine != ContaineeBegLine ||
   1084            SM.getExpansionColumnNumber(ContainerRBeg) <=
   1085            SM.getExpansionColumnNumber(ContaineeRBeg)) &&
   1086           (ContainerEndLine != ContaineeEndLine ||
   1087            SM.getExpansionColumnNumber(ContainerREnd) >=
   1088            SM.getExpansionColumnNumber(ContaineeREnd)));
   1089 }
   1090 
   1091 void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
   1092   if (!PrevLoc.isValid()) {
   1093     PrevLoc = NewLoc;
   1094     return;
   1095   }
   1096 
   1097   const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc, PDB.LC);
   1098   const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc, PDB.LC);
   1099 
   1100   if (PrevLocClean.asLocation().isInvalid()) {
   1101     PrevLoc = NewLoc;
   1102     return;
   1103   }
   1104 
   1105   if (NewLocClean.asLocation() == PrevLocClean.asLocation())
   1106     return;
   1107 
   1108   // FIXME: Ignore intra-macro edges for now.
   1109   if (NewLocClean.asLocation().getExpansionLoc() ==
   1110       PrevLocClean.asLocation().getExpansionLoc())
   1111     return;
   1112 
   1113   PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
   1114   PrevLoc = NewLoc;
   1115 }
   1116 
   1117 void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd,
   1118                           bool IsPostJump) {
   1119 
   1120   if (!alwaysAdd && NewLoc.asLocation().isMacroID())
   1121     return;
   1122 
   1123   const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
   1124 
   1125   while (!CLocs.empty()) {
   1126     ContextLocation &TopContextLoc = CLocs.back();
   1127 
   1128     // Is the top location context the same as the one for the new location?
   1129     if (TopContextLoc == CLoc) {
   1130       if (alwaysAdd) {
   1131         if (IsConsumedExpr(TopContextLoc))
   1132           TopContextLoc.markDead();
   1133 
   1134         rawAddEdge(NewLoc);
   1135       }
   1136 
   1137       if (IsPostJump)
   1138         TopContextLoc.markDead();
   1139       return;
   1140     }
   1141 
   1142     if (containsLocation(TopContextLoc, CLoc)) {
   1143       if (alwaysAdd) {
   1144         rawAddEdge(NewLoc);
   1145 
   1146         if (IsConsumedExpr(CLoc)) {
   1147           CLocs.push_back(ContextLocation(CLoc, /*IsDead=*/true));
   1148           return;
   1149         }
   1150       }
   1151 
   1152       CLocs.push_back(ContextLocation(CLoc, /*IsDead=*/IsPostJump));
   1153       return;
   1154     }
   1155 
   1156     // Context does not contain the location.  Flush it.
   1157     popLocation();
   1158   }
   1159 
   1160   // If we reach here, there is no enclosing context.  Just add the edge.
   1161   rawAddEdge(NewLoc);
   1162 }
   1163 
   1164 bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
   1165   if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
   1166     return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
   1167 
   1168   return false;
   1169 }
   1170 
   1171 void EdgeBuilder::addExtendedContext(const Stmt *S) {
   1172   if (!S)
   1173     return;
   1174 
   1175   const Stmt *Parent = PDB.getParent(S);
   1176   while (Parent) {
   1177     if (isa<CompoundStmt>(Parent))
   1178       Parent = PDB.getParent(Parent);
   1179     else
   1180       break;
   1181   }
   1182 
   1183   if (Parent) {
   1184     switch (Parent->getStmtClass()) {
   1185       case Stmt::DoStmtClass:
   1186       case Stmt::ObjCAtSynchronizedStmtClass:
   1187         addContext(Parent);
   1188       default:
   1189         break;
   1190     }
   1191   }
   1192 
   1193   addContext(S);
   1194 }
   1195 
   1196 void EdgeBuilder::addContext(const Stmt *S) {
   1197   if (!S)
   1198     return;
   1199 
   1200   PathDiagnosticLocation L(S, PDB.getSourceManager(), PDB.LC);
   1201   addContext(L);
   1202 }
   1203 
   1204 void EdgeBuilder::addContext(const PathDiagnosticLocation &L) {
   1205   while (!CLocs.empty()) {
   1206     const PathDiagnosticLocation &TopContextLoc = CLocs.back();
   1207 
   1208     // Is the top location context the same as the one for the new location?
   1209     if (TopContextLoc == L)
   1210       return;
   1211 
   1212     if (containsLocation(TopContextLoc, L)) {
   1213       CLocs.push_back(L);
   1214       return;
   1215     }
   1216 
   1217     // Context does not contain the location.  Flush it.
   1218     popLocation();
   1219   }
   1220 
   1221   CLocs.push_back(L);
   1222 }
   1223 
   1224 // Cone-of-influence: support the reverse propagation of "interesting" symbols
   1225 // and values by tracing interesting calculations backwards through evaluated
   1226 // expressions along a path.  This is probably overly complicated, but the idea
   1227 // is that if an expression computed an "interesting" value, the child
   1228 // expressions are are also likely to be "interesting" as well (which then
   1229 // propagates to the values they in turn compute).  This reverse propagation
   1230 // is needed to track interesting correlations across function call boundaries,
   1231 // where formal arguments bind to actual arguments, etc.  This is also needed
   1232 // because the constraint solver sometimes simplifies certain symbolic values
   1233 // into constants when appropriate, and this complicates reasoning about
   1234 // interesting values.
   1235 typedef llvm::DenseSet<const Expr *> InterestingExprs;
   1236 
   1237 static void reversePropagateIntererstingSymbols(BugReport &R,
   1238                                                 InterestingExprs &IE,
   1239                                                 const ProgramState *State,
   1240                                                 const Expr *Ex,
   1241                                                 const LocationContext *LCtx) {
   1242   SVal V = State->getSVal(Ex, LCtx);
   1243   if (!(R.isInteresting(V) || IE.count(Ex)))
   1244     return;
   1245 
   1246   switch (Ex->getStmtClass()) {
   1247     default:
   1248       if (!isa<CastExpr>(Ex))
   1249         break;
   1250       // Fall through.
   1251     case Stmt::BinaryOperatorClass:
   1252     case Stmt::UnaryOperatorClass: {
   1253       for (Stmt::const_child_iterator CI = Ex->child_begin(),
   1254             CE = Ex->child_end();
   1255             CI != CE; ++CI) {
   1256         if (const Expr *child = dyn_cast_or_null<Expr>(*CI)) {
   1257           IE.insert(child);
   1258           SVal ChildV = State->getSVal(child, LCtx);
   1259           R.markInteresting(ChildV);
   1260         }
   1261       }
   1262       break;
   1263     }
   1264   }
   1265 
   1266   R.markInteresting(V);
   1267 }
   1268 
   1269 static void reversePropagateInterestingSymbols(BugReport &R,
   1270                                                InterestingExprs &IE,
   1271                                                const ProgramState *State,
   1272                                                const LocationContext *CalleeCtx,
   1273                                                const LocationContext *CallerCtx)
   1274 {
   1275   // FIXME: Handle non-CallExpr-based CallEvents.
   1276   const StackFrameContext *Callee = CalleeCtx->getCurrentStackFrame();
   1277   const Stmt *CallSite = Callee->getCallSite();
   1278   if (const CallExpr *CE = dyn_cast_or_null<CallExpr>(CallSite)) {
   1279     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CalleeCtx->getDecl())) {
   1280       FunctionDecl::param_const_iterator PI = FD->param_begin(),
   1281                                          PE = FD->param_end();
   1282       CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end();
   1283       for (; AI != AE && PI != PE; ++AI, ++PI) {
   1284         if (const Expr *ArgE = *AI) {
   1285           if (const ParmVarDecl *PD = *PI) {
   1286             Loc LV = State->getLValue(PD, CalleeCtx);
   1287             if (R.isInteresting(LV) || R.isInteresting(State->getRawSVal(LV)))
   1288               IE.insert(ArgE);
   1289           }
   1290         }
   1291       }
   1292     }
   1293   }
   1294 }
   1295 
   1296 //===----------------------------------------------------------------------===//
   1297 // Functions for determining if a loop was executed 0 times.
   1298 //===----------------------------------------------------------------------===//
   1299 
   1300 static bool isLoop(const Stmt *Term) {
   1301   switch (Term->getStmtClass()) {
   1302     case Stmt::ForStmtClass:
   1303     case Stmt::WhileStmtClass:
   1304     case Stmt::ObjCForCollectionStmtClass:
   1305     case Stmt::CXXForRangeStmtClass:
   1306       return true;
   1307     default:
   1308       // Note that we intentionally do not include do..while here.
   1309       return false;
   1310   }
   1311 }
   1312 
   1313 static bool isJumpToFalseBranch(const BlockEdge *BE) {
   1314   const CFGBlock *Src = BE->getSrc();
   1315   assert(Src->succ_size() == 2);
   1316   return (*(Src->succ_begin()+1) == BE->getDst());
   1317 }
   1318 
   1319 /// Return true if the terminator is a loop and the destination is the
   1320 /// false branch.
   1321 static bool isLoopJumpPastBody(const Stmt *Term, const BlockEdge *BE) {
   1322   if (!isLoop(Term))
   1323     return false;
   1324 
   1325   // Did we take the false branch?
   1326   return isJumpToFalseBranch(BE);
   1327 }
   1328 
   1329 static bool isContainedByStmt(ParentMap &PM, const Stmt *S, const Stmt *SubS) {
   1330   while (SubS) {
   1331     if (SubS == S)
   1332       return true;
   1333     SubS = PM.getParent(SubS);
   1334   }
   1335   return false;
   1336 }
   1337 
   1338 static const Stmt *getStmtBeforeCond(ParentMap &PM, const Stmt *Term,
   1339                                      const ExplodedNode *N) {
   1340   while (N) {
   1341     Optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>();
   1342     if (SP) {
   1343       const Stmt *S = SP->getStmt();
   1344       if (!isContainedByStmt(PM, Term, S))
   1345         return S;
   1346     }
   1347     N = N->getFirstPred();
   1348   }
   1349   return nullptr;
   1350 }
   1351 
   1352 static bool isInLoopBody(ParentMap &PM, const Stmt *S, const Stmt *Term) {
   1353   const Stmt *LoopBody = nullptr;
   1354   switch (Term->getStmtClass()) {
   1355     case Stmt::CXXForRangeStmtClass: {
   1356       const CXXForRangeStmt *FR = cast<CXXForRangeStmt>(Term);
   1357       if (isContainedByStmt(PM, FR->getInc(), S))
   1358         return true;
   1359       if (isContainedByStmt(PM, FR->getLoopVarStmt(), S))
   1360         return true;
   1361       LoopBody = FR->getBody();
   1362       break;
   1363     }
   1364     case Stmt::ForStmtClass: {
   1365       const ForStmt *FS = cast<ForStmt>(Term);
   1366       if (isContainedByStmt(PM, FS->getInc(), S))
   1367         return true;
   1368       LoopBody = FS->getBody();
   1369       break;
   1370     }
   1371     case Stmt::ObjCForCollectionStmtClass: {
   1372       const ObjCForCollectionStmt *FC = cast<ObjCForCollectionStmt>(Term);
   1373       LoopBody = FC->getBody();
   1374       break;
   1375     }
   1376     case Stmt::WhileStmtClass:
   1377       LoopBody = cast<WhileStmt>(Term)->getBody();
   1378       break;
   1379     default:
   1380       return false;
   1381   }
   1382   return isContainedByStmt(PM, LoopBody, S);
   1383 }
   1384 
   1385 //===----------------------------------------------------------------------===//
   1386 // Top-level logic for generating extensive path diagnostics.
   1387 //===----------------------------------------------------------------------===//
   1388 
   1389 static bool GenerateExtensivePathDiagnostic(
   1390     PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
   1391     LocationContextMap &LCM,
   1392     ArrayRef<std::unique_ptr<BugReporterVisitor>> visitors) {
   1393   EdgeBuilder EB(PD, PDB);
   1394   const SourceManager& SM = PDB.getSourceManager();
   1395   StackDiagVector CallStack;
   1396   InterestingExprs IE;
   1397 
   1398   const ExplodedNode *NextNode = N->pred_empty() ? nullptr : *(N->pred_begin());
   1399   while (NextNode) {
   1400     N = NextNode;
   1401     NextNode = N->getFirstPred();
   1402     ProgramPoint P = N->getLocation();
   1403 
   1404     do {
   1405       if (Optional<PostStmt> PS = P.getAs<PostStmt>()) {
   1406         if (const Expr *Ex = PS->getStmtAs<Expr>())
   1407           reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
   1408                                               N->getState().get(), Ex,
   1409                                               N->getLocationContext());
   1410       }
   1411 
   1412       if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
   1413         const Stmt *S = CE->getCalleeContext()->getCallSite();
   1414         if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) {
   1415             reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
   1416                                                 N->getState().get(), Ex,
   1417                                                 N->getLocationContext());
   1418         }
   1419 
   1420         PathDiagnosticCallPiece *C =
   1421           PathDiagnosticCallPiece::construct(N, *CE, SM);
   1422         LCM[&C->path] = CE->getCalleeContext();
   1423 
   1424         EB.addEdge(C->callReturn, /*AlwaysAdd=*/true, /*IsPostJump=*/true);
   1425         EB.flushLocations();
   1426 
   1427         PD.getActivePath().push_front(C);
   1428         PD.pushActivePath(&C->path);
   1429         CallStack.push_back(StackDiagPair(C, N));
   1430         break;
   1431       }
   1432 
   1433       // Pop the call hierarchy if we are done walking the contents
   1434       // of a function call.
   1435       if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
   1436         // Add an edge to the start of the function.
   1437         const Decl *D = CE->getCalleeContext()->getDecl();
   1438         PathDiagnosticLocation pos =
   1439           PathDiagnosticLocation::createBegin(D, SM);
   1440         EB.addEdge(pos);
   1441 
   1442         // Flush all locations, and pop the active path.
   1443         bool VisitedEntireCall = PD.isWithinCall();
   1444         EB.flushLocations();
   1445         PD.popActivePath();
   1446         PDB.LC = N->getLocationContext();
   1447 
   1448         // Either we just added a bunch of stuff to the top-level path, or
   1449         // we have a previous CallExitEnd.  If the former, it means that the
   1450         // path terminated within a function call.  We must then take the
   1451         // current contents of the active path and place it within
   1452         // a new PathDiagnosticCallPiece.
   1453         PathDiagnosticCallPiece *C;
   1454         if (VisitedEntireCall) {
   1455           C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
   1456         } else {
   1457           const Decl *Caller = CE->getLocationContext()->getDecl();
   1458           C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
   1459           LCM[&C->path] = CE->getCalleeContext();
   1460         }
   1461 
   1462         C->setCallee(*CE, SM);
   1463         EB.addContext(C->getLocation());
   1464 
   1465         if (!CallStack.empty()) {
   1466           assert(CallStack.back().first == C);
   1467           CallStack.pop_back();
   1468         }
   1469         break;
   1470       }
   1471 
   1472       // Note that is important that we update the LocationContext
   1473       // after looking at CallExits.  CallExit basically adds an
   1474       // edge in the *caller*, so we don't want to update the LocationContext
   1475       // too soon.
   1476       PDB.LC = N->getLocationContext();
   1477 
   1478       // Block edges.
   1479       if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
   1480         // Does this represent entering a call?  If so, look at propagating
   1481         // interesting symbols across call boundaries.
   1482         if (NextNode) {
   1483           const LocationContext *CallerCtx = NextNode->getLocationContext();
   1484           const LocationContext *CalleeCtx = PDB.LC;
   1485           if (CallerCtx != CalleeCtx) {
   1486             reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
   1487                                                N->getState().get(),
   1488                                                CalleeCtx, CallerCtx);
   1489           }
   1490         }
   1491 
   1492         // Are we jumping to the head of a loop?  Add a special diagnostic.
   1493         if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
   1494           PathDiagnosticLocation L(Loop, SM, PDB.LC);
   1495           const CompoundStmt *CS = nullptr;
   1496 
   1497           if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
   1498             CS = dyn_cast<CompoundStmt>(FS->getBody());
   1499           else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
   1500             CS = dyn_cast<CompoundStmt>(WS->getBody());
   1501 
   1502           PathDiagnosticEventPiece *p =
   1503             new PathDiagnosticEventPiece(L,
   1504                                         "Looping back to the head of the loop");
   1505           p->setPrunable(true);
   1506 
   1507           EB.addEdge(p->getLocation(), true);
   1508           PD.getActivePath().push_front(p);
   1509 
   1510           if (CS) {
   1511             PathDiagnosticLocation BL =
   1512               PathDiagnosticLocation::createEndBrace(CS, SM);
   1513             EB.addEdge(BL);
   1514           }
   1515         }
   1516 
   1517         const CFGBlock *BSrc = BE->getSrc();
   1518         ParentMap &PM = PDB.getParentMap();
   1519 
   1520         if (const Stmt *Term = BSrc->getTerminator()) {
   1521           // Are we jumping past the loop body without ever executing the
   1522           // loop (because the condition was false)?
   1523           if (isLoopJumpPastBody(Term, &*BE) &&
   1524               !isInLoopBody(PM,
   1525                             getStmtBeforeCond(PM,
   1526                                               BSrc->getTerminatorCondition(),
   1527                                               N),
   1528                             Term)) {
   1529             PathDiagnosticLocation L(Term, SM, PDB.LC);
   1530             PathDiagnosticEventPiece *PE =
   1531                 new PathDiagnosticEventPiece(L, "Loop body executed 0 times");
   1532             PE->setPrunable(true);
   1533 
   1534             EB.addEdge(PE->getLocation(), true);
   1535             PD.getActivePath().push_front(PE);
   1536           }
   1537 
   1538           // In any case, add the terminator as the current statement
   1539           // context for control edges.
   1540           EB.addContext(Term);
   1541         }
   1542 
   1543         break;
   1544       }
   1545 
   1546       if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) {
   1547         Optional<CFGElement> First = BE->getFirstElement();
   1548         if (Optional<CFGStmt> S = First ? First->getAs<CFGStmt>() : None) {
   1549           const Stmt *stmt = S->getStmt();
   1550           if (IsControlFlowExpr(stmt)) {
   1551             // Add the proper context for '&&', '||', and '?'.
   1552             EB.addContext(stmt);
   1553           }
   1554           else
   1555             EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt());
   1556         }
   1557 
   1558         break;
   1559       }
   1560 
   1561 
   1562     } while (0);
   1563 
   1564     if (!NextNode)
   1565       continue;
   1566 
   1567     // Add pieces from custom visitors.
   1568     BugReport *R = PDB.getBugReport();
   1569     for (auto &V : visitors) {
   1570       if (PathDiagnosticPiece *p = V->VisitNode(N, NextNode, PDB, *R)) {
   1571         const PathDiagnosticLocation &Loc = p->getLocation();
   1572         EB.addEdge(Loc, true);
   1573         PD.getActivePath().push_front(p);
   1574         updateStackPiecesWithMessage(p, CallStack);
   1575 
   1576         if (const Stmt *S = Loc.asStmt())
   1577           EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
   1578       }
   1579     }
   1580   }
   1581 
   1582   return PDB.getBugReport()->isValid();
   1583 }
   1584 
   1585 /// \brief Adds a sanitized control-flow diagnostic edge to a path.
   1586 static void addEdgeToPath(PathPieces &path,
   1587                           PathDiagnosticLocation &PrevLoc,
   1588                           PathDiagnosticLocation NewLoc,
   1589                           const LocationContext *LC) {
   1590   if (!NewLoc.isValid())
   1591     return;
   1592 
   1593   SourceLocation NewLocL = NewLoc.asLocation();
   1594   if (NewLocL.isInvalid())
   1595     return;
   1596 
   1597   if (!PrevLoc.isValid() || !PrevLoc.asLocation().isValid()) {
   1598     PrevLoc = NewLoc;
   1599     return;
   1600   }
   1601 
   1602   // Ignore self-edges, which occur when there are multiple nodes at the same
   1603   // statement.
   1604   if (NewLoc.asStmt() && NewLoc.asStmt() == PrevLoc.asStmt())
   1605     return;
   1606 
   1607   path.push_front(new PathDiagnosticControlFlowPiece(NewLoc,
   1608                                                      PrevLoc));
   1609   PrevLoc = NewLoc;
   1610 }
   1611 
   1612 /// A customized wrapper for CFGBlock::getTerminatorCondition()
   1613 /// which returns the element for ObjCForCollectionStmts.
   1614 static const Stmt *getTerminatorCondition(const CFGBlock *B) {
   1615   const Stmt *S = B->getTerminatorCondition();
   1616   if (const ObjCForCollectionStmt *FS =
   1617       dyn_cast_or_null<ObjCForCollectionStmt>(S))
   1618     return FS->getElement();
   1619   return S;
   1620 }
   1621 
   1622 static const char StrEnteringLoop[] = "Entering loop body";
   1623 static const char StrLoopBodyZero[] = "Loop body executed 0 times";
   1624 static const char StrLoopRangeEmpty[] =
   1625   "Loop body skipped when range is empty";
   1626 static const char StrLoopCollectionEmpty[] =
   1627   "Loop body skipped when collection is empty";
   1628 
   1629 static bool GenerateAlternateExtensivePathDiagnostic(
   1630     PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
   1631     LocationContextMap &LCM,
   1632     ArrayRef<std::unique_ptr<BugReporterVisitor>> visitors) {
   1633 
   1634   BugReport *report = PDB.getBugReport();
   1635   const SourceManager& SM = PDB.getSourceManager();
   1636   StackDiagVector CallStack;
   1637   InterestingExprs IE;
   1638 
   1639   PathDiagnosticLocation PrevLoc = PD.getLocation();
   1640 
   1641   const ExplodedNode *NextNode = N->getFirstPred();
   1642   while (NextNode) {
   1643     N = NextNode;
   1644     NextNode = N->getFirstPred();
   1645     ProgramPoint P = N->getLocation();
   1646 
   1647     do {
   1648       // Have we encountered an entrance to a call?  It may be
   1649       // the case that we have not encountered a matching
   1650       // call exit before this point.  This means that the path
   1651       // terminated within the call itself.
   1652       if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
   1653         // Add an edge to the start of the function.
   1654         const StackFrameContext *CalleeLC = CE->getCalleeContext();
   1655         const Decl *D = CalleeLC->getDecl();
   1656         addEdgeToPath(PD.getActivePath(), PrevLoc,
   1657                       PathDiagnosticLocation::createBegin(D, SM),
   1658                       CalleeLC);
   1659 
   1660         // Did we visit an entire call?
   1661         bool VisitedEntireCall = PD.isWithinCall();
   1662         PD.popActivePath();
   1663 
   1664         PathDiagnosticCallPiece *C;
   1665         if (VisitedEntireCall) {
   1666           PathDiagnosticPiece *P = PD.getActivePath().front().get();
   1667           C = cast<PathDiagnosticCallPiece>(P);
   1668         } else {
   1669           const Decl *Caller = CE->getLocationContext()->getDecl();
   1670           C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
   1671 
   1672           // Since we just transferred the path over to the call piece,
   1673           // reset the mapping from active to location context.
   1674           assert(PD.getActivePath().size() == 1 &&
   1675                  PD.getActivePath().front() == C);
   1676           LCM[&PD.getActivePath()] = nullptr;
   1677 
   1678           // Record the location context mapping for the path within
   1679           // the call.
   1680           assert(LCM[&C->path] == nullptr ||
   1681                  LCM[&C->path] == CE->getCalleeContext());
   1682           LCM[&C->path] = CE->getCalleeContext();
   1683 
   1684           // If this is the first item in the active path, record
   1685           // the new mapping from active path to location context.
   1686           const LocationContext *&NewLC = LCM[&PD.getActivePath()];
   1687           if (!NewLC)
   1688             NewLC = N->getLocationContext();
   1689 
   1690           PDB.LC = NewLC;
   1691         }
   1692         C->setCallee(*CE, SM);
   1693 
   1694         // Update the previous location in the active path.
   1695         PrevLoc = C->getLocation();
   1696 
   1697         if (!CallStack.empty()) {
   1698           assert(CallStack.back().first == C);
   1699           CallStack.pop_back();
   1700         }
   1701         break;
   1702       }
   1703 
   1704       // Query the location context here and the previous location
   1705       // as processing CallEnter may change the active path.
   1706       PDB.LC = N->getLocationContext();
   1707 
   1708       // Record the mapping from the active path to the location
   1709       // context.
   1710       assert(!LCM[&PD.getActivePath()] ||
   1711              LCM[&PD.getActivePath()] == PDB.LC);
   1712       LCM[&PD.getActivePath()] = PDB.LC;
   1713 
   1714       // Have we encountered an exit from a function call?
   1715       if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
   1716         const Stmt *S = CE->getCalleeContext()->getCallSite();
   1717         // Propagate the interesting symbols accordingly.
   1718         if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) {
   1719           reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
   1720                                               N->getState().get(), Ex,
   1721                                               N->getLocationContext());
   1722         }
   1723 
   1724         // We are descending into a call (backwards).  Construct
   1725         // a new call piece to contain the path pieces for that call.
   1726         PathDiagnosticCallPiece *C =
   1727           PathDiagnosticCallPiece::construct(N, *CE, SM);
   1728 
   1729         // Record the location context for this call piece.
   1730         LCM[&C->path] = CE->getCalleeContext();
   1731 
   1732         // Add the edge to the return site.
   1733         addEdgeToPath(PD.getActivePath(), PrevLoc, C->callReturn, PDB.LC);
   1734         PD.getActivePath().push_front(C);
   1735         PrevLoc.invalidate();
   1736 
   1737         // Make the contents of the call the active path for now.
   1738         PD.pushActivePath(&C->path);
   1739         CallStack.push_back(StackDiagPair(C, N));
   1740         break;
   1741       }
   1742 
   1743       if (Optional<PostStmt> PS = P.getAs<PostStmt>()) {
   1744         // For expressions, make sure we propagate the
   1745         // interesting symbols correctly.
   1746         if (const Expr *Ex = PS->getStmtAs<Expr>())
   1747           reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
   1748                                               N->getState().get(), Ex,
   1749                                               N->getLocationContext());
   1750 
   1751         // Add an edge.  If this is an ObjCForCollectionStmt do
   1752         // not add an edge here as it appears in the CFG both
   1753         // as a terminator and as a terminator condition.
   1754         if (!isa<ObjCForCollectionStmt>(PS->getStmt())) {
   1755           PathDiagnosticLocation L =
   1756             PathDiagnosticLocation(PS->getStmt(), SM, PDB.LC);
   1757           addEdgeToPath(PD.getActivePath(), PrevLoc, L, PDB.LC);
   1758         }
   1759         break;
   1760       }
   1761 
   1762       // Block edges.
   1763       if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
   1764         // Does this represent entering a call?  If so, look at propagating
   1765         // interesting symbols across call boundaries.
   1766         if (NextNode) {
   1767           const LocationContext *CallerCtx = NextNode->getLocationContext();
   1768           const LocationContext *CalleeCtx = PDB.LC;
   1769           if (CallerCtx != CalleeCtx) {
   1770             reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
   1771                                                N->getState().get(),
   1772                                                CalleeCtx, CallerCtx);
   1773           }
   1774         }
   1775 
   1776         // Are we jumping to the head of a loop?  Add a special diagnostic.
   1777         if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
   1778           PathDiagnosticLocation L(Loop, SM, PDB.LC);
   1779           const Stmt *Body = nullptr;
   1780 
   1781           if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
   1782             Body = FS->getBody();
   1783           else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
   1784             Body = WS->getBody();
   1785           else if (const ObjCForCollectionStmt *OFS =
   1786                      dyn_cast<ObjCForCollectionStmt>(Loop)) {
   1787             Body = OFS->getBody();
   1788           } else if (const CXXForRangeStmt *FRS =
   1789                        dyn_cast<CXXForRangeStmt>(Loop)) {
   1790             Body = FRS->getBody();
   1791           }
   1792           // do-while statements are explicitly excluded here
   1793 
   1794           PathDiagnosticEventPiece *p =
   1795             new PathDiagnosticEventPiece(L, "Looping back to the head "
   1796                                             "of the loop");
   1797           p->setPrunable(true);
   1798 
   1799           addEdgeToPath(PD.getActivePath(), PrevLoc, p->getLocation(), PDB.LC);
   1800           PD.getActivePath().push_front(p);
   1801 
   1802           if (const CompoundStmt *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
   1803             addEdgeToPath(PD.getActivePath(), PrevLoc,
   1804                           PathDiagnosticLocation::createEndBrace(CS, SM),
   1805                           PDB.LC);
   1806           }
   1807         }
   1808 
   1809         const CFGBlock *BSrc = BE->getSrc();
   1810         ParentMap &PM = PDB.getParentMap();
   1811 
   1812         if (const Stmt *Term = BSrc->getTerminator()) {
   1813           // Are we jumping past the loop body without ever executing the
   1814           // loop (because the condition was false)?
   1815           if (isLoop(Term)) {
   1816             const Stmt *TermCond = getTerminatorCondition(BSrc);
   1817             bool IsInLoopBody =
   1818               isInLoopBody(PM, getStmtBeforeCond(PM, TermCond, N), Term);
   1819 
   1820             const char *str = nullptr;
   1821 
   1822             if (isJumpToFalseBranch(&*BE)) {
   1823               if (!IsInLoopBody) {
   1824                 if (isa<ObjCForCollectionStmt>(Term)) {
   1825                   str = StrLoopCollectionEmpty;
   1826                 } else if (isa<CXXForRangeStmt>(Term)) {
   1827                   str = StrLoopRangeEmpty;
   1828                 } else {
   1829                   str = StrLoopBodyZero;
   1830                 }
   1831               }
   1832             } else {
   1833               str = StrEnteringLoop;
   1834             }
   1835 
   1836             if (str) {
   1837               PathDiagnosticLocation L(TermCond ? TermCond : Term, SM, PDB.LC);
   1838               PathDiagnosticEventPiece *PE =
   1839                 new PathDiagnosticEventPiece(L, str);
   1840               PE->setPrunable(true);
   1841               addEdgeToPath(PD.getActivePath(), PrevLoc,
   1842                             PE->getLocation(), PDB.LC);
   1843               PD.getActivePath().push_front(PE);
   1844             }
   1845           } else if (isa<BreakStmt>(Term) || isa<ContinueStmt>(Term) ||
   1846                      isa<GotoStmt>(Term)) {
   1847             PathDiagnosticLocation L(Term, SM, PDB.LC);
   1848             addEdgeToPath(PD.getActivePath(), PrevLoc, L, PDB.LC);
   1849           }
   1850         }
   1851         break;
   1852       }
   1853     } while (0);
   1854 
   1855     if (!NextNode)
   1856       continue;
   1857 
   1858     // Add pieces from custom visitors.
   1859     for (auto &V : visitors) {
   1860       if (PathDiagnosticPiece *p = V->VisitNode(N, NextNode, PDB, *report)) {
   1861         addEdgeToPath(PD.getActivePath(), PrevLoc, p->getLocation(), PDB.LC);
   1862         PD.getActivePath().push_front(p);
   1863         updateStackPiecesWithMessage(p, CallStack);
   1864       }
   1865     }
   1866   }
   1867 
   1868   // Add an edge to the start of the function.
   1869   // We'll prune it out later, but it helps make diagnostics more uniform.
   1870   const StackFrameContext *CalleeLC = PDB.LC->getCurrentStackFrame();
   1871   const Decl *D = CalleeLC->getDecl();
   1872   addEdgeToPath(PD.getActivePath(), PrevLoc,
   1873                 PathDiagnosticLocation::createBegin(D, SM),
   1874                 CalleeLC);
   1875 
   1876   return report->isValid();
   1877 }
   1878 
   1879 static const Stmt *getLocStmt(PathDiagnosticLocation L) {
   1880   if (!L.isValid())
   1881     return nullptr;
   1882   return L.asStmt();
   1883 }
   1884 
   1885 static const Stmt *getStmtParent(const Stmt *S, const ParentMap &PM) {
   1886   if (!S)
   1887     return nullptr;
   1888 
   1889   while (true) {
   1890     S = PM.getParentIgnoreParens(S);
   1891 
   1892     if (!S)
   1893       break;
   1894 
   1895     if (isa<ExprWithCleanups>(S) ||
   1896         isa<CXXBindTemporaryExpr>(S) ||
   1897         isa<SubstNonTypeTemplateParmExpr>(S))
   1898       continue;
   1899 
   1900     break;
   1901   }
   1902 
   1903   return S;
   1904 }
   1905 
   1906 static bool isConditionForTerminator(const Stmt *S, const Stmt *Cond) {
   1907   switch (S->getStmtClass()) {
   1908     case Stmt::BinaryOperatorClass: {
   1909       const BinaryOperator *BO = cast<BinaryOperator>(S);
   1910       if (!BO->isLogicalOp())
   1911         return false;
   1912       return BO->getLHS() == Cond || BO->getRHS() == Cond;
   1913     }
   1914     case Stmt::IfStmtClass:
   1915       return cast<IfStmt>(S)->getCond() == Cond;
   1916     case Stmt::ForStmtClass:
   1917       return cast<ForStmt>(S)->getCond() == Cond;
   1918     case Stmt::WhileStmtClass:
   1919       return cast<WhileStmt>(S)->getCond() == Cond;
   1920     case Stmt::DoStmtClass:
   1921       return cast<DoStmt>(S)->getCond() == Cond;
   1922     case Stmt::ChooseExprClass:
   1923       return cast<ChooseExpr>(S)->getCond() == Cond;
   1924     case Stmt::IndirectGotoStmtClass:
   1925       return cast<IndirectGotoStmt>(S)->getTarget() == Cond;
   1926     case Stmt::SwitchStmtClass:
   1927       return cast<SwitchStmt>(S)->getCond() == Cond;
   1928     case Stmt::BinaryConditionalOperatorClass:
   1929       return cast<BinaryConditionalOperator>(S)->getCond() == Cond;
   1930     case Stmt::ConditionalOperatorClass: {
   1931       const ConditionalOperator *CO = cast<ConditionalOperator>(S);
   1932       return CO->getCond() == Cond ||
   1933              CO->getLHS() == Cond ||
   1934              CO->getRHS() == Cond;
   1935     }
   1936     case Stmt::ObjCForCollectionStmtClass:
   1937       return cast<ObjCForCollectionStmt>(S)->getElement() == Cond;
   1938     case Stmt::CXXForRangeStmtClass: {
   1939       const CXXForRangeStmt *FRS = cast<CXXForRangeStmt>(S);
   1940       return FRS->getCond() == Cond || FRS->getRangeInit() == Cond;
   1941     }
   1942     default:
   1943       return false;
   1944   }
   1945 }
   1946 
   1947 static bool isIncrementOrInitInForLoop(const Stmt *S, const Stmt *FL) {
   1948   if (const ForStmt *FS = dyn_cast<ForStmt>(FL))
   1949     return FS->getInc() == S || FS->getInit() == S;
   1950   if (const CXXForRangeStmt *FRS = dyn_cast<CXXForRangeStmt>(FL))
   1951     return FRS->getInc() == S || FRS->getRangeStmt() == S ||
   1952            FRS->getLoopVarStmt() || FRS->getRangeInit() == S;
   1953   return false;
   1954 }
   1955 
   1956 typedef llvm::DenseSet<const PathDiagnosticCallPiece *>
   1957         OptimizedCallsSet;
   1958 
   1959 /// Adds synthetic edges from top-level statements to their subexpressions.
   1960 ///
   1961 /// This avoids a "swoosh" effect, where an edge from a top-level statement A
   1962 /// points to a sub-expression B.1 that's not at the start of B. In these cases,
   1963 /// we'd like to see an edge from A to B, then another one from B to B.1.
   1964 static void addContextEdges(PathPieces &pieces, SourceManager &SM,
   1965                             const ParentMap &PM, const LocationContext *LCtx) {
   1966   PathPieces::iterator Prev = pieces.end();
   1967   for (PathPieces::iterator I = pieces.begin(), E = Prev; I != E;
   1968        Prev = I, ++I) {
   1969     PathDiagnosticControlFlowPiece *Piece =
   1970       dyn_cast<PathDiagnosticControlFlowPiece>(*I);
   1971 
   1972     if (!Piece)
   1973       continue;
   1974 
   1975     PathDiagnosticLocation SrcLoc = Piece->getStartLocation();
   1976     SmallVector<PathDiagnosticLocation, 4> SrcContexts;
   1977 
   1978     PathDiagnosticLocation NextSrcContext = SrcLoc;
   1979     const Stmt *InnerStmt = nullptr;
   1980     while (NextSrcContext.isValid() && NextSrcContext.asStmt() != InnerStmt) {
   1981       SrcContexts.push_back(NextSrcContext);
   1982       InnerStmt = NextSrcContext.asStmt();
   1983       NextSrcContext = getEnclosingStmtLocation(InnerStmt, SM, PM, LCtx,
   1984                                                 /*allowNested=*/true);
   1985     }
   1986 
   1987     // Repeatedly split the edge as necessary.
   1988     // This is important for nested logical expressions (||, &&, ?:) where we
   1989     // want to show all the levels of context.
   1990     while (true) {
   1991       const Stmt *Dst = getLocStmt(Piece->getEndLocation());
   1992 
   1993       // We are looking at an edge. Is the destination within a larger
   1994       // expression?
   1995       PathDiagnosticLocation DstContext =
   1996         getEnclosingStmtLocation(Dst, SM, PM, LCtx, /*allowNested=*/true);
   1997       if (!DstContext.isValid() || DstContext.asStmt() == Dst)
   1998         break;
   1999 
   2000       // If the source is in the same context, we're already good.
   2001       if (std::find(SrcContexts.begin(), SrcContexts.end(), DstContext) !=
   2002           SrcContexts.end())
   2003         break;
   2004 
   2005       // Update the subexpression node to point to the context edge.
   2006       Piece->setStartLocation(DstContext);
   2007 
   2008       // Try to extend the previous edge if it's at the same level as the source
   2009       // context.
   2010       if (Prev != E) {
   2011         PathDiagnosticControlFlowPiece *PrevPiece =
   2012           dyn_cast<PathDiagnosticControlFlowPiece>(*Prev);
   2013 
   2014         if (PrevPiece) {
   2015           if (const Stmt *PrevSrc = getLocStmt(PrevPiece->getStartLocation())) {
   2016             const Stmt *PrevSrcParent = getStmtParent(PrevSrc, PM);
   2017             if (PrevSrcParent == getStmtParent(getLocStmt(DstContext), PM)) {
   2018               PrevPiece->setEndLocation(DstContext);
   2019               break;
   2020             }
   2021           }
   2022         }
   2023       }
   2024 
   2025       // Otherwise, split the current edge into a context edge and a
   2026       // subexpression edge. Note that the context statement may itself have
   2027       // context.
   2028       Piece = new PathDiagnosticControlFlowPiece(SrcLoc, DstContext);
   2029       I = pieces.insert(I, Piece);
   2030     }
   2031   }
   2032 }
   2033 
   2034 /// \brief Move edges from a branch condition to a branch target
   2035 ///        when the condition is simple.
   2036 ///
   2037 /// This restructures some of the work of addContextEdges.  That function
   2038 /// creates edges this may destroy, but they work together to create a more
   2039 /// aesthetically set of edges around branches.  After the call to
   2040 /// addContextEdges, we may have (1) an edge to the branch, (2) an edge from
   2041 /// the branch to the branch condition, and (3) an edge from the branch
   2042 /// condition to the branch target.  We keep (1), but may wish to remove (2)
   2043 /// and move the source of (3) to the branch if the branch condition is simple.
   2044 ///
   2045 static void simplifySimpleBranches(PathPieces &pieces) {
   2046   for (PathPieces::iterator I = pieces.begin(), E = pieces.end(); I != E; ++I) {
   2047 
   2048     PathDiagnosticControlFlowPiece *PieceI =
   2049       dyn_cast<PathDiagnosticControlFlowPiece>(*I);
   2050 
   2051     if (!PieceI)
   2052       continue;
   2053 
   2054     const Stmt *s1Start = getLocStmt(PieceI->getStartLocation());
   2055     const Stmt *s1End   = getLocStmt(PieceI->getEndLocation());
   2056 
   2057     if (!s1Start || !s1End)
   2058       continue;
   2059 
   2060     PathPieces::iterator NextI = I; ++NextI;
   2061     if (NextI == E)
   2062       break;
   2063 
   2064     PathDiagnosticControlFlowPiece *PieceNextI = nullptr;
   2065 
   2066     while (true) {
   2067       if (NextI == E)
   2068         break;
   2069 
   2070       PathDiagnosticEventPiece *EV = dyn_cast<PathDiagnosticEventPiece>(*NextI);
   2071       if (EV) {
   2072         StringRef S = EV->getString();
   2073         if (S == StrEnteringLoop || S == StrLoopBodyZero ||
   2074             S == StrLoopCollectionEmpty || S == StrLoopRangeEmpty) {
   2075           ++NextI;
   2076           continue;
   2077         }
   2078         break;
   2079       }
   2080 
   2081       PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(*NextI);
   2082       break;
   2083     }
   2084 
   2085     if (!PieceNextI)
   2086       continue;
   2087 
   2088     const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation());
   2089     const Stmt *s2End   = getLocStmt(PieceNextI->getEndLocation());
   2090 
   2091     if (!s2Start || !s2End || s1End != s2Start)
   2092       continue;
   2093 
   2094     // We only perform this transformation for specific branch kinds.
   2095     // We don't want to do this for do..while, for example.
   2096     if (!(isa<ForStmt>(s1Start) || isa<WhileStmt>(s1Start) ||
   2097           isa<IfStmt>(s1Start) || isa<ObjCForCollectionStmt>(s1Start) ||
   2098           isa<CXXForRangeStmt>(s1Start)))
   2099       continue;
   2100 
   2101     // Is s1End the branch condition?
   2102     if (!isConditionForTerminator(s1Start, s1End))
   2103       continue;
   2104 
   2105     // Perform the hoisting by eliminating (2) and changing the start
   2106     // location of (3).
   2107     PieceNextI->setStartLocation(PieceI->getStartLocation());
   2108     I = pieces.erase(I);
   2109   }
   2110 }
   2111 
   2112 /// Returns the number of bytes in the given (character-based) SourceRange.
   2113 ///
   2114 /// If the locations in the range are not on the same line, returns None.
   2115 ///
   2116 /// Note that this does not do a precise user-visible character or column count.
   2117 static Optional<size_t> getLengthOnSingleLine(SourceManager &SM,
   2118                                               SourceRange Range) {
   2119   SourceRange ExpansionRange(SM.getExpansionLoc(Range.getBegin()),
   2120                              SM.getExpansionRange(Range.getEnd()).second);
   2121 
   2122   FileID FID = SM.getFileID(ExpansionRange.getBegin());
   2123   if (FID != SM.getFileID(ExpansionRange.getEnd()))
   2124     return None;
   2125 
   2126   bool Invalid;
   2127   const llvm::MemoryBuffer *Buffer = SM.getBuffer(FID, &Invalid);
   2128   if (Invalid)
   2129     return None;
   2130 
   2131   unsigned BeginOffset = SM.getFileOffset(ExpansionRange.getBegin());
   2132   unsigned EndOffset = SM.getFileOffset(ExpansionRange.getEnd());
   2133   StringRef Snippet = Buffer->getBuffer().slice(BeginOffset, EndOffset);
   2134 
   2135   // We're searching the raw bytes of the buffer here, which might include
   2136   // escaped newlines and such. That's okay; we're trying to decide whether the
   2137   // SourceRange is covering a large or small amount of space in the user's
   2138   // editor.
   2139   if (Snippet.find_first_of("\r\n") != StringRef::npos)
   2140     return None;
   2141 
   2142   // This isn't Unicode-aware, but it doesn't need to be.
   2143   return Snippet.size();
   2144 }
   2145 
   2146 /// \sa getLengthOnSingleLine(SourceManager, SourceRange)
   2147 static Optional<size_t> getLengthOnSingleLine(SourceManager &SM,
   2148                                               const Stmt *S) {
   2149   return getLengthOnSingleLine(SM, S->getSourceRange());
   2150 }
   2151 
   2152 /// Eliminate two-edge cycles created by addContextEdges().
   2153 ///
   2154 /// Once all the context edges are in place, there are plenty of cases where
   2155 /// there's a single edge from a top-level statement to a subexpression,
   2156 /// followed by a single path note, and then a reverse edge to get back out to
   2157 /// the top level. If the statement is simple enough, the subexpression edges
   2158 /// just add noise and make it harder to understand what's going on.
   2159 ///
   2160 /// This function only removes edges in pairs, because removing only one edge
   2161 /// might leave other edges dangling.
   2162 ///
   2163 /// This will not remove edges in more complicated situations:
   2164 /// - if there is more than one "hop" leading to or from a subexpression.
   2165 /// - if there is an inlined call between the edges instead of a single event.
   2166 /// - if the whole statement is large enough that having subexpression arrows
   2167 ///   might be helpful.
   2168 static void removeContextCycles(PathPieces &Path, SourceManager &SM,
   2169                                 ParentMap &PM) {
   2170   for (PathPieces::iterator I = Path.begin(), E = Path.end(); I != E; ) {
   2171     // Pattern match the current piece and its successor.
   2172     PathDiagnosticControlFlowPiece *PieceI =
   2173       dyn_cast<PathDiagnosticControlFlowPiece>(*I);
   2174 
   2175     if (!PieceI) {
   2176       ++I;
   2177       continue;
   2178     }
   2179 
   2180     const Stmt *s1Start = getLocStmt(PieceI->getStartLocation());
   2181     const Stmt *s1End   = getLocStmt(PieceI->getEndLocation());
   2182 
   2183     PathPieces::iterator NextI = I; ++NextI;
   2184     if (NextI == E)
   2185       break;
   2186 
   2187     PathDiagnosticControlFlowPiece *PieceNextI =
   2188       dyn_cast<PathDiagnosticControlFlowPiece>(*NextI);
   2189 
   2190     if (!PieceNextI) {
   2191       if (isa<PathDiagnosticEventPiece>(*NextI)) {
   2192         ++NextI;
   2193         if (NextI == E)
   2194           break;
   2195         PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(*NextI);
   2196       }
   2197 
   2198       if (!PieceNextI) {
   2199         ++I;
   2200         continue;
   2201       }
   2202     }
   2203 
   2204     const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation());
   2205     const Stmt *s2End   = getLocStmt(PieceNextI->getEndLocation());
   2206 
   2207     if (s1Start && s2Start && s1Start == s2End && s2Start == s1End) {
   2208       const size_t MAX_SHORT_LINE_LENGTH = 80;
   2209       Optional<size_t> s1Length = getLengthOnSingleLine(SM, s1Start);
   2210       if (s1Length && *s1Length <= MAX_SHORT_LINE_LENGTH) {
   2211         Optional<size_t> s2Length = getLengthOnSingleLine(SM, s2Start);
   2212         if (s2Length && *s2Length <= MAX_SHORT_LINE_LENGTH) {
   2213           Path.erase(I);
   2214           I = Path.erase(NextI);
   2215           continue;
   2216         }
   2217       }
   2218     }
   2219 
   2220     ++I;
   2221   }
   2222 }
   2223 
   2224 /// \brief Return true if X is contained by Y.
   2225 static bool lexicalContains(ParentMap &PM,
   2226                             const Stmt *X,
   2227                             const Stmt *Y) {
   2228   while (X) {
   2229     if (X == Y)
   2230       return true;
   2231     X = PM.getParent(X);
   2232   }
   2233   return false;
   2234 }
   2235 
   2236 // Remove short edges on the same line less than 3 columns in difference.
   2237 static void removePunyEdges(PathPieces &path,
   2238                             SourceManager &SM,
   2239                             ParentMap &PM) {
   2240 
   2241   bool erased = false;
   2242 
   2243   for (PathPieces::iterator I = path.begin(), E = path.end(); I != E;
   2244        erased ? I : ++I) {
   2245 
   2246     erased = false;
   2247 
   2248     PathDiagnosticControlFlowPiece *PieceI =
   2249       dyn_cast<PathDiagnosticControlFlowPiece>(*I);
   2250 
   2251     if (!PieceI)
   2252       continue;
   2253 
   2254     const Stmt *start = getLocStmt(PieceI->getStartLocation());
   2255     const Stmt *end   = getLocStmt(PieceI->getEndLocation());
   2256 
   2257     if (!start || !end)
   2258       continue;
   2259 
   2260     const Stmt *endParent = PM.getParent(end);
   2261     if (!endParent)
   2262       continue;
   2263 
   2264     if (isConditionForTerminator(end, endParent))
   2265       continue;
   2266 
   2267     SourceLocation FirstLoc = start->getLocStart();
   2268     SourceLocation SecondLoc = end->getLocStart();
   2269 
   2270     if (!SM.isWrittenInSameFile(FirstLoc, SecondLoc))
   2271       continue;
   2272     if (SM.isBeforeInTranslationUnit(SecondLoc, FirstLoc))
   2273       std::swap(SecondLoc, FirstLoc);
   2274 
   2275     SourceRange EdgeRange(FirstLoc, SecondLoc);
   2276     Optional<size_t> ByteWidth = getLengthOnSingleLine(SM, EdgeRange);
   2277 
   2278     // If the statements are on different lines, continue.
   2279     if (!ByteWidth)
   2280       continue;
   2281 
   2282     const size_t MAX_PUNY_EDGE_LENGTH = 2;
   2283     if (*ByteWidth <= MAX_PUNY_EDGE_LENGTH) {
   2284       // FIXME: There are enough /bytes/ between the endpoints of the edge, but
   2285       // there might not be enough /columns/. A proper user-visible column count
   2286       // is probably too expensive, though.
   2287       I = path.erase(I);
   2288       erased = true;
   2289       continue;
   2290     }
   2291   }
   2292 }
   2293 
   2294 static void removeIdenticalEvents(PathPieces &path) {
   2295   for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ++I) {
   2296     PathDiagnosticEventPiece *PieceI =
   2297       dyn_cast<PathDiagnosticEventPiece>(*I);
   2298 
   2299     if (!PieceI)
   2300       continue;
   2301 
   2302     PathPieces::iterator NextI = I; ++NextI;
   2303     if (NextI == E)
   2304       return;
   2305 
   2306     PathDiagnosticEventPiece *PieceNextI =
   2307       dyn_cast<PathDiagnosticEventPiece>(*NextI);
   2308 
   2309     if (!PieceNextI)
   2310       continue;
   2311 
   2312     // Erase the second piece if it has the same exact message text.
   2313     if (PieceI->getString() == PieceNextI->getString()) {
   2314       path.erase(NextI);
   2315     }
   2316   }
   2317 }
   2318 
   2319 static bool optimizeEdges(PathPieces &path, SourceManager &SM,
   2320                           OptimizedCallsSet &OCS,
   2321                           LocationContextMap &LCM) {
   2322   bool hasChanges = false;
   2323   const LocationContext *LC = LCM[&path];
   2324   assert(LC);
   2325   ParentMap &PM = LC->getParentMap();
   2326 
   2327   for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ) {
   2328     // Optimize subpaths.
   2329     if (PathDiagnosticCallPiece *CallI = dyn_cast<PathDiagnosticCallPiece>(*I)){
   2330       // Record the fact that a call has been optimized so we only do the
   2331       // effort once.
   2332       if (!OCS.count(CallI)) {
   2333         while (optimizeEdges(CallI->path, SM, OCS, LCM)) {}
   2334         OCS.insert(CallI);
   2335       }
   2336       ++I;
   2337       continue;
   2338     }
   2339 
   2340     // Pattern match the current piece and its successor.
   2341     PathDiagnosticControlFlowPiece *PieceI =
   2342       dyn_cast<PathDiagnosticControlFlowPiece>(*I);
   2343 
   2344     if (!PieceI) {
   2345       ++I;
   2346       continue;
   2347     }
   2348 
   2349     const Stmt *s1Start = getLocStmt(PieceI->getStartLocation());
   2350     const Stmt *s1End   = getLocStmt(PieceI->getEndLocation());
   2351     const Stmt *level1 = getStmtParent(s1Start, PM);
   2352     const Stmt *level2 = getStmtParent(s1End, PM);
   2353 
   2354     PathPieces::iterator NextI = I; ++NextI;
   2355     if (NextI == E)
   2356       break;
   2357 
   2358     PathDiagnosticControlFlowPiece *PieceNextI =
   2359       dyn_cast<PathDiagnosticControlFlowPiece>(*NextI);
   2360 
   2361     if (!PieceNextI) {
   2362       ++I;
   2363       continue;
   2364     }
   2365 
   2366     const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation());
   2367     const Stmt *s2End   = getLocStmt(PieceNextI->getEndLocation());
   2368     const Stmt *level3 = getStmtParent(s2Start, PM);
   2369     const Stmt *level4 = getStmtParent(s2End, PM);
   2370 
   2371     // Rule I.
   2372     //
   2373     // If we have two consecutive control edges whose end/begin locations
   2374     // are at the same level (e.g. statements or top-level expressions within
   2375     // a compound statement, or siblings share a single ancestor expression),
   2376     // then merge them if they have no interesting intermediate event.
   2377     //
   2378     // For example:
   2379     //
   2380     // (1.1 -> 1.2) -> (1.2 -> 1.3) becomes (1.1 -> 1.3) because the common
   2381     // parent is '1'.  Here 'x.y.z' represents the hierarchy of statements.
   2382     //
   2383     // NOTE: this will be limited later in cases where we add barriers
   2384     // to prevent this optimization.
   2385     //
   2386     if (level1 && level1 == level2 && level1 == level3 && level1 == level4) {
   2387       PieceI->setEndLocation(PieceNextI->getEndLocation());
   2388       path.erase(NextI);
   2389       hasChanges = true;
   2390       continue;
   2391     }
   2392 
   2393     // Rule II.
   2394     //
   2395     // Eliminate edges between subexpressions and parent expressions
   2396     // when the subexpression is consumed.
   2397     //
   2398     // NOTE: this will be limited later in cases where we add barriers
   2399     // to prevent this optimization.
   2400     //
   2401     if (s1End && s1End == s2Start && level2) {
   2402       bool removeEdge = false;
   2403       // Remove edges into the increment or initialization of a
   2404       // loop that have no interleaving event.  This means that
   2405       // they aren't interesting.
   2406       if (isIncrementOrInitInForLoop(s1End, level2))
   2407         removeEdge = true;
   2408       // Next only consider edges that are not anchored on
   2409       // the condition of a terminator.  This are intermediate edges
   2410       // that we might want to trim.
   2411       else if (!isConditionForTerminator(level2, s1End)) {
   2412         // Trim edges on expressions that are consumed by
   2413         // the parent expression.
   2414         if (isa<Expr>(s1End) && PM.isConsumedExpr(cast<Expr>(s1End))) {
   2415           removeEdge = true;
   2416         }
   2417         // Trim edges where a lexical containment doesn't exist.
   2418         // For example:
   2419         //
   2420         //  X -> Y -> Z
   2421         //
   2422         // If 'Z' lexically contains Y (it is an ancestor) and
   2423         // 'X' does not lexically contain Y (it is a descendant OR
   2424         // it has no lexical relationship at all) then trim.
   2425         //
   2426         // This can eliminate edges where we dive into a subexpression
   2427         // and then pop back out, etc.
   2428         else if (s1Start && s2End &&
   2429                  lexicalContains(PM, s2Start, s2End) &&
   2430                  !lexicalContains(PM, s1End, s1Start)) {
   2431           removeEdge = true;
   2432         }
   2433         // Trim edges from a subexpression back to the top level if the
   2434         // subexpression is on a different line.
   2435         //
   2436         // A.1 -> A -> B
   2437         // becomes
   2438         // A.1 -> B
   2439         //
   2440         // These edges just look ugly and don't usually add anything.
   2441         else if (s1Start && s2End &&
   2442                  lexicalContains(PM, s1Start, s1End)) {
   2443           SourceRange EdgeRange(PieceI->getEndLocation().asLocation(),
   2444                                 PieceI->getStartLocation().asLocation());
   2445           if (!getLengthOnSingleLine(SM, EdgeRange).hasValue())
   2446             removeEdge = true;
   2447         }
   2448       }
   2449 
   2450       if (removeEdge) {
   2451         PieceI->setEndLocation(PieceNextI->getEndLocation());
   2452         path.erase(NextI);
   2453         hasChanges = true;
   2454         continue;
   2455       }
   2456     }
   2457 
   2458     // Optimize edges for ObjC fast-enumeration loops.
   2459     //
   2460     // (X -> collection) -> (collection -> element)
   2461     //
   2462     // becomes:
   2463     //
   2464     // (X -> element)
   2465     if (s1End == s2Start) {
   2466       const ObjCForCollectionStmt *FS =
   2467         dyn_cast_or_null<ObjCForCollectionStmt>(level3);
   2468       if (FS && FS->getCollection()->IgnoreParens() == s2Start &&
   2469           s2End == FS->getElement()) {
   2470         PieceI->setEndLocation(PieceNextI->getEndLocation());
   2471         path.erase(NextI);
   2472         hasChanges = true;
   2473         continue;
   2474       }
   2475     }
   2476 
   2477     // No changes at this index?  Move to the next one.
   2478     ++I;
   2479   }
   2480 
   2481   if (!hasChanges) {
   2482     // Adjust edges into subexpressions to make them more uniform
   2483     // and aesthetically pleasing.
   2484     addContextEdges(path, SM, PM, LC);
   2485     // Remove "cyclical" edges that include one or more context edges.
   2486     removeContextCycles(path, SM, PM);
   2487     // Hoist edges originating from branch conditions to branches
   2488     // for simple branches.
   2489     simplifySimpleBranches(path);
   2490     // Remove any puny edges left over after primary optimization pass.
   2491     removePunyEdges(path, SM, PM);
   2492     // Remove identical events.
   2493     removeIdenticalEvents(path);
   2494   }
   2495 
   2496   return hasChanges;
   2497 }
   2498 
   2499 /// Drop the very first edge in a path, which should be a function entry edge.
   2500 ///
   2501 /// If the first edge is not a function entry edge (say, because the first
   2502 /// statement had an invalid source location), this function does nothing.
   2503 // FIXME: We should just generate invalid edges anyway and have the optimizer
   2504 // deal with them.
   2505 static void dropFunctionEntryEdge(PathPieces &Path,
   2506                                   LocationContextMap &LCM,
   2507                                   SourceManager &SM) {
   2508   const PathDiagnosticControlFlowPiece *FirstEdge =
   2509     dyn_cast<PathDiagnosticControlFlowPiece>(Path.front());
   2510   if (!FirstEdge)
   2511     return;
   2512 
   2513   const Decl *D = LCM[&Path]->getDecl();
   2514   PathDiagnosticLocation EntryLoc = PathDiagnosticLocation::createBegin(D, SM);
   2515   if (FirstEdge->getStartLocation() != EntryLoc)
   2516     return;
   2517 
   2518   Path.pop_front();
   2519 }
   2520 
   2521 
   2522 //===----------------------------------------------------------------------===//
   2523 // Methods for BugType and subclasses.
   2524 //===----------------------------------------------------------------------===//
   2525 void BugType::anchor() { }
   2526 
   2527 void BugType::FlushReports(BugReporter &BR) {}
   2528 
   2529 void BuiltinBug::anchor() {}
   2530 
   2531 //===----------------------------------------------------------------------===//
   2532 // Methods for BugReport and subclasses.
   2533 //===----------------------------------------------------------------------===//
   2534 
   2535 void BugReport::NodeResolver::anchor() {}
   2536 
   2537 void BugReport::addVisitor(std::unique_ptr<BugReporterVisitor> visitor) {
   2538   if (!visitor)
   2539     return;
   2540 
   2541   llvm::FoldingSetNodeID ID;
   2542   visitor->Profile(ID);
   2543   void *InsertPos;
   2544 
   2545   if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos))
   2546     return;
   2547 
   2548   CallbacksSet.InsertNode(visitor.get(), InsertPos);
   2549   Callbacks.push_back(std::move(visitor));
   2550   ++ConfigurationChangeToken;
   2551 }
   2552 
   2553 BugReport::~BugReport() {
   2554   while (!interestingSymbols.empty()) {
   2555     popInterestingSymbolsAndRegions();
   2556   }
   2557 }
   2558 
   2559 const Decl *BugReport::getDeclWithIssue() const {
   2560   if (DeclWithIssue)
   2561     return DeclWithIssue;
   2562 
   2563   const ExplodedNode *N = getErrorNode();
   2564   if (!N)
   2565     return nullptr;
   2566 
   2567   const LocationContext *LC = N->getLocationContext();
   2568   return LC->getCurrentStackFrame()->getDecl();
   2569 }
   2570 
   2571 void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
   2572   hash.AddPointer(&BT);
   2573   hash.AddString(Description);
   2574   PathDiagnosticLocation UL = getUniqueingLocation();
   2575   if (UL.isValid()) {
   2576     UL.Profile(hash);
   2577   } else if (Location.isValid()) {
   2578     Location.Profile(hash);
   2579   } else {
   2580     assert(ErrorNode);
   2581     hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
   2582   }
   2583 
   2584   for (SmallVectorImpl<SourceRange>::const_iterator I =
   2585       Ranges.begin(), E = Ranges.end(); I != E; ++I) {
   2586     const SourceRange range = *I;
   2587     if (!range.isValid())
   2588       continue;
   2589     hash.AddInteger(range.getBegin().getRawEncoding());
   2590     hash.AddInteger(range.getEnd().getRawEncoding());
   2591   }
   2592 }
   2593 
   2594 void BugReport::markInteresting(SymbolRef sym) {
   2595   if (!sym)
   2596     return;
   2597 
   2598   // If the symbol wasn't already in our set, note a configuration change.
   2599   if (getInterestingSymbols().insert(sym).second)
   2600     ++ConfigurationChangeToken;
   2601 
   2602   if (const SymbolMetadata *meta = dyn_cast<SymbolMetadata>(sym))
   2603     getInterestingRegions().insert(meta->getRegion());
   2604 }
   2605 
   2606 void BugReport::markInteresting(const MemRegion *R) {
   2607   if (!R)
   2608     return;
   2609 
   2610   // If the base region wasn't already in our set, note a configuration change.
   2611   R = R->getBaseRegion();
   2612   if (getInterestingRegions().insert(R).second)
   2613     ++ConfigurationChangeToken;
   2614 
   2615   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
   2616     getInterestingSymbols().insert(SR->getSymbol());
   2617 }
   2618 
   2619 void BugReport::markInteresting(SVal V) {
   2620   markInteresting(V.getAsRegion());
   2621   markInteresting(V.getAsSymbol());
   2622 }
   2623 
   2624 void BugReport::markInteresting(const LocationContext *LC) {
   2625   if (!LC)
   2626     return;
   2627   InterestingLocationContexts.insert(LC);
   2628 }
   2629 
   2630 bool BugReport::isInteresting(SVal V) {
   2631   return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol());
   2632 }
   2633 
   2634 bool BugReport::isInteresting(SymbolRef sym) {
   2635   if (!sym)
   2636     return false;
   2637   // We don't currently consider metadata symbols to be interesting
   2638   // even if we know their region is interesting. Is that correct behavior?
   2639   return getInterestingSymbols().count(sym);
   2640 }
   2641 
   2642 bool BugReport::isInteresting(const MemRegion *R) {
   2643   if (!R)
   2644     return false;
   2645   R = R->getBaseRegion();
   2646   bool b = getInterestingRegions().count(R);
   2647   if (b)
   2648     return true;
   2649   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
   2650     return getInterestingSymbols().count(SR->getSymbol());
   2651   return false;
   2652 }
   2653 
   2654 bool BugReport::isInteresting(const LocationContext *LC) {
   2655   if (!LC)
   2656     return false;
   2657   return InterestingLocationContexts.count(LC);
   2658 }
   2659 
   2660 void BugReport::lazyInitializeInterestingSets() {
   2661   if (interestingSymbols.empty()) {
   2662     interestingSymbols.push_back(new Symbols());
   2663     interestingRegions.push_back(new Regions());
   2664   }
   2665 }
   2666 
   2667 BugReport::Symbols &BugReport::getInterestingSymbols() {
   2668   lazyInitializeInterestingSets();
   2669   return *interestingSymbols.back();
   2670 }
   2671 
   2672 BugReport::Regions &BugReport::getInterestingRegions() {
   2673   lazyInitializeInterestingSets();
   2674   return *interestingRegions.back();
   2675 }
   2676 
   2677 void BugReport::pushInterestingSymbolsAndRegions() {
   2678   interestingSymbols.push_back(new Symbols(getInterestingSymbols()));
   2679   interestingRegions.push_back(new Regions(getInterestingRegions()));
   2680 }
   2681 
   2682 void BugReport::popInterestingSymbolsAndRegions() {
   2683   delete interestingSymbols.pop_back_val();
   2684   delete interestingRegions.pop_back_val();
   2685 }
   2686 
   2687 const Stmt *BugReport::getStmt() const {
   2688   if (!ErrorNode)
   2689     return nullptr;
   2690 
   2691   ProgramPoint ProgP = ErrorNode->getLocation();
   2692   const Stmt *S = nullptr;
   2693 
   2694   if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
   2695     CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
   2696     if (BE->getBlock() == &Exit)
   2697       S = GetPreviousStmt(ErrorNode);
   2698   }
   2699   if (!S)
   2700     S = PathDiagnosticLocation::getStmt(ErrorNode);
   2701 
   2702   return S;
   2703 }
   2704 
   2705 llvm::iterator_range<BugReport::ranges_iterator> BugReport::getRanges() {
   2706   // If no custom ranges, add the range of the statement corresponding to
   2707   // the error node.
   2708   if (Ranges.empty()) {
   2709     if (const Expr *E = dyn_cast_or_null<Expr>(getStmt()))
   2710       addRange(E->getSourceRange());
   2711     else
   2712       return llvm::make_range(ranges_iterator(), ranges_iterator());
   2713   }
   2714 
   2715   // User-specified absence of range info.
   2716   if (Ranges.size() == 1 && !Ranges.begin()->isValid())
   2717     return llvm::make_range(ranges_iterator(), ranges_iterator());
   2718 
   2719   return llvm::iterator_range<BugReport::ranges_iterator>(Ranges.begin(),
   2720                                                           Ranges.end());
   2721 }
   2722 
   2723 PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
   2724   if (ErrorNode) {
   2725     assert(!Location.isValid() &&
   2726      "Either Location or ErrorNode should be specified but not both.");
   2727     return PathDiagnosticLocation::createEndOfPath(ErrorNode, SM);
   2728   }
   2729 
   2730   assert(Location.isValid());
   2731   return Location;
   2732 }
   2733 
   2734 //===----------------------------------------------------------------------===//
   2735 // Methods for BugReporter and subclasses.
   2736 //===----------------------------------------------------------------------===//
   2737 
   2738 BugReportEquivClass::~BugReportEquivClass() { }
   2739 GRBugReporter::~GRBugReporter() { }
   2740 BugReporterData::~BugReporterData() {}
   2741 
   2742 ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
   2743 
   2744 ProgramStateManager&
   2745 GRBugReporter::getStateManager() { return Eng.getStateManager(); }
   2746 
   2747 BugReporter::~BugReporter() {
   2748   FlushReports();
   2749 
   2750   // Free the bug reports we are tracking.
   2751   typedef std::vector<BugReportEquivClass *> ContTy;
   2752   for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end();
   2753        I != E; ++I) {
   2754     delete *I;
   2755   }
   2756 }
   2757 
   2758 void BugReporter::FlushReports() {
   2759   if (BugTypes.isEmpty())
   2760     return;
   2761 
   2762   // First flush the warnings for each BugType.  This may end up creating new
   2763   // warnings and new BugTypes.
   2764   // FIXME: Only NSErrorChecker needs BugType's FlushReports.
   2765   // Turn NSErrorChecker into a proper checker and remove this.
   2766   SmallVector<const BugType *, 16> bugTypes(BugTypes.begin(), BugTypes.end());
   2767   for (SmallVectorImpl<const BugType *>::iterator
   2768          I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I)
   2769     const_cast<BugType*>(*I)->FlushReports(*this);
   2770 
   2771   // We need to flush reports in deterministic order to ensure the order
   2772   // of the reports is consistent between runs.
   2773   typedef std::vector<BugReportEquivClass *> ContVecTy;
   2774   for (ContVecTy::iterator EI=EQClassesVector.begin(), EE=EQClassesVector.end();
   2775        EI != EE; ++EI){
   2776     BugReportEquivClass& EQ = **EI;
   2777     FlushReport(EQ);
   2778   }
   2779 
   2780   // BugReporter owns and deletes only BugTypes created implicitly through
   2781   // EmitBasicReport.
   2782   // FIXME: There are leaks from checkers that assume that the BugTypes they
   2783   // create will be destroyed by the BugReporter.
   2784   llvm::DeleteContainerSeconds(StrBugTypes);
   2785 
   2786   // Remove all references to the BugType objects.
   2787   BugTypes = F.getEmptySet();
   2788 }
   2789 
   2790 //===----------------------------------------------------------------------===//
   2791 // PathDiagnostics generation.
   2792 //===----------------------------------------------------------------------===//
   2793 
   2794 namespace {
   2795 /// A wrapper around a report graph, which contains only a single path, and its
   2796 /// node maps.
   2797 class ReportGraph {
   2798 public:
   2799   InterExplodedGraphMap BackMap;
   2800   std::unique_ptr<ExplodedGraph> Graph;
   2801   const ExplodedNode *ErrorNode;
   2802   size_t Index;
   2803 };
   2804 
   2805 /// A wrapper around a trimmed graph and its node maps.
   2806 class TrimmedGraph {
   2807   InterExplodedGraphMap InverseMap;
   2808 
   2809   typedef llvm::DenseMap<const ExplodedNode *, unsigned> PriorityMapTy;
   2810   PriorityMapTy PriorityMap;
   2811 
   2812   typedef std::pair<const ExplodedNode *, size_t> NodeIndexPair;
   2813   SmallVector<NodeIndexPair, 32> ReportNodes;
   2814 
   2815   std::unique_ptr<ExplodedGraph> G;
   2816 
   2817   /// A helper class for sorting ExplodedNodes by priority.
   2818   template <bool Descending>
   2819   class PriorityCompare {
   2820     const PriorityMapTy &PriorityMap;
   2821 
   2822   public:
   2823     PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {}
   2824 
   2825     bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const {
   2826       PriorityMapTy::const_iterator LI = PriorityMap.find(LHS);
   2827       PriorityMapTy::const_iterator RI = PriorityMap.find(RHS);
   2828       PriorityMapTy::const_iterator E = PriorityMap.end();
   2829 
   2830       if (LI == E)
   2831         return Descending;
   2832       if (RI == E)
   2833         return !Descending;
   2834 
   2835       return Descending ? LI->second > RI->second
   2836                         : LI->second < RI->second;
   2837     }
   2838 
   2839     bool operator()(const NodeIndexPair &LHS, const NodeIndexPair &RHS) const {
   2840       return (*this)(LHS.first, RHS.first);
   2841     }
   2842   };
   2843 
   2844 public:
   2845   TrimmedGraph(const ExplodedGraph *OriginalGraph,
   2846                ArrayRef<const ExplodedNode *> Nodes);
   2847 
   2848   bool popNextReportGraph(ReportGraph &GraphWrapper);
   2849 };
   2850 }
   2851 
   2852 TrimmedGraph::TrimmedGraph(const ExplodedGraph *OriginalGraph,
   2853                            ArrayRef<const ExplodedNode *> Nodes) {
   2854   // The trimmed graph is created in the body of the constructor to ensure
   2855   // that the DenseMaps have been initialized already.
   2856   InterExplodedGraphMap ForwardMap;
   2857   G = OriginalGraph->trim(Nodes, &ForwardMap, &InverseMap);
   2858 
   2859   // Find the (first) error node in the trimmed graph.  We just need to consult
   2860   // the node map which maps from nodes in the original graph to nodes
   2861   // in the new graph.
   2862   llvm::SmallPtrSet<const ExplodedNode *, 32> RemainingNodes;
   2863 
   2864   for (unsigned i = 0, count = Nodes.size(); i < count; ++i) {
   2865     if (const ExplodedNode *NewNode = ForwardMap.lookup(Nodes[i])) {
   2866       ReportNodes.push_back(std::make_pair(NewNode, i));
   2867       RemainingNodes.insert(NewNode);
   2868     }
   2869   }
   2870 
   2871   assert(!RemainingNodes.empty() && "No error node found in the trimmed graph");
   2872 
   2873   // Perform a forward BFS to find all the shortest paths.
   2874   std::queue<const ExplodedNode *> WS;
   2875 
   2876   assert(G->num_roots() == 1);
   2877   WS.push(*G->roots_begin());
   2878   unsigned Priority = 0;
   2879 
   2880   while (!WS.empty()) {
   2881     const ExplodedNode *Node = WS.front();
   2882     WS.pop();
   2883 
   2884     PriorityMapTy::iterator PriorityEntry;
   2885     bool IsNew;
   2886     std::tie(PriorityEntry, IsNew) =
   2887       PriorityMap.insert(std::make_pair(Node, Priority));
   2888     ++Priority;
   2889 
   2890     if (!IsNew) {
   2891       assert(PriorityEntry->second <= Priority);
   2892       continue;
   2893     }
   2894 
   2895     if (RemainingNodes.erase(Node))
   2896       if (RemainingNodes.empty())
   2897         break;
   2898 
   2899     for (ExplodedNode::const_pred_iterator I = Node->succ_begin(),
   2900                                            E = Node->succ_end();
   2901          I != E; ++I)
   2902       WS.push(*I);
   2903   }
   2904 
   2905   // Sort the error paths from longest to shortest.
   2906   std::sort(ReportNodes.begin(), ReportNodes.end(),
   2907             PriorityCompare<true>(PriorityMap));
   2908 }
   2909 
   2910 bool TrimmedGraph::popNextReportGraph(ReportGraph &GraphWrapper) {
   2911   if (ReportNodes.empty())
   2912     return false;
   2913 
   2914   const ExplodedNode *OrigN;
   2915   std::tie(OrigN, GraphWrapper.Index) = ReportNodes.pop_back_val();
   2916   assert(PriorityMap.find(OrigN) != PriorityMap.end() &&
   2917          "error node not accessible from root");
   2918 
   2919   // Create a new graph with a single path.  This is the graph
   2920   // that will be returned to the caller.
   2921   auto GNew = llvm::make_unique<ExplodedGraph>();
   2922   GraphWrapper.BackMap.clear();
   2923 
   2924   // Now walk from the error node up the BFS path, always taking the
   2925   // predeccessor with the lowest number.
   2926   ExplodedNode *Succ = nullptr;
   2927   while (true) {
   2928     // Create the equivalent node in the new graph with the same state
   2929     // and location.
   2930     ExplodedNode *NewN = GNew->getNode(OrigN->getLocation(), OrigN->getState(),
   2931                                        OrigN->isSink());
   2932 
   2933     // Store the mapping to the original node.
   2934     InterExplodedGraphMap::const_iterator IMitr = InverseMap.find(OrigN);
   2935     assert(IMitr != InverseMap.end() && "No mapping to original node.");
   2936     GraphWrapper.BackMap[NewN] = IMitr->second;
   2937 
   2938     // Link up the new node with the previous node.
   2939     if (Succ)
   2940       Succ->addPredecessor(NewN, *GNew);
   2941     else
   2942       GraphWrapper.ErrorNode = NewN;
   2943 
   2944     Succ = NewN;
   2945 
   2946     // Are we at the final node?
   2947     if (OrigN->pred_empty()) {
   2948       GNew->addRoot(NewN);
   2949       break;
   2950     }
   2951 
   2952     // Find the next predeccessor node.  We choose the node that is marked
   2953     // with the lowest BFS number.
   2954     OrigN = *std::min_element(OrigN->pred_begin(), OrigN->pred_end(),
   2955                           PriorityCompare<false>(PriorityMap));
   2956   }
   2957 
   2958   GraphWrapper.Graph = std::move(GNew);
   2959 
   2960   return true;
   2961 }
   2962 
   2963 
   2964 /// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
   2965 ///  and collapses PathDiagosticPieces that are expanded by macros.
   2966 static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM) {
   2967   typedef std::vector<std::pair<IntrusiveRefCntPtr<PathDiagnosticMacroPiece>,
   2968                                 SourceLocation> > MacroStackTy;
   2969 
   2970   typedef std::vector<IntrusiveRefCntPtr<PathDiagnosticPiece> >
   2971           PiecesTy;
   2972 
   2973   MacroStackTy MacroStack;
   2974   PiecesTy Pieces;
   2975 
   2976   for (PathPieces::const_iterator I = path.begin(), E = path.end();
   2977        I!=E; ++I) {
   2978 
   2979     PathDiagnosticPiece *piece = I->get();
   2980 
   2981     // Recursively compact calls.
   2982     if (PathDiagnosticCallPiece *call=dyn_cast<PathDiagnosticCallPiece>(piece)){
   2983       CompactPathDiagnostic(call->path, SM);
   2984     }
   2985 
   2986     // Get the location of the PathDiagnosticPiece.
   2987     const FullSourceLoc Loc = piece->getLocation().asLocation();
   2988 
   2989     // Determine the instantiation location, which is the location we group
   2990     // related PathDiagnosticPieces.
   2991     SourceLocation InstantiationLoc = Loc.isMacroID() ?
   2992                                       SM.getExpansionLoc(Loc) :
   2993                                       SourceLocation();
   2994 
   2995     if (Loc.isFileID()) {
   2996       MacroStack.clear();
   2997       Pieces.push_back(piece);
   2998       continue;
   2999     }
   3000 
   3001     assert(Loc.isMacroID());
   3002 
   3003     // Is the PathDiagnosticPiece within the same macro group?
   3004     if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
   3005       MacroStack.back().first->subPieces.push_back(piece);
   3006       continue;
   3007     }
   3008 
   3009     // We aren't in the same group.  Are we descending into a new macro
   3010     // or are part of an old one?
   3011     IntrusiveRefCntPtr<PathDiagnosticMacroPiece> MacroGroup;
   3012 
   3013     SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
   3014                                           SM.getExpansionLoc(Loc) :
   3015                                           SourceLocation();
   3016 
   3017     // Walk the entire macro stack.
   3018     while (!MacroStack.empty()) {
   3019       if (InstantiationLoc == MacroStack.back().second) {
   3020         MacroGroup = MacroStack.back().first;
   3021         break;
   3022       }
   3023 
   3024       if (ParentInstantiationLoc == MacroStack.back().second) {
   3025         MacroGroup = MacroStack.back().first;
   3026         break;
   3027       }
   3028 
   3029       MacroStack.pop_back();
   3030     }
   3031 
   3032     if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
   3033       // Create a new macro group and add it to the stack.
   3034       PathDiagnosticMacroPiece *NewGroup =
   3035         new PathDiagnosticMacroPiece(
   3036           PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
   3037 
   3038       if (MacroGroup)
   3039         MacroGroup->subPieces.push_back(NewGroup);
   3040       else {
   3041         assert(InstantiationLoc.isFileID());
   3042         Pieces.push_back(NewGroup);
   3043       }
   3044 
   3045       MacroGroup = NewGroup;
   3046       MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
   3047     }
   3048 
   3049     // Finally, add the PathDiagnosticPiece to the group.
   3050     MacroGroup->subPieces.push_back(piece);
   3051   }
   3052 
   3053   // Now take the pieces and construct a new PathDiagnostic.
   3054   path.clear();
   3055 
   3056   path.insert(path.end(), Pieces.begin(), Pieces.end());
   3057 }
   3058 
   3059 bool GRBugReporter::generatePathDiagnostic(PathDiagnostic& PD,
   3060                                            PathDiagnosticConsumer &PC,
   3061                                            ArrayRef<BugReport *> &bugReports) {
   3062   assert(!bugReports.empty());
   3063 
   3064   bool HasValid = false;
   3065   bool HasInvalid = false;
   3066   SmallVector<const ExplodedNode *, 32> errorNodes;
   3067   for (ArrayRef<BugReport*>::iterator I = bugReports.begin(),
   3068                                       E = bugReports.end(); I != E; ++I) {
   3069     if ((*I)->isValid()) {
   3070       HasValid = true;
   3071       errorNodes.push_back((*I)->getErrorNode());
   3072     } else {
   3073       // Keep the errorNodes list in sync with the bugReports list.
   3074       HasInvalid = true;
   3075       errorNodes.push_back(nullptr);
   3076     }
   3077   }
   3078 
   3079   // If all the reports have been marked invalid by a previous path generation,
   3080   // we're done.
   3081   if (!HasValid)
   3082     return false;
   3083 
   3084   typedef PathDiagnosticConsumer::PathGenerationScheme PathGenerationScheme;
   3085   PathGenerationScheme ActiveScheme = PC.getGenerationScheme();
   3086 
   3087   if (ActiveScheme == PathDiagnosticConsumer::Extensive) {
   3088     AnalyzerOptions &options = getAnalyzerOptions();
   3089     if (options.getBooleanOption("path-diagnostics-alternate", true)) {
   3090       ActiveScheme = PathDiagnosticConsumer::AlternateExtensive;
   3091     }
   3092   }
   3093 
   3094   TrimmedGraph TrimG(&getGraph(), errorNodes);
   3095   ReportGraph ErrorGraph;
   3096 
   3097   while (TrimG.popNextReportGraph(ErrorGraph)) {
   3098     // Find the BugReport with the original location.
   3099     assert(ErrorGraph.Index < bugReports.size());
   3100     BugReport *R = bugReports[ErrorGraph.Index];
   3101     assert(R && "No original report found for sliced graph.");
   3102     assert(R->isValid() && "Report selected by trimmed graph marked invalid.");
   3103 
   3104     // Start building the path diagnostic...
   3105     PathDiagnosticBuilder PDB(*this, R, ErrorGraph.BackMap, &PC);
   3106     const ExplodedNode *N = ErrorGraph.ErrorNode;
   3107 
   3108     // Register additional node visitors.
   3109     R->addVisitor(llvm::make_unique<NilReceiverBRVisitor>());
   3110     R->addVisitor(llvm::make_unique<ConditionBRVisitor>());
   3111     R->addVisitor(llvm::make_unique<LikelyFalsePositiveSuppressionBRVisitor>());
   3112 
   3113     BugReport::VisitorList visitors;
   3114     unsigned origReportConfigToken, finalReportConfigToken;
   3115     LocationContextMap LCM;
   3116 
   3117     // While generating diagnostics, it's possible the visitors will decide
   3118     // new symbols and regions are interesting, or add other visitors based on
   3119     // the information they find. If they do, we need to regenerate the path
   3120     // based on our new report configuration.
   3121     do {
   3122       // Get a clean copy of all the visitors.
   3123       for (BugReport::visitor_iterator I = R->visitor_begin(),
   3124                                        E = R->visitor_end(); I != E; ++I)
   3125         visitors.push_back((*I)->clone());
   3126 
   3127       // Clear out the active path from any previous work.
   3128       PD.resetPath();
   3129       origReportConfigToken = R->getConfigurationChangeToken();
   3130 
   3131       // Generate the very last diagnostic piece - the piece is visible before
   3132       // the trace is expanded.
   3133       std::unique_ptr<PathDiagnosticPiece> LastPiece;
   3134       for (BugReport::visitor_iterator I = visitors.begin(), E = visitors.end();
   3135           I != E; ++I) {
   3136         if (std::unique_ptr<PathDiagnosticPiece> Piece =
   3137                 (*I)->getEndPath(PDB, N, *R)) {
   3138           assert (!LastPiece &&
   3139               "There can only be one final piece in a diagnostic.");
   3140           LastPiece = std::move(Piece);
   3141         }
   3142       }
   3143 
   3144       if (ActiveScheme != PathDiagnosticConsumer::None) {
   3145         if (!LastPiece)
   3146           LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R);
   3147         assert(LastPiece);
   3148         PD.setEndOfPath(std::move(LastPiece));
   3149       }
   3150 
   3151       // Make sure we get a clean location context map so we don't
   3152       // hold onto old mappings.
   3153       LCM.clear();
   3154 
   3155       switch (ActiveScheme) {
   3156       case PathDiagnosticConsumer::AlternateExtensive:
   3157         GenerateAlternateExtensivePathDiagnostic(PD, PDB, N, LCM, visitors);
   3158         break;
   3159       case PathDiagnosticConsumer::Extensive:
   3160         GenerateExtensivePathDiagnostic(PD, PDB, N, LCM, visitors);
   3161         break;
   3162       case PathDiagnosticConsumer::Minimal:
   3163         GenerateMinimalPathDiagnostic(PD, PDB, N, LCM, visitors);
   3164         break;
   3165       case PathDiagnosticConsumer::None:
   3166         GenerateVisitorsOnlyPathDiagnostic(PD, PDB, N, visitors);
   3167         break;
   3168       }
   3169 
   3170       // Clean up the visitors we used.
   3171       visitors.clear();
   3172 
   3173       // Did anything change while generating this path?
   3174       finalReportConfigToken = R->getConfigurationChangeToken();
   3175     } while (finalReportConfigToken != origReportConfigToken);
   3176 
   3177     if (!R->isValid())
   3178       continue;
   3179 
   3180     // Finally, prune the diagnostic path of uninteresting stuff.
   3181     if (!PD.path.empty()) {
   3182       if (R->shouldPrunePath() && getAnalyzerOptions().shouldPrunePaths()) {
   3183         bool stillHasNotes = removeUnneededCalls(PD.getMutablePieces(), R, LCM);
   3184         assert(stillHasNotes);
   3185         (void)stillHasNotes;
   3186       }
   3187 
   3188       // Redirect all call pieces to have valid locations.
   3189       adjustCallLocations(PD.getMutablePieces());
   3190       removePiecesWithInvalidLocations(PD.getMutablePieces());
   3191 
   3192       if (ActiveScheme == PathDiagnosticConsumer::AlternateExtensive) {
   3193         SourceManager &SM = getSourceManager();
   3194 
   3195         // Reduce the number of edges from a very conservative set
   3196         // to an aesthetically pleasing subset that conveys the
   3197         // necessary information.
   3198         OptimizedCallsSet OCS;
   3199         while (optimizeEdges(PD.getMutablePieces(), SM, OCS, LCM)) {}
   3200 
   3201         // Drop the very first function-entry edge. It's not really necessary
   3202         // for top-level functions.
   3203         dropFunctionEntryEdge(PD.getMutablePieces(), LCM, SM);
   3204       }
   3205 
   3206       // Remove messages that are basically the same, and edges that may not
   3207       // make sense.
   3208       // We have to do this after edge optimization in the Extensive mode.
   3209       removeRedundantMsgs(PD.getMutablePieces());
   3210       removeEdgesToDefaultInitializers(PD.getMutablePieces());
   3211     }
   3212 
   3213     // We found a report and didn't suppress it.
   3214     return true;
   3215   }
   3216 
   3217   // We suppressed all the reports in this equivalence class.
   3218   assert(!HasInvalid && "Inconsistent suppression");
   3219   (void)HasInvalid;
   3220   return false;
   3221 }
   3222 
   3223 void BugReporter::Register(BugType *BT) {
   3224   BugTypes = F.add(BugTypes, BT);
   3225 }
   3226 
   3227 void BugReporter::emitReport(BugReport* R) {
   3228   // To guarantee memory release.
   3229   std::unique_ptr<BugReport> UniqueR(R);
   3230 
   3231   if (const ExplodedNode *E = R->getErrorNode()) {
   3232     const AnalysisDeclContext *DeclCtx =
   3233         E->getLocationContext()->getAnalysisDeclContext();
   3234     // The source of autosynthesized body can be handcrafted AST or a model
   3235     // file. The locations from handcrafted ASTs have no valid source locations
   3236     // and have to be discarded. Locations from model files should be preserved
   3237     // for processing and reporting.
   3238     if (DeclCtx->isBodyAutosynthesized() &&
   3239         !DeclCtx->isBodyAutosynthesizedFromModelFile())
   3240       return;
   3241   }
   3242 
   3243   bool ValidSourceLoc = R->getLocation(getSourceManager()).isValid();
   3244   assert(ValidSourceLoc);
   3245   // If we mess up in a release build, we'd still prefer to just drop the bug
   3246   // instead of trying to go on.
   3247   if (!ValidSourceLoc)
   3248     return;
   3249 
   3250   // Compute the bug report's hash to determine its equivalence class.
   3251   llvm::FoldingSetNodeID ID;
   3252   R->Profile(ID);
   3253 
   3254   // Lookup the equivance class.  If there isn't one, create it.
   3255   BugType& BT = R->getBugType();
   3256   Register(&BT);
   3257   void *InsertPos;
   3258   BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
   3259 
   3260   if (!EQ) {
   3261     EQ = new BugReportEquivClass(std::move(UniqueR));
   3262     EQClasses.InsertNode(EQ, InsertPos);
   3263     EQClassesVector.push_back(EQ);
   3264   } else
   3265     EQ->AddReport(std::move(UniqueR));
   3266 }
   3267 
   3268 
   3269 //===----------------------------------------------------------------------===//
   3270 // Emitting reports in equivalence classes.
   3271 //===----------------------------------------------------------------------===//
   3272 
   3273 namespace {
   3274 struct FRIEC_WLItem {
   3275   const ExplodedNode *N;
   3276   ExplodedNode::const_succ_iterator I, E;
   3277 
   3278   FRIEC_WLItem(const ExplodedNode *n)
   3279   : N(n), I(N->succ_begin()), E(N->succ_end()) {}
   3280 };
   3281 }
   3282 
   3283 static BugReport *
   3284 FindReportInEquivalenceClass(BugReportEquivClass& EQ,
   3285                              SmallVectorImpl<BugReport*> &bugReports) {
   3286 
   3287   BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
   3288   assert(I != E);
   3289   BugType& BT = I->getBugType();
   3290 
   3291   // If we don't need to suppress any of the nodes because they are
   3292   // post-dominated by a sink, simply add all the nodes in the equivalence class
   3293   // to 'Nodes'.  Any of the reports will serve as a "representative" report.
   3294   if (!BT.isSuppressOnSink()) {
   3295     BugReport *R = I;
   3296     for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
   3297       const ExplodedNode *N = I->getErrorNode();
   3298       if (N) {
   3299         R = I;
   3300         bugReports.push_back(R);
   3301       }
   3302     }
   3303     return R;
   3304   }
   3305 
   3306   // For bug reports that should be suppressed when all paths are post-dominated
   3307   // by a sink node, iterate through the reports in the equivalence class
   3308   // until we find one that isn't post-dominated (if one exists).  We use a
   3309   // DFS traversal of the ExplodedGraph to find a non-sink node.  We could write
   3310   // this as a recursive function, but we don't want to risk blowing out the
   3311   // stack for very long paths.
   3312   BugReport *exampleReport = nullptr;
   3313 
   3314   for (; I != E; ++I) {
   3315     const ExplodedNode *errorNode = I->getErrorNode();
   3316 
   3317     if (!errorNode)
   3318       continue;
   3319     if (errorNode->isSink()) {
   3320       llvm_unreachable(
   3321            "BugType::isSuppressSink() should not be 'true' for sink end nodes");
   3322     }
   3323     // No successors?  By definition this nodes isn't post-dominated by a sink.
   3324     if (errorNode->succ_empty()) {
   3325       bugReports.push_back(I);
   3326       if (!exampleReport)
   3327         exampleReport = I;
   3328       continue;
   3329     }
   3330 
   3331     // At this point we know that 'N' is not a sink and it has at least one
   3332     // successor.  Use a DFS worklist to find a non-sink end-of-path node.
   3333     typedef FRIEC_WLItem WLItem;
   3334     typedef SmallVector<WLItem, 10> DFSWorkList;
   3335     llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
   3336 
   3337     DFSWorkList WL;
   3338     WL.push_back(errorNode);
   3339     Visited[errorNode] = 1;
   3340 
   3341     while (!WL.empty()) {
   3342       WLItem &WI = WL.back();
   3343       assert(!WI.N->succ_empty());
   3344 
   3345       for (; WI.I != WI.E; ++WI.I) {
   3346         const ExplodedNode *Succ = *WI.I;
   3347         // End-of-path node?
   3348         if (Succ->succ_empty()) {
   3349           // If we found an end-of-path node that is not a sink.
   3350           if (!Succ->isSink()) {
   3351             bugReports.push_back(I);
   3352             if (!exampleReport)
   3353               exampleReport = I;
   3354             WL.clear();
   3355             break;
   3356           }
   3357           // Found a sink?  Continue on to the next successor.
   3358           continue;
   3359         }
   3360         // Mark the successor as visited.  If it hasn't been explored,
   3361         // enqueue it to the DFS worklist.
   3362         unsigned &mark = Visited[Succ];
   3363         if (!mark) {
   3364           mark = 1;
   3365           WL.push_back(Succ);
   3366           break;
   3367         }
   3368       }
   3369 
   3370       // The worklist may have been cleared at this point.  First
   3371       // check if it is empty before checking the last item.
   3372       if (!WL.empty() && &WL.back() == &WI)
   3373         WL.pop_back();
   3374     }
   3375   }
   3376 
   3377   // ExampleReport will be NULL if all the nodes in the equivalence class
   3378   // were post-dominated by sinks.
   3379   return exampleReport;
   3380 }
   3381 
   3382 void BugReporter::FlushReport(BugReportEquivClass& EQ) {
   3383   SmallVector<BugReport*, 10> bugReports;
   3384   BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports);
   3385   if (exampleReport) {
   3386     for (PathDiagnosticConsumer *PDC : getPathDiagnosticConsumers()) {
   3387       FlushReport(exampleReport, *PDC, bugReports);
   3388     }
   3389   }
   3390 }
   3391 
   3392 void BugReporter::FlushReport(BugReport *exampleReport,
   3393                               PathDiagnosticConsumer &PD,
   3394                               ArrayRef<BugReport*> bugReports) {
   3395 
   3396   // FIXME: Make sure we use the 'R' for the path that was actually used.
   3397   // Probably doesn't make a difference in practice.
   3398   BugType& BT = exampleReport->getBugType();
   3399 
   3400   std::unique_ptr<PathDiagnostic> D(new PathDiagnostic(
   3401       exampleReport->getBugType().getCheckName(),
   3402       exampleReport->getDeclWithIssue(), exampleReport->getBugType().getName(),
   3403       exampleReport->getDescription(),
   3404       exampleReport->getShortDescription(/*Fallback=*/false), BT.getCategory(),
   3405       exampleReport->getUniqueingLocation(),
   3406       exampleReport->getUniqueingDecl()));
   3407 
   3408   MaxBugClassSize = std::max(bugReports.size(),
   3409                              static_cast<size_t>(MaxBugClassSize));
   3410 
   3411   // Generate the full path diagnostic, using the generation scheme
   3412   // specified by the PathDiagnosticConsumer. Note that we have to generate
   3413   // path diagnostics even for consumers which do not support paths, because
   3414   // the BugReporterVisitors may mark this bug as a false positive.
   3415   if (!bugReports.empty())
   3416     if (!generatePathDiagnostic(*D.get(), PD, bugReports))
   3417       return;
   3418 
   3419   MaxValidBugClassSize = std::max(bugReports.size(),
   3420                                   static_cast<size_t>(MaxValidBugClassSize));
   3421 
   3422   // Examine the report and see if the last piece is in a header. Reset the
   3423   // report location to the last piece in the main source file.
   3424   AnalyzerOptions& Opts = getAnalyzerOptions();
   3425   if (Opts.shouldReportIssuesInMainSourceFile() && !Opts.AnalyzeAll)
   3426     D->resetDiagnosticLocationToMainFile();
   3427 
   3428   // If the path is empty, generate a single step path with the location
   3429   // of the issue.
   3430   if (D->path.empty()) {
   3431     PathDiagnosticLocation L = exampleReport->getLocation(getSourceManager());
   3432     auto piece = llvm::make_unique<PathDiagnosticEventPiece>(
   3433         L, exampleReport->getDescription());
   3434     for (const SourceRange &Range : exampleReport->getRanges())
   3435       piece->addRange(Range);
   3436     D->setEndOfPath(std::move(piece));
   3437   }
   3438 
   3439   // Get the meta data.
   3440   const BugReport::ExtraTextList &Meta = exampleReport->getExtraText();
   3441   for (BugReport::ExtraTextList::const_iterator i = Meta.begin(),
   3442                                                 e = Meta.end(); i != e; ++i) {
   3443     D->addMeta(*i);
   3444   }
   3445 
   3446   PD.HandlePathDiagnostic(std::move(D));
   3447 }
   3448 
   3449 void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
   3450                                   const CheckerBase *Checker,
   3451                                   StringRef Name, StringRef Category,
   3452                                   StringRef Str, PathDiagnosticLocation Loc,
   3453                                   ArrayRef<SourceRange> Ranges) {
   3454   EmitBasicReport(DeclWithIssue, Checker->getCheckName(), Name, Category, Str,
   3455                   Loc, Ranges);
   3456 }
   3457 void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
   3458                                   CheckName CheckName,
   3459                                   StringRef name, StringRef category,
   3460                                   StringRef str, PathDiagnosticLocation Loc,
   3461                                   ArrayRef<SourceRange> Ranges) {
   3462 
   3463   // 'BT' is owned by BugReporter.
   3464   BugType *BT = getBugTypeForName(CheckName, name, category);
   3465   BugReport *R = new BugReport(*BT, str, Loc);
   3466   R->setDeclWithIssue(DeclWithIssue);
   3467   for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
   3468        I != E; ++I)
   3469     R->addRange(*I);
   3470   emitReport(R);
   3471 }
   3472 
   3473 BugType *BugReporter::getBugTypeForName(CheckName CheckName, StringRef name,
   3474                                         StringRef category) {
   3475   SmallString<136> fullDesc;
   3476   llvm::raw_svector_ostream(fullDesc) << CheckName.getName() << ":" << name
   3477                                       << ":" << category;
   3478   BugType *&BT = StrBugTypes[fullDesc];
   3479   if (!BT)
   3480     BT = new BugType(CheckName, name, category);
   3481   return BT;
   3482 }
   3483 
   3484 LLVM_DUMP_METHOD void PathPieces::dump() const {
   3485   unsigned index = 0;
   3486   for (PathPieces::const_iterator I = begin(), E = end(); I != E; ++I) {
   3487     llvm::errs() << "[" << index++ << "]  ";
   3488     (*I)->dump();
   3489     llvm::errs() << "\n";
   3490   }
   3491 }
   3492 
   3493 void PathDiagnosticCallPiece::dump() const {
   3494   llvm::errs() << "CALL\n--------------\n";
   3495 
   3496   if (const Stmt *SLoc = getLocStmt(getLocation()))
   3497     SLoc->dump();
   3498   else if (const NamedDecl *ND = dyn_cast<NamedDecl>(getCallee()))
   3499     llvm::errs() << *ND << "\n";
   3500   else
   3501     getLocation().dump();
   3502 }
   3503 
   3504 void PathDiagnosticEventPiece::dump() const {
   3505   llvm::errs() << "EVENT\n--------------\n";
   3506   llvm::errs() << getString() << "\n";
   3507   llvm::errs() << " ---- at ----\n";
   3508   getLocation().dump();
   3509 }
   3510 
   3511 void PathDiagnosticControlFlowPiece::dump() const {
   3512   llvm::errs() << "CONTROL\n--------------\n";
   3513   getStartLocation().dump();
   3514   llvm::errs() << " ---- to ----\n";
   3515   getEndLocation().dump();
   3516 }
   3517 
   3518 void PathDiagnosticMacroPiece::dump() const {
   3519   llvm::errs() << "MACRO\n--------------\n";
   3520   // FIXME: Print which macro is being invoked.
   3521 }
   3522 
   3523 void PathDiagnosticLocation::dump() const {
   3524   if (!isValid()) {
   3525     llvm::errs() << "<INVALID>\n";
   3526     return;
   3527   }
   3528 
   3529   switch (K) {
   3530   case RangeK:
   3531     // FIXME: actually print the range.
   3532     llvm::errs() << "<range>\n";
   3533     break;
   3534   case SingleLocK:
   3535     asLocation().dump();
   3536     llvm::errs() << "\n";
   3537     break;
   3538   case StmtK:
   3539     if (S)
   3540       S->dump();
   3541     else
   3542       llvm::errs() << "<NULL STMT>\n";
   3543     break;
   3544   case DeclK:
   3545     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
   3546       llvm::errs() << *ND << "\n";
   3547     else if (isa<BlockDecl>(D))
   3548       // FIXME: Make this nicer.
   3549       llvm::errs() << "<block>\n";
   3550     else if (D)
   3551       llvm::errs() << "<unknown decl>\n";
   3552     else
   3553       llvm::errs() << "<NULL DECL>\n";
   3554     break;
   3555   }
   3556 }
   3557