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