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