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