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