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