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