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