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