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