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