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