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