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