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     case Stmt::OMPTaskLoopDirectiveClass:
833     case Stmt::OMPTaskLoopSimdDirectiveClass:
834     case Stmt::OMPDistributeDirectiveClass:
835       llvm_unreachable("Stmt should not be in analyzer evaluation loop");
836 
837     case Stmt::ObjCSubscriptRefExprClass:
838     case Stmt::ObjCPropertyRefExprClass:
839       llvm_unreachable("These are handled by PseudoObjectExpr");
840 
841     case Stmt::GNUNullExprClass: {
842       // GNU __null is a pointer-width integer, not an actual pointer.
843       ProgramStateRef state = Pred->getState();
844       state = state->BindExpr(S, Pred->getLocationContext(),
845                               svalBuilder.makeIntValWithPtrWidth(0, false));
846       Bldr.generateNode(S, Pred, state);
847       break;
848     }
849 
850     case Stmt::ObjCAtSynchronizedStmtClass:
851       Bldr.takeNodes(Pred);
852       VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
853       Bldr.addNodes(Dst);
854       break;
855 
856     case Stmt::ExprWithCleanupsClass:
857       // Handled due to fully linearised CFG.
858       break;
859 
860     case Stmt::CXXBindTemporaryExprClass: {
861       Bldr.takeNodes(Pred);
862       ExplodedNodeSet PreVisit;
863       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
864       ExplodedNodeSet Next;
865       VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
866       getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
867       Bldr.addNodes(Dst);
868       break;
869     }
870 
871     // Cases not handled yet; but will handle some day.
872     case Stmt::DesignatedInitExprClass:
873     case Stmt::DesignatedInitUpdateExprClass:
874     case Stmt::ExtVectorElementExprClass:
875     case Stmt::ImaginaryLiteralClass:
876     case Stmt::ObjCAtCatchStmtClass:
877     case Stmt::ObjCAtFinallyStmtClass:
878     case Stmt::ObjCAtTryStmtClass:
879     case Stmt::ObjCAutoreleasePoolStmtClass:
880     case Stmt::ObjCEncodeExprClass:
881     case Stmt::ObjCIsaExprClass:
882     case Stmt::ObjCProtocolExprClass:
883     case Stmt::ObjCSelectorExprClass:
884     case Stmt::ParenListExprClass:
885     case Stmt::ShuffleVectorExprClass:
886     case Stmt::ConvertVectorExprClass:
887     case Stmt::VAArgExprClass:
888     case Stmt::CUDAKernelCallExprClass:
889     case Stmt::OpaqueValueExprClass:
890     case Stmt::AsTypeExprClass:
891     case Stmt::AtomicExprClass:
892       // Fall through.
893 
894     // Cases we intentionally don't evaluate, since they don't need
895     // to be explicitly evaluated.
896     case Stmt::PredefinedExprClass:
897     case Stmt::AddrLabelExprClass:
898     case Stmt::AttributedStmtClass:
899     case Stmt::IntegerLiteralClass:
900     case Stmt::CharacterLiteralClass:
901     case Stmt::ImplicitValueInitExprClass:
902     case Stmt::CXXScalarValueInitExprClass:
903     case Stmt::CXXBoolLiteralExprClass:
904     case Stmt::ObjCBoolLiteralExprClass:
905     case Stmt::FloatingLiteralClass:
906     case Stmt::NoInitExprClass:
907     case Stmt::SizeOfPackExprClass:
908     case Stmt::StringLiteralClass:
909     case Stmt::ObjCStringLiteralClass:
910     case Stmt::CXXPseudoDestructorExprClass:
911     case Stmt::SubstNonTypeTemplateParmExprClass:
912     case Stmt::CXXNullPtrLiteralExprClass:
913     case Stmt::OMPArraySectionExprClass:
914     case Stmt::TypeTraitExprClass: {
915       Bldr.takeNodes(Pred);
916       ExplodedNodeSet preVisit;
917       getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
918       getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
919       Bldr.addNodes(Dst);
920       break;
921     }
922 
923     case Stmt::CXXDefaultArgExprClass:
924     case Stmt::CXXDefaultInitExprClass: {
925       Bldr.takeNodes(Pred);
926       ExplodedNodeSet PreVisit;
927       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
928 
929       ExplodedNodeSet Tmp;
930       StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
931 
932       const Expr *ArgE;
933       if (const CXXDefaultArgExpr *DefE = dyn_cast<CXXDefaultArgExpr>(S))
934         ArgE = DefE->getExpr();
935       else if (const CXXDefaultInitExpr *DefE = dyn_cast<CXXDefaultInitExpr>(S))
936         ArgE = DefE->getExpr();
937       else
938         llvm_unreachable("unknown constant wrapper kind");
939 
940       bool IsTemporary = false;
941       if (const MaterializeTemporaryExpr *MTE =
942             dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
943         ArgE = MTE->GetTemporaryExpr();
944         IsTemporary = true;
945       }
946 
947       Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
948       if (!ConstantVal)
949         ConstantVal = UnknownVal();
950 
951       const LocationContext *LCtx = Pred->getLocationContext();
952       for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end();
953            I != E; ++I) {
954         ProgramStateRef State = (*I)->getState();
955         State = State->BindExpr(S, LCtx, *ConstantVal);
956         if (IsTemporary)
957           State = createTemporaryRegionIfNeeded(State, LCtx,
958                                                 cast<Expr>(S),
959                                                 cast<Expr>(S));
960         Bldr2.generateNode(S, *I, State);
961       }
962 
963       getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
964       Bldr.addNodes(Dst);
965       break;
966     }
967 
968     // Cases we evaluate as opaque expressions, conjuring a symbol.
969     case Stmt::CXXStdInitializerListExprClass:
970     case Expr::ObjCArrayLiteralClass:
971     case Expr::ObjCDictionaryLiteralClass:
972     case Expr::ObjCBoxedExprClass: {
973       Bldr.takeNodes(Pred);
974 
975       ExplodedNodeSet preVisit;
976       getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
977 
978       ExplodedNodeSet Tmp;
979       StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
980 
981       const Expr *Ex = cast<Expr>(S);
982       QualType resultType = Ex->getType();
983 
984       for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end();
985            it != et; ++it) {
986         ExplodedNode *N = *it;
987         const LocationContext *LCtx = N->getLocationContext();
988         SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
989                                                    resultType,
990                                                    currBldrCtx->blockCount());
991         ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result);
992         Bldr2.generateNode(S, N, state);
993       }
994 
995       getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
996       Bldr.addNodes(Dst);
997       break;
998     }
999 
1000     case Stmt::ArraySubscriptExprClass:
1001       Bldr.takeNodes(Pred);
1002       VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
1003       Bldr.addNodes(Dst);
1004       break;
1005 
1006     case Stmt::GCCAsmStmtClass:
1007       Bldr.takeNodes(Pred);
1008       VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
1009       Bldr.addNodes(Dst);
1010       break;
1011 
1012     case Stmt::MSAsmStmtClass:
1013       Bldr.takeNodes(Pred);
1014       VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
1015       Bldr.addNodes(Dst);
1016       break;
1017 
1018     case Stmt::BlockExprClass:
1019       Bldr.takeNodes(Pred);
1020       VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
1021       Bldr.addNodes(Dst);
1022       break;
1023 
1024     case Stmt::LambdaExprClass:
1025       if (AMgr.options.shouldInlineLambdas()) {
1026         Bldr.takeNodes(Pred);
1027         VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
1028         Bldr.addNodes(Dst);
1029       } else {
1030         const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1031         Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1032       }
1033       break;
1034 
1035     case Stmt::BinaryOperatorClass: {
1036       const BinaryOperator* B = cast<BinaryOperator>(S);
1037       if (B->isLogicalOp()) {
1038         Bldr.takeNodes(Pred);
1039         VisitLogicalExpr(B, Pred, Dst);
1040         Bldr.addNodes(Dst);
1041         break;
1042       }
1043       else if (B->getOpcode() == BO_Comma) {
1044         ProgramStateRef state = Pred->getState();
1045         Bldr.generateNode(B, Pred,
1046                           state->BindExpr(B, Pred->getLocationContext(),
1047                                           state->getSVal(B->getRHS(),
1048                                                   Pred->getLocationContext())));
1049         break;
1050       }
1051 
1052       Bldr.takeNodes(Pred);
1053 
1054       if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
1055           (B->isRelationalOp() || B->isEqualityOp())) {
1056         ExplodedNodeSet Tmp;
1057         VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
1058         evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
1059       }
1060       else
1061         VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1062 
1063       Bldr.addNodes(Dst);
1064       break;
1065     }
1066 
1067     case Stmt::CXXOperatorCallExprClass: {
1068       const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S);
1069 
1070       // For instance method operators, make sure the 'this' argument has a
1071       // valid region.
1072       const Decl *Callee = OCE->getCalleeDecl();
1073       if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
1074         if (MD->isInstance()) {
1075           ProgramStateRef State = Pred->getState();
1076           const LocationContext *LCtx = Pred->getLocationContext();
1077           ProgramStateRef NewState =
1078             createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
1079           if (NewState != State) {
1080             Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
1081                                      ProgramPoint::PreStmtKind);
1082             // Did we cache out?
1083             if (!Pred)
1084               break;
1085           }
1086         }
1087       }
1088       // FALLTHROUGH
1089     }
1090     case Stmt::CallExprClass:
1091     case Stmt::CXXMemberCallExprClass:
1092     case Stmt::UserDefinedLiteralClass: {
1093       Bldr.takeNodes(Pred);
1094       VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
1095       Bldr.addNodes(Dst);
1096       break;
1097     }
1098 
1099     case Stmt::CXXCatchStmtClass: {
1100       Bldr.takeNodes(Pred);
1101       VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
1102       Bldr.addNodes(Dst);
1103       break;
1104     }
1105 
1106     case Stmt::CXXTemporaryObjectExprClass:
1107     case Stmt::CXXConstructExprClass: {
1108       Bldr.takeNodes(Pred);
1109       VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
1110       Bldr.addNodes(Dst);
1111       break;
1112     }
1113 
1114     case Stmt::CXXNewExprClass: {
1115       Bldr.takeNodes(Pred);
1116       ExplodedNodeSet PostVisit;
1117       VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit);
1118       getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1119       Bldr.addNodes(Dst);
1120       break;
1121     }
1122 
1123     case Stmt::CXXDeleteExprClass: {
1124       Bldr.takeNodes(Pred);
1125       ExplodedNodeSet PreVisit;
1126       const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
1127       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1128 
1129       for (ExplodedNodeSet::iterator i = PreVisit.begin(),
1130                                      e = PreVisit.end(); i != e ; ++i)
1131         VisitCXXDeleteExpr(CDE, *i, Dst);
1132 
1133       Bldr.addNodes(Dst);
1134       break;
1135     }
1136       // FIXME: ChooseExpr is really a constant.  We need to fix
1137       //        the CFG do not model them as explicit control-flow.
1138 
1139     case Stmt::ChooseExprClass: { // __builtin_choose_expr
1140       Bldr.takeNodes(Pred);
1141       const ChooseExpr *C = cast<ChooseExpr>(S);
1142       VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
1143       Bldr.addNodes(Dst);
1144       break;
1145     }
1146 
1147     case Stmt::CompoundAssignOperatorClass:
1148       Bldr.takeNodes(Pred);
1149       VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1150       Bldr.addNodes(Dst);
1151       break;
1152 
1153     case Stmt::CompoundLiteralExprClass:
1154       Bldr.takeNodes(Pred);
1155       VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
1156       Bldr.addNodes(Dst);
1157       break;
1158 
1159     case Stmt::BinaryConditionalOperatorClass:
1160     case Stmt::ConditionalOperatorClass: { // '?' operator
1161       Bldr.takeNodes(Pred);
1162       const AbstractConditionalOperator *C
1163         = cast<AbstractConditionalOperator>(S);
1164       VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
1165       Bldr.addNodes(Dst);
1166       break;
1167     }
1168 
1169     case Stmt::CXXThisExprClass:
1170       Bldr.takeNodes(Pred);
1171       VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
1172       Bldr.addNodes(Dst);
1173       break;
1174 
1175     case Stmt::DeclRefExprClass: {
1176       Bldr.takeNodes(Pred);
1177       const DeclRefExpr *DE = cast<DeclRefExpr>(S);
1178       VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
1179       Bldr.addNodes(Dst);
1180       break;
1181     }
1182 
1183     case Stmt::DeclStmtClass:
1184       Bldr.takeNodes(Pred);
1185       VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
1186       Bldr.addNodes(Dst);
1187       break;
1188 
1189     case Stmt::ImplicitCastExprClass:
1190     case Stmt::CStyleCastExprClass:
1191     case Stmt::CXXStaticCastExprClass:
1192     case Stmt::CXXDynamicCastExprClass:
1193     case Stmt::CXXReinterpretCastExprClass:
1194     case Stmt::CXXConstCastExprClass:
1195     case Stmt::CXXFunctionalCastExprClass:
1196     case Stmt::ObjCBridgedCastExprClass: {
1197       Bldr.takeNodes(Pred);
1198       const CastExpr *C = cast<CastExpr>(S);
1199       // Handle the previsit checks.
1200       ExplodedNodeSet dstPrevisit;
1201       getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this);
1202 
1203       // Handle the expression itself.
1204       ExplodedNodeSet dstExpr;
1205       for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
1206                                      e = dstPrevisit.end(); i != e ; ++i) {
1207         VisitCast(C, C->getSubExpr(), *i, dstExpr);
1208       }
1209 
1210       // Handle the postvisit checks.
1211       getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1212       Bldr.addNodes(Dst);
1213       break;
1214     }
1215 
1216     case Expr::MaterializeTemporaryExprClass: {
1217       Bldr.takeNodes(Pred);
1218       const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
1219       CreateCXXTemporaryObject(MTE, Pred, Dst);
1220       Bldr.addNodes(Dst);
1221       break;
1222     }
1223 
1224     case Stmt::InitListExprClass:
1225       Bldr.takeNodes(Pred);
1226       VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1227       Bldr.addNodes(Dst);
1228       break;
1229 
1230     case Stmt::MemberExprClass:
1231       Bldr.takeNodes(Pred);
1232       VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1233       Bldr.addNodes(Dst);
1234       break;
1235 
1236     case Stmt::ObjCIvarRefExprClass:
1237       Bldr.takeNodes(Pred);
1238       VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1239       Bldr.addNodes(Dst);
1240       break;
1241 
1242     case Stmt::ObjCForCollectionStmtClass:
1243       Bldr.takeNodes(Pred);
1244       VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1245       Bldr.addNodes(Dst);
1246       break;
1247 
1248     case Stmt::ObjCMessageExprClass:
1249       Bldr.takeNodes(Pred);
1250       VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1251       Bldr.addNodes(Dst);
1252       break;
1253 
1254     case Stmt::ObjCAtThrowStmtClass:
1255     case Stmt::CXXThrowExprClass:
1256       // FIXME: This is not complete.  We basically treat @throw as
1257       // an abort.
1258       Bldr.generateSink(S, Pred, Pred->getState());
1259       break;
1260 
1261     case Stmt::ReturnStmtClass:
1262       Bldr.takeNodes(Pred);
1263       VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1264       Bldr.addNodes(Dst);
1265       break;
1266 
1267     case Stmt::OffsetOfExprClass:
1268       Bldr.takeNodes(Pred);
1269       VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
1270       Bldr.addNodes(Dst);
1271       break;
1272 
1273     case Stmt::UnaryExprOrTypeTraitExprClass:
1274       Bldr.takeNodes(Pred);
1275       VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1276                                     Pred, Dst);
1277       Bldr.addNodes(Dst);
1278       break;
1279 
1280     case Stmt::StmtExprClass: {
1281       const StmtExpr *SE = cast<StmtExpr>(S);
1282 
1283       if (SE->getSubStmt()->body_empty()) {
1284         // Empty statement expression.
1285         assert(SE->getType() == getContext().VoidTy
1286                && "Empty statement expression must have void type.");
1287         break;
1288       }
1289 
1290       if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1291         ProgramStateRef state = Pred->getState();
1292         Bldr.generateNode(SE, Pred,
1293                           state->BindExpr(SE, Pred->getLocationContext(),
1294                                           state->getSVal(LastExpr,
1295                                                   Pred->getLocationContext())));
1296       }
1297       break;
1298     }
1299 
1300     case Stmt::UnaryOperatorClass: {
1301       Bldr.takeNodes(Pred);
1302       const UnaryOperator *U = cast<UnaryOperator>(S);
1303       if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
1304         ExplodedNodeSet Tmp;
1305         VisitUnaryOperator(U, Pred, Tmp);
1306         evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1307       }
1308       else
1309         VisitUnaryOperator(U, Pred, Dst);
1310       Bldr.addNodes(Dst);
1311       break;
1312     }
1313 
1314     case Stmt::PseudoObjectExprClass: {
1315       Bldr.takeNodes(Pred);
1316       ProgramStateRef state = Pred->getState();
1317       const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
1318       if (const Expr *Result = PE->getResultExpr()) {
1319         SVal V = state->getSVal(Result, Pred->getLocationContext());
1320         Bldr.generateNode(S, Pred,
1321                           state->BindExpr(S, Pred->getLocationContext(), V));
1322       }
1323       else
1324         Bldr.generateNode(S, Pred,
1325                           state->BindExpr(S, Pred->getLocationContext(),
1326                                                    UnknownVal()));
1327 
1328       Bldr.addNodes(Dst);
1329       break;
1330     }
1331   }
1332 }
1333 
1334 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1335                                        const LocationContext *CalleeLC) {
1336   const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1337   const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
1338   assert(CalleeSF && CallerSF);
1339   ExplodedNode *BeforeProcessingCall = nullptr;
1340   const Stmt *CE = CalleeSF->getCallSite();
1341 
1342   // Find the first node before we started processing the call expression.
1343   while (N) {
1344     ProgramPoint L = N->getLocation();
1345     BeforeProcessingCall = N;
1346     N = N->pred_empty() ? nullptr : *(N->pred_begin());
1347 
1348     // Skip the nodes corresponding to the inlined code.
1349     if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
1350       continue;
1351     // We reached the caller. Find the node right before we started
1352     // processing the call.
1353     if (L.isPurgeKind())
1354       continue;
1355     if (L.getAs<PreImplicitCall>())
1356       continue;
1357     if (L.getAs<CallEnter>())
1358       continue;
1359     if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1360       if (SP->getStmt() == CE)
1361         continue;
1362     break;
1363   }
1364 
1365   if (!BeforeProcessingCall)
1366     return false;
1367 
1368   // TODO: Clean up the unneeded nodes.
1369 
1370   // Build an Epsilon node from which we will restart the analyzes.
1371   // Note that CE is permitted to be NULL!
1372   ProgramPoint NewNodeLoc =
1373                EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1374   // Add the special flag to GDM to signal retrying with no inlining.
1375   // Note, changing the state ensures that we are not going to cache out.
1376   ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1377   NewNodeState =
1378     NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1379 
1380   // Make the new node a successor of BeforeProcessingCall.
1381   bool IsNew = false;
1382   ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1383   // We cached out at this point. Caching out is common due to us backtracking
1384   // from the inlined function, which might spawn several paths.
1385   if (!IsNew)
1386     return true;
1387 
1388   NewNode->addPredecessor(BeforeProcessingCall, G);
1389 
1390   // Add the new node to the work list.
1391   Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1392                                   CalleeSF->getIndex());
1393   NumTimesRetriedWithoutInlining++;
1394   return true;
1395 }
1396 
1397 /// Block entrance.  (Update counters).
1398 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
1399                                          NodeBuilderWithSinks &nodeBuilder,
1400                                          ExplodedNode *Pred) {
1401   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1402 
1403   // If this block is terminated by a loop and it has already been visited the
1404   // maximum number of times, widen the loop.
1405   unsigned int BlockCount = nodeBuilder.getContext().blockCount();
1406   if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
1407       AMgr.options.shouldWidenLoops()) {
1408     const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
1409     if (!(Term &&
1410           (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
1411       return;
1412     // Widen.
1413     const LocationContext *LCtx = Pred->getLocationContext();
1414     ProgramStateRef WidenedState =
1415         getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
1416     nodeBuilder.generateNode(WidenedState, Pred);
1417     return;
1418   }
1419 
1420   // FIXME: Refactor this into a checker.
1421   if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
1422     static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
1423     const ExplodedNode *Sink =
1424                    nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1425 
1426     // Check if we stopped at the top level function or not.
1427     // Root node should have the location context of the top most function.
1428     const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1429     const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1430     const LocationContext *RootLC =
1431                         (*G.roots_begin())->getLocation().getLocationContext();
1432     if (RootLC->getCurrentStackFrame() != CalleeSF) {
1433       Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1434 
1435       // Re-run the call evaluation without inlining it, by storing the
1436       // no-inlining policy in the state and enqueuing the new work item on
1437       // the list. Replay should almost never fail. Use the stats to catch it
1438       // if it does.
1439       if ((!AMgr.options.NoRetryExhausted &&
1440            replayWithoutInlining(Pred, CalleeLC)))
1441         return;
1442       NumMaxBlockCountReachedInInlined++;
1443     } else
1444       NumMaxBlockCountReached++;
1445 
1446     // Make sink nodes as exhausted(for stats) only if retry failed.
1447     Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1448   }
1449 }
1450 
1451 //===----------------------------------------------------------------------===//
1452 // Branch processing.
1453 //===----------------------------------------------------------------------===//
1454 
1455 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1456 /// to try to recover some path-sensitivity for casts of symbolic
1457 /// integers that promote their values (which are currently not tracked well).
1458 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1459 //  cast(s) did was sign-extend the original value.
1460 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
1461                                 ProgramStateRef state,
1462                                 const Stmt *Condition,
1463                                 const LocationContext *LCtx,
1464                                 ASTContext &Ctx) {
1465 
1466   const Expr *Ex = dyn_cast<Expr>(Condition);
1467   if (!Ex)
1468     return UnknownVal();
1469 
1470   uint64_t bits = 0;
1471   bool bitsInit = false;
1472 
1473   while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
1474     QualType T = CE->getType();
1475 
1476     if (!T->isIntegralOrEnumerationType())
1477       return UnknownVal();
1478 
1479     uint64_t newBits = Ctx.getTypeSize(T);
1480     if (!bitsInit || newBits < bits) {
1481       bitsInit = true;
1482       bits = newBits;
1483     }
1484 
1485     Ex = CE->getSubExpr();
1486   }
1487 
1488   // We reached a non-cast.  Is it a symbolic value?
1489   QualType T = Ex->getType();
1490 
1491   if (!bitsInit || !T->isIntegralOrEnumerationType() ||
1492       Ctx.getTypeSize(T) > bits)
1493     return UnknownVal();
1494 
1495   return state->getSVal(Ex, LCtx);
1496 }
1497 
1498 #ifndef NDEBUG
1499 static const Stmt *getRightmostLeaf(const Stmt *Condition) {
1500   while (Condition) {
1501     const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1502     if (!BO || !BO->isLogicalOp()) {
1503       return Condition;
1504     }
1505     Condition = BO->getRHS()->IgnoreParens();
1506   }
1507   return nullptr;
1508 }
1509 #endif
1510 
1511 // Returns the condition the branch at the end of 'B' depends on and whose value
1512 // has been evaluated within 'B'.
1513 // In most cases, the terminator condition of 'B' will be evaluated fully in
1514 // the last statement of 'B'; in those cases, the resolved condition is the
1515 // given 'Condition'.
1516 // If the condition of the branch is a logical binary operator tree, the CFG is
1517 // optimized: in that case, we know that the expression formed by all but the
1518 // rightmost leaf of the logical binary operator tree must be true, and thus
1519 // the branch condition is at this point equivalent to the truth value of that
1520 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
1521 // expression in its final statement. As the full condition in that case was
1522 // not evaluated, and is thus not in the SVal cache, we need to use that leaf
1523 // expression to evaluate the truth value of the condition in the current state
1524 // space.
1525 static const Stmt *ResolveCondition(const Stmt *Condition,
1526                                     const CFGBlock *B) {
1527   if (const Expr *Ex = dyn_cast<Expr>(Condition))
1528     Condition = Ex->IgnoreParens();
1529 
1530   const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1531   if (!BO || !BO->isLogicalOp())
1532     return Condition;
1533 
1534   assert(!B->getTerminator().isTemporaryDtorsBranch() &&
1535          "Temporary destructor branches handled by processBindTemporary.");
1536 
1537   // For logical operations, we still have the case where some branches
1538   // use the traditional "merge" approach and others sink the branch
1539   // directly into the basic blocks representing the logical operation.
1540   // We need to distinguish between those two cases here.
1541 
1542   // The invariants are still shifting, but it is possible that the
1543   // last element in a CFGBlock is not a CFGStmt.  Look for the last
1544   // CFGStmt as the value of the condition.
1545   CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
1546   for (; I != E; ++I) {
1547     CFGElement Elem = *I;
1548     Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
1549     if (!CS)
1550       continue;
1551     const Stmt *LastStmt = CS->getStmt();
1552     assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
1553     return LastStmt;
1554   }
1555   llvm_unreachable("could not resolve condition");
1556 }
1557 
1558 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
1559                                NodeBuilderContext& BldCtx,
1560                                ExplodedNode *Pred,
1561                                ExplodedNodeSet &Dst,
1562                                const CFGBlock *DstT,
1563                                const CFGBlock *DstF) {
1564   assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
1565          "CXXBindTemporaryExprs are handled by processBindTemporary.");
1566   const LocationContext *LCtx = Pred->getLocationContext();
1567   PrettyStackTraceLocationContext StackCrashInfo(LCtx);
1568   currBldrCtx = &BldCtx;
1569 
1570   // Check for NULL conditions; e.g. "for(;;)"
1571   if (!Condition) {
1572     BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
1573     NullCondBldr.markInfeasible(false);
1574     NullCondBldr.generateNode(Pred->getState(), true, Pred);
1575     return;
1576   }
1577 
1578 
1579   if (const Expr *Ex = dyn_cast<Expr>(Condition))
1580     Condition = Ex->IgnoreParens();
1581 
1582   Condition = ResolveCondition(Condition, BldCtx.getBlock());
1583   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1584                                 Condition->getLocStart(),
1585                                 "Error evaluating branch");
1586 
1587   ExplodedNodeSet CheckersOutSet;
1588   getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
1589                                                     Pred, *this);
1590   // We generated only sinks.
1591   if (CheckersOutSet.empty())
1592     return;
1593 
1594   BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
1595   for (NodeBuilder::iterator I = CheckersOutSet.begin(),
1596                              E = CheckersOutSet.end(); E != I; ++I) {
1597     ExplodedNode *PredI = *I;
1598 
1599     if (PredI->isSink())
1600       continue;
1601 
1602     ProgramStateRef PrevState = PredI->getState();
1603     SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
1604 
1605     if (X.isUnknownOrUndef()) {
1606       // Give it a chance to recover from unknown.
1607       if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
1608         if (Ex->getType()->isIntegralOrEnumerationType()) {
1609           // Try to recover some path-sensitivity.  Right now casts of symbolic
1610           // integers that promote their values are currently not tracked well.
1611           // If 'Condition' is such an expression, try and recover the
1612           // underlying value and use that instead.
1613           SVal recovered = RecoverCastedSymbol(getStateManager(),
1614                                                PrevState, Condition,
1615                                                PredI->getLocationContext(),
1616                                                getContext());
1617 
1618           if (!recovered.isUnknown()) {
1619             X = recovered;
1620           }
1621         }
1622       }
1623     }
1624 
1625     // If the condition is still unknown, give up.
1626     if (X.isUnknownOrUndef()) {
1627       builder.generateNode(PrevState, true, PredI);
1628       builder.generateNode(PrevState, false, PredI);
1629       continue;
1630     }
1631 
1632     DefinedSVal V = X.castAs<DefinedSVal>();
1633 
1634     ProgramStateRef StTrue, StFalse;
1635     std::tie(StTrue, StFalse) = PrevState->assume(V);
1636 
1637     // Process the true branch.
1638     if (builder.isFeasible(true)) {
1639       if (StTrue)
1640         builder.generateNode(StTrue, true, PredI);
1641       else
1642         builder.markInfeasible(true);
1643     }
1644 
1645     // Process the false branch.
1646     if (builder.isFeasible(false)) {
1647       if (StFalse)
1648         builder.generateNode(StFalse, false, PredI);
1649       else
1650         builder.markInfeasible(false);
1651     }
1652   }
1653   currBldrCtx = nullptr;
1654 }
1655 
1656 /// The GDM component containing the set of global variables which have been
1657 /// previously initialized with explicit initializers.
1658 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
1659                                  llvm::ImmutableSet<const VarDecl *>)
1660 
1661 void ExprEngine::processStaticInitializer(const DeclStmt *DS,
1662                                           NodeBuilderContext &BuilderCtx,
1663                                           ExplodedNode *Pred,
1664                                           clang::ento::ExplodedNodeSet &Dst,
1665                                           const CFGBlock *DstT,
1666                                           const CFGBlock *DstF) {
1667   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1668   currBldrCtx = &BuilderCtx;
1669 
1670   const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
1671   ProgramStateRef state = Pred->getState();
1672   bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
1673   BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
1674 
1675   if (!initHasRun) {
1676     state = state->add<InitializedGlobalsSet>(VD);
1677   }
1678 
1679   builder.generateNode(state, initHasRun, Pred);
1680   builder.markInfeasible(!initHasRun);
1681 
1682   currBldrCtx = nullptr;
1683 }
1684 
1685 /// processIndirectGoto - Called by CoreEngine.  Used to generate successor
1686 ///  nodes by processing the 'effects' of a computed goto jump.
1687 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
1688 
1689   ProgramStateRef state = builder.getState();
1690   SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
1691 
1692   // Three possibilities:
1693   //
1694   //   (1) We know the computed label.
1695   //   (2) The label is NULL (or some other constant), or Undefined.
1696   //   (3) We have no clue about the label.  Dispatch to all targets.
1697   //
1698 
1699   typedef IndirectGotoNodeBuilder::iterator iterator;
1700 
1701   if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
1702     const LabelDecl *L = LV->getLabel();
1703 
1704     for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
1705       if (I.getLabel() == L) {
1706         builder.generateNode(I, state);
1707         return;
1708       }
1709     }
1710 
1711     llvm_unreachable("No block with label.");
1712   }
1713 
1714   if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
1715     // Dispatch to the first target and mark it as a sink.
1716     //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
1717     // FIXME: add checker visit.
1718     //    UndefBranches.insert(N);
1719     return;
1720   }
1721 
1722   // This is really a catch-all.  We don't support symbolics yet.
1723   // FIXME: Implement dispatch for symbolic pointers.
1724 
1725   for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
1726     builder.generateNode(I, state);
1727 }
1728 
1729 #if 0
1730 static bool stackFrameDoesNotContainInitializedTemporaries(ExplodedNode &Pred) {
1731   const StackFrameContext* Frame = Pred.getStackFrame();
1732   const llvm::ImmutableSet<CXXBindTemporaryContext> &Set =
1733       Pred.getState()->get<InitializedTemporariesSet>();
1734   return std::find_if(Set.begin(), Set.end(),
1735                       [&](const CXXBindTemporaryContext &Ctx) {
1736                         if (Ctx.second == Frame) {
1737                           Ctx.first->dump();
1738                           llvm::errs() << "\n";
1739                         }
1740            return Ctx.second == Frame;
1741          }) == Set.end();
1742 }
1743 #endif
1744 
1745 /// ProcessEndPath - Called by CoreEngine.  Used to generate end-of-path
1746 ///  nodes when the control reaches the end of a function.
1747 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
1748                                       ExplodedNode *Pred) {
1749   // FIXME: Assert that stackFrameDoesNotContainInitializedTemporaries(*Pred)).
1750   // We currently cannot enable this assert, as lifetime extended temporaries
1751   // are not modelled correctly.
1752   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1753   StateMgr.EndPath(Pred->getState());
1754 
1755   ExplodedNodeSet Dst;
1756   if (Pred->getLocationContext()->inTopFrame()) {
1757     // Remove dead symbols.
1758     ExplodedNodeSet AfterRemovedDead;
1759     removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
1760 
1761     // Notify checkers.
1762     for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(),
1763         E = AfterRemovedDead.end(); I != E; ++I) {
1764       getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this);
1765     }
1766   } else {
1767     getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
1768   }
1769 
1770   Engine.enqueueEndOfFunction(Dst);
1771 }
1772 
1773 /// ProcessSwitch - Called by CoreEngine.  Used to generate successor
1774 ///  nodes by processing the 'effects' of a switch statement.
1775 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
1776   typedef SwitchNodeBuilder::iterator iterator;
1777   ProgramStateRef state = builder.getState();
1778   const Expr *CondE = builder.getCondition();
1779   SVal  CondV_untested = state->getSVal(CondE, builder.getLocationContext());
1780 
1781   if (CondV_untested.isUndef()) {
1782     //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
1783     // FIXME: add checker
1784     //UndefBranches.insert(N);
1785 
1786     return;
1787   }
1788   DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
1789 
1790   ProgramStateRef DefaultSt = state;
1791 
1792   iterator I = builder.begin(), EI = builder.end();
1793   bool defaultIsFeasible = I == EI;
1794 
1795   for ( ; I != EI; ++I) {
1796     // Successor may be pruned out during CFG construction.
1797     if (!I.getBlock())
1798       continue;
1799 
1800     const CaseStmt *Case = I.getCase();
1801 
1802     // Evaluate the LHS of the case value.
1803     llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
1804     assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType()));
1805 
1806     // Get the RHS of the case, if it exists.
1807     llvm::APSInt V2;
1808     if (const Expr *E = Case->getRHS())
1809       V2 = E->EvaluateKnownConstInt(getContext());
1810     else
1811       V2 = V1;
1812 
1813     ProgramStateRef StateCase;
1814     if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
1815       std::tie(StateCase, DefaultSt) =
1816           DefaultSt->assumeWithinInclusiveRange(*NL, V1, V2);
1817     else // UnknownVal
1818       StateCase = DefaultSt;
1819 
1820     if (StateCase)
1821       builder.generateCaseStmtNode(I, StateCase);
1822 
1823     // Now "assume" that the case doesn't match.  Add this state
1824     // to the default state (if it is feasible).
1825     if (DefaultSt)
1826       defaultIsFeasible = true;
1827     else {
1828       defaultIsFeasible = false;
1829       break;
1830     }
1831   }
1832 
1833   if (!defaultIsFeasible)
1834     return;
1835 
1836   // If we have switch(enum value), the default branch is not
1837   // feasible if all of the enum constants not covered by 'case:' statements
1838   // are not feasible values for the switch condition.
1839   //
1840   // Note that this isn't as accurate as it could be.  Even if there isn't
1841   // a case for a particular enum value as long as that enum value isn't
1842   // feasible then it shouldn't be considered for making 'default:' reachable.
1843   const SwitchStmt *SS = builder.getSwitch();
1844   const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
1845   if (CondExpr->getType()->getAs<EnumType>()) {
1846     if (SS->isAllEnumCasesCovered())
1847       return;
1848   }
1849 
1850   builder.generateDefaultCaseNode(DefaultSt);
1851 }
1852 
1853 //===----------------------------------------------------------------------===//
1854 // Transfer functions: Loads and stores.
1855 //===----------------------------------------------------------------------===//
1856 
1857 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
1858                                         ExplodedNode *Pred,
1859                                         ExplodedNodeSet &Dst) {
1860   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1861 
1862   ProgramStateRef state = Pred->getState();
1863   const LocationContext *LCtx = Pred->getLocationContext();
1864 
1865   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1866     // C permits "extern void v", and if you cast the address to a valid type,
1867     // you can even do things with it. We simply pretend
1868     assert(Ex->isGLValue() || VD->getType()->isVoidType());
1869     const LocationContext *LocCtxt = Pred->getLocationContext();
1870     const Decl *D = LocCtxt->getDecl();
1871     const auto *MD = D ? dyn_cast<CXXMethodDecl>(D) : nullptr;
1872     const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
1873     SVal V;
1874     bool IsReference;
1875     if (AMgr.options.shouldInlineLambdas() && DeclRefEx &&
1876         DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
1877         MD->getParent()->isLambda()) {
1878       // Lookup the field of the lambda.
1879       const CXXRecordDecl *CXXRec = MD->getParent();
1880       llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
1881       FieldDecl *LambdaThisCaptureField;
1882       CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
1883       const FieldDecl *FD = LambdaCaptureFields[VD];
1884       if (!FD) {
1885         // When a constant is captured, sometimes no corresponding field is
1886         // created in the lambda object.
1887         assert(VD->getType().isConstQualified());
1888         V = state->getLValue(VD, LocCtxt);
1889         IsReference = false;
1890       } else {
1891         Loc CXXThis =
1892             svalBuilder.getCXXThis(MD, LocCtxt->getCurrentStackFrame());
1893         SVal CXXThisVal = state->getSVal(CXXThis);
1894         V = state->getLValue(FD, CXXThisVal);
1895         IsReference = FD->getType()->isReferenceType();
1896       }
1897     } else {
1898       V = state->getLValue(VD, LocCtxt);
1899       IsReference = VD->getType()->isReferenceType();
1900     }
1901 
1902     // For references, the 'lvalue' is the pointer address stored in the
1903     // reference region.
1904     if (IsReference) {
1905       if (const MemRegion *R = V.getAsRegion())
1906         V = state->getSVal(R);
1907       else
1908         V = UnknownVal();
1909     }
1910 
1911     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1912                       ProgramPoint::PostLValueKind);
1913     return;
1914   }
1915   if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
1916     assert(!Ex->isGLValue());
1917     SVal V = svalBuilder.makeIntVal(ED->getInitVal());
1918     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
1919     return;
1920   }
1921   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1922     SVal V = svalBuilder.getFunctionPointer(FD);
1923     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1924                       ProgramPoint::PostLValueKind);
1925     return;
1926   }
1927   if (isa<FieldDecl>(D)) {
1928     // FIXME: Compute lvalue of field pointers-to-member.
1929     // Right now we just use a non-null void pointer, so that it gives proper
1930     // results in boolean contexts.
1931     SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
1932                                           currBldrCtx->blockCount());
1933     state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
1934     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1935 		      ProgramPoint::PostLValueKind);
1936     return;
1937   }
1938 
1939   llvm_unreachable("Support for this Decl not implemented.");
1940 }
1941 
1942 /// VisitArraySubscriptExpr - Transfer function for array accesses
1943 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A,
1944                                              ExplodedNode *Pred,
1945                                              ExplodedNodeSet &Dst){
1946 
1947   const Expr *Base = A->getBase()->IgnoreParens();
1948   const Expr *Idx  = A->getIdx()->IgnoreParens();
1949 
1950 
1951   ExplodedNodeSet checkerPreStmt;
1952   getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this);
1953 
1954   StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currBldrCtx);
1955   assert(A->isGLValue() ||
1956           (!AMgr.getLangOpts().CPlusPlus &&
1957            A->getType().isCForbiddenLValueType()));
1958 
1959   for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(),
1960                                  ei = checkerPreStmt.end(); it != ei; ++it) {
1961     const LocationContext *LCtx = (*it)->getLocationContext();
1962     ProgramStateRef state = (*it)->getState();
1963     SVal V = state->getLValue(A->getType(),
1964                               state->getSVal(Idx, LCtx),
1965                               state->getSVal(Base, LCtx));
1966     Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), nullptr,
1967                       ProgramPoint::PostLValueKind);
1968   }
1969 }
1970 
1971 /// VisitMemberExpr - Transfer function for member expressions.
1972 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
1973                                  ExplodedNodeSet &Dst) {
1974 
1975   // FIXME: Prechecks eventually go in ::Visit().
1976   ExplodedNodeSet CheckedSet;
1977   getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
1978 
1979   ExplodedNodeSet EvalSet;
1980   ValueDecl *Member = M->getMemberDecl();
1981 
1982   // Handle static member variables and enum constants accessed via
1983   // member syntax.
1984   if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
1985     ExplodedNodeSet Dst;
1986     for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
1987          I != E; ++I) {
1988       VisitCommonDeclRefExpr(M, Member, Pred, EvalSet);
1989     }
1990   } else {
1991     StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
1992     ExplodedNodeSet Tmp;
1993 
1994     for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
1995          I != E; ++I) {
1996       ProgramStateRef state = (*I)->getState();
1997       const LocationContext *LCtx = (*I)->getLocationContext();
1998       Expr *BaseExpr = M->getBase();
1999 
2000       // Handle C++ method calls.
2001       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
2002         if (MD->isInstance())
2003           state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2004 
2005         SVal MDVal = svalBuilder.getFunctionPointer(MD);
2006         state = state->BindExpr(M, LCtx, MDVal);
2007 
2008         Bldr.generateNode(M, *I, state);
2009         continue;
2010       }
2011 
2012       // Handle regular struct fields / member variables.
2013       state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2014       SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
2015 
2016       FieldDecl *field = cast<FieldDecl>(Member);
2017       SVal L = state->getLValue(field, baseExprVal);
2018 
2019       if (M->isGLValue() || M->getType()->isArrayType()) {
2020         // We special-case rvalues of array type because the analyzer cannot
2021         // reason about them, since we expect all regions to be wrapped in Locs.
2022         // We instead treat these as lvalues and assume that they will decay to
2023         // pointers as soon as they are used.
2024         if (!M->isGLValue()) {
2025           assert(M->getType()->isArrayType());
2026           const ImplicitCastExpr *PE =
2027             dyn_cast<ImplicitCastExpr>((*I)->getParentMap().getParent(M));
2028           if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
2029             llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
2030           }
2031         }
2032 
2033         if (field->getType()->isReferenceType()) {
2034           if (const MemRegion *R = L.getAsRegion())
2035             L = state->getSVal(R);
2036           else
2037             L = UnknownVal();
2038         }
2039 
2040         Bldr.generateNode(M, *I, state->BindExpr(M, LCtx, L), nullptr,
2041                           ProgramPoint::PostLValueKind);
2042       } else {
2043         Bldr.takeNodes(*I);
2044         evalLoad(Tmp, M, M, *I, state, L);
2045         Bldr.addNodes(Tmp);
2046       }
2047     }
2048   }
2049 
2050   getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
2051 }
2052 
2053 namespace {
2054 class CollectReachableSymbolsCallback final : public SymbolVisitor {
2055   InvalidatedSymbols Symbols;
2056 public:
2057   CollectReachableSymbolsCallback(ProgramStateRef State) {}
2058   const InvalidatedSymbols &getSymbols() const { return Symbols; }
2059 
2060   bool VisitSymbol(SymbolRef Sym) override {
2061     Symbols.insert(Sym);
2062     return true;
2063   }
2064 };
2065 } // end anonymous namespace
2066 
2067 // A value escapes in three possible cases:
2068 // (1) We are binding to something that is not a memory region.
2069 // (2) We are binding to a MemrRegion that does not have stack storage.
2070 // (3) We are binding to a MemRegion with stack storage that the store
2071 //     does not understand.
2072 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
2073                                                         SVal Loc, SVal Val) {
2074   // Are we storing to something that causes the value to "escape"?
2075   bool escapes = true;
2076 
2077   // TODO: Move to StoreManager.
2078   if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
2079     escapes = !regionLoc->getRegion()->hasStackStorage();
2080 
2081     if (!escapes) {
2082       // To test (3), generate a new state with the binding added.  If it is
2083       // the same state, then it escapes (since the store cannot represent
2084       // the binding).
2085       // Do this only if we know that the store is not supposed to generate the
2086       // same state.
2087       SVal StoredVal = State->getSVal(regionLoc->getRegion());
2088       if (StoredVal != Val)
2089         escapes = (State == (State->bindLoc(*regionLoc, Val)));
2090     }
2091   }
2092 
2093   // If our store can represent the binding and we aren't storing to something
2094   // that doesn't have local storage then just return and have the simulation
2095   // state continue as is.
2096   if (!escapes)
2097     return State;
2098 
2099   // Otherwise, find all symbols referenced by 'val' that we are tracking
2100   // and stop tracking them.
2101   CollectReachableSymbolsCallback Scanner =
2102       State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val);
2103   const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
2104   State = getCheckerManager().runCheckersForPointerEscape(State,
2105                                                           EscapedSymbols,
2106                                                           /*CallEvent*/ nullptr,
2107                                                           PSK_EscapeOnBind,
2108                                                           nullptr);
2109 
2110   return State;
2111 }
2112 
2113 ProgramStateRef
2114 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
2115     const InvalidatedSymbols *Invalidated,
2116     ArrayRef<const MemRegion *> ExplicitRegions,
2117     ArrayRef<const MemRegion *> Regions,
2118     const CallEvent *Call,
2119     RegionAndSymbolInvalidationTraits &ITraits) {
2120 
2121   if (!Invalidated || Invalidated->empty())
2122     return State;
2123 
2124   if (!Call)
2125     return getCheckerManager().runCheckersForPointerEscape(State,
2126                                                            *Invalidated,
2127                                                            nullptr,
2128                                                            PSK_EscapeOther,
2129                                                            &ITraits);
2130 
2131   // If the symbols were invalidated by a call, we want to find out which ones
2132   // were invalidated directly due to being arguments to the call.
2133   InvalidatedSymbols SymbolsDirectlyInvalidated;
2134   for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
2135       E = ExplicitRegions.end(); I != E; ++I) {
2136     if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
2137       SymbolsDirectlyInvalidated.insert(R->getSymbol());
2138   }
2139 
2140   InvalidatedSymbols SymbolsIndirectlyInvalidated;
2141   for (InvalidatedSymbols::const_iterator I=Invalidated->begin(),
2142       E = Invalidated->end(); I!=E; ++I) {
2143     SymbolRef sym = *I;
2144     if (SymbolsDirectlyInvalidated.count(sym))
2145       continue;
2146     SymbolsIndirectlyInvalidated.insert(sym);
2147   }
2148 
2149   if (!SymbolsDirectlyInvalidated.empty())
2150     State = getCheckerManager().runCheckersForPointerEscape(State,
2151         SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
2152 
2153   // Notify about the symbols that get indirectly invalidated by the call.
2154   if (!SymbolsIndirectlyInvalidated.empty())
2155     State = getCheckerManager().runCheckersForPointerEscape(State,
2156         SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
2157 
2158   return State;
2159 }
2160 
2161 /// evalBind - Handle the semantics of binding a value to a specific location.
2162 ///  This method is used by evalStore and (soon) VisitDeclStmt, and others.
2163 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
2164                           ExplodedNode *Pred,
2165                           SVal location, SVal Val,
2166                           bool atDeclInit, const ProgramPoint *PP) {
2167 
2168   const LocationContext *LC = Pred->getLocationContext();
2169   PostStmt PS(StoreE, LC);
2170   if (!PP)
2171     PP = &PS;
2172 
2173   // Do a previsit of the bind.
2174   ExplodedNodeSet CheckedSet;
2175   getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
2176                                          StoreE, *this, *PP);
2177 
2178 
2179   StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
2180 
2181   // If the location is not a 'Loc', it will already be handled by
2182   // the checkers.  There is nothing left to do.
2183   if (!location.getAs<Loc>()) {
2184     const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
2185                                      /*tag*/nullptr);
2186     ProgramStateRef state = Pred->getState();
2187     state = processPointerEscapedOnBind(state, location, Val);
2188     Bldr.generateNode(L, state, Pred);
2189     return;
2190   }
2191 
2192 
2193   for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2194        I!=E; ++I) {
2195     ExplodedNode *PredI = *I;
2196     ProgramStateRef state = PredI->getState();
2197 
2198     state = processPointerEscapedOnBind(state, location, Val);
2199 
2200     // When binding the value, pass on the hint that this is a initialization.
2201     // For initializations, we do not need to inform clients of region
2202     // changes.
2203     state = state->bindLoc(location.castAs<Loc>(),
2204                            Val, /* notifyChanges = */ !atDeclInit);
2205 
2206     const MemRegion *LocReg = nullptr;
2207     if (Optional<loc::MemRegionVal> LocRegVal =
2208             location.getAs<loc::MemRegionVal>()) {
2209       LocReg = LocRegVal->getRegion();
2210     }
2211 
2212     const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
2213     Bldr.generateNode(L, state, PredI);
2214   }
2215 }
2216 
2217 /// evalStore - Handle the semantics of a store via an assignment.
2218 ///  @param Dst The node set to store generated state nodes
2219 ///  @param AssignE The assignment expression if the store happens in an
2220 ///         assignment.
2221 ///  @param LocationE The location expression that is stored to.
2222 ///  @param state The current simulation state
2223 ///  @param location The location to store the value
2224 ///  @param Val The value to be stored
2225 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
2226                              const Expr *LocationE,
2227                              ExplodedNode *Pred,
2228                              ProgramStateRef state, SVal location, SVal Val,
2229                              const ProgramPointTag *tag) {
2230   // Proceed with the store.  We use AssignE as the anchor for the PostStore
2231   // ProgramPoint if it is non-NULL, and LocationE otherwise.
2232   const Expr *StoreE = AssignE ? AssignE : LocationE;
2233 
2234   // Evaluate the location (checks for bad dereferences).
2235   ExplodedNodeSet Tmp;
2236   evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
2237 
2238   if (Tmp.empty())
2239     return;
2240 
2241   if (location.isUndef())
2242     return;
2243 
2244   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
2245     evalBind(Dst, StoreE, *NI, location, Val, false);
2246 }
2247 
2248 void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
2249                           const Expr *NodeEx,
2250                           const Expr *BoundEx,
2251                           ExplodedNode *Pred,
2252                           ProgramStateRef state,
2253                           SVal location,
2254                           const ProgramPointTag *tag,
2255                           QualType LoadTy)
2256 {
2257   assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2258 
2259   // Are we loading from a region?  This actually results in two loads; one
2260   // to fetch the address of the referenced value and one to fetch the
2261   // referenced value.
2262   if (const TypedValueRegion *TR =
2263         dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
2264 
2265     QualType ValTy = TR->getValueType();
2266     if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
2267       static SimpleProgramPointTag
2268              loadReferenceTag(TagProviderName, "Load Reference");
2269       ExplodedNodeSet Tmp;
2270       evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
2271                      location, &loadReferenceTag,
2272                      getContext().getPointerType(RT->getPointeeType()));
2273 
2274       // Perform the load from the referenced value.
2275       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
2276         state = (*I)->getState();
2277         location = state->getSVal(BoundEx, (*I)->getLocationContext());
2278         evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
2279       }
2280       return;
2281     }
2282   }
2283 
2284   evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
2285 }
2286 
2287 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
2288                                 const Expr *NodeEx,
2289                                 const Expr *BoundEx,
2290                                 ExplodedNode *Pred,
2291                                 ProgramStateRef state,
2292                                 SVal location,
2293                                 const ProgramPointTag *tag,
2294                                 QualType LoadTy) {
2295   assert(NodeEx);
2296   assert(BoundEx);
2297   // Evaluate the location (checks for bad dereferences).
2298   ExplodedNodeSet Tmp;
2299   evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
2300   if (Tmp.empty())
2301     return;
2302 
2303   StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2304   if (location.isUndef())
2305     return;
2306 
2307   // Proceed with the load.
2308   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
2309     state = (*NI)->getState();
2310     const LocationContext *LCtx = (*NI)->getLocationContext();
2311 
2312     SVal V = UnknownVal();
2313     if (location.isValid()) {
2314       if (LoadTy.isNull())
2315         LoadTy = BoundEx->getType();
2316       V = state->getSVal(location.castAs<Loc>(), LoadTy);
2317     }
2318 
2319     Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
2320                       ProgramPoint::PostLoadKind);
2321   }
2322 }
2323 
2324 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2325                               const Stmt *NodeEx,
2326                               const Stmt *BoundEx,
2327                               ExplodedNode *Pred,
2328                               ProgramStateRef state,
2329                               SVal location,
2330                               const ProgramPointTag *tag,
2331                               bool isLoad) {
2332   StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2333   // Early checks for performance reason.
2334   if (location.isUnknown()) {
2335     return;
2336   }
2337 
2338   ExplodedNodeSet Src;
2339   BldrTop.takeNodes(Pred);
2340   StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2341   if (Pred->getState() != state) {
2342     // Associate this new state with an ExplodedNode.
2343     // FIXME: If I pass null tag, the graph is incorrect, e.g for
2344     //   int *p;
2345     //   p = 0;
2346     //   *p = 0xDEADBEEF;
2347     // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2348     // instead "int *p" is noted as
2349     // "Variable 'p' initialized to a null pointer value"
2350 
2351     static SimpleProgramPointTag tag(TagProviderName, "Location");
2352     Bldr.generateNode(NodeEx, Pred, state, &tag);
2353   }
2354   ExplodedNodeSet Tmp;
2355   getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2356                                              NodeEx, BoundEx, *this);
2357   BldrTop.addNodes(Tmp);
2358 }
2359 
2360 std::pair<const ProgramPointTag *, const ProgramPointTag*>
2361 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
2362   static SimpleProgramPointTag
2363          eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
2364                                            "Eagerly Assume True"),
2365          eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
2366                                             "Eagerly Assume False");
2367   return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2368                         &eagerlyAssumeBinOpBifurcationFalse);
2369 }
2370 
2371 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
2372                                                    ExplodedNodeSet &Src,
2373                                                    const Expr *Ex) {
2374   StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2375 
2376   for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
2377     ExplodedNode *Pred = *I;
2378     // Test if the previous node was as the same expression.  This can happen
2379     // when the expression fails to evaluate to anything meaningful and
2380     // (as an optimization) we don't generate a node.
2381     ProgramPoint P = Pred->getLocation();
2382     if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2383       continue;
2384     }
2385 
2386     ProgramStateRef state = Pred->getState();
2387     SVal V = state->getSVal(Ex, Pred->getLocationContext());
2388     Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
2389     if (SEV && SEV->isExpression()) {
2390       const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2391         geteagerlyAssumeBinOpBifurcationTags();
2392 
2393       ProgramStateRef StateTrue, StateFalse;
2394       std::tie(StateTrue, StateFalse) = state->assume(*SEV);
2395 
2396       // First assume that the condition is true.
2397       if (StateTrue) {
2398         SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2399         StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2400         Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2401       }
2402 
2403       // Next, assume that the condition is false.
2404       if (StateFalse) {
2405         SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2406         StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2407         Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2408       }
2409     }
2410   }
2411 }
2412 
2413 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
2414                                  ExplodedNodeSet &Dst) {
2415   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2416   // We have processed both the inputs and the outputs.  All of the outputs
2417   // should evaluate to Locs.  Nuke all of their values.
2418 
2419   // FIXME: Some day in the future it would be nice to allow a "plug-in"
2420   // which interprets the inline asm and stores proper results in the
2421   // outputs.
2422 
2423   ProgramStateRef state = Pred->getState();
2424 
2425   for (const Expr *O : A->outputs()) {
2426     SVal X = state->getSVal(O, Pred->getLocationContext());
2427     assert (!X.getAs<NonLoc>());  // Should be an Lval, or unknown, undef.
2428 
2429     if (Optional<Loc> LV = X.getAs<Loc>())
2430       state = state->bindLoc(*LV, UnknownVal());
2431   }
2432 
2433   Bldr.generateNode(A, Pred, state);
2434 }
2435 
2436 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
2437                                 ExplodedNodeSet &Dst) {
2438   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2439   Bldr.generateNode(A, Pred, Pred->getState());
2440 }
2441 
2442 //===----------------------------------------------------------------------===//
2443 // Visualization.
2444 //===----------------------------------------------------------------------===//
2445 
2446 #ifndef NDEBUG
2447 static ExprEngine* GraphPrintCheckerState;
2448 static SourceManager* GraphPrintSourceManager;
2449 
2450 namespace llvm {
2451 template<>
2452 struct DOTGraphTraits<ExplodedNode*> :
2453   public DefaultDOTGraphTraits {
2454 
2455   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2456 
2457   // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
2458   // work.
2459   static std::string getNodeAttributes(const ExplodedNode *N, void*) {
2460 
2461 #if 0
2462       // FIXME: Replace with a general scheme to tell if the node is
2463       // an error node.
2464     if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
2465         GraphPrintCheckerState->isExplicitNullDeref(N) ||
2466         GraphPrintCheckerState->isUndefDeref(N) ||
2467         GraphPrintCheckerState->isUndefStore(N) ||
2468         GraphPrintCheckerState->isUndefControlFlow(N) ||
2469         GraphPrintCheckerState->isUndefResult(N) ||
2470         GraphPrintCheckerState->isBadCall(N) ||
2471         GraphPrintCheckerState->isUndefArg(N))
2472       return "color=\"red\",style=\"filled\"";
2473 
2474     if (GraphPrintCheckerState->isNoReturnCall(N))
2475       return "color=\"blue\",style=\"filled\"";
2476 #endif
2477     return "";
2478   }
2479 
2480   static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
2481     if (SLoc.isFileID()) {
2482       Out << "\\lline="
2483         << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2484         << " col="
2485         << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
2486         << "\\l";
2487     }
2488   }
2489 
2490   static std::string getNodeLabel(const ExplodedNode *N, void*){
2491 
2492     std::string sbuf;
2493     llvm::raw_string_ostream Out(sbuf);
2494 
2495     // Program Location.
2496     ProgramPoint Loc = N->getLocation();
2497 
2498     switch (Loc.getKind()) {
2499       case ProgramPoint::BlockEntranceKind: {
2500         Out << "Block Entrance: B"
2501             << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
2502         if (const NamedDecl *ND =
2503                     dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) {
2504           Out << " (";
2505           ND->printName(Out);
2506           Out << ")";
2507         }
2508         break;
2509       }
2510 
2511       case ProgramPoint::BlockExitKind:
2512         assert (false);
2513         break;
2514 
2515       case ProgramPoint::CallEnterKind:
2516         Out << "CallEnter";
2517         break;
2518 
2519       case ProgramPoint::CallExitBeginKind:
2520         Out << "CallExitBegin";
2521         break;
2522 
2523       case ProgramPoint::CallExitEndKind:
2524         Out << "CallExitEnd";
2525         break;
2526 
2527       case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
2528         Out << "PostStmtPurgeDeadSymbols";
2529         break;
2530 
2531       case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
2532         Out << "PreStmtPurgeDeadSymbols";
2533         break;
2534 
2535       case ProgramPoint::EpsilonKind:
2536         Out << "Epsilon Point";
2537         break;
2538 
2539       case ProgramPoint::PreImplicitCallKind: {
2540         ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2541         Out << "PreCall: ";
2542 
2543         // FIXME: Get proper printing options.
2544         PC.getDecl()->print(Out, LangOptions());
2545         printLocation(Out, PC.getLocation());
2546         break;
2547       }
2548 
2549       case ProgramPoint::PostImplicitCallKind: {
2550         ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2551         Out << "PostCall: ";
2552 
2553         // FIXME: Get proper printing options.
2554         PC.getDecl()->print(Out, LangOptions());
2555         printLocation(Out, PC.getLocation());
2556         break;
2557       }
2558 
2559       case ProgramPoint::PostInitializerKind: {
2560         Out << "PostInitializer: ";
2561         const CXXCtorInitializer *Init =
2562           Loc.castAs<PostInitializer>().getInitializer();
2563         if (const FieldDecl *FD = Init->getAnyMember())
2564           Out << *FD;
2565         else {
2566           QualType Ty = Init->getTypeSourceInfo()->getType();
2567           Ty = Ty.getLocalUnqualifiedType();
2568           LangOptions LO; // FIXME.
2569           Ty.print(Out, LO);
2570         }
2571         break;
2572       }
2573 
2574       case ProgramPoint::BlockEdgeKind: {
2575         const BlockEdge &E = Loc.castAs<BlockEdge>();
2576         Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
2577             << E.getDst()->getBlockID()  << ')';
2578 
2579         if (const Stmt *T = E.getSrc()->getTerminator()) {
2580           SourceLocation SLoc = T->getLocStart();
2581 
2582           Out << "\\|Terminator: ";
2583           LangOptions LO; // FIXME.
2584           E.getSrc()->printTerminator(Out, LO);
2585 
2586           if (SLoc.isFileID()) {
2587             Out << "\\lline="
2588               << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2589               << " col="
2590               << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
2591           }
2592 
2593           if (isa<SwitchStmt>(T)) {
2594             const Stmt *Label = E.getDst()->getLabel();
2595 
2596             if (Label) {
2597               if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
2598                 Out << "\\lcase ";
2599                 LangOptions LO; // FIXME.
2600                 if (C->getLHS())
2601                   C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO));
2602 
2603                 if (const Stmt *RHS = C->getRHS()) {
2604                   Out << " .. ";
2605                   RHS->printPretty(Out, nullptr, PrintingPolicy(LO));
2606                 }
2607 
2608                 Out << ":";
2609               }
2610               else {
2611                 assert (isa<DefaultStmt>(Label));
2612                 Out << "\\ldefault:";
2613               }
2614             }
2615             else
2616               Out << "\\l(implicit) default:";
2617           }
2618           else if (isa<IndirectGotoStmt>(T)) {
2619             // FIXME
2620           }
2621           else {
2622             Out << "\\lCondition: ";
2623             if (*E.getSrc()->succ_begin() == E.getDst())
2624               Out << "true";
2625             else
2626               Out << "false";
2627           }
2628 
2629           Out << "\\l";
2630         }
2631 
2632 #if 0
2633           // FIXME: Replace with a general scheme to determine
2634           // the name of the check.
2635         if (GraphPrintCheckerState->isUndefControlFlow(N)) {
2636           Out << "\\|Control-flow based on\\lUndefined value.\\l";
2637         }
2638 #endif
2639         break;
2640       }
2641 
2642       default: {
2643         const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
2644         assert(S != nullptr && "Expecting non-null Stmt");
2645 
2646         Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
2647         LangOptions LO; // FIXME.
2648         S->printPretty(Out, nullptr, PrintingPolicy(LO));
2649         printLocation(Out, S->getLocStart());
2650 
2651         if (Loc.getAs<PreStmt>())
2652           Out << "\\lPreStmt\\l;";
2653         else if (Loc.getAs<PostLoad>())
2654           Out << "\\lPostLoad\\l;";
2655         else if (Loc.getAs<PostStore>())
2656           Out << "\\lPostStore\\l";
2657         else if (Loc.getAs<PostLValue>())
2658           Out << "\\lPostLValue\\l";
2659 
2660 #if 0
2661           // FIXME: Replace with a general scheme to determine
2662           // the name of the check.
2663         if (GraphPrintCheckerState->isImplicitNullDeref(N))
2664           Out << "\\|Implicit-Null Dereference.\\l";
2665         else if (GraphPrintCheckerState->isExplicitNullDeref(N))
2666           Out << "\\|Explicit-Null Dereference.\\l";
2667         else if (GraphPrintCheckerState->isUndefDeref(N))
2668           Out << "\\|Dereference of undefialied value.\\l";
2669         else if (GraphPrintCheckerState->isUndefStore(N))
2670           Out << "\\|Store to Undefined Loc.";
2671         else if (GraphPrintCheckerState->isUndefResult(N))
2672           Out << "\\|Result of operation is undefined.";
2673         else if (GraphPrintCheckerState->isNoReturnCall(N))
2674           Out << "\\|Call to function marked \"noreturn\".";
2675         else if (GraphPrintCheckerState->isBadCall(N))
2676           Out << "\\|Call to NULL/Undefined.";
2677         else if (GraphPrintCheckerState->isUndefArg(N))
2678           Out << "\\|Argument in call is undefined";
2679 #endif
2680 
2681         break;
2682       }
2683     }
2684 
2685     ProgramStateRef state = N->getState();
2686     Out << "\\|StateID: " << (const void*) state.get()
2687         << " NodeID: " << (const void*) N << "\\|";
2688     state->printDOT(Out);
2689 
2690     Out << "\\l";
2691 
2692     if (const ProgramPointTag *tag = Loc.getTag()) {
2693       Out << "\\|Tag: " << tag->getTagDescription();
2694       Out << "\\l";
2695     }
2696     return Out.str();
2697   }
2698 };
2699 } // end llvm namespace
2700 #endif
2701 
2702 void ExprEngine::ViewGraph(bool trim) {
2703 #ifndef NDEBUG
2704   if (trim) {
2705     std::vector<const ExplodedNode*> Src;
2706 
2707     // Flush any outstanding reports to make sure we cover all the nodes.
2708     // This does not cause them to get displayed.
2709     for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
2710       const_cast<BugType*>(*I)->FlushReports(BR);
2711 
2712     // Iterate through the reports and get their nodes.
2713     for (BugReporter::EQClasses_iterator
2714            EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
2715       ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
2716       if (N) Src.push_back(N);
2717     }
2718 
2719     ViewGraph(Src);
2720   }
2721   else {
2722     GraphPrintCheckerState = this;
2723     GraphPrintSourceManager = &getContext().getSourceManager();
2724 
2725     llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
2726 
2727     GraphPrintCheckerState = nullptr;
2728     GraphPrintSourceManager = nullptr;
2729   }
2730 #endif
2731 }
2732 
2733 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
2734 #ifndef NDEBUG
2735   GraphPrintCheckerState = this;
2736   GraphPrintSourceManager = &getContext().getSourceManager();
2737 
2738   std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
2739 
2740   if (!TrimmedG.get())
2741     llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
2742   else
2743     llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
2744 
2745   GraphPrintCheckerState = nullptr;
2746   GraphPrintSourceManager = nullptr;
2747 #endif
2748 }
2749