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