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