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