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