1 //=-- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- 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 a meta-engine for path-sensitive dataflow analysis that
11 //  is built on GREngine, but provides the boilerplate to execute transfer
12 //  functions and build the ExplodedGraph at the expression level.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #define DEBUG_TYPE "ExprEngine"
17 
18 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/ParentMap.h"
21 #include "clang/AST/StmtCXX.h"
22 #include "clang/AST/StmtObjC.h"
23 #include "clang/Basic/Builtins.h"
24 #include "clang/Basic/PrettyStackTrace.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
27 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
29 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
30 #include "llvm/ADT/ImmutableList.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/raw_ostream.h"
33 
34 #ifndef NDEBUG
35 #include "llvm/Support/GraphWriter.h"
36 #endif
37 
38 using namespace clang;
39 using namespace ento;
40 using llvm::APSInt;
41 
42 STATISTIC(NumRemoveDeadBindings,
43             "The # of times RemoveDeadBindings is called");
44 STATISTIC(NumMaxBlockCountReached,
45             "The # of aborted paths due to reaching the maximum block count in "
46             "a top level function");
47 STATISTIC(NumMaxBlockCountReachedInInlined,
48             "The # of aborted paths due to reaching the maximum block count in "
49             "an inlined function");
50 STATISTIC(NumTimesRetriedWithoutInlining,
51             "The # of times we re-evaluated a call without inlining");
52 
53 //===----------------------------------------------------------------------===//
54 // Engine construction and deletion.
55 //===----------------------------------------------------------------------===//
56 
57 ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled,
58                        SetOfConstDecls *VisitedCalleesIn,
59                        FunctionSummariesTy *FS,
60                        InliningModes HowToInlineIn)
61   : AMgr(mgr),
62     AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
63     Engine(*this, FS),
64     G(Engine.getGraph()),
65     StateMgr(getContext(), mgr.getStoreManagerCreator(),
66              mgr.getConstraintManagerCreator(), G.getAllocator(),
67              this),
68     SymMgr(StateMgr.getSymbolManager()),
69     svalBuilder(StateMgr.getSValBuilder()),
70     currStmtIdx(0), currBldrCtx(0),
71     ObjCNoRet(mgr.getASTContext()),
72     ObjCGCEnabled(gcEnabled), BR(mgr, *this),
73     VisitedCallees(VisitedCalleesIn),
74     HowToInline(HowToInlineIn)
75 {
76   unsigned TrimInterval = mgr.options.getGraphTrimInterval();
77   if (TrimInterval != 0) {
78     // Enable eager node reclaimation when constructing the ExplodedGraph.
79     G.enableNodeReclamation(TrimInterval);
80   }
81 }
82 
83 ExprEngine::~ExprEngine() {
84   BR.FlushReports();
85 }
86 
87 //===----------------------------------------------------------------------===//
88 // Utility methods.
89 //===----------------------------------------------------------------------===//
90 
91 ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
92   ProgramStateRef state = StateMgr.getInitialState(InitLoc);
93   const Decl *D = InitLoc->getDecl();
94 
95   // Preconditions.
96   // FIXME: It would be nice if we had a more general mechanism to add
97   // such preconditions.  Some day.
98   do {
99 
100     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
101       // Precondition: the first argument of 'main' is an integer guaranteed
102       //  to be > 0.
103       const IdentifierInfo *II = FD->getIdentifier();
104       if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
105         break;
106 
107       const ParmVarDecl *PD = FD->getParamDecl(0);
108       QualType T = PD->getType();
109       if (!T->isIntegerType())
110         break;
111 
112       const MemRegion *R = state->getRegion(PD, InitLoc);
113       if (!R)
114         break;
115 
116       SVal V = state->getSVal(loc::MemRegionVal(R));
117       SVal Constraint_untested = evalBinOp(state, BO_GT, V,
118                                            svalBuilder.makeZeroVal(T),
119                                            getContext().IntTy);
120 
121       DefinedOrUnknownSVal *Constraint =
122         dyn_cast<DefinedOrUnknownSVal>(&Constraint_untested);
123 
124       if (!Constraint)
125         break;
126 
127       if (ProgramStateRef newState = state->assume(*Constraint, true))
128         state = newState;
129     }
130     break;
131   }
132   while (0);
133 
134   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
135     // Precondition: 'self' is always non-null upon entry to an Objective-C
136     // method.
137     const ImplicitParamDecl *SelfD = MD->getSelfDecl();
138     const MemRegion *R = state->getRegion(SelfD, InitLoc);
139     SVal V = state->getSVal(loc::MemRegionVal(R));
140 
141     if (const Loc *LV = dyn_cast<Loc>(&V)) {
142       // Assume that the pointer value in 'self' is non-null.
143       state = state->assume(*LV, true);
144       assert(state && "'self' cannot be null");
145     }
146   }
147 
148   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
149     if (!MD->isStatic()) {
150       // Precondition: 'this' is always non-null upon entry to the
151       // top-level function.  This is our starting assumption for
152       // analyzing an "open" program.
153       const StackFrameContext *SFC = InitLoc->getCurrentStackFrame();
154       if (SFC->getParent() == 0) {
155         loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
156         SVal V = state->getSVal(L);
157         if (const Loc *LV = dyn_cast<Loc>(&V)) {
158           state = state->assume(*LV, true);
159           assert(state && "'this' cannot be null");
160         }
161       }
162     }
163   }
164 
165   return state;
166 }
167 
168 /// If the value of the given expression is a NonLoc, copy it into a new
169 /// temporary region, and replace the value of the expression with that.
170 static ProgramStateRef createTemporaryRegionIfNeeded(ProgramStateRef State,
171                                                      const LocationContext *LC,
172                                                      const Expr *E) {
173   SVal V = State->getSVal(E, LC);
174 
175   if (isa<NonLoc>(V)) {
176     MemRegionManager &MRMgr = State->getStateManager().getRegionManager();
177     const MemRegion *R  = MRMgr.getCXXTempObjectRegion(E, LC);
178     State = State->bindLoc(loc::MemRegionVal(R), V);
179     State = State->BindExpr(E, LC, loc::MemRegionVal(R));
180   }
181 
182   return State;
183 }
184 
185 //===----------------------------------------------------------------------===//
186 // Top-level transfer function logic (Dispatcher).
187 //===----------------------------------------------------------------------===//
188 
189 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
190 ///  logic for handling assumptions on symbolic values.
191 ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
192                                               SVal cond, bool assumption) {
193   return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
194 }
195 
196 bool ExprEngine::wantsRegionChangeUpdate(ProgramStateRef state) {
197   return getCheckerManager().wantsRegionChangeUpdate(state);
198 }
199 
200 ProgramStateRef
201 ExprEngine::processRegionChanges(ProgramStateRef state,
202                                  const InvalidatedSymbols *invalidated,
203                                  ArrayRef<const MemRegion *> Explicits,
204                                  ArrayRef<const MemRegion *> Regions,
205                                  const CallEvent *Call) {
206   return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
207                                                       Explicits, Regions, Call);
208 }
209 
210 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
211                             const char *NL, const char *Sep) {
212   getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
213 }
214 
215 void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
216   getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
217 }
218 
219 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
220                                    unsigned StmtIdx, NodeBuilderContext *Ctx) {
221   currStmtIdx = StmtIdx;
222   currBldrCtx = Ctx;
223 
224   switch (E.getKind()) {
225     case CFGElement::Invalid:
226       llvm_unreachable("Unexpected CFGElement kind.");
227     case CFGElement::Statement:
228       ProcessStmt(const_cast<Stmt*>(E.getAs<CFGStmt>()->getStmt()), Pred);
229       return;
230     case CFGElement::Initializer:
231       ProcessInitializer(E.getAs<CFGInitializer>()->getInitializer(), Pred);
232       return;
233     case CFGElement::AutomaticObjectDtor:
234     case CFGElement::BaseDtor:
235     case CFGElement::MemberDtor:
236     case CFGElement::TemporaryDtor:
237       ProcessImplicitDtor(*E.getAs<CFGImplicitDtor>(), Pred);
238       return;
239   }
240   currBldrCtx = 0;
241 }
242 
243 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
244                                      const CFGStmt S,
245                                      const ExplodedNode *Pred,
246                                      const LocationContext *LC) {
247 
248   // Are we never purging state values?
249   if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
250     return false;
251 
252   // Is this the beginning of a basic block?
253   if (isa<BlockEntrance>(Pred->getLocation()))
254     return true;
255 
256   // Is this on a non-expression?
257   if (!isa<Expr>(S.getStmt()))
258     return true;
259 
260   // Run before processing a call.
261   if (CallEvent::isCallStmt(S.getStmt()))
262     return true;
263 
264   // Is this an expression that is consumed by another expression?  If so,
265   // postpone cleaning out the state.
266   ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
267   return !PM.isConsumedExpr(cast<Expr>(S.getStmt()));
268 }
269 
270 void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
271                             const Stmt *ReferenceStmt,
272                             const LocationContext *LC,
273                             const Stmt *DiagnosticStmt,
274                             ProgramPoint::Kind K) {
275   assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
276           ReferenceStmt == 0 || isa<ReturnStmt>(ReferenceStmt))
277           && "PostStmt is not generally supported by the SymbolReaper yet");
278   assert(LC && "Must pass the current (or expiring) LocationContext");
279 
280   if (!DiagnosticStmt) {
281     DiagnosticStmt = ReferenceStmt;
282     assert(DiagnosticStmt && "Required for clearing a LocationContext");
283   }
284 
285   NumRemoveDeadBindings++;
286   ProgramStateRef CleanedState = Pred->getState();
287 
288   // LC is the location context being destroyed, but SymbolReaper wants a
289   // location context that is still live. (If this is the top-level stack
290   // frame, this will be null.)
291   if (!ReferenceStmt) {
292     assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
293            "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
294     LC = LC->getParent();
295   }
296 
297   const StackFrameContext *SFC = LC ? LC->getCurrentStackFrame() : 0;
298   SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
299 
300   getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
301 
302   // Create a state in which dead bindings are removed from the environment
303   // and the store. TODO: The function should just return new env and store,
304   // not a new state.
305   CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
306 
307   // Process any special transfer function for dead symbols.
308   // A tag to track convenience transitions, which can be removed at cleanup.
309   static SimpleProgramPointTag cleanupTag("ExprEngine : Clean Node");
310   if (!SymReaper.hasDeadSymbols()) {
311     // Generate a CleanedNode that has the environment and store cleaned
312     // up. Since no symbols are dead, we can optimize and not clean out
313     // the constraint manager.
314     StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx);
315     Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K);
316 
317   } else {
318     // Call checkers with the non-cleaned state so that they could query the
319     // values of the soon to be dead symbols.
320     ExplodedNodeSet CheckedSet;
321     getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
322                                                   DiagnosticStmt, *this, K);
323 
324     // For each node in CheckedSet, generate CleanedNodes that have the
325     // environment, the store, and the constraints cleaned up but have the
326     // user-supplied states as the predecessors.
327     StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
328     for (ExplodedNodeSet::const_iterator
329           I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) {
330       ProgramStateRef CheckerState = (*I)->getState();
331 
332       // The constraint manager has not been cleaned up yet, so clean up now.
333       CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
334                                                                SymReaper);
335 
336       assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
337         "Checkers are not allowed to modify the Environment as a part of "
338         "checkDeadSymbols processing.");
339       assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
340         "Checkers are not allowed to modify the Store as a part of "
341         "checkDeadSymbols processing.");
342 
343       // Create a state based on CleanedState with CheckerState GDM and
344       // generate a transition to that state.
345       ProgramStateRef CleanedCheckerSt =
346         StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
347       Bldr.generateNode(DiagnosticStmt, *I, CleanedCheckerSt, &cleanupTag, K);
348     }
349   }
350 }
351 
352 void ExprEngine::ProcessStmt(const CFGStmt S,
353                              ExplodedNode *Pred) {
354   // Reclaim any unnecessary nodes in the ExplodedGraph.
355   G.reclaimRecentlyAllocatedNodes();
356 
357   const Stmt *currStmt = S.getStmt();
358   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
359                                 currStmt->getLocStart(),
360                                 "Error evaluating statement");
361 
362   // Remove dead bindings and symbols.
363   ExplodedNodeSet CleanedStates;
364   if (shouldRemoveDeadBindings(AMgr, S, Pred, Pred->getLocationContext())){
365     removeDead(Pred, CleanedStates, currStmt, Pred->getLocationContext());
366   } else
367     CleanedStates.Add(Pred);
368 
369   // Visit the statement.
370   ExplodedNodeSet Dst;
371   for (ExplodedNodeSet::iterator I = CleanedStates.begin(),
372                                  E = CleanedStates.end(); I != E; ++I) {
373     ExplodedNodeSet DstI;
374     // Visit the statement.
375     Visit(currStmt, *I, DstI);
376     Dst.insert(DstI);
377   }
378 
379   // Enqueue the new nodes onto the work list.
380   Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
381 }
382 
383 void ExprEngine::ProcessInitializer(const CFGInitializer Init,
384                                     ExplodedNode *Pred) {
385   const CXXCtorInitializer *BMI = Init.getInitializer();
386 
387   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
388                                 BMI->getSourceLocation(),
389                                 "Error evaluating initializer");
390 
391   // We don't clean up dead bindings here.
392   const StackFrameContext *stackFrame =
393                            cast<StackFrameContext>(Pred->getLocationContext());
394   const CXXConstructorDecl *decl =
395                            cast<CXXConstructorDecl>(stackFrame->getDecl());
396 
397   ProgramStateRef State = Pred->getState();
398   SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
399 
400   PostInitializer PP(BMI, stackFrame);
401   ExplodedNodeSet Tmp(Pred);
402 
403   // Evaluate the initializer, if necessary
404   if (BMI->isAnyMemberInitializer()) {
405     // Constructors build the object directly in the field,
406     // but non-objects must be copied in from the initializer.
407     const Expr *Init = BMI->getInit()->IgnoreImplicit();
408     if (!isa<CXXConstructExpr>(Init)) {
409       SVal FieldLoc;
410       if (BMI->isIndirectMemberInitializer())
411         FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
412       else
413         FieldLoc = State->getLValue(BMI->getMember(), thisVal);
414 
415       SVal InitVal = State->getSVal(BMI->getInit(), stackFrame);
416 
417       Tmp.clear();
418       evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
419     }
420   } else {
421     assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
422     // We already did all the work when visiting the CXXConstructExpr.
423   }
424 
425   // Construct PostInitializer nodes whether the state changed or not,
426   // so that the diagnostics don't get confused.
427   ExplodedNodeSet Dst;
428   NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
429   for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) {
430     ExplodedNode *N = *I;
431     Bldr.generateNode(PP, N->getState(), N);
432   }
433 
434   // Enqueue the new nodes onto the work list.
435   Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
436 }
437 
438 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
439                                      ExplodedNode *Pred) {
440   ExplodedNodeSet Dst;
441   switch (D.getKind()) {
442   case CFGElement::AutomaticObjectDtor:
443     ProcessAutomaticObjDtor(cast<CFGAutomaticObjDtor>(D), Pred, Dst);
444     break;
445   case CFGElement::BaseDtor:
446     ProcessBaseDtor(cast<CFGBaseDtor>(D), Pred, Dst);
447     break;
448   case CFGElement::MemberDtor:
449     ProcessMemberDtor(cast<CFGMemberDtor>(D), Pred, Dst);
450     break;
451   case CFGElement::TemporaryDtor:
452     ProcessTemporaryDtor(cast<CFGTemporaryDtor>(D), Pred, Dst);
453     break;
454   default:
455     llvm_unreachable("Unexpected dtor kind.");
456   }
457 
458   // Enqueue the new nodes onto the work list.
459   Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
460 }
461 
462 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
463                                          ExplodedNode *Pred,
464                                          ExplodedNodeSet &Dst) {
465   ProgramStateRef state = Pred->getState();
466   const VarDecl *varDecl = Dtor.getVarDecl();
467 
468   QualType varType = varDecl->getType();
469 
470   if (const ReferenceType *refType = varType->getAs<ReferenceType>())
471     varType = refType->getPointeeType();
472 
473   Loc dest = state->getLValue(varDecl, Pred->getLocationContext());
474 
475   VisitCXXDestructor(varType, cast<loc::MemRegionVal>(dest).getRegion(),
476                      Dtor.getTriggerStmt(), /*IsBase=*/false, Pred, Dst);
477 }
478 
479 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
480                                  ExplodedNode *Pred, ExplodedNodeSet &Dst) {
481   const LocationContext *LCtx = Pred->getLocationContext();
482   ProgramStateRef State = Pred->getState();
483 
484   const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
485   Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
486                                             LCtx->getCurrentStackFrame());
487   SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
488 
489   // Create the base object region.
490   QualType BaseTy = D.getBaseSpecifier()->getType();
491   SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy);
492 
493   VisitCXXDestructor(BaseTy, cast<loc::MemRegionVal>(BaseVal).getRegion(),
494                      CurDtor->getBody(), /*IsBase=*/true, Pred, Dst);
495 }
496 
497 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
498                                    ExplodedNode *Pred, ExplodedNodeSet &Dst) {
499   const FieldDecl *Member = D.getFieldDecl();
500   ProgramStateRef State = Pred->getState();
501   const LocationContext *LCtx = Pred->getLocationContext();
502 
503   const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
504   Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
505                                             LCtx->getCurrentStackFrame());
506   SVal FieldVal = State->getLValue(Member, cast<Loc>(State->getSVal(ThisVal)));
507 
508   VisitCXXDestructor(Member->getType(),
509                      cast<loc::MemRegionVal>(FieldVal).getRegion(),
510                      CurDtor->getBody(), /*IsBase=*/false, Pred, Dst);
511 }
512 
513 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
514                                       ExplodedNode *Pred,
515                                       ExplodedNodeSet &Dst) {}
516 
517 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
518                        ExplodedNodeSet &DstTop) {
519   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
520                                 S->getLocStart(),
521                                 "Error evaluating statement");
522   ExplodedNodeSet Dst;
523   StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
524 
525   assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
526 
527   switch (S->getStmtClass()) {
528     // C++ and ARC stuff we don't support yet.
529     case Expr::ObjCIndirectCopyRestoreExprClass:
530     case Stmt::CXXDependentScopeMemberExprClass:
531     case Stmt::CXXPseudoDestructorExprClass:
532     case Stmt::CXXTryStmtClass:
533     case Stmt::CXXTypeidExprClass:
534     case Stmt::CXXUuidofExprClass:
535     case Stmt::CXXUnresolvedConstructExprClass:
536     case Stmt::DependentScopeDeclRefExprClass:
537     case Stmt::UnaryTypeTraitExprClass:
538     case Stmt::BinaryTypeTraitExprClass:
539     case Stmt::TypeTraitExprClass:
540     case Stmt::ArrayTypeTraitExprClass:
541     case Stmt::ExpressionTraitExprClass:
542     case Stmt::UnresolvedLookupExprClass:
543     case Stmt::UnresolvedMemberExprClass:
544     case Stmt::CXXNoexceptExprClass:
545     case Stmt::PackExpansionExprClass:
546     case Stmt::SubstNonTypeTemplateParmPackExprClass:
547     case Stmt::FunctionParmPackExprClass:
548     case Stmt::SEHTryStmtClass:
549     case Stmt::SEHExceptStmtClass:
550     case Stmt::LambdaExprClass:
551     case Stmt::SEHFinallyStmtClass: {
552       const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
553       Engine.addAbortedBlock(node, currBldrCtx->getBlock());
554       break;
555     }
556 
557     case Stmt::ParenExprClass:
558       llvm_unreachable("ParenExprs already handled.");
559     case Stmt::GenericSelectionExprClass:
560       llvm_unreachable("GenericSelectionExprs already handled.");
561     // Cases that should never be evaluated simply because they shouldn't
562     // appear in the CFG.
563     case Stmt::BreakStmtClass:
564     case Stmt::CaseStmtClass:
565     case Stmt::CompoundStmtClass:
566     case Stmt::ContinueStmtClass:
567     case Stmt::CXXForRangeStmtClass:
568     case Stmt::DefaultStmtClass:
569     case Stmt::DoStmtClass:
570     case Stmt::ForStmtClass:
571     case Stmt::GotoStmtClass:
572     case Stmt::IfStmtClass:
573     case Stmt::IndirectGotoStmtClass:
574     case Stmt::LabelStmtClass:
575     case Stmt::AttributedStmtClass:
576     case Stmt::NoStmtClass:
577     case Stmt::NullStmtClass:
578     case Stmt::SwitchStmtClass:
579     case Stmt::WhileStmtClass:
580     case Expr::MSDependentExistsStmtClass:
581       llvm_unreachable("Stmt should not be in analyzer evaluation loop");
582 
583     case Stmt::ObjCSubscriptRefExprClass:
584     case Stmt::ObjCPropertyRefExprClass:
585       llvm_unreachable("These are handled by PseudoObjectExpr");
586 
587     case Stmt::GNUNullExprClass: {
588       // GNU __null is a pointer-width integer, not an actual pointer.
589       ProgramStateRef state = Pred->getState();
590       state = state->BindExpr(S, Pred->getLocationContext(),
591                               svalBuilder.makeIntValWithPtrWidth(0, false));
592       Bldr.generateNode(S, Pred, state);
593       break;
594     }
595 
596     case Stmt::ObjCAtSynchronizedStmtClass:
597       Bldr.takeNodes(Pred);
598       VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
599       Bldr.addNodes(Dst);
600       break;
601 
602     case Stmt::ExprWithCleanupsClass:
603       // Handled due to fully linearised CFG.
604       break;
605 
606     // Cases not handled yet; but will handle some day.
607     case Stmt::DesignatedInitExprClass:
608     case Stmt::ExtVectorElementExprClass:
609     case Stmt::ImaginaryLiteralClass:
610     case Stmt::ObjCAtCatchStmtClass:
611     case Stmt::ObjCAtFinallyStmtClass:
612     case Stmt::ObjCAtTryStmtClass:
613     case Stmt::ObjCAutoreleasePoolStmtClass:
614     case Stmt::ObjCEncodeExprClass:
615     case Stmt::ObjCIsaExprClass:
616     case Stmt::ObjCProtocolExprClass:
617     case Stmt::ObjCSelectorExprClass:
618     case Stmt::ParenListExprClass:
619     case Stmt::PredefinedExprClass:
620     case Stmt::ShuffleVectorExprClass:
621     case Stmt::VAArgExprClass:
622     case Stmt::CUDAKernelCallExprClass:
623     case Stmt::OpaqueValueExprClass:
624     case Stmt::AsTypeExprClass:
625     case Stmt::AtomicExprClass:
626       // Fall through.
627 
628     // Cases we intentionally don't evaluate, since they don't need
629     // to be explicitly evaluated.
630     case Stmt::AddrLabelExprClass:
631     case Stmt::IntegerLiteralClass:
632     case Stmt::CharacterLiteralClass:
633     case Stmt::ImplicitValueInitExprClass:
634     case Stmt::CXXScalarValueInitExprClass:
635     case Stmt::CXXBoolLiteralExprClass:
636     case Stmt::ObjCBoolLiteralExprClass:
637     case Stmt::FloatingLiteralClass:
638     case Stmt::SizeOfPackExprClass:
639     case Stmt::StringLiteralClass:
640     case Stmt::ObjCStringLiteralClass:
641     case Stmt::CXXBindTemporaryExprClass:
642     case Stmt::SubstNonTypeTemplateParmExprClass:
643     case Stmt::CXXNullPtrLiteralExprClass: {
644       Bldr.takeNodes(Pred);
645       ExplodedNodeSet preVisit;
646       getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
647       getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
648       Bldr.addNodes(Dst);
649       break;
650     }
651 
652     case Stmt::CXXDefaultArgExprClass: {
653       Bldr.takeNodes(Pred);
654       ExplodedNodeSet PreVisit;
655       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
656 
657       ExplodedNodeSet Tmp;
658       StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
659 
660       const LocationContext *LCtx = Pred->getLocationContext();
661       const Expr *ArgE = cast<CXXDefaultArgExpr>(S)->getExpr();
662 
663       // Avoid creating and destroying a lot of APSInts.
664       SVal V;
665       llvm::APSInt Result;
666 
667       for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end();
668            I != E; ++I) {
669         ProgramStateRef State = (*I)->getState();
670 
671         if (ArgE->EvaluateAsInt(Result, getContext()))
672           V = svalBuilder.makeIntVal(Result);
673         else
674           V = State->getSVal(ArgE, LCtx);
675 
676         State = State->BindExpr(S, LCtx, V);
677         Bldr2.generateNode(S, *I, State);
678       }
679 
680       getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
681       Bldr.addNodes(Dst);
682       break;
683     }
684 
685     case Expr::ObjCArrayLiteralClass:
686     case Expr::ObjCDictionaryLiteralClass:
687       // FIXME: explicitly model with a region and the actual contents
688       // of the container.  For now, conjure a symbol.
689     case Expr::ObjCBoxedExprClass: {
690       Bldr.takeNodes(Pred);
691 
692       ExplodedNodeSet preVisit;
693       getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
694 
695       ExplodedNodeSet Tmp;
696       StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
697 
698       const Expr *Ex = cast<Expr>(S);
699       QualType resultType = Ex->getType();
700 
701       for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end();
702            it != et; ++it) {
703         ExplodedNode *N = *it;
704         const LocationContext *LCtx = N->getLocationContext();
705         SVal result = svalBuilder.conjureSymbolVal(0, Ex, LCtx, resultType,
706                                                    currBldrCtx->blockCount());
707         ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result);
708         Bldr2.generateNode(S, N, state);
709       }
710 
711       getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
712       Bldr.addNodes(Dst);
713       break;
714     }
715 
716     case Stmt::ArraySubscriptExprClass:
717       Bldr.takeNodes(Pred);
718       VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
719       Bldr.addNodes(Dst);
720       break;
721 
722     case Stmt::GCCAsmStmtClass:
723       Bldr.takeNodes(Pred);
724       VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
725       Bldr.addNodes(Dst);
726       break;
727 
728     case Stmt::MSAsmStmtClass:
729       Bldr.takeNodes(Pred);
730       VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
731       Bldr.addNodes(Dst);
732       break;
733 
734     case Stmt::BlockExprClass:
735       Bldr.takeNodes(Pred);
736       VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
737       Bldr.addNodes(Dst);
738       break;
739 
740     case Stmt::BinaryOperatorClass: {
741       const BinaryOperator* B = cast<BinaryOperator>(S);
742       if (B->isLogicalOp()) {
743         Bldr.takeNodes(Pred);
744         VisitLogicalExpr(B, Pred, Dst);
745         Bldr.addNodes(Dst);
746         break;
747       }
748       else if (B->getOpcode() == BO_Comma) {
749         ProgramStateRef state = Pred->getState();
750         Bldr.generateNode(B, Pred,
751                           state->BindExpr(B, Pred->getLocationContext(),
752                                           state->getSVal(B->getRHS(),
753                                                   Pred->getLocationContext())));
754         break;
755       }
756 
757       Bldr.takeNodes(Pred);
758 
759       if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
760           (B->isRelationalOp() || B->isEqualityOp())) {
761         ExplodedNodeSet Tmp;
762         VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
763         evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
764       }
765       else
766         VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
767 
768       Bldr.addNodes(Dst);
769       break;
770     }
771 
772     case Stmt::CXXOperatorCallExprClass: {
773       const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S);
774 
775       // For instance method operators, make sure the 'this' argument has a
776       // valid region.
777       const Decl *Callee = OCE->getCalleeDecl();
778       if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
779         if (MD->isInstance()) {
780           ProgramStateRef State = Pred->getState();
781           const LocationContext *LCtx = Pred->getLocationContext();
782           ProgramStateRef NewState =
783             createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
784           if (NewState != State)
785             Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/0,
786                                      ProgramPoint::PreStmtKind);
787         }
788       }
789       // FALLTHROUGH
790     }
791     case Stmt::CallExprClass:
792     case Stmt::CXXMemberCallExprClass:
793     case Stmt::UserDefinedLiteralClass: {
794       Bldr.takeNodes(Pred);
795       VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
796       Bldr.addNodes(Dst);
797       break;
798     }
799 
800     case Stmt::CXXCatchStmtClass: {
801       Bldr.takeNodes(Pred);
802       VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
803       Bldr.addNodes(Dst);
804       break;
805     }
806 
807     case Stmt::CXXTemporaryObjectExprClass:
808     case Stmt::CXXConstructExprClass: {
809       Bldr.takeNodes(Pred);
810       VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
811       Bldr.addNodes(Dst);
812       break;
813     }
814 
815     case Stmt::CXXNewExprClass: {
816       Bldr.takeNodes(Pred);
817       ExplodedNodeSet PostVisit;
818       VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit);
819       getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
820       Bldr.addNodes(Dst);
821       break;
822     }
823 
824     case Stmt::CXXDeleteExprClass: {
825       Bldr.takeNodes(Pred);
826       ExplodedNodeSet PreVisit;
827       const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
828       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
829 
830       for (ExplodedNodeSet::iterator i = PreVisit.begin(),
831                                      e = PreVisit.end(); i != e ; ++i)
832         VisitCXXDeleteExpr(CDE, *i, Dst);
833 
834       Bldr.addNodes(Dst);
835       break;
836     }
837       // FIXME: ChooseExpr is really a constant.  We need to fix
838       //        the CFG do not model them as explicit control-flow.
839 
840     case Stmt::ChooseExprClass: { // __builtin_choose_expr
841       Bldr.takeNodes(Pred);
842       const ChooseExpr *C = cast<ChooseExpr>(S);
843       VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
844       Bldr.addNodes(Dst);
845       break;
846     }
847 
848     case Stmt::CompoundAssignOperatorClass:
849       Bldr.takeNodes(Pred);
850       VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
851       Bldr.addNodes(Dst);
852       break;
853 
854     case Stmt::CompoundLiteralExprClass:
855       Bldr.takeNodes(Pred);
856       VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
857       Bldr.addNodes(Dst);
858       break;
859 
860     case Stmt::BinaryConditionalOperatorClass:
861     case Stmt::ConditionalOperatorClass: { // '?' operator
862       Bldr.takeNodes(Pred);
863       const AbstractConditionalOperator *C
864         = cast<AbstractConditionalOperator>(S);
865       VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
866       Bldr.addNodes(Dst);
867       break;
868     }
869 
870     case Stmt::CXXThisExprClass:
871       Bldr.takeNodes(Pred);
872       VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
873       Bldr.addNodes(Dst);
874       break;
875 
876     case Stmt::DeclRefExprClass: {
877       Bldr.takeNodes(Pred);
878       const DeclRefExpr *DE = cast<DeclRefExpr>(S);
879       VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
880       Bldr.addNodes(Dst);
881       break;
882     }
883 
884     case Stmt::DeclStmtClass:
885       Bldr.takeNodes(Pred);
886       VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
887       Bldr.addNodes(Dst);
888       break;
889 
890     case Stmt::ImplicitCastExprClass:
891     case Stmt::CStyleCastExprClass:
892     case Stmt::CXXStaticCastExprClass:
893     case Stmt::CXXDynamicCastExprClass:
894     case Stmt::CXXReinterpretCastExprClass:
895     case Stmt::CXXConstCastExprClass:
896     case Stmt::CXXFunctionalCastExprClass:
897     case Stmt::ObjCBridgedCastExprClass: {
898       Bldr.takeNodes(Pred);
899       const CastExpr *C = cast<CastExpr>(S);
900       // Handle the previsit checks.
901       ExplodedNodeSet dstPrevisit;
902       getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this);
903 
904       // Handle the expression itself.
905       ExplodedNodeSet dstExpr;
906       for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
907                                      e = dstPrevisit.end(); i != e ; ++i) {
908         VisitCast(C, C->getSubExpr(), *i, dstExpr);
909       }
910 
911       // Handle the postvisit checks.
912       getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
913       Bldr.addNodes(Dst);
914       break;
915     }
916 
917     case Expr::MaterializeTemporaryExprClass: {
918       Bldr.takeNodes(Pred);
919       const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
920       CreateCXXTemporaryObject(MTE, Pred, Dst);
921       Bldr.addNodes(Dst);
922       break;
923     }
924 
925     case Stmt::InitListExprClass:
926       Bldr.takeNodes(Pred);
927       VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
928       Bldr.addNodes(Dst);
929       break;
930 
931     case Stmt::MemberExprClass:
932       Bldr.takeNodes(Pred);
933       VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
934       Bldr.addNodes(Dst);
935       break;
936 
937     case Stmt::ObjCIvarRefExprClass:
938       Bldr.takeNodes(Pred);
939       VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
940       Bldr.addNodes(Dst);
941       break;
942 
943     case Stmt::ObjCForCollectionStmtClass:
944       Bldr.takeNodes(Pred);
945       VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
946       Bldr.addNodes(Dst);
947       break;
948 
949     case Stmt::ObjCMessageExprClass:
950       Bldr.takeNodes(Pred);
951       VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
952       Bldr.addNodes(Dst);
953       break;
954 
955     case Stmt::ObjCAtThrowStmtClass:
956     case Stmt::CXXThrowExprClass:
957       // FIXME: This is not complete.  We basically treat @throw as
958       // an abort.
959       Bldr.generateSink(S, Pred, Pred->getState());
960       break;
961 
962     case Stmt::ReturnStmtClass:
963       Bldr.takeNodes(Pred);
964       VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
965       Bldr.addNodes(Dst);
966       break;
967 
968     case Stmt::OffsetOfExprClass:
969       Bldr.takeNodes(Pred);
970       VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
971       Bldr.addNodes(Dst);
972       break;
973 
974     case Stmt::UnaryExprOrTypeTraitExprClass:
975       Bldr.takeNodes(Pred);
976       VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
977                                     Pred, Dst);
978       Bldr.addNodes(Dst);
979       break;
980 
981     case Stmt::StmtExprClass: {
982       const StmtExpr *SE = cast<StmtExpr>(S);
983 
984       if (SE->getSubStmt()->body_empty()) {
985         // Empty statement expression.
986         assert(SE->getType() == getContext().VoidTy
987                && "Empty statement expression must have void type.");
988         break;
989       }
990 
991       if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
992         ProgramStateRef state = Pred->getState();
993         Bldr.generateNode(SE, Pred,
994                           state->BindExpr(SE, Pred->getLocationContext(),
995                                           state->getSVal(LastExpr,
996                                                   Pred->getLocationContext())));
997       }
998       break;
999     }
1000 
1001     case Stmt::UnaryOperatorClass: {
1002       Bldr.takeNodes(Pred);
1003       const UnaryOperator *U = cast<UnaryOperator>(S);
1004       if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
1005         ExplodedNodeSet Tmp;
1006         VisitUnaryOperator(U, Pred, Tmp);
1007         evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1008       }
1009       else
1010         VisitUnaryOperator(U, Pred, Dst);
1011       Bldr.addNodes(Dst);
1012       break;
1013     }
1014 
1015     case Stmt::PseudoObjectExprClass: {
1016       Bldr.takeNodes(Pred);
1017       ProgramStateRef state = Pred->getState();
1018       const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
1019       if (const Expr *Result = PE->getResultExpr()) {
1020         SVal V = state->getSVal(Result, Pred->getLocationContext());
1021         Bldr.generateNode(S, Pred,
1022                           state->BindExpr(S, Pred->getLocationContext(), V));
1023       }
1024       else
1025         Bldr.generateNode(S, Pred,
1026                           state->BindExpr(S, Pred->getLocationContext(),
1027                                                    UnknownVal()));
1028 
1029       Bldr.addNodes(Dst);
1030       break;
1031     }
1032   }
1033 }
1034 
1035 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1036                                        const LocationContext *CalleeLC) {
1037   const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1038   const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
1039   assert(CalleeSF && CallerSF);
1040   ExplodedNode *BeforeProcessingCall = 0;
1041   const Stmt *CE = CalleeSF->getCallSite();
1042 
1043   // Find the first node before we started processing the call expression.
1044   while (N) {
1045     ProgramPoint L = N->getLocation();
1046     BeforeProcessingCall = N;
1047     N = N->pred_empty() ? NULL : *(N->pred_begin());
1048 
1049     // Skip the nodes corresponding to the inlined code.
1050     if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
1051       continue;
1052     // We reached the caller. Find the node right before we started
1053     // processing the call.
1054     if (L.isPurgeKind())
1055       continue;
1056     if (isa<PreImplicitCall>(&L))
1057       continue;
1058     if (isa<CallEnter>(&L))
1059       continue;
1060     if (const StmtPoint *SP = dyn_cast<StmtPoint>(&L))
1061       if (SP->getStmt() == CE)
1062         continue;
1063     break;
1064   }
1065 
1066   if (!BeforeProcessingCall)
1067     return false;
1068 
1069   // TODO: Clean up the unneeded nodes.
1070 
1071   // Build an Epsilon node from which we will restart the analyzes.
1072   // Note that CE is permitted to be NULL!
1073   ProgramPoint NewNodeLoc =
1074                EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1075   // Add the special flag to GDM to signal retrying with no inlining.
1076   // Note, changing the state ensures that we are not going to cache out.
1077   ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1078   NewNodeState =
1079     NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1080 
1081   // Make the new node a successor of BeforeProcessingCall.
1082   bool IsNew = false;
1083   ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1084   // We cached out at this point. Caching out is common due to us backtracking
1085   // from the inlined function, which might spawn several paths.
1086   if (!IsNew)
1087     return true;
1088 
1089   NewNode->addPredecessor(BeforeProcessingCall, G);
1090 
1091   // Add the new node to the work list.
1092   Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1093                                   CalleeSF->getIndex());
1094   NumTimesRetriedWithoutInlining++;
1095   return true;
1096 }
1097 
1098 /// Block entrance.  (Update counters).
1099 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
1100                                          NodeBuilderWithSinks &nodeBuilder,
1101                                          ExplodedNode *Pred) {
1102 
1103   // FIXME: Refactor this into a checker.
1104   if (nodeBuilder.getContext().blockCount() >= AMgr.options.maxBlockVisitOnPath) {
1105     static SimpleProgramPointTag tag("ExprEngine : Block count exceeded");
1106     const ExplodedNode *Sink =
1107                    nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1108 
1109     // Check if we stopped at the top level function or not.
1110     // Root node should have the location context of the top most function.
1111     const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1112     const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1113     const LocationContext *RootLC =
1114                         (*G.roots_begin())->getLocation().getLocationContext();
1115     if (RootLC->getCurrentStackFrame() != CalleeSF) {
1116       Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1117 
1118       // Re-run the call evaluation without inlining it, by storing the
1119       // no-inlining policy in the state and enqueuing the new work item on
1120       // the list. Replay should almost never fail. Use the stats to catch it
1121       // if it does.
1122       if ((!AMgr.options.NoRetryExhausted &&
1123            replayWithoutInlining(Pred, CalleeLC)))
1124         return;
1125       NumMaxBlockCountReachedInInlined++;
1126     } else
1127       NumMaxBlockCountReached++;
1128 
1129     // Make sink nodes as exhausted(for stats) only if retry failed.
1130     Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1131   }
1132 }
1133 
1134 //===----------------------------------------------------------------------===//
1135 // Branch processing.
1136 //===----------------------------------------------------------------------===//
1137 
1138 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1139 /// to try to recover some path-sensitivity for casts of symbolic
1140 /// integers that promote their values (which are currently not tracked well).
1141 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1142 //  cast(s) did was sign-extend the original value.
1143 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
1144                                 ProgramStateRef state,
1145                                 const Stmt *Condition,
1146                                 const LocationContext *LCtx,
1147                                 ASTContext &Ctx) {
1148 
1149   const Expr *Ex = dyn_cast<Expr>(Condition);
1150   if (!Ex)
1151     return UnknownVal();
1152 
1153   uint64_t bits = 0;
1154   bool bitsInit = false;
1155 
1156   while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
1157     QualType T = CE->getType();
1158 
1159     if (!T->isIntegerType())
1160       return UnknownVal();
1161 
1162     uint64_t newBits = Ctx.getTypeSize(T);
1163     if (!bitsInit || newBits < bits) {
1164       bitsInit = true;
1165       bits = newBits;
1166     }
1167 
1168     Ex = CE->getSubExpr();
1169   }
1170 
1171   // We reached a non-cast.  Is it a symbolic value?
1172   QualType T = Ex->getType();
1173 
1174   if (!bitsInit || !T->isIntegerType() || Ctx.getTypeSize(T) > bits)
1175     return UnknownVal();
1176 
1177   return state->getSVal(Ex, LCtx);
1178 }
1179 
1180 static const Stmt *ResolveCondition(const Stmt *Condition,
1181                                     const CFGBlock *B) {
1182   if (const Expr *Ex = dyn_cast<Expr>(Condition))
1183     Condition = Ex->IgnoreParens();
1184 
1185   const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1186   if (!BO || !BO->isLogicalOp())
1187     return Condition;
1188 
1189   // For logical operations, we still have the case where some branches
1190   // use the traditional "merge" approach and others sink the branch
1191   // directly into the basic blocks representing the logical operation.
1192   // We need to distinguish between those two cases here.
1193 
1194   // The invariants are still shifting, but it is possible that the
1195   // last element in a CFGBlock is not a CFGStmt.  Look for the last
1196   // CFGStmt as the value of the condition.
1197   CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
1198   for (; I != E; ++I) {
1199     CFGElement Elem = *I;
1200     CFGStmt *CS = dyn_cast<CFGStmt>(&Elem);
1201     if (!CS)
1202       continue;
1203     if (CS->getStmt() != Condition)
1204       break;
1205     return Condition;
1206   }
1207 
1208   assert(I != E);
1209 
1210   while (Condition) {
1211     BO = dyn_cast<BinaryOperator>(Condition);
1212     if (!BO || !BO->isLogicalOp())
1213       return Condition;
1214     Condition = BO->getRHS()->IgnoreParens();
1215   }
1216   llvm_unreachable("could not resolve condition");
1217 }
1218 
1219 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
1220                                NodeBuilderContext& BldCtx,
1221                                ExplodedNode *Pred,
1222                                ExplodedNodeSet &Dst,
1223                                const CFGBlock *DstT,
1224                                const CFGBlock *DstF) {
1225   currBldrCtx = &BldCtx;
1226 
1227   // Check for NULL conditions; e.g. "for(;;)"
1228   if (!Condition) {
1229     BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
1230     NullCondBldr.markInfeasible(false);
1231     NullCondBldr.generateNode(Pred->getState(), true, Pred);
1232     return;
1233   }
1234 
1235 
1236   // Resolve the condition in the precense of nested '||' and '&&'.
1237   if (const Expr *Ex = dyn_cast<Expr>(Condition))
1238     Condition = Ex->IgnoreParens();
1239 
1240   Condition = ResolveCondition(Condition, BldCtx.getBlock());
1241   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1242                                 Condition->getLocStart(),
1243                                 "Error evaluating branch");
1244 
1245   ExplodedNodeSet CheckersOutSet;
1246   getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
1247                                                     Pred, *this);
1248   // We generated only sinks.
1249   if (CheckersOutSet.empty())
1250     return;
1251 
1252   BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
1253   for (NodeBuilder::iterator I = CheckersOutSet.begin(),
1254                              E = CheckersOutSet.end(); E != I; ++I) {
1255     ExplodedNode *PredI = *I;
1256 
1257     if (PredI->isSink())
1258       continue;
1259 
1260     ProgramStateRef PrevState = PredI->getState();
1261     SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
1262 
1263     if (X.isUnknownOrUndef()) {
1264       // Give it a chance to recover from unknown.
1265       if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
1266         if (Ex->getType()->isIntegerType()) {
1267           // Try to recover some path-sensitivity.  Right now casts of symbolic
1268           // integers that promote their values are currently not tracked well.
1269           // If 'Condition' is such an expression, try and recover the
1270           // underlying value and use that instead.
1271           SVal recovered = RecoverCastedSymbol(getStateManager(),
1272                                                PrevState, Condition,
1273                                                PredI->getLocationContext(),
1274                                                getContext());
1275 
1276           if (!recovered.isUnknown()) {
1277             X = recovered;
1278           }
1279         }
1280       }
1281     }
1282 
1283     // If the condition is still unknown, give up.
1284     if (X.isUnknownOrUndef()) {
1285       builder.generateNode(PrevState, true, PredI);
1286       builder.generateNode(PrevState, false, PredI);
1287       continue;
1288     }
1289 
1290     DefinedSVal V = cast<DefinedSVal>(X);
1291 
1292     ProgramStateRef StTrue, StFalse;
1293     tie(StTrue, StFalse) = PrevState->assume(V);
1294 
1295     // Process the true branch.
1296     if (builder.isFeasible(true)) {
1297       if (StTrue)
1298         builder.generateNode(StTrue, true, PredI);
1299       else
1300         builder.markInfeasible(true);
1301     }
1302 
1303     // Process the false branch.
1304     if (builder.isFeasible(false)) {
1305       if (StFalse)
1306         builder.generateNode(StFalse, false, PredI);
1307       else
1308         builder.markInfeasible(false);
1309     }
1310   }
1311   currBldrCtx = 0;
1312 }
1313 
1314 /// processIndirectGoto - Called by CoreEngine.  Used to generate successor
1315 ///  nodes by processing the 'effects' of a computed goto jump.
1316 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
1317 
1318   ProgramStateRef state = builder.getState();
1319   SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
1320 
1321   // Three possibilities:
1322   //
1323   //   (1) We know the computed label.
1324   //   (2) The label is NULL (or some other constant), or Undefined.
1325   //   (3) We have no clue about the label.  Dispatch to all targets.
1326   //
1327 
1328   typedef IndirectGotoNodeBuilder::iterator iterator;
1329 
1330   if (isa<loc::GotoLabel>(V)) {
1331     const LabelDecl *L = cast<loc::GotoLabel>(V).getLabel();
1332 
1333     for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
1334       if (I.getLabel() == L) {
1335         builder.generateNode(I, state);
1336         return;
1337       }
1338     }
1339 
1340     llvm_unreachable("No block with label.");
1341   }
1342 
1343   if (isa<loc::ConcreteInt>(V) || isa<UndefinedVal>(V)) {
1344     // Dispatch to the first target and mark it as a sink.
1345     //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
1346     // FIXME: add checker visit.
1347     //    UndefBranches.insert(N);
1348     return;
1349   }
1350 
1351   // This is really a catch-all.  We don't support symbolics yet.
1352   // FIXME: Implement dispatch for symbolic pointers.
1353 
1354   for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
1355     builder.generateNode(I, state);
1356 }
1357 
1358 /// ProcessEndPath - Called by CoreEngine.  Used to generate end-of-path
1359 ///  nodes when the control reaches the end of a function.
1360 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
1361                                       ExplodedNode *Pred) {
1362   StateMgr.EndPath(Pred->getState());
1363 
1364   ExplodedNodeSet Dst;
1365   if (Pred->getLocationContext()->inTopFrame()) {
1366     // Remove dead symbols.
1367     ExplodedNodeSet AfterRemovedDead;
1368     removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
1369 
1370     // Notify checkers.
1371     for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(),
1372         E = AfterRemovedDead.end(); I != E; ++I) {
1373       getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this);
1374     }
1375   } else {
1376     getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
1377   }
1378 
1379   Engine.enqueueEndOfFunction(Dst);
1380 }
1381 
1382 /// ProcessSwitch - Called by CoreEngine.  Used to generate successor
1383 ///  nodes by processing the 'effects' of a switch statement.
1384 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
1385   typedef SwitchNodeBuilder::iterator iterator;
1386   ProgramStateRef state = builder.getState();
1387   const Expr *CondE = builder.getCondition();
1388   SVal  CondV_untested = state->getSVal(CondE, builder.getLocationContext());
1389 
1390   if (CondV_untested.isUndef()) {
1391     //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
1392     // FIXME: add checker
1393     //UndefBranches.insert(N);
1394 
1395     return;
1396   }
1397   DefinedOrUnknownSVal CondV = cast<DefinedOrUnknownSVal>(CondV_untested);
1398 
1399   ProgramStateRef DefaultSt = state;
1400 
1401   iterator I = builder.begin(), EI = builder.end();
1402   bool defaultIsFeasible = I == EI;
1403 
1404   for ( ; I != EI; ++I) {
1405     // Successor may be pruned out during CFG construction.
1406     if (!I.getBlock())
1407       continue;
1408 
1409     const CaseStmt *Case = I.getCase();
1410 
1411     // Evaluate the LHS of the case value.
1412     llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
1413     assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType()));
1414 
1415     // Get the RHS of the case, if it exists.
1416     llvm::APSInt V2;
1417     if (const Expr *E = Case->getRHS())
1418       V2 = E->EvaluateKnownConstInt(getContext());
1419     else
1420       V2 = V1;
1421 
1422     // FIXME: Eventually we should replace the logic below with a range
1423     //  comparison, rather than concretize the values within the range.
1424     //  This should be easy once we have "ranges" for NonLVals.
1425 
1426     do {
1427       nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1));
1428       DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state,
1429                                                CondV, CaseVal);
1430 
1431       // Now "assume" that the case matches.
1432       if (ProgramStateRef stateNew = state->assume(Res, true)) {
1433         builder.generateCaseStmtNode(I, stateNew);
1434 
1435         // If CondV evaluates to a constant, then we know that this
1436         // is the *only* case that we can take, so stop evaluating the
1437         // others.
1438         if (isa<nonloc::ConcreteInt>(CondV))
1439           return;
1440       }
1441 
1442       // Now "assume" that the case doesn't match.  Add this state
1443       // to the default state (if it is feasible).
1444       if (DefaultSt) {
1445         if (ProgramStateRef stateNew = DefaultSt->assume(Res, false)) {
1446           defaultIsFeasible = true;
1447           DefaultSt = stateNew;
1448         }
1449         else {
1450           defaultIsFeasible = false;
1451           DefaultSt = NULL;
1452         }
1453       }
1454 
1455       // Concretize the next value in the range.
1456       if (V1 == V2)
1457         break;
1458 
1459       ++V1;
1460       assert (V1 <= V2);
1461 
1462     } while (true);
1463   }
1464 
1465   if (!defaultIsFeasible)
1466     return;
1467 
1468   // If we have switch(enum value), the default branch is not
1469   // feasible if all of the enum constants not covered by 'case:' statements
1470   // are not feasible values for the switch condition.
1471   //
1472   // Note that this isn't as accurate as it could be.  Even if there isn't
1473   // a case for a particular enum value as long as that enum value isn't
1474   // feasible then it shouldn't be considered for making 'default:' reachable.
1475   const SwitchStmt *SS = builder.getSwitch();
1476   const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
1477   if (CondExpr->getType()->getAs<EnumType>()) {
1478     if (SS->isAllEnumCasesCovered())
1479       return;
1480   }
1481 
1482   builder.generateDefaultCaseNode(DefaultSt);
1483 }
1484 
1485 //===----------------------------------------------------------------------===//
1486 // Transfer functions: Loads and stores.
1487 //===----------------------------------------------------------------------===//
1488 
1489 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
1490                                         ExplodedNode *Pred,
1491                                         ExplodedNodeSet &Dst) {
1492   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1493 
1494   ProgramStateRef state = Pred->getState();
1495   const LocationContext *LCtx = Pred->getLocationContext();
1496 
1497   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1498     assert(Ex->isGLValue());
1499     SVal V = state->getLValue(VD, Pred->getLocationContext());
1500 
1501     // For references, the 'lvalue' is the pointer address stored in the
1502     // reference region.
1503     if (VD->getType()->isReferenceType()) {
1504       if (const MemRegion *R = V.getAsRegion())
1505         V = state->getSVal(R);
1506       else
1507         V = UnknownVal();
1508     }
1509 
1510     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0,
1511                       ProgramPoint::PostLValueKind);
1512     return;
1513   }
1514   if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
1515     assert(!Ex->isGLValue());
1516     SVal V = svalBuilder.makeIntVal(ED->getInitVal());
1517     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
1518     return;
1519   }
1520   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1521     SVal V = svalBuilder.getFunctionPointer(FD);
1522     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0,
1523                       ProgramPoint::PostLValueKind);
1524     return;
1525   }
1526   if (isa<FieldDecl>(D)) {
1527     // FIXME: Compute lvalue of field pointers-to-member.
1528     // Right now we just use a non-null void pointer, so that it gives proper
1529     // results in boolean contexts.
1530     SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
1531                                           currBldrCtx->blockCount());
1532     state = state->assume(cast<DefinedOrUnknownSVal>(V), true);
1533     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0,
1534 		      ProgramPoint::PostLValueKind);
1535     return;
1536   }
1537 
1538   llvm_unreachable("Support for this Decl not implemented.");
1539 }
1540 
1541 /// VisitArraySubscriptExpr - Transfer function for array accesses
1542 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A,
1543                                              ExplodedNode *Pred,
1544                                              ExplodedNodeSet &Dst){
1545 
1546   const Expr *Base = A->getBase()->IgnoreParens();
1547   const Expr *Idx  = A->getIdx()->IgnoreParens();
1548 
1549 
1550   ExplodedNodeSet checkerPreStmt;
1551   getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this);
1552 
1553   StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currBldrCtx);
1554 
1555   for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(),
1556                                  ei = checkerPreStmt.end(); it != ei; ++it) {
1557     const LocationContext *LCtx = (*it)->getLocationContext();
1558     ProgramStateRef state = (*it)->getState();
1559     SVal V = state->getLValue(A->getType(),
1560                               state->getSVal(Idx, LCtx),
1561                               state->getSVal(Base, LCtx));
1562     assert(A->isGLValue());
1563     Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), 0,
1564                       ProgramPoint::PostLValueKind);
1565   }
1566 }
1567 
1568 /// VisitMemberExpr - Transfer function for member expressions.
1569 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
1570                                  ExplodedNodeSet &TopDst) {
1571 
1572   StmtNodeBuilder Bldr(Pred, TopDst, *currBldrCtx);
1573   ExplodedNodeSet Dst;
1574   ValueDecl *Member = M->getMemberDecl();
1575 
1576   // Handle static member variables and enum constants accessed via
1577   // member syntax.
1578   if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
1579     Bldr.takeNodes(Pred);
1580     VisitCommonDeclRefExpr(M, Member, Pred, Dst);
1581     Bldr.addNodes(Dst);
1582     return;
1583   }
1584 
1585   ProgramStateRef state = Pred->getState();
1586   const LocationContext *LCtx = Pred->getLocationContext();
1587   Expr *BaseExpr = M->getBase();
1588 
1589   // Handle C++ method calls.
1590   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
1591     if (MD->isInstance())
1592       state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
1593 
1594     SVal MDVal = svalBuilder.getFunctionPointer(MD);
1595     state = state->BindExpr(M, LCtx, MDVal);
1596 
1597     Bldr.generateNode(M, Pred, state);
1598     return;
1599   }
1600 
1601   // Handle regular struct fields / member variables.
1602   state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
1603   SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
1604 
1605   FieldDecl *field = cast<FieldDecl>(Member);
1606   SVal L = state->getLValue(field, baseExprVal);
1607   if (M->isGLValue()) {
1608     if (field->getType()->isReferenceType()) {
1609       if (const MemRegion *R = L.getAsRegion())
1610         L = state->getSVal(R);
1611       else
1612         L = UnknownVal();
1613     }
1614 
1615     Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, L), 0,
1616                       ProgramPoint::PostLValueKind);
1617   } else {
1618     Bldr.takeNodes(Pred);
1619     evalLoad(Dst, M, M, Pred, state, L);
1620     Bldr.addNodes(Dst);
1621   }
1622 }
1623 
1624 namespace {
1625 class CollectReachableSymbolsCallback : public SymbolVisitor {
1626   InvalidatedSymbols Symbols;
1627 public:
1628   CollectReachableSymbolsCallback(ProgramStateRef State) {}
1629   const InvalidatedSymbols &getSymbols() const { return Symbols; }
1630 
1631   bool VisitSymbol(SymbolRef Sym) {
1632     Symbols.insert(Sym);
1633     return true;
1634   }
1635 };
1636 } // end anonymous namespace
1637 
1638 // A value escapes in three possible cases:
1639 // (1) We are binding to something that is not a memory region.
1640 // (2) We are binding to a MemrRegion that does not have stack storage.
1641 // (3) We are binding to a MemRegion with stack storage that the store
1642 //     does not understand.
1643 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
1644                                                         SVal Loc, SVal Val) {
1645   // Are we storing to something that causes the value to "escape"?
1646   bool escapes = true;
1647 
1648   // TODO: Move to StoreManager.
1649   if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&Loc)) {
1650     escapes = !regionLoc->getRegion()->hasStackStorage();
1651 
1652     if (!escapes) {
1653       // To test (3), generate a new state with the binding added.  If it is
1654       // the same state, then it escapes (since the store cannot represent
1655       // the binding).
1656       // Do this only if we know that the store is not supposed to generate the
1657       // same state.
1658       SVal StoredVal = State->getSVal(regionLoc->getRegion());
1659       if (StoredVal != Val)
1660         escapes = (State == (State->bindLoc(*regionLoc, Val)));
1661     }
1662     if (!escapes) {
1663       // Case 4: We do not currently model what happens when a symbol is
1664       // assigned to a struct field, so be conservative here and let the symbol
1665       // go. TODO: This could definitely be improved upon.
1666       escapes = !isa<VarRegion>(regionLoc->getRegion());
1667     }
1668   }
1669 
1670   // If our store can represent the binding and we aren't storing to something
1671   // that doesn't have local storage then just return and have the simulation
1672   // state continue as is.
1673   if (!escapes)
1674     return State;
1675 
1676   // Otherwise, find all symbols referenced by 'val' that we are tracking
1677   // and stop tracking them.
1678   CollectReachableSymbolsCallback Scanner =
1679       State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val);
1680   const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
1681   State = getCheckerManager().runCheckersForPointerEscape(State,
1682                                                           EscapedSymbols,
1683                                                           /*CallEvent*/ 0,
1684                                                           PSK_EscapeOnBind);
1685 
1686   return State;
1687 }
1688 
1689 ProgramStateRef
1690 ExprEngine::processPointerEscapedOnInvalidateRegions(ProgramStateRef State,
1691     const InvalidatedSymbols *Invalidated,
1692     ArrayRef<const MemRegion *> ExplicitRegions,
1693     ArrayRef<const MemRegion *> Regions,
1694     const CallEvent *Call) {
1695 
1696   if (!Invalidated || Invalidated->empty())
1697     return State;
1698 
1699   if (!Call)
1700     return getCheckerManager().runCheckersForPointerEscape(State,
1701                                                            *Invalidated,
1702                                                            0,
1703                                                            PSK_EscapeOther);
1704 
1705   // If the symbols were invalidated by a call, we want to find out which ones
1706   // were invalidated directly due to being arguments to the call.
1707   InvalidatedSymbols SymbolsDirectlyInvalidated;
1708   for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1709       E = ExplicitRegions.end(); I != E; ++I) {
1710     if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1711       SymbolsDirectlyInvalidated.insert(R->getSymbol());
1712   }
1713 
1714   InvalidatedSymbols SymbolsIndirectlyInvalidated;
1715   for (InvalidatedSymbols::const_iterator I=Invalidated->begin(),
1716       E = Invalidated->end(); I!=E; ++I) {
1717     SymbolRef sym = *I;
1718     if (SymbolsDirectlyInvalidated.count(sym))
1719       continue;
1720     SymbolsIndirectlyInvalidated.insert(sym);
1721   }
1722 
1723   if (!SymbolsDirectlyInvalidated.empty())
1724     State = getCheckerManager().runCheckersForPointerEscape(State,
1725         SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall);
1726 
1727   // Notify about the symbols that get indirectly invalidated by the call.
1728   if (!SymbolsIndirectlyInvalidated.empty())
1729     State = getCheckerManager().runCheckersForPointerEscape(State,
1730         SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall);
1731 
1732   return State;
1733 }
1734 
1735 /// evalBind - Handle the semantics of binding a value to a specific location.
1736 ///  This method is used by evalStore and (soon) VisitDeclStmt, and others.
1737 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
1738                           ExplodedNode *Pred,
1739                           SVal location, SVal Val,
1740                           bool atDeclInit, const ProgramPoint *PP) {
1741 
1742   const LocationContext *LC = Pred->getLocationContext();
1743   PostStmt PS(StoreE, LC);
1744   if (!PP)
1745     PP = &PS;
1746 
1747   // Do a previsit of the bind.
1748   ExplodedNodeSet CheckedSet;
1749   getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
1750                                          StoreE, *this, *PP);
1751 
1752 
1753   StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
1754 
1755   // If the location is not a 'Loc', it will already be handled by
1756   // the checkers.  There is nothing left to do.
1757   if (!isa<Loc>(location)) {
1758     const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/0, /*tag*/0);
1759     ProgramStateRef state = Pred->getState();
1760     state = processPointerEscapedOnBind(state, location, Val);
1761     Bldr.generateNode(L, state, Pred);
1762     return;
1763   }
1764 
1765 
1766   for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
1767        I!=E; ++I) {
1768     ExplodedNode *PredI = *I;
1769     ProgramStateRef state = PredI->getState();
1770 
1771     state = processPointerEscapedOnBind(state, location, Val);
1772 
1773     // When binding the value, pass on the hint that this is a initialization.
1774     // For initializations, we do not need to inform clients of region
1775     // changes.
1776     state = state->bindLoc(cast<Loc>(location),
1777                            Val, /* notifyChanges = */ !atDeclInit);
1778 
1779     const MemRegion *LocReg = 0;
1780     if (loc::MemRegionVal *LocRegVal = dyn_cast<loc::MemRegionVal>(&location)) {
1781       LocReg = LocRegVal->getRegion();
1782     }
1783 
1784     const ProgramPoint L = PostStore(StoreE, LC, LocReg, 0);
1785     Bldr.generateNode(L, state, PredI);
1786   }
1787 }
1788 
1789 /// evalStore - Handle the semantics of a store via an assignment.
1790 ///  @param Dst The node set to store generated state nodes
1791 ///  @param AssignE The assignment expression if the store happens in an
1792 ///         assignment.
1793 ///  @param LocationE The location expression that is stored to.
1794 ///  @param state The current simulation state
1795 ///  @param location The location to store the value
1796 ///  @param Val The value to be stored
1797 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
1798                              const Expr *LocationE,
1799                              ExplodedNode *Pred,
1800                              ProgramStateRef state, SVal location, SVal Val,
1801                              const ProgramPointTag *tag) {
1802   // Proceed with the store.  We use AssignE as the anchor for the PostStore
1803   // ProgramPoint if it is non-NULL, and LocationE otherwise.
1804   const Expr *StoreE = AssignE ? AssignE : LocationE;
1805 
1806   // Evaluate the location (checks for bad dereferences).
1807   ExplodedNodeSet Tmp;
1808   evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
1809 
1810   if (Tmp.empty())
1811     return;
1812 
1813   if (location.isUndef())
1814     return;
1815 
1816   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
1817     evalBind(Dst, StoreE, *NI, location, Val, false);
1818 }
1819 
1820 void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
1821                           const Expr *NodeEx,
1822                           const Expr *BoundEx,
1823                           ExplodedNode *Pred,
1824                           ProgramStateRef state,
1825                           SVal location,
1826                           const ProgramPointTag *tag,
1827                           QualType LoadTy)
1828 {
1829   assert(!isa<NonLoc>(location) && "location cannot be a NonLoc.");
1830 
1831   // Are we loading from a region?  This actually results in two loads; one
1832   // to fetch the address of the referenced value and one to fetch the
1833   // referenced value.
1834   if (const TypedValueRegion *TR =
1835         dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
1836 
1837     QualType ValTy = TR->getValueType();
1838     if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
1839       static SimpleProgramPointTag
1840              loadReferenceTag("ExprEngine : Load Reference");
1841       ExplodedNodeSet Tmp;
1842       evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
1843                      location, &loadReferenceTag,
1844                      getContext().getPointerType(RT->getPointeeType()));
1845 
1846       // Perform the load from the referenced value.
1847       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
1848         state = (*I)->getState();
1849         location = state->getSVal(BoundEx, (*I)->getLocationContext());
1850         evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
1851       }
1852       return;
1853     }
1854   }
1855 
1856   evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
1857 }
1858 
1859 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
1860                                 const Expr *NodeEx,
1861                                 const Expr *BoundEx,
1862                                 ExplodedNode *Pred,
1863                                 ProgramStateRef state,
1864                                 SVal location,
1865                                 const ProgramPointTag *tag,
1866                                 QualType LoadTy) {
1867   assert(NodeEx);
1868   assert(BoundEx);
1869   // Evaluate the location (checks for bad dereferences).
1870   ExplodedNodeSet Tmp;
1871   evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
1872   if (Tmp.empty())
1873     return;
1874 
1875   StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
1876   if (location.isUndef())
1877     return;
1878 
1879   // Proceed with the load.
1880   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
1881     state = (*NI)->getState();
1882     const LocationContext *LCtx = (*NI)->getLocationContext();
1883 
1884     SVal V = UnknownVal();
1885     if (location.isValid()) {
1886       if (LoadTy.isNull())
1887         LoadTy = BoundEx->getType();
1888       V = state->getSVal(cast<Loc>(location), LoadTy);
1889     }
1890 
1891     Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
1892                       ProgramPoint::PostLoadKind);
1893   }
1894 }
1895 
1896 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
1897                               const Stmt *NodeEx,
1898                               const Stmt *BoundEx,
1899                               ExplodedNode *Pred,
1900                               ProgramStateRef state,
1901                               SVal location,
1902                               const ProgramPointTag *tag,
1903                               bool isLoad) {
1904   StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
1905   // Early checks for performance reason.
1906   if (location.isUnknown()) {
1907     return;
1908   }
1909 
1910   ExplodedNodeSet Src;
1911   BldrTop.takeNodes(Pred);
1912   StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
1913   if (Pred->getState() != state) {
1914     // Associate this new state with an ExplodedNode.
1915     // FIXME: If I pass null tag, the graph is incorrect, e.g for
1916     //   int *p;
1917     //   p = 0;
1918     //   *p = 0xDEADBEEF;
1919     // "p = 0" is not noted as "Null pointer value stored to 'p'" but
1920     // instead "int *p" is noted as
1921     // "Variable 'p' initialized to a null pointer value"
1922 
1923     static SimpleProgramPointTag tag("ExprEngine: Location");
1924     Bldr.generateNode(NodeEx, Pred, state, &tag);
1925   }
1926   ExplodedNodeSet Tmp;
1927   getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
1928                                              NodeEx, BoundEx, *this);
1929   BldrTop.addNodes(Tmp);
1930 }
1931 
1932 std::pair<const ProgramPointTag *, const ProgramPointTag*>
1933 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
1934   static SimpleProgramPointTag
1935          eagerlyAssumeBinOpBifurcationTrue("ExprEngine : Eagerly Assume True"),
1936          eagerlyAssumeBinOpBifurcationFalse("ExprEngine : Eagerly Assume False");
1937   return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
1938                         &eagerlyAssumeBinOpBifurcationFalse);
1939 }
1940 
1941 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
1942                                                    ExplodedNodeSet &Src,
1943                                                    const Expr *Ex) {
1944   StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
1945 
1946   for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
1947     ExplodedNode *Pred = *I;
1948     // Test if the previous node was as the same expression.  This can happen
1949     // when the expression fails to evaluate to anything meaningful and
1950     // (as an optimization) we don't generate a node.
1951     ProgramPoint P = Pred->getLocation();
1952     if (!isa<PostStmt>(P) || cast<PostStmt>(P).getStmt() != Ex) {
1953       continue;
1954     }
1955 
1956     ProgramStateRef state = Pred->getState();
1957     SVal V = state->getSVal(Ex, Pred->getLocationContext());
1958     nonloc::SymbolVal *SEV = dyn_cast<nonloc::SymbolVal>(&V);
1959     if (SEV && SEV->isExpression()) {
1960       const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
1961         geteagerlyAssumeBinOpBifurcationTags();
1962 
1963       ProgramStateRef StateTrue, StateFalse;
1964       tie(StateTrue, StateFalse) = state->assume(*SEV);
1965 
1966       // First assume that the condition is true.
1967       if (StateTrue) {
1968         SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
1969         StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
1970         Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
1971       }
1972 
1973       // Next, assume that the condition is false.
1974       if (StateFalse) {
1975         SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
1976         StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
1977         Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
1978       }
1979     }
1980   }
1981 }
1982 
1983 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
1984                                  ExplodedNodeSet &Dst) {
1985   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1986   // We have processed both the inputs and the outputs.  All of the outputs
1987   // should evaluate to Locs.  Nuke all of their values.
1988 
1989   // FIXME: Some day in the future it would be nice to allow a "plug-in"
1990   // which interprets the inline asm and stores proper results in the
1991   // outputs.
1992 
1993   ProgramStateRef state = Pred->getState();
1994 
1995   for (GCCAsmStmt::const_outputs_iterator OI = A->begin_outputs(),
1996        OE = A->end_outputs(); OI != OE; ++OI) {
1997     SVal X = state->getSVal(*OI, Pred->getLocationContext());
1998     assert (!isa<NonLoc>(X));  // Should be an Lval, or unknown, undef.
1999 
2000     if (isa<Loc>(X))
2001       state = state->bindLoc(cast<Loc>(X), UnknownVal());
2002   }
2003 
2004   Bldr.generateNode(A, Pred, state);
2005 }
2006 
2007 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
2008                                 ExplodedNodeSet &Dst) {
2009   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2010   Bldr.generateNode(A, Pred, Pred->getState());
2011 }
2012 
2013 //===----------------------------------------------------------------------===//
2014 // Visualization.
2015 //===----------------------------------------------------------------------===//
2016 
2017 #ifndef NDEBUG
2018 static ExprEngine* GraphPrintCheckerState;
2019 static SourceManager* GraphPrintSourceManager;
2020 
2021 namespace llvm {
2022 template<>
2023 struct DOTGraphTraits<ExplodedNode*> :
2024   public DefaultDOTGraphTraits {
2025 
2026   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2027 
2028   // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
2029   // work.
2030   static std::string getNodeAttributes(const ExplodedNode *N, void*) {
2031 
2032 #if 0
2033       // FIXME: Replace with a general scheme to tell if the node is
2034       // an error node.
2035     if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
2036         GraphPrintCheckerState->isExplicitNullDeref(N) ||
2037         GraphPrintCheckerState->isUndefDeref(N) ||
2038         GraphPrintCheckerState->isUndefStore(N) ||
2039         GraphPrintCheckerState->isUndefControlFlow(N) ||
2040         GraphPrintCheckerState->isUndefResult(N) ||
2041         GraphPrintCheckerState->isBadCall(N) ||
2042         GraphPrintCheckerState->isUndefArg(N))
2043       return "color=\"red\",style=\"filled\"";
2044 
2045     if (GraphPrintCheckerState->isNoReturnCall(N))
2046       return "color=\"blue\",style=\"filled\"";
2047 #endif
2048     return "";
2049   }
2050 
2051   static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
2052     if (SLoc.isFileID()) {
2053       Out << "\\lline="
2054         << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2055         << " col="
2056         << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
2057         << "\\l";
2058     }
2059   }
2060 
2061   static std::string getNodeLabel(const ExplodedNode *N, void*){
2062 
2063     std::string sbuf;
2064     llvm::raw_string_ostream Out(sbuf);
2065 
2066     // Program Location.
2067     ProgramPoint Loc = N->getLocation();
2068 
2069     switch (Loc.getKind()) {
2070       case ProgramPoint::BlockEntranceKind: {
2071         Out << "Block Entrance: B"
2072             << cast<BlockEntrance>(Loc).getBlock()->getBlockID();
2073         if (const NamedDecl *ND =
2074                     dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) {
2075           Out << " (";
2076           ND->printName(Out);
2077           Out << ")";
2078         }
2079         break;
2080       }
2081 
2082       case ProgramPoint::BlockExitKind:
2083         assert (false);
2084         break;
2085 
2086       case ProgramPoint::CallEnterKind:
2087         Out << "CallEnter";
2088         break;
2089 
2090       case ProgramPoint::CallExitBeginKind:
2091         Out << "CallExitBegin";
2092         break;
2093 
2094       case ProgramPoint::CallExitEndKind:
2095         Out << "CallExitEnd";
2096         break;
2097 
2098       case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
2099         Out << "PostStmtPurgeDeadSymbols";
2100         break;
2101 
2102       case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
2103         Out << "PreStmtPurgeDeadSymbols";
2104         break;
2105 
2106       case ProgramPoint::EpsilonKind:
2107         Out << "Epsilon Point";
2108         break;
2109 
2110       case ProgramPoint::PreImplicitCallKind: {
2111         ImplicitCallPoint *PC = cast<ImplicitCallPoint>(&Loc);
2112         Out << "PreCall: ";
2113 
2114         // FIXME: Get proper printing options.
2115         PC->getDecl()->print(Out, LangOptions());
2116         printLocation(Out, PC->getLocation());
2117         break;
2118       }
2119 
2120       case ProgramPoint::PostImplicitCallKind: {
2121         ImplicitCallPoint *PC = cast<ImplicitCallPoint>(&Loc);
2122         Out << "PostCall: ";
2123 
2124         // FIXME: Get proper printing options.
2125         PC->getDecl()->print(Out, LangOptions());
2126         printLocation(Out, PC->getLocation());
2127         break;
2128       }
2129 
2130       default: {
2131         if (StmtPoint *L = dyn_cast<StmtPoint>(&Loc)) {
2132           const Stmt *S = L->getStmt();
2133 
2134           Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
2135           LangOptions LO; // FIXME.
2136           S->printPretty(Out, 0, PrintingPolicy(LO));
2137           printLocation(Out, S->getLocStart());
2138 
2139           if (isa<PreStmt>(Loc))
2140             Out << "\\lPreStmt\\l;";
2141           else if (isa<PostLoad>(Loc))
2142             Out << "\\lPostLoad\\l;";
2143           else if (isa<PostStore>(Loc))
2144             Out << "\\lPostStore\\l";
2145           else if (isa<PostLValue>(Loc))
2146             Out << "\\lPostLValue\\l";
2147 
2148 #if 0
2149             // FIXME: Replace with a general scheme to determine
2150             // the name of the check.
2151           if (GraphPrintCheckerState->isImplicitNullDeref(N))
2152             Out << "\\|Implicit-Null Dereference.\\l";
2153           else if (GraphPrintCheckerState->isExplicitNullDeref(N))
2154             Out << "\\|Explicit-Null Dereference.\\l";
2155           else if (GraphPrintCheckerState->isUndefDeref(N))
2156             Out << "\\|Dereference of undefialied value.\\l";
2157           else if (GraphPrintCheckerState->isUndefStore(N))
2158             Out << "\\|Store to Undefined Loc.";
2159           else if (GraphPrintCheckerState->isUndefResult(N))
2160             Out << "\\|Result of operation is undefined.";
2161           else if (GraphPrintCheckerState->isNoReturnCall(N))
2162             Out << "\\|Call to function marked \"noreturn\".";
2163           else if (GraphPrintCheckerState->isBadCall(N))
2164             Out << "\\|Call to NULL/Undefined.";
2165           else if (GraphPrintCheckerState->isUndefArg(N))
2166             Out << "\\|Argument in call is undefined";
2167 #endif
2168 
2169           break;
2170         }
2171 
2172         const BlockEdge &E = cast<BlockEdge>(Loc);
2173         Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
2174             << E.getDst()->getBlockID()  << ')';
2175 
2176         if (const Stmt *T = E.getSrc()->getTerminator()) {
2177 
2178           SourceLocation SLoc = T->getLocStart();
2179 
2180           Out << "\\|Terminator: ";
2181           LangOptions LO; // FIXME.
2182           E.getSrc()->printTerminator(Out, LO);
2183 
2184           if (SLoc.isFileID()) {
2185             Out << "\\lline="
2186               << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2187               << " col="
2188               << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
2189           }
2190 
2191           if (isa<SwitchStmt>(T)) {
2192             const Stmt *Label = E.getDst()->getLabel();
2193 
2194             if (Label) {
2195               if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
2196                 Out << "\\lcase ";
2197                 LangOptions LO; // FIXME.
2198                 C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO));
2199 
2200                 if (const Stmt *RHS = C->getRHS()) {
2201                   Out << " .. ";
2202                   RHS->printPretty(Out, 0, PrintingPolicy(LO));
2203                 }
2204 
2205                 Out << ":";
2206               }
2207               else {
2208                 assert (isa<DefaultStmt>(Label));
2209                 Out << "\\ldefault:";
2210               }
2211             }
2212             else
2213               Out << "\\l(implicit) default:";
2214           }
2215           else if (isa<IndirectGotoStmt>(T)) {
2216             // FIXME
2217           }
2218           else {
2219             Out << "\\lCondition: ";
2220             if (*E.getSrc()->succ_begin() == E.getDst())
2221               Out << "true";
2222             else
2223               Out << "false";
2224           }
2225 
2226           Out << "\\l";
2227         }
2228 
2229 #if 0
2230           // FIXME: Replace with a general scheme to determine
2231           // the name of the check.
2232         if (GraphPrintCheckerState->isUndefControlFlow(N)) {
2233           Out << "\\|Control-flow based on\\lUndefined value.\\l";
2234         }
2235 #endif
2236       }
2237     }
2238 
2239     ProgramStateRef state = N->getState();
2240     Out << "\\|StateID: " << (const void*) state.getPtr()
2241         << " NodeID: " << (const void*) N << "\\|";
2242     state->printDOT(Out);
2243 
2244     Out << "\\l";
2245 
2246     if (const ProgramPointTag *tag = Loc.getTag()) {
2247       Out << "\\|Tag: " << tag->getTagDescription();
2248       Out << "\\l";
2249     }
2250     return Out.str();
2251   }
2252 };
2253 } // end llvm namespace
2254 #endif
2255 
2256 #ifndef NDEBUG
2257 template <typename ITERATOR>
2258 ExplodedNode *GetGraphNode(ITERATOR I) { return *I; }
2259 
2260 template <> ExplodedNode*
2261 GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator>
2262   (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) {
2263   return I->first;
2264 }
2265 #endif
2266 
2267 void ExprEngine::ViewGraph(bool trim) {
2268 #ifndef NDEBUG
2269   if (trim) {
2270     std::vector<ExplodedNode*> Src;
2271 
2272     // Flush any outstanding reports to make sure we cover all the nodes.
2273     // This does not cause them to get displayed.
2274     for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
2275       const_cast<BugType*>(*I)->FlushReports(BR);
2276 
2277     // Iterate through the reports and get their nodes.
2278     for (BugReporter::EQClasses_iterator
2279            EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
2280       ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
2281       if (N) Src.push_back(N);
2282     }
2283 
2284     ViewGraph(&Src[0], &Src[0]+Src.size());
2285   }
2286   else {
2287     GraphPrintCheckerState = this;
2288     GraphPrintSourceManager = &getContext().getSourceManager();
2289 
2290     llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
2291 
2292     GraphPrintCheckerState = NULL;
2293     GraphPrintSourceManager = NULL;
2294   }
2295 #endif
2296 }
2297 
2298 void ExprEngine::ViewGraph(ExplodedNode** Beg, ExplodedNode** End) {
2299 #ifndef NDEBUG
2300   GraphPrintCheckerState = this;
2301   GraphPrintSourceManager = &getContext().getSourceManager();
2302 
2303   std::auto_ptr<ExplodedGraph> TrimmedG(G.Trim(Beg, End).first);
2304 
2305   if (!TrimmedG.get())
2306     llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
2307   else
2308     llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
2309 
2310   GraphPrintCheckerState = NULL;
2311   GraphPrintSourceManager = NULL;
2312 #endif
2313 }
2314