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