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