ExprEngine.cpp revision d74324371465a152387ac45e737ab7d23e543552
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 StoreManager::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
1591/// evalBind - Handle the semantics of binding a value to a specific location.
1592///  This method is used by evalStore and (soon) VisitDeclStmt, and others.
1593void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
1594                          ExplodedNode *Pred,
1595                          SVal location, SVal Val,
1596                          bool atDeclInit, const ProgramPoint *PP) {
1597
1598  const LocationContext *LC = Pred->getLocationContext();
1599  PostStmt PS(StoreE, LC);
1600  if (!PP)
1601    PP = &PS;
1602
1603  // Do a previsit of the bind.
1604  ExplodedNodeSet CheckedSet;
1605  getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
1606                                         StoreE, *this, *PP);
1607
1608  // If the location is not a 'Loc', it will already be handled by
1609  // the checkers.  There is nothing left to do.
1610  if (!isa<Loc>(location)) {
1611    Dst = CheckedSet;
1612    return;
1613  }
1614
1615  ExplodedNodeSet TmpDst;
1616  StmtNodeBuilder Bldr(CheckedSet, TmpDst, *currBldrCtx);
1617
1618  for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
1619       I!=E; ++I) {
1620    ExplodedNode *PredI = *I;
1621    ProgramStateRef state = PredI->getState();
1622
1623    // When binding the value, pass on the hint that this is a initialization.
1624    // For initializations, we do not need to inform clients of region
1625    // changes.
1626    state = state->bindLoc(cast<Loc>(location),
1627                           Val, /* notifyChanges = */ !atDeclInit);
1628
1629    const MemRegion *LocReg = 0;
1630    if (loc::MemRegionVal *LocRegVal = dyn_cast<loc::MemRegionVal>(&location)) {
1631      LocReg = LocRegVal->getRegion();
1632    }
1633
1634    const ProgramPoint L = PostStore(StoreE, LC, LocReg, 0);
1635    Bldr.generateNode(L, state, PredI);
1636  }
1637  Dst.insert(TmpDst);
1638}
1639
1640/// evalStore - Handle the semantics of a store via an assignment.
1641///  @param Dst The node set to store generated state nodes
1642///  @param AssignE The assignment expression if the store happens in an
1643///         assignment.
1644///  @param LocationE The location expression that is stored to.
1645///  @param state The current simulation state
1646///  @param location The location to store the value
1647///  @param Val The value to be stored
1648void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
1649                             const Expr *LocationE,
1650                             ExplodedNode *Pred,
1651                             ProgramStateRef state, SVal location, SVal Val,
1652                             const ProgramPointTag *tag) {
1653  // Proceed with the store.  We use AssignE as the anchor for the PostStore
1654  // ProgramPoint if it is non-NULL, and LocationE otherwise.
1655  const Expr *StoreE = AssignE ? AssignE : LocationE;
1656
1657  // Evaluate the location (checks for bad dereferences).
1658  ExplodedNodeSet Tmp;
1659  evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
1660
1661  if (Tmp.empty())
1662    return;
1663
1664  if (location.isUndef())
1665    return;
1666
1667  for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
1668    evalBind(Dst, StoreE, *NI, location, Val, false);
1669}
1670
1671void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
1672                          const Expr *NodeEx,
1673                          const Expr *BoundEx,
1674                          ExplodedNode *Pred,
1675                          ProgramStateRef state,
1676                          SVal location,
1677                          const ProgramPointTag *tag,
1678                          QualType LoadTy)
1679{
1680  assert(!isa<NonLoc>(location) && "location cannot be a NonLoc.");
1681
1682  // Are we loading from a region?  This actually results in two loads; one
1683  // to fetch the address of the referenced value and one to fetch the
1684  // referenced value.
1685  if (const TypedValueRegion *TR =
1686        dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
1687
1688    QualType ValTy = TR->getValueType();
1689    if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
1690      static SimpleProgramPointTag
1691             loadReferenceTag("ExprEngine : Load Reference");
1692      ExplodedNodeSet Tmp;
1693      evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
1694                     location, &loadReferenceTag,
1695                     getContext().getPointerType(RT->getPointeeType()));
1696
1697      // Perform the load from the referenced value.
1698      for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
1699        state = (*I)->getState();
1700        location = state->getSVal(BoundEx, (*I)->getLocationContext());
1701        evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
1702      }
1703      return;
1704    }
1705  }
1706
1707  evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
1708}
1709
1710void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
1711                                const Expr *NodeEx,
1712                                const Expr *BoundEx,
1713                                ExplodedNode *Pred,
1714                                ProgramStateRef state,
1715                                SVal location,
1716                                const ProgramPointTag *tag,
1717                                QualType LoadTy) {
1718  assert(NodeEx);
1719  assert(BoundEx);
1720  // Evaluate the location (checks for bad dereferences).
1721  ExplodedNodeSet Tmp;
1722  evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
1723  if (Tmp.empty())
1724    return;
1725
1726  StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
1727  if (location.isUndef())
1728    return;
1729
1730  // Proceed with the load.
1731  for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
1732    state = (*NI)->getState();
1733    const LocationContext *LCtx = (*NI)->getLocationContext();
1734
1735    SVal V = UnknownVal();
1736    if (location.isValid()) {
1737      if (LoadTy.isNull())
1738        LoadTy = BoundEx->getType();
1739      V = state->getSVal(cast<Loc>(location), LoadTy);
1740    }
1741
1742    Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
1743                      ProgramPoint::PostLoadKind);
1744  }
1745}
1746
1747void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
1748                              const Stmt *NodeEx,
1749                              const Stmt *BoundEx,
1750                              ExplodedNode *Pred,
1751                              ProgramStateRef state,
1752                              SVal location,
1753                              const ProgramPointTag *tag,
1754                              bool isLoad) {
1755  StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
1756  // Early checks for performance reason.
1757  if (location.isUnknown()) {
1758    return;
1759  }
1760
1761  ExplodedNodeSet Src;
1762  BldrTop.takeNodes(Pred);
1763  StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
1764  if (Pred->getState() != state) {
1765    // Associate this new state with an ExplodedNode.
1766    // FIXME: If I pass null tag, the graph is incorrect, e.g for
1767    //   int *p;
1768    //   p = 0;
1769    //   *p = 0xDEADBEEF;
1770    // "p = 0" is not noted as "Null pointer value stored to 'p'" but
1771    // instead "int *p" is noted as
1772    // "Variable 'p' initialized to a null pointer value"
1773
1774    static SimpleProgramPointTag tag("ExprEngine: Location");
1775    Bldr.generateNode(NodeEx, Pred, state, &tag);
1776  }
1777  ExplodedNodeSet Tmp;
1778  getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
1779                                             NodeEx, BoundEx, *this);
1780  BldrTop.addNodes(Tmp);
1781}
1782
1783std::pair<const ProgramPointTag *, const ProgramPointTag*>
1784ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
1785  static SimpleProgramPointTag
1786         eagerlyAssumeBinOpBifurcationTrue("ExprEngine : Eagerly Assume True"),
1787         eagerlyAssumeBinOpBifurcationFalse("ExprEngine : Eagerly Assume False");
1788  return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
1789                        &eagerlyAssumeBinOpBifurcationFalse);
1790}
1791
1792void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
1793                                                   ExplodedNodeSet &Src,
1794                                                   const Expr *Ex) {
1795  StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
1796
1797  for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
1798    ExplodedNode *Pred = *I;
1799    // Test if the previous node was as the same expression.  This can happen
1800    // when the expression fails to evaluate to anything meaningful and
1801    // (as an optimization) we don't generate a node.
1802    ProgramPoint P = Pred->getLocation();
1803    if (!isa<PostStmt>(P) || cast<PostStmt>(P).getStmt() != Ex) {
1804      continue;
1805    }
1806
1807    ProgramStateRef state = Pred->getState();
1808    SVal V = state->getSVal(Ex, Pred->getLocationContext());
1809    nonloc::SymbolVal *SEV = dyn_cast<nonloc::SymbolVal>(&V);
1810    if (SEV && SEV->isExpression()) {
1811      const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
1812        geteagerlyAssumeBinOpBifurcationTags();
1813
1814      ProgramStateRef StateTrue, StateFalse;
1815      tie(StateTrue, StateFalse) = state->assume(*SEV);
1816
1817      // First assume that the condition is true.
1818      if (StateTrue) {
1819        SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
1820        StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
1821        Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
1822      }
1823
1824      // Next, assume that the condition is false.
1825      if (StateFalse) {
1826        SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
1827        StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
1828        Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
1829      }
1830    }
1831  }
1832}
1833
1834void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
1835                                 ExplodedNodeSet &Dst) {
1836  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1837  // We have processed both the inputs and the outputs.  All of the outputs
1838  // should evaluate to Locs.  Nuke all of their values.
1839
1840  // FIXME: Some day in the future it would be nice to allow a "plug-in"
1841  // which interprets the inline asm and stores proper results in the
1842  // outputs.
1843
1844  ProgramStateRef state = Pred->getState();
1845
1846  for (GCCAsmStmt::const_outputs_iterator OI = A->begin_outputs(),
1847       OE = A->end_outputs(); OI != OE; ++OI) {
1848    SVal X = state->getSVal(*OI, Pred->getLocationContext());
1849    assert (!isa<NonLoc>(X));  // Should be an Lval, or unknown, undef.
1850
1851    if (isa<Loc>(X))
1852      state = state->bindLoc(cast<Loc>(X), UnknownVal());
1853  }
1854
1855  Bldr.generateNode(A, Pred, state);
1856}
1857
1858void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
1859                                ExplodedNodeSet &Dst) {
1860  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1861  Bldr.generateNode(A, Pred, Pred->getState());
1862}
1863
1864//===----------------------------------------------------------------------===//
1865// Visualization.
1866//===----------------------------------------------------------------------===//
1867
1868#ifndef NDEBUG
1869static ExprEngine* GraphPrintCheckerState;
1870static SourceManager* GraphPrintSourceManager;
1871
1872namespace llvm {
1873template<>
1874struct DOTGraphTraits<ExplodedNode*> :
1875  public DefaultDOTGraphTraits {
1876
1877  DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
1878
1879  // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
1880  // work.
1881  static std::string getNodeAttributes(const ExplodedNode *N, void*) {
1882
1883#if 0
1884      // FIXME: Replace with a general scheme to tell if the node is
1885      // an error node.
1886    if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
1887        GraphPrintCheckerState->isExplicitNullDeref(N) ||
1888        GraphPrintCheckerState->isUndefDeref(N) ||
1889        GraphPrintCheckerState->isUndefStore(N) ||
1890        GraphPrintCheckerState->isUndefControlFlow(N) ||
1891        GraphPrintCheckerState->isUndefResult(N) ||
1892        GraphPrintCheckerState->isBadCall(N) ||
1893        GraphPrintCheckerState->isUndefArg(N))
1894      return "color=\"red\",style=\"filled\"";
1895
1896    if (GraphPrintCheckerState->isNoReturnCall(N))
1897      return "color=\"blue\",style=\"filled\"";
1898#endif
1899    return "";
1900  }
1901
1902  static void printLocation(llvm::raw_ostream &Out, SourceLocation SLoc) {
1903    if (SLoc.isFileID()) {
1904      Out << "\\lline="
1905        << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
1906        << " col="
1907        << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
1908        << "\\l";
1909    }
1910  }
1911
1912  static std::string getNodeLabel(const ExplodedNode *N, void*){
1913
1914    std::string sbuf;
1915    llvm::raw_string_ostream Out(sbuf);
1916
1917    // Program Location.
1918    ProgramPoint Loc = N->getLocation();
1919
1920    switch (Loc.getKind()) {
1921      case ProgramPoint::BlockEntranceKind: {
1922        Out << "Block Entrance: B"
1923            << cast<BlockEntrance>(Loc).getBlock()->getBlockID();
1924        if (const NamedDecl *ND =
1925                    dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) {
1926          Out << " (";
1927          ND->printName(Out);
1928          Out << ")";
1929        }
1930        break;
1931      }
1932
1933      case ProgramPoint::BlockExitKind:
1934        assert (false);
1935        break;
1936
1937      case ProgramPoint::CallEnterKind:
1938        Out << "CallEnter";
1939        break;
1940
1941      case ProgramPoint::CallExitBeginKind:
1942        Out << "CallExitBegin";
1943        break;
1944
1945      case ProgramPoint::CallExitEndKind:
1946        Out << "CallExitEnd";
1947        break;
1948
1949      case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
1950        Out << "PostStmtPurgeDeadSymbols";
1951        break;
1952
1953      case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
1954        Out << "PreStmtPurgeDeadSymbols";
1955        break;
1956
1957      case ProgramPoint::EpsilonKind:
1958        Out << "Epsilon Point";
1959        break;
1960
1961      case ProgramPoint::PreImplicitCallKind: {
1962        ImplicitCallPoint *PC = cast<ImplicitCallPoint>(&Loc);
1963        Out << "PreCall: ";
1964
1965        // FIXME: Get proper printing options.
1966        PC->getDecl()->print(Out, LangOptions());
1967        printLocation(Out, PC->getLocation());
1968        break;
1969      }
1970
1971      case ProgramPoint::PostImplicitCallKind: {
1972        ImplicitCallPoint *PC = cast<ImplicitCallPoint>(&Loc);
1973        Out << "PostCall: ";
1974
1975        // FIXME: Get proper printing options.
1976        PC->getDecl()->print(Out, LangOptions());
1977        printLocation(Out, PC->getLocation());
1978        break;
1979      }
1980
1981      default: {
1982        if (StmtPoint *L = dyn_cast<StmtPoint>(&Loc)) {
1983          const Stmt *S = L->getStmt();
1984
1985          Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
1986          LangOptions LO; // FIXME.
1987          S->printPretty(Out, 0, PrintingPolicy(LO));
1988          printLocation(Out, S->getLocStart());
1989
1990          if (isa<PreStmt>(Loc))
1991            Out << "\\lPreStmt\\l;";
1992          else if (isa<PostLoad>(Loc))
1993            Out << "\\lPostLoad\\l;";
1994          else if (isa<PostStore>(Loc))
1995            Out << "\\lPostStore\\l";
1996          else if (isa<PostLValue>(Loc))
1997            Out << "\\lPostLValue\\l";
1998
1999#if 0
2000            // FIXME: Replace with a general scheme to determine
2001            // the name of the check.
2002          if (GraphPrintCheckerState->isImplicitNullDeref(N))
2003            Out << "\\|Implicit-Null Dereference.\\l";
2004          else if (GraphPrintCheckerState->isExplicitNullDeref(N))
2005            Out << "\\|Explicit-Null Dereference.\\l";
2006          else if (GraphPrintCheckerState->isUndefDeref(N))
2007            Out << "\\|Dereference of undefialied value.\\l";
2008          else if (GraphPrintCheckerState->isUndefStore(N))
2009            Out << "\\|Store to Undefined Loc.";
2010          else if (GraphPrintCheckerState->isUndefResult(N))
2011            Out << "\\|Result of operation is undefined.";
2012          else if (GraphPrintCheckerState->isNoReturnCall(N))
2013            Out << "\\|Call to function marked \"noreturn\".";
2014          else if (GraphPrintCheckerState->isBadCall(N))
2015            Out << "\\|Call to NULL/Undefined.";
2016          else if (GraphPrintCheckerState->isUndefArg(N))
2017            Out << "\\|Argument in call is undefined";
2018#endif
2019
2020          break;
2021        }
2022
2023        const BlockEdge &E = cast<BlockEdge>(Loc);
2024        Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
2025            << E.getDst()->getBlockID()  << ')';
2026
2027        if (const Stmt *T = E.getSrc()->getTerminator()) {
2028
2029          SourceLocation SLoc = T->getLocStart();
2030
2031          Out << "\\|Terminator: ";
2032          LangOptions LO; // FIXME.
2033          E.getSrc()->printTerminator(Out, LO);
2034
2035          if (SLoc.isFileID()) {
2036            Out << "\\lline="
2037              << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2038              << " col="
2039              << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
2040          }
2041
2042          if (isa<SwitchStmt>(T)) {
2043            const Stmt *Label = E.getDst()->getLabel();
2044
2045            if (Label) {
2046              if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
2047                Out << "\\lcase ";
2048                LangOptions LO; // FIXME.
2049                C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO));
2050
2051                if (const Stmt *RHS = C->getRHS()) {
2052                  Out << " .. ";
2053                  RHS->printPretty(Out, 0, PrintingPolicy(LO));
2054                }
2055
2056                Out << ":";
2057              }
2058              else {
2059                assert (isa<DefaultStmt>(Label));
2060                Out << "\\ldefault:";
2061              }
2062            }
2063            else
2064              Out << "\\l(implicit) default:";
2065          }
2066          else if (isa<IndirectGotoStmt>(T)) {
2067            // FIXME
2068          }
2069          else {
2070            Out << "\\lCondition: ";
2071            if (*E.getSrc()->succ_begin() == E.getDst())
2072              Out << "true";
2073            else
2074              Out << "false";
2075          }
2076
2077          Out << "\\l";
2078        }
2079
2080#if 0
2081          // FIXME: Replace with a general scheme to determine
2082          // the name of the check.
2083        if (GraphPrintCheckerState->isUndefControlFlow(N)) {
2084          Out << "\\|Control-flow based on\\lUndefined value.\\l";
2085        }
2086#endif
2087      }
2088    }
2089
2090    ProgramStateRef state = N->getState();
2091    Out << "\\|StateID: " << (const void*) state.getPtr()
2092        << " NodeID: " << (const void*) N << "\\|";
2093    state->printDOT(Out);
2094
2095    Out << "\\l";
2096
2097    if (const ProgramPointTag *tag = Loc.getTag()) {
2098      Out << "\\|Tag: " << tag->getTagDescription();
2099      Out << "\\l";
2100    }
2101    return Out.str();
2102  }
2103};
2104} // end llvm namespace
2105#endif
2106
2107#ifndef NDEBUG
2108template <typename ITERATOR>
2109ExplodedNode *GetGraphNode(ITERATOR I) { return *I; }
2110
2111template <> ExplodedNode*
2112GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator>
2113  (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) {
2114  return I->first;
2115}
2116#endif
2117
2118void ExprEngine::ViewGraph(bool trim) {
2119#ifndef NDEBUG
2120  if (trim) {
2121    std::vector<ExplodedNode*> Src;
2122
2123    // Flush any outstanding reports to make sure we cover all the nodes.
2124    // This does not cause them to get displayed.
2125    for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
2126      const_cast<BugType*>(*I)->FlushReports(BR);
2127
2128    // Iterate through the reports and get their nodes.
2129    for (BugReporter::EQClasses_iterator
2130           EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
2131      ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
2132      if (N) Src.push_back(N);
2133    }
2134
2135    ViewGraph(&Src[0], &Src[0]+Src.size());
2136  }
2137  else {
2138    GraphPrintCheckerState = this;
2139    GraphPrintSourceManager = &getContext().getSourceManager();
2140
2141    llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
2142
2143    GraphPrintCheckerState = NULL;
2144    GraphPrintSourceManager = NULL;
2145  }
2146#endif
2147}
2148
2149void ExprEngine::ViewGraph(ExplodedNode** Beg, ExplodedNode** End) {
2150#ifndef NDEBUG
2151  GraphPrintCheckerState = this;
2152  GraphPrintSourceManager = &getContext().getSourceManager();
2153
2154  std::auto_ptr<ExplodedGraph> TrimmedG(G.Trim(Beg, End).first);
2155
2156  if (!TrimmedG.get())
2157    llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
2158  else
2159    llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
2160
2161  GraphPrintCheckerState = NULL;
2162  GraphPrintSourceManager = NULL;
2163#endif
2164}
2165