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