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