]> granicus.if.org Git - clang/blob - lib/StaticAnalyzer/Core/ExprEngine.cpp
d4f2e40605f16a92ec0b449aabc65a52174a5347
[clang] / lib / StaticAnalyzer / Core / ExprEngine.cpp
1 //=-- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- C++ -*-=
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines a meta-engine for path-sensitive dataflow analysis that
11 //  is built on GREngine, but provides the boilerplate to execute transfer
12 //  functions and build the ExplodedGraph at the expression level.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
17 #include "PrettyStackTraceLocationContext.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ParentMap.h"
20 #include "clang/AST/StmtCXX.h"
21 #include "clang/AST/StmtObjC.h"
22 #include "clang/Basic/Builtins.h"
23 #include "clang/Basic/PrettyStackTrace.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
26 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
29 #include "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::CXXFoldExprClass:
756     case Stmt::MSPropertyRefExprClass:
757     case Stmt::CXXUnresolvedConstructExprClass:
758     case Stmt::DependentScopeDeclRefExprClass:
759     case Stmt::TypeTraitExprClass:
760     case Stmt::ArrayTypeTraitExprClass:
761     case Stmt::ExpressionTraitExprClass:
762     case Stmt::UnresolvedLookupExprClass:
763     case Stmt::UnresolvedMemberExprClass:
764     case Stmt::TypoExprClass:
765     case Stmt::CXXNoexceptExprClass:
766     case Stmt::PackExpansionExprClass:
767     case Stmt::SubstNonTypeTemplateParmPackExprClass:
768     case Stmt::FunctionParmPackExprClass:
769     case Stmt::SEHTryStmtClass:
770     case Stmt::SEHExceptStmtClass:
771     case Stmt::SEHLeaveStmtClass:
772     case Stmt::LambdaExprClass:
773     case Stmt::SEHFinallyStmtClass: {
774       const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
775       Engine.addAbortedBlock(node, currBldrCtx->getBlock());
776       break;
777     }
778
779     case Stmt::ParenExprClass:
780       llvm_unreachable("ParenExprs already handled.");
781     case Stmt::GenericSelectionExprClass:
782       llvm_unreachable("GenericSelectionExprs already handled.");
783     // Cases that should never be evaluated simply because they shouldn't
784     // appear in the CFG.
785     case Stmt::BreakStmtClass:
786     case Stmt::CaseStmtClass:
787     case Stmt::CompoundStmtClass:
788     case Stmt::ContinueStmtClass:
789     case Stmt::CXXForRangeStmtClass:
790     case Stmt::DefaultStmtClass:
791     case Stmt::DoStmtClass:
792     case Stmt::ForStmtClass:
793     case Stmt::GotoStmtClass:
794     case Stmt::IfStmtClass:
795     case Stmt::IndirectGotoStmtClass:
796     case Stmt::LabelStmtClass:
797     case Stmt::NoStmtClass:
798     case Stmt::NullStmtClass:
799     case Stmt::SwitchStmtClass:
800     case Stmt::WhileStmtClass:
801     case Expr::MSDependentExistsStmtClass:
802     case Stmt::CapturedStmtClass:
803     case Stmt::OMPParallelDirectiveClass:
804     case Stmt::OMPSimdDirectiveClass:
805     case Stmt::OMPForDirectiveClass:
806     case Stmt::OMPForSimdDirectiveClass:
807     case Stmt::OMPSectionsDirectiveClass:
808     case Stmt::OMPSectionDirectiveClass:
809     case Stmt::OMPSingleDirectiveClass:
810     case Stmt::OMPMasterDirectiveClass:
811     case Stmt::OMPCriticalDirectiveClass:
812     case Stmt::OMPParallelForDirectiveClass:
813     case Stmt::OMPParallelForSimdDirectiveClass:
814     case Stmt::OMPParallelSectionsDirectiveClass:
815     case Stmt::OMPTaskDirectiveClass:
816     case Stmt::OMPTaskyieldDirectiveClass:
817     case Stmt::OMPBarrierDirectiveClass:
818     case Stmt::OMPTaskwaitDirectiveClass:
819     case Stmt::OMPTaskgroupDirectiveClass:
820     case Stmt::OMPFlushDirectiveClass:
821     case Stmt::OMPOrderedDirectiveClass:
822     case Stmt::OMPAtomicDirectiveClass:
823     case Stmt::OMPTargetDirectiveClass:
824     case Stmt::OMPTargetDataDirectiveClass:
825     case Stmt::OMPTeamsDirectiveClass:
826     case Stmt::OMPCancellationPointDirectiveClass:
827     case Stmt::OMPCancelDirectiveClass:
828       llvm_unreachable("Stmt should not be in analyzer evaluation loop");
829
830     case Stmt::ObjCSubscriptRefExprClass:
831     case Stmt::ObjCPropertyRefExprClass:
832       llvm_unreachable("These are handled by PseudoObjectExpr");
833
834     case Stmt::GNUNullExprClass: {
835       // GNU __null is a pointer-width integer, not an actual pointer.
836       ProgramStateRef state = Pred->getState();
837       state = state->BindExpr(S, Pred->getLocationContext(),
838                               svalBuilder.makeIntValWithPtrWidth(0, false));
839       Bldr.generateNode(S, Pred, state);
840       break;
841     }
842
843     case Stmt::ObjCAtSynchronizedStmtClass:
844       Bldr.takeNodes(Pred);
845       VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
846       Bldr.addNodes(Dst);
847       break;
848
849     case Stmt::ExprWithCleanupsClass:
850       // Handled due to fully linearised CFG.
851       break;
852
853     case Stmt::CXXBindTemporaryExprClass: {
854       Bldr.takeNodes(Pred);
855       ExplodedNodeSet PreVisit;
856       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
857       ExplodedNodeSet Next;
858       VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
859       getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
860       Bldr.addNodes(Dst);
861       break;
862     }
863
864     // Cases not handled yet; but will handle some day.
865     case Stmt::DesignatedInitExprClass:
866     case Stmt::DesignatedInitUpdateExprClass:
867     case Stmt::ExtVectorElementExprClass:
868     case Stmt::ImaginaryLiteralClass:
869     case Stmt::ObjCAtCatchStmtClass:
870     case Stmt::ObjCAtFinallyStmtClass:
871     case Stmt::ObjCAtTryStmtClass:
872     case Stmt::ObjCAutoreleasePoolStmtClass:
873     case Stmt::ObjCEncodeExprClass:
874     case Stmt::ObjCIsaExprClass:
875     case Stmt::ObjCProtocolExprClass:
876     case Stmt::ObjCSelectorExprClass:
877     case Stmt::ParenListExprClass:
878     case Stmt::ShuffleVectorExprClass:
879     case Stmt::ConvertVectorExprClass:
880     case Stmt::VAArgExprClass:
881     case Stmt::CUDAKernelCallExprClass:
882     case Stmt::OpaqueValueExprClass:
883     case Stmt::AsTypeExprClass:
884     case Stmt::AtomicExprClass:
885       // Fall through.
886
887     // Cases we intentionally don't evaluate, since they don't need
888     // to be explicitly evaluated.
889     case Stmt::PredefinedExprClass:
890     case Stmt::AddrLabelExprClass:
891     case Stmt::AttributedStmtClass:
892     case Stmt::IntegerLiteralClass:
893     case Stmt::CharacterLiteralClass:
894     case Stmt::ImplicitValueInitExprClass:
895     case Stmt::CXXScalarValueInitExprClass:
896     case Stmt::CXXBoolLiteralExprClass:
897     case Stmt::ObjCBoolLiteralExprClass:
898     case Stmt::FloatingLiteralClass:
899     case Stmt::NoInitExprClass:
900     case Stmt::SizeOfPackExprClass:
901     case Stmt::StringLiteralClass:
902     case Stmt::ObjCStringLiteralClass:
903     case Stmt::CXXPseudoDestructorExprClass:
904     case Stmt::SubstNonTypeTemplateParmExprClass:
905     case Stmt::CXXNullPtrLiteralExprClass:
906     case Stmt::OMPArraySectionExprClass: {
907       Bldr.takeNodes(Pred);
908       ExplodedNodeSet preVisit;
909       getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
910       getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
911       Bldr.addNodes(Dst);
912       break;
913     }
914
915     case Stmt::CXXDefaultArgExprClass:
916     case Stmt::CXXDefaultInitExprClass: {
917       Bldr.takeNodes(Pred);
918       ExplodedNodeSet PreVisit;
919       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
920
921       ExplodedNodeSet Tmp;
922       StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
923
924       const Expr *ArgE;
925       if (const CXXDefaultArgExpr *DefE = dyn_cast<CXXDefaultArgExpr>(S))
926         ArgE = DefE->getExpr();
927       else if (const CXXDefaultInitExpr *DefE = dyn_cast<CXXDefaultInitExpr>(S))
928         ArgE = DefE->getExpr();
929       else
930         llvm_unreachable("unknown constant wrapper kind");
931
932       bool IsTemporary = false;
933       if (const MaterializeTemporaryExpr *MTE =
934             dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
935         ArgE = MTE->GetTemporaryExpr();
936         IsTemporary = true;
937       }
938
939       Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
940       if (!ConstantVal)
941         ConstantVal = UnknownVal();
942
943       const LocationContext *LCtx = Pred->getLocationContext();
944       for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end();
945            I != E; ++I) {
946         ProgramStateRef State = (*I)->getState();
947         State = State->BindExpr(S, LCtx, *ConstantVal);
948         if (IsTemporary)
949           State = createTemporaryRegionIfNeeded(State, LCtx,
950                                                 cast<Expr>(S),
951                                                 cast<Expr>(S));
952         Bldr2.generateNode(S, *I, State);
953       }
954
955       getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
956       Bldr.addNodes(Dst);
957       break;
958     }
959
960     // Cases we evaluate as opaque expressions, conjuring a symbol.
961     case Stmt::CXXStdInitializerListExprClass:
962     case Expr::ObjCArrayLiteralClass:
963     case Expr::ObjCDictionaryLiteralClass:
964     case Expr::ObjCBoxedExprClass: {
965       Bldr.takeNodes(Pred);
966
967       ExplodedNodeSet preVisit;
968       getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
969
970       ExplodedNodeSet Tmp;
971       StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
972
973       const Expr *Ex = cast<Expr>(S);
974       QualType resultType = Ex->getType();
975
976       for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end();
977            it != et; ++it) {
978         ExplodedNode *N = *it;
979         const LocationContext *LCtx = N->getLocationContext();
980         SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
981                                                    resultType,
982                                                    currBldrCtx->blockCount());
983         ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result);
984         Bldr2.generateNode(S, N, state);
985       }
986
987       getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
988       Bldr.addNodes(Dst);
989       break;
990     }
991
992     case Stmt::ArraySubscriptExprClass:
993       Bldr.takeNodes(Pred);
994       VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
995       Bldr.addNodes(Dst);
996       break;
997
998     case Stmt::GCCAsmStmtClass:
999       Bldr.takeNodes(Pred);
1000       VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
1001       Bldr.addNodes(Dst);
1002       break;
1003
1004     case Stmt::MSAsmStmtClass:
1005       Bldr.takeNodes(Pred);
1006       VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
1007       Bldr.addNodes(Dst);
1008       break;
1009
1010     case Stmt::BlockExprClass:
1011       Bldr.takeNodes(Pred);
1012       VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
1013       Bldr.addNodes(Dst);
1014       break;
1015
1016     case Stmt::BinaryOperatorClass: {
1017       const BinaryOperator* B = cast<BinaryOperator>(S);
1018       if (B->isLogicalOp()) {
1019         Bldr.takeNodes(Pred);
1020         VisitLogicalExpr(B, Pred, Dst);
1021         Bldr.addNodes(Dst);
1022         break;
1023       }
1024       else if (B->getOpcode() == BO_Comma) {
1025         ProgramStateRef state = Pred->getState();
1026         Bldr.generateNode(B, Pred,
1027                           state->BindExpr(B, Pred->getLocationContext(),
1028                                           state->getSVal(B->getRHS(),
1029                                                   Pred->getLocationContext())));
1030         break;
1031       }
1032
1033       Bldr.takeNodes(Pred);
1034
1035       if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
1036           (B->isRelationalOp() || B->isEqualityOp())) {
1037         ExplodedNodeSet Tmp;
1038         VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
1039         evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
1040       }
1041       else
1042         VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1043
1044       Bldr.addNodes(Dst);
1045       break;
1046     }
1047
1048     case Stmt::CXXOperatorCallExprClass: {
1049       const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S);
1050
1051       // For instance method operators, make sure the 'this' argument has a
1052       // valid region.
1053       const Decl *Callee = OCE->getCalleeDecl();
1054       if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
1055         if (MD->isInstance()) {
1056           ProgramStateRef State = Pred->getState();
1057           const LocationContext *LCtx = Pred->getLocationContext();
1058           ProgramStateRef NewState =
1059             createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
1060           if (NewState != State) {
1061             Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
1062                                      ProgramPoint::PreStmtKind);
1063             // Did we cache out?
1064             if (!Pred)
1065               break;
1066           }
1067         }
1068       }
1069       // FALLTHROUGH
1070     }
1071     case Stmt::CallExprClass:
1072     case Stmt::CXXMemberCallExprClass:
1073     case Stmt::UserDefinedLiteralClass: {
1074       Bldr.takeNodes(Pred);
1075       VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
1076       Bldr.addNodes(Dst);
1077       break;
1078     }
1079
1080     case Stmt::CXXCatchStmtClass: {
1081       Bldr.takeNodes(Pred);
1082       VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
1083       Bldr.addNodes(Dst);
1084       break;
1085     }
1086
1087     case Stmt::CXXTemporaryObjectExprClass:
1088     case Stmt::CXXConstructExprClass: {
1089       Bldr.takeNodes(Pred);
1090       VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
1091       Bldr.addNodes(Dst);
1092       break;
1093     }
1094
1095     case Stmt::CXXNewExprClass: {
1096       Bldr.takeNodes(Pred);
1097       ExplodedNodeSet PostVisit;
1098       VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit);
1099       getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1100       Bldr.addNodes(Dst);
1101       break;
1102     }
1103
1104     case Stmt::CXXDeleteExprClass: {
1105       Bldr.takeNodes(Pred);
1106       ExplodedNodeSet PreVisit;
1107       const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
1108       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1109
1110       for (ExplodedNodeSet::iterator i = PreVisit.begin(),
1111                                      e = PreVisit.end(); i != e ; ++i)
1112         VisitCXXDeleteExpr(CDE, *i, Dst);
1113
1114       Bldr.addNodes(Dst);
1115       break;
1116     }
1117       // FIXME: ChooseExpr is really a constant.  We need to fix
1118       //        the CFG do not model them as explicit control-flow.
1119
1120     case Stmt::ChooseExprClass: { // __builtin_choose_expr
1121       Bldr.takeNodes(Pred);
1122       const ChooseExpr *C = cast<ChooseExpr>(S);
1123       VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
1124       Bldr.addNodes(Dst);
1125       break;
1126     }
1127
1128     case Stmt::CompoundAssignOperatorClass:
1129       Bldr.takeNodes(Pred);
1130       VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1131       Bldr.addNodes(Dst);
1132       break;
1133
1134     case Stmt::CompoundLiteralExprClass:
1135       Bldr.takeNodes(Pred);
1136       VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
1137       Bldr.addNodes(Dst);
1138       break;
1139
1140     case Stmt::BinaryConditionalOperatorClass:
1141     case Stmt::ConditionalOperatorClass: { // '?' operator
1142       Bldr.takeNodes(Pred);
1143       const AbstractConditionalOperator *C
1144         = cast<AbstractConditionalOperator>(S);
1145       VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
1146       Bldr.addNodes(Dst);
1147       break;
1148     }
1149
1150     case Stmt::CXXThisExprClass:
1151       Bldr.takeNodes(Pred);
1152       VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
1153       Bldr.addNodes(Dst);
1154       break;
1155
1156     case Stmt::DeclRefExprClass: {
1157       Bldr.takeNodes(Pred);
1158       const DeclRefExpr *DE = cast<DeclRefExpr>(S);
1159       VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
1160       Bldr.addNodes(Dst);
1161       break;
1162     }
1163
1164     case Stmt::DeclStmtClass:
1165       Bldr.takeNodes(Pred);
1166       VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
1167       Bldr.addNodes(Dst);
1168       break;
1169
1170     case Stmt::ImplicitCastExprClass:
1171     case Stmt::CStyleCastExprClass:
1172     case Stmt::CXXStaticCastExprClass:
1173     case Stmt::CXXDynamicCastExprClass:
1174     case Stmt::CXXReinterpretCastExprClass:
1175     case Stmt::CXXConstCastExprClass:
1176     case Stmt::CXXFunctionalCastExprClass:
1177     case Stmt::ObjCBridgedCastExprClass: {
1178       Bldr.takeNodes(Pred);
1179       const CastExpr *C = cast<CastExpr>(S);
1180       // Handle the previsit checks.
1181       ExplodedNodeSet dstPrevisit;
1182       getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this);
1183
1184       // Handle the expression itself.
1185       ExplodedNodeSet dstExpr;
1186       for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
1187                                      e = dstPrevisit.end(); i != e ; ++i) {
1188         VisitCast(C, C->getSubExpr(), *i, dstExpr);
1189       }
1190
1191       // Handle the postvisit checks.
1192       getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1193       Bldr.addNodes(Dst);
1194       break;
1195     }
1196
1197     case Expr::MaterializeTemporaryExprClass: {
1198       Bldr.takeNodes(Pred);
1199       const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
1200       CreateCXXTemporaryObject(MTE, Pred, Dst);
1201       Bldr.addNodes(Dst);
1202       break;
1203     }
1204
1205     case Stmt::InitListExprClass:
1206       Bldr.takeNodes(Pred);
1207       VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1208       Bldr.addNodes(Dst);
1209       break;
1210
1211     case Stmt::MemberExprClass:
1212       Bldr.takeNodes(Pred);
1213       VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1214       Bldr.addNodes(Dst);
1215       break;
1216
1217     case Stmt::ObjCIvarRefExprClass:
1218       Bldr.takeNodes(Pred);
1219       VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1220       Bldr.addNodes(Dst);
1221       break;
1222
1223     case Stmt::ObjCForCollectionStmtClass:
1224       Bldr.takeNodes(Pred);
1225       VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1226       Bldr.addNodes(Dst);
1227       break;
1228
1229     case Stmt::ObjCMessageExprClass:
1230       Bldr.takeNodes(Pred);
1231       VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1232       Bldr.addNodes(Dst);
1233       break;
1234
1235     case Stmt::ObjCAtThrowStmtClass:
1236     case Stmt::CXXThrowExprClass:
1237       // FIXME: This is not complete.  We basically treat @throw as
1238       // an abort.
1239       Bldr.generateSink(S, Pred, Pred->getState());
1240       break;
1241
1242     case Stmt::ReturnStmtClass:
1243       Bldr.takeNodes(Pred);
1244       VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1245       Bldr.addNodes(Dst);
1246       break;
1247
1248     case Stmt::OffsetOfExprClass:
1249       Bldr.takeNodes(Pred);
1250       VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
1251       Bldr.addNodes(Dst);
1252       break;
1253
1254     case Stmt::UnaryExprOrTypeTraitExprClass:
1255       Bldr.takeNodes(Pred);
1256       VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1257                                     Pred, Dst);
1258       Bldr.addNodes(Dst);
1259       break;
1260
1261     case Stmt::StmtExprClass: {
1262       const StmtExpr *SE = cast<StmtExpr>(S);
1263
1264       if (SE->getSubStmt()->body_empty()) {
1265         // Empty statement expression.
1266         assert(SE->getType() == getContext().VoidTy
1267                && "Empty statement expression must have void type.");
1268         break;
1269       }
1270
1271       if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1272         ProgramStateRef state = Pred->getState();
1273         Bldr.generateNode(SE, Pred,
1274                           state->BindExpr(SE, Pred->getLocationContext(),
1275                                           state->getSVal(LastExpr,
1276                                                   Pred->getLocationContext())));
1277       }
1278       break;
1279     }
1280
1281     case Stmt::UnaryOperatorClass: {
1282       Bldr.takeNodes(Pred);
1283       const UnaryOperator *U = cast<UnaryOperator>(S);
1284       if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
1285         ExplodedNodeSet Tmp;
1286         VisitUnaryOperator(U, Pred, Tmp);
1287         evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1288       }
1289       else
1290         VisitUnaryOperator(U, Pred, Dst);
1291       Bldr.addNodes(Dst);
1292       break;
1293     }
1294
1295     case Stmt::PseudoObjectExprClass: {
1296       Bldr.takeNodes(Pred);
1297       ProgramStateRef state = Pred->getState();
1298       const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
1299       if (const Expr *Result = PE->getResultExpr()) {
1300         SVal V = state->getSVal(Result, Pred->getLocationContext());
1301         Bldr.generateNode(S, Pred,
1302                           state->BindExpr(S, Pred->getLocationContext(), V));
1303       }
1304       else
1305         Bldr.generateNode(S, Pred,
1306                           state->BindExpr(S, Pred->getLocationContext(),
1307                                                    UnknownVal()));
1308
1309       Bldr.addNodes(Dst);
1310       break;
1311     }
1312   }
1313 }
1314
1315 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1316                                        const LocationContext *CalleeLC) {
1317   const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1318   const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
1319   assert(CalleeSF && CallerSF);
1320   ExplodedNode *BeforeProcessingCall = nullptr;
1321   const Stmt *CE = CalleeSF->getCallSite();
1322
1323   // Find the first node before we started processing the call expression.
1324   while (N) {
1325     ProgramPoint L = N->getLocation();
1326     BeforeProcessingCall = N;
1327     N = N->pred_empty() ? nullptr : *(N->pred_begin());
1328
1329     // Skip the nodes corresponding to the inlined code.
1330     if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
1331       continue;
1332     // We reached the caller. Find the node right before we started
1333     // processing the call.
1334     if (L.isPurgeKind())
1335       continue;
1336     if (L.getAs<PreImplicitCall>())
1337       continue;
1338     if (L.getAs<CallEnter>())
1339       continue;
1340     if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1341       if (SP->getStmt() == CE)
1342         continue;
1343     break;
1344   }
1345
1346   if (!BeforeProcessingCall)
1347     return false;
1348
1349   // TODO: Clean up the unneeded nodes.
1350
1351   // Build an Epsilon node from which we will restart the analyzes.
1352   // Note that CE is permitted to be NULL!
1353   ProgramPoint NewNodeLoc =
1354                EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1355   // Add the special flag to GDM to signal retrying with no inlining.
1356   // Note, changing the state ensures that we are not going to cache out.
1357   ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1358   NewNodeState =
1359     NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1360
1361   // Make the new node a successor of BeforeProcessingCall.
1362   bool IsNew = false;
1363   ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1364   // We cached out at this point. Caching out is common due to us backtracking
1365   // from the inlined function, which might spawn several paths.
1366   if (!IsNew)
1367     return true;
1368
1369   NewNode->addPredecessor(BeforeProcessingCall, G);
1370
1371   // Add the new node to the work list.
1372   Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1373                                   CalleeSF->getIndex());
1374   NumTimesRetriedWithoutInlining++;
1375   return true;
1376 }
1377
1378 /// Block entrance.  (Update counters).
1379 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
1380                                          NodeBuilderWithSinks &nodeBuilder,
1381                                          ExplodedNode *Pred) {
1382   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1383
1384   // FIXME: Refactor this into a checker.
1385   if (nodeBuilder.getContext().blockCount() >= AMgr.options.maxBlockVisitOnPath) {
1386     static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
1387     const ExplodedNode *Sink =
1388                    nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1389
1390     // Check if we stopped at the top level function or not.
1391     // Root node should have the location context of the top most function.
1392     const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1393     const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1394     const LocationContext *RootLC =
1395                         (*G.roots_begin())->getLocation().getLocationContext();
1396     if (RootLC->getCurrentStackFrame() != CalleeSF) {
1397       Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1398
1399       // Re-run the call evaluation without inlining it, by storing the
1400       // no-inlining policy in the state and enqueuing the new work item on
1401       // the list. Replay should almost never fail. Use the stats to catch it
1402       // if it does.
1403       if ((!AMgr.options.NoRetryExhausted &&
1404            replayWithoutInlining(Pred, CalleeLC)))
1405         return;
1406       NumMaxBlockCountReachedInInlined++;
1407     } else
1408       NumMaxBlockCountReached++;
1409
1410     // Make sink nodes as exhausted(for stats) only if retry failed.
1411     Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1412   }
1413 }
1414
1415 //===----------------------------------------------------------------------===//
1416 // Branch processing.
1417 //===----------------------------------------------------------------------===//
1418
1419 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1420 /// to try to recover some path-sensitivity for casts of symbolic
1421 /// integers that promote their values (which are currently not tracked well).
1422 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1423 //  cast(s) did was sign-extend the original value.
1424 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
1425                                 ProgramStateRef state,
1426                                 const Stmt *Condition,
1427                                 const LocationContext *LCtx,
1428                                 ASTContext &Ctx) {
1429
1430   const Expr *Ex = dyn_cast<Expr>(Condition);
1431   if (!Ex)
1432     return UnknownVal();
1433
1434   uint64_t bits = 0;
1435   bool bitsInit = false;
1436
1437   while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
1438     QualType T = CE->getType();
1439
1440     if (!T->isIntegralOrEnumerationType())
1441       return UnknownVal();
1442
1443     uint64_t newBits = Ctx.getTypeSize(T);
1444     if (!bitsInit || newBits < bits) {
1445       bitsInit = true;
1446       bits = newBits;
1447     }
1448
1449     Ex = CE->getSubExpr();
1450   }
1451
1452   // We reached a non-cast.  Is it a symbolic value?
1453   QualType T = Ex->getType();
1454
1455   if (!bitsInit || !T->isIntegralOrEnumerationType() ||
1456       Ctx.getTypeSize(T) > bits)
1457     return UnknownVal();
1458
1459   return state->getSVal(Ex, LCtx);
1460 }
1461
1462 #ifndef NDEBUG
1463 static const Stmt *getRightmostLeaf(const Stmt *Condition) {
1464   while (Condition) {
1465     const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1466     if (!BO || !BO->isLogicalOp()) {
1467       return Condition;
1468     }
1469     Condition = BO->getRHS()->IgnoreParens();
1470   }
1471   return nullptr;
1472 }
1473 #endif
1474
1475 // Returns the condition the branch at the end of 'B' depends on and whose value
1476 // has been evaluated within 'B'.
1477 // In most cases, the terminator condition of 'B' will be evaluated fully in
1478 // the last statement of 'B'; in those cases, the resolved condition is the
1479 // given 'Condition'.
1480 // If the condition of the branch is a logical binary operator tree, the CFG is
1481 // optimized: in that case, we know that the expression formed by all but the
1482 // rightmost leaf of the logical binary operator tree must be true, and thus
1483 // the branch condition is at this point equivalent to the truth value of that
1484 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
1485 // expression in its final statement. As the full condition in that case was
1486 // not evaluated, and is thus not in the SVal cache, we need to use that leaf
1487 // expression to evaluate the truth value of the condition in the current state
1488 // space.
1489 static const Stmt *ResolveCondition(const Stmt *Condition,
1490                                     const CFGBlock *B) {
1491   if (const Expr *Ex = dyn_cast<Expr>(Condition))
1492     Condition = Ex->IgnoreParens();
1493
1494   const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1495   if (!BO || !BO->isLogicalOp())
1496     return Condition;
1497
1498   assert(!B->getTerminator().isTemporaryDtorsBranch() &&
1499          "Temporary destructor branches handled by processBindTemporary.");
1500
1501   // For logical operations, we still have the case where some branches
1502   // use the traditional "merge" approach and others sink the branch
1503   // directly into the basic blocks representing the logical operation.
1504   // We need to distinguish between those two cases here.
1505
1506   // The invariants are still shifting, but it is possible that the
1507   // last element in a CFGBlock is not a CFGStmt.  Look for the last
1508   // CFGStmt as the value of the condition.
1509   CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
1510   for (; I != E; ++I) {
1511     CFGElement Elem = *I;
1512     Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
1513     if (!CS)
1514       continue;
1515     const Stmt *LastStmt = CS->getStmt();
1516     assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
1517     return LastStmt;
1518   }
1519   llvm_unreachable("could not resolve condition");
1520 }
1521
1522 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
1523                                NodeBuilderContext& BldCtx,
1524                                ExplodedNode *Pred,
1525                                ExplodedNodeSet &Dst,
1526                                const CFGBlock *DstT,
1527                                const CFGBlock *DstF) {
1528   assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
1529          "CXXBindTemporaryExprs are handled by processBindTemporary.");
1530   const LocationContext *LCtx = Pred->getLocationContext();
1531   PrettyStackTraceLocationContext StackCrashInfo(LCtx);
1532   currBldrCtx = &BldCtx;
1533
1534   // Check for NULL conditions; e.g. "for(;;)"
1535   if (!Condition) {
1536     BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
1537     NullCondBldr.markInfeasible(false);
1538     NullCondBldr.generateNode(Pred->getState(), true, Pred);
1539     return;
1540   }
1541
1542
1543   if (const Expr *Ex = dyn_cast<Expr>(Condition))
1544     Condition = Ex->IgnoreParens();
1545
1546   Condition = ResolveCondition(Condition, BldCtx.getBlock());
1547   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1548                                 Condition->getLocStart(),
1549                                 "Error evaluating branch");
1550
1551   ExplodedNodeSet CheckersOutSet;
1552   getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
1553                                                     Pred, *this);
1554   // We generated only sinks.
1555   if (CheckersOutSet.empty())
1556     return;
1557
1558   BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
1559   for (NodeBuilder::iterator I = CheckersOutSet.begin(),
1560                              E = CheckersOutSet.end(); E != I; ++I) {
1561     ExplodedNode *PredI = *I;
1562
1563     if (PredI->isSink())
1564       continue;
1565
1566     ProgramStateRef PrevState = PredI->getState();
1567     SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
1568
1569     if (X.isUnknownOrUndef()) {
1570       // Give it a chance to recover from unknown.
1571       if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
1572         if (Ex->getType()->isIntegralOrEnumerationType()) {
1573           // Try to recover some path-sensitivity.  Right now casts of symbolic
1574           // integers that promote their values are currently not tracked well.
1575           // If 'Condition' is such an expression, try and recover the
1576           // underlying value and use that instead.
1577           SVal recovered = RecoverCastedSymbol(getStateManager(),
1578                                                PrevState, Condition,
1579                                                PredI->getLocationContext(),
1580                                                getContext());
1581
1582           if (!recovered.isUnknown()) {
1583             X = recovered;
1584           }
1585         }
1586       }
1587     }
1588
1589     // If the condition is still unknown, give up.
1590     if (X.isUnknownOrUndef()) {
1591       builder.generateNode(PrevState, true, PredI);
1592       builder.generateNode(PrevState, false, PredI);
1593       continue;
1594     }
1595
1596     DefinedSVal V = X.castAs<DefinedSVal>();
1597
1598     ProgramStateRef StTrue, StFalse;
1599     std::tie(StTrue, StFalse) = PrevState->assume(V);
1600
1601     // Process the true branch.
1602     if (builder.isFeasible(true)) {
1603       if (StTrue)
1604         builder.generateNode(StTrue, true, PredI);
1605       else
1606         builder.markInfeasible(true);
1607     }
1608
1609     // Process the false branch.
1610     if (builder.isFeasible(false)) {
1611       if (StFalse)
1612         builder.generateNode(StFalse, false, PredI);
1613       else
1614         builder.markInfeasible(false);
1615     }
1616   }
1617   currBldrCtx = nullptr;
1618 }
1619
1620 /// The GDM component containing the set of global variables which have been
1621 /// previously initialized with explicit initializers.
1622 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
1623                                  llvm::ImmutableSet<const VarDecl *>)
1624
1625 void ExprEngine::processStaticInitializer(const DeclStmt *DS,
1626                                           NodeBuilderContext &BuilderCtx,
1627                                           ExplodedNode *Pred,
1628                                           clang::ento::ExplodedNodeSet &Dst,
1629                                           const CFGBlock *DstT,
1630                                           const CFGBlock *DstF) {
1631   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1632   currBldrCtx = &BuilderCtx;
1633
1634   const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
1635   ProgramStateRef state = Pred->getState();
1636   bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
1637   BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
1638
1639   if (!initHasRun) {
1640     state = state->add<InitializedGlobalsSet>(VD);
1641   }
1642
1643   builder.generateNode(state, initHasRun, Pred);
1644   builder.markInfeasible(!initHasRun);
1645
1646   currBldrCtx = nullptr;
1647 }
1648
1649 /// processIndirectGoto - Called by CoreEngine.  Used to generate successor
1650 ///  nodes by processing the 'effects' of a computed goto jump.
1651 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
1652
1653   ProgramStateRef state = builder.getState();
1654   SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
1655
1656   // Three possibilities:
1657   //
1658   //   (1) We know the computed label.
1659   //   (2) The label is NULL (or some other constant), or Undefined.
1660   //   (3) We have no clue about the label.  Dispatch to all targets.
1661   //
1662
1663   typedef IndirectGotoNodeBuilder::iterator iterator;
1664
1665   if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
1666     const LabelDecl *L = LV->getLabel();
1667
1668     for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
1669       if (I.getLabel() == L) {
1670         builder.generateNode(I, state);
1671         return;
1672       }
1673     }
1674
1675     llvm_unreachable("No block with label.");
1676   }
1677
1678   if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
1679     // Dispatch to the first target and mark it as a sink.
1680     //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
1681     // FIXME: add checker visit.
1682     //    UndefBranches.insert(N);
1683     return;
1684   }
1685
1686   // This is really a catch-all.  We don't support symbolics yet.
1687   // FIXME: Implement dispatch for symbolic pointers.
1688
1689   for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
1690     builder.generateNode(I, state);
1691 }
1692
1693 #if 0
1694 static bool stackFrameDoesNotContainInitializedTemporaries(ExplodedNode &Pred) {
1695   const StackFrameContext* Frame = Pred.getStackFrame();
1696   const llvm::ImmutableSet<CXXBindTemporaryContext> &Set =
1697       Pred.getState()->get<InitializedTemporariesSet>();
1698   return std::find_if(Set.begin(), Set.end(),
1699                       [&](const CXXBindTemporaryContext &Ctx) {
1700                         if (Ctx.second == Frame) {
1701                           Ctx.first->dump();
1702                           llvm::errs() << "\n";
1703                         }
1704            return Ctx.second == Frame;
1705          }) == Set.end();
1706 }
1707 #endif
1708
1709 /// ProcessEndPath - Called by CoreEngine.  Used to generate end-of-path
1710 ///  nodes when the control reaches the end of a function.
1711 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
1712                                       ExplodedNode *Pred) {
1713   // FIXME: Assert that stackFrameDoesNotContainInitializedTemporaries(*Pred)).
1714   // We currently cannot enable this assert, as lifetime extended temporaries
1715   // are not modelled correctly.
1716   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1717   StateMgr.EndPath(Pred->getState());
1718
1719   ExplodedNodeSet Dst;
1720   if (Pred->getLocationContext()->inTopFrame()) {
1721     // Remove dead symbols.
1722     ExplodedNodeSet AfterRemovedDead;
1723     removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
1724
1725     // Notify checkers.
1726     for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(),
1727         E = AfterRemovedDead.end(); I != E; ++I) {
1728       getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this);
1729     }
1730   } else {
1731     getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
1732   }
1733
1734   Engine.enqueueEndOfFunction(Dst);
1735 }
1736
1737 /// ProcessSwitch - Called by CoreEngine.  Used to generate successor
1738 ///  nodes by processing the 'effects' of a switch statement.
1739 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
1740   typedef SwitchNodeBuilder::iterator iterator;
1741   ProgramStateRef state = builder.getState();
1742   const Expr *CondE = builder.getCondition();
1743   SVal  CondV_untested = state->getSVal(CondE, builder.getLocationContext());
1744
1745   if (CondV_untested.isUndef()) {
1746     //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
1747     // FIXME: add checker
1748     //UndefBranches.insert(N);
1749
1750     return;
1751   }
1752   DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
1753
1754   ProgramStateRef DefaultSt = state;
1755
1756   iterator I = builder.begin(), EI = builder.end();
1757   bool defaultIsFeasible = I == EI;
1758
1759   for ( ; I != EI; ++I) {
1760     // Successor may be pruned out during CFG construction.
1761     if (!I.getBlock())
1762       continue;
1763
1764     const CaseStmt *Case = I.getCase();
1765
1766     // Evaluate the LHS of the case value.
1767     llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
1768     assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType()));
1769
1770     // Get the RHS of the case, if it exists.
1771     llvm::APSInt V2;
1772     if (const Expr *E = Case->getRHS())
1773       V2 = E->EvaluateKnownConstInt(getContext());
1774     else
1775       V2 = V1;
1776
1777     // FIXME: Eventually we should replace the logic below with a range
1778     //  comparison, rather than concretize the values within the range.
1779     //  This should be easy once we have "ranges" for NonLVals.
1780
1781     do {
1782       nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1));
1783       DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state,
1784                                                CondV, CaseVal);
1785
1786       // Now "assume" that the case matches.
1787       if (ProgramStateRef stateNew = state->assume(Res, true)) {
1788         builder.generateCaseStmtNode(I, stateNew);
1789
1790         // If CondV evaluates to a constant, then we know that this
1791         // is the *only* case that we can take, so stop evaluating the
1792         // others.
1793         if (CondV.getAs<nonloc::ConcreteInt>())
1794           return;
1795       }
1796
1797       // Now "assume" that the case doesn't match.  Add this state
1798       // to the default state (if it is feasible).
1799       if (DefaultSt) {
1800         if (ProgramStateRef stateNew = DefaultSt->assume(Res, false)) {
1801           defaultIsFeasible = true;
1802           DefaultSt = stateNew;
1803         }
1804         else {
1805           defaultIsFeasible = false;
1806           DefaultSt = nullptr;
1807         }
1808       }
1809
1810       // Concretize the next value in the range.
1811       if (V1 == V2)
1812         break;
1813
1814       ++V1;
1815       assert (V1 <= V2);
1816
1817     } while (true);
1818   }
1819
1820   if (!defaultIsFeasible)
1821     return;
1822
1823   // If we have switch(enum value), the default branch is not
1824   // feasible if all of the enum constants not covered by 'case:' statements
1825   // are not feasible values for the switch condition.
1826   //
1827   // Note that this isn't as accurate as it could be.  Even if there isn't
1828   // a case for a particular enum value as long as that enum value isn't
1829   // feasible then it shouldn't be considered for making 'default:' reachable.
1830   const SwitchStmt *SS = builder.getSwitch();
1831   const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
1832   if (CondExpr->getType()->getAs<EnumType>()) {
1833     if (SS->isAllEnumCasesCovered())
1834       return;
1835   }
1836
1837   builder.generateDefaultCaseNode(DefaultSt);
1838 }
1839
1840 //===----------------------------------------------------------------------===//
1841 // Transfer functions: Loads and stores.
1842 //===----------------------------------------------------------------------===//
1843
1844 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
1845                                         ExplodedNode *Pred,
1846                                         ExplodedNodeSet &Dst) {
1847   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1848
1849   ProgramStateRef state = Pred->getState();
1850   const LocationContext *LCtx = Pred->getLocationContext();
1851
1852   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1853     // C permits "extern void v", and if you cast the address to a valid type,
1854     // you can even do things with it. We simply pretend
1855     assert(Ex->isGLValue() || VD->getType()->isVoidType());
1856     SVal V = state->getLValue(VD, Pred->getLocationContext());
1857
1858     // For references, the 'lvalue' is the pointer address stored in the
1859     // reference region.
1860     if (VD->getType()->isReferenceType()) {
1861       if (const MemRegion *R = V.getAsRegion())
1862         V = state->getSVal(R);
1863       else
1864         V = UnknownVal();
1865     }
1866
1867     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1868                       ProgramPoint::PostLValueKind);
1869     return;
1870   }
1871   if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
1872     assert(!Ex->isGLValue());
1873     SVal V = svalBuilder.makeIntVal(ED->getInitVal());
1874     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
1875     return;
1876   }
1877   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1878     SVal V = svalBuilder.getFunctionPointer(FD);
1879     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1880                       ProgramPoint::PostLValueKind);
1881     return;
1882   }
1883   if (isa<FieldDecl>(D)) {
1884     // FIXME: Compute lvalue of field pointers-to-member.
1885     // Right now we just use a non-null void pointer, so that it gives proper
1886     // results in boolean contexts.
1887     SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
1888                                           currBldrCtx->blockCount());
1889     state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
1890     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1891                       ProgramPoint::PostLValueKind);
1892     return;
1893   }
1894
1895   llvm_unreachable("Support for this Decl not implemented.");
1896 }
1897
1898 /// VisitArraySubscriptExpr - Transfer function for array accesses
1899 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A,
1900                                              ExplodedNode *Pred,
1901                                              ExplodedNodeSet &Dst){
1902
1903   const Expr *Base = A->getBase()->IgnoreParens();
1904   const Expr *Idx  = A->getIdx()->IgnoreParens();
1905
1906
1907   ExplodedNodeSet checkerPreStmt;
1908   getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this);
1909
1910   StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currBldrCtx);
1911   assert(A->isGLValue() ||
1912           (!AMgr.getLangOpts().CPlusPlus &&
1913            A->getType().isCForbiddenLValueType()));
1914
1915   for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(),
1916                                  ei = checkerPreStmt.end(); it != ei; ++it) {
1917     const LocationContext *LCtx = (*it)->getLocationContext();
1918     ProgramStateRef state = (*it)->getState();
1919     SVal V = state->getLValue(A->getType(),
1920                               state->getSVal(Idx, LCtx),
1921                               state->getSVal(Base, LCtx));
1922     Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), nullptr,
1923                       ProgramPoint::PostLValueKind);
1924   }
1925 }
1926
1927 /// VisitMemberExpr - Transfer function for member expressions.
1928 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
1929                                  ExplodedNodeSet &Dst) {
1930
1931   // FIXME: Prechecks eventually go in ::Visit().
1932   ExplodedNodeSet CheckedSet;
1933   getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
1934
1935   ExplodedNodeSet EvalSet;
1936   ValueDecl *Member = M->getMemberDecl();
1937
1938   // Handle static member variables and enum constants accessed via
1939   // member syntax.
1940   if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
1941     ExplodedNodeSet Dst;
1942     for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
1943          I != E; ++I) {
1944       VisitCommonDeclRefExpr(M, Member, Pred, EvalSet);
1945     }
1946   } else {
1947     StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
1948     ExplodedNodeSet Tmp;
1949
1950     for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
1951          I != E; ++I) {
1952       ProgramStateRef state = (*I)->getState();
1953       const LocationContext *LCtx = (*I)->getLocationContext();
1954       Expr *BaseExpr = M->getBase();
1955
1956       // Handle C++ method calls.
1957       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
1958         if (MD->isInstance())
1959           state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
1960
1961         SVal MDVal = svalBuilder.getFunctionPointer(MD);
1962         state = state->BindExpr(M, LCtx, MDVal);
1963
1964         Bldr.generateNode(M, *I, state);
1965         continue;
1966       }
1967
1968       // Handle regular struct fields / member variables.
1969       state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
1970       SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
1971
1972       FieldDecl *field = cast<FieldDecl>(Member);
1973       SVal L = state->getLValue(field, baseExprVal);
1974
1975       if (M->isGLValue() || M->getType()->isArrayType()) {
1976         // We special-case rvalues of array type because the analyzer cannot
1977         // reason about them, since we expect all regions to be wrapped in Locs.
1978         // We instead treat these as lvalues and assume that they will decay to
1979         // pointers as soon as they are used.
1980         if (!M->isGLValue()) {
1981           assert(M->getType()->isArrayType());
1982           const ImplicitCastExpr *PE =
1983             dyn_cast<ImplicitCastExpr>((*I)->getParentMap().getParent(M));
1984           if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
1985             llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
1986           }
1987         }
1988
1989         if (field->getType()->isReferenceType()) {
1990           if (const MemRegion *R = L.getAsRegion())
1991             L = state->getSVal(R);
1992           else
1993             L = UnknownVal();
1994         }
1995
1996         Bldr.generateNode(M, *I, state->BindExpr(M, LCtx, L), nullptr,
1997                           ProgramPoint::PostLValueKind);
1998       } else {
1999         Bldr.takeNodes(*I);
2000         evalLoad(Tmp, M, M, *I, state, L);
2001         Bldr.addNodes(Tmp);
2002       }
2003     }
2004   }
2005
2006   getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
2007 }
2008
2009 namespace {
2010 class CollectReachableSymbolsCallback final : public SymbolVisitor {
2011   InvalidatedSymbols Symbols;
2012 public:
2013   CollectReachableSymbolsCallback(ProgramStateRef State) {}
2014   const InvalidatedSymbols &getSymbols() const { return Symbols; }
2015
2016   bool VisitSymbol(SymbolRef Sym) override {
2017     Symbols.insert(Sym);
2018     return true;
2019   }
2020 };
2021 } // end anonymous namespace
2022
2023 // A value escapes in three possible cases:
2024 // (1) We are binding to something that is not a memory region.
2025 // (2) We are binding to a MemrRegion that does not have stack storage.
2026 // (3) We are binding to a MemRegion with stack storage that the store
2027 //     does not understand.
2028 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
2029                                                         SVal Loc, SVal Val) {
2030   // Are we storing to something that causes the value to "escape"?
2031   bool escapes = true;
2032
2033   // TODO: Move to StoreManager.
2034   if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
2035     escapes = !regionLoc->getRegion()->hasStackStorage();
2036
2037     if (!escapes) {
2038       // To test (3), generate a new state with the binding added.  If it is
2039       // the same state, then it escapes (since the store cannot represent
2040       // the binding).
2041       // Do this only if we know that the store is not supposed to generate the
2042       // same state.
2043       SVal StoredVal = State->getSVal(regionLoc->getRegion());
2044       if (StoredVal != Val)
2045         escapes = (State == (State->bindLoc(*regionLoc, Val)));
2046     }
2047   }
2048
2049   // If our store can represent the binding and we aren't storing to something
2050   // that doesn't have local storage then just return and have the simulation
2051   // state continue as is.
2052   if (!escapes)
2053     return State;
2054
2055   // Otherwise, find all symbols referenced by 'val' that we are tracking
2056   // and stop tracking them.
2057   CollectReachableSymbolsCallback Scanner =
2058       State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val);
2059   const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
2060   State = getCheckerManager().runCheckersForPointerEscape(State,
2061                                                           EscapedSymbols,
2062                                                           /*CallEvent*/ nullptr,
2063                                                           PSK_EscapeOnBind,
2064                                                           nullptr);
2065
2066   return State;
2067 }
2068
2069 ProgramStateRef
2070 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
2071     const InvalidatedSymbols *Invalidated,
2072     ArrayRef<const MemRegion *> ExplicitRegions,
2073     ArrayRef<const MemRegion *> Regions,
2074     const CallEvent *Call,
2075     RegionAndSymbolInvalidationTraits &ITraits) {
2076
2077   if (!Invalidated || Invalidated->empty())
2078     return State;
2079
2080   if (!Call)
2081     return getCheckerManager().runCheckersForPointerEscape(State,
2082                                                            *Invalidated,
2083                                                            nullptr,
2084                                                            PSK_EscapeOther,
2085                                                            &ITraits);
2086
2087   // If the symbols were invalidated by a call, we want to find out which ones
2088   // were invalidated directly due to being arguments to the call.
2089   InvalidatedSymbols SymbolsDirectlyInvalidated;
2090   for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
2091       E = ExplicitRegions.end(); I != E; ++I) {
2092     if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
2093       SymbolsDirectlyInvalidated.insert(R->getSymbol());
2094   }
2095
2096   InvalidatedSymbols SymbolsIndirectlyInvalidated;
2097   for (InvalidatedSymbols::const_iterator I=Invalidated->begin(),
2098       E = Invalidated->end(); I!=E; ++I) {
2099     SymbolRef sym = *I;
2100     if (SymbolsDirectlyInvalidated.count(sym))
2101       continue;
2102     SymbolsIndirectlyInvalidated.insert(sym);
2103   }
2104
2105   if (!SymbolsDirectlyInvalidated.empty())
2106     State = getCheckerManager().runCheckersForPointerEscape(State,
2107         SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
2108
2109   // Notify about the symbols that get indirectly invalidated by the call.
2110   if (!SymbolsIndirectlyInvalidated.empty())
2111     State = getCheckerManager().runCheckersForPointerEscape(State,
2112         SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
2113
2114   return State;
2115 }
2116
2117 /// evalBind - Handle the semantics of binding a value to a specific location.
2118 ///  This method is used by evalStore and (soon) VisitDeclStmt, and others.
2119 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
2120                           ExplodedNode *Pred,
2121                           SVal location, SVal Val,
2122                           bool atDeclInit, const ProgramPoint *PP) {
2123
2124   const LocationContext *LC = Pred->getLocationContext();
2125   PostStmt PS(StoreE, LC);
2126   if (!PP)
2127     PP = &PS;
2128
2129   // Do a previsit of the bind.
2130   ExplodedNodeSet CheckedSet;
2131   getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
2132                                          StoreE, *this, *PP);
2133
2134
2135   StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
2136
2137   // If the location is not a 'Loc', it will already be handled by
2138   // the checkers.  There is nothing left to do.
2139   if (!location.getAs<Loc>()) {
2140     const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
2141                                      /*tag*/nullptr);
2142     ProgramStateRef state = Pred->getState();
2143     state = processPointerEscapedOnBind(state, location, Val);
2144     Bldr.generateNode(L, state, Pred);
2145     return;
2146   }
2147
2148
2149   for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2150        I!=E; ++I) {
2151     ExplodedNode *PredI = *I;
2152     ProgramStateRef state = PredI->getState();
2153
2154     state = processPointerEscapedOnBind(state, location, Val);
2155
2156     // When binding the value, pass on the hint that this is a initialization.
2157     // For initializations, we do not need to inform clients of region
2158     // changes.
2159     state = state->bindLoc(location.castAs<Loc>(),
2160                            Val, /* notifyChanges = */ !atDeclInit);
2161
2162     const MemRegion *LocReg = nullptr;
2163     if (Optional<loc::MemRegionVal> LocRegVal =
2164             location.getAs<loc::MemRegionVal>()) {
2165       LocReg = LocRegVal->getRegion();
2166     }
2167
2168     const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
2169     Bldr.generateNode(L, state, PredI);
2170   }
2171 }
2172
2173 /// evalStore - Handle the semantics of a store via an assignment.
2174 ///  @param Dst The node set to store generated state nodes
2175 ///  @param AssignE The assignment expression if the store happens in an
2176 ///         assignment.
2177 ///  @param LocationE The location expression that is stored to.
2178 ///  @param state The current simulation state
2179 ///  @param location The location to store the value
2180 ///  @param Val The value to be stored
2181 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
2182                              const Expr *LocationE,
2183                              ExplodedNode *Pred,
2184                              ProgramStateRef state, SVal location, SVal Val,
2185                              const ProgramPointTag *tag) {
2186   // Proceed with the store.  We use AssignE as the anchor for the PostStore
2187   // ProgramPoint if it is non-NULL, and LocationE otherwise.
2188   const Expr *StoreE = AssignE ? AssignE : LocationE;
2189
2190   // Evaluate the location (checks for bad dereferences).
2191   ExplodedNodeSet Tmp;
2192   evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
2193
2194   if (Tmp.empty())
2195     return;
2196
2197   if (location.isUndef())
2198     return;
2199
2200   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
2201     evalBind(Dst, StoreE, *NI, location, Val, false);
2202 }
2203
2204 void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
2205                           const Expr *NodeEx,
2206                           const Expr *BoundEx,
2207                           ExplodedNode *Pred,
2208                           ProgramStateRef state,
2209                           SVal location,
2210                           const ProgramPointTag *tag,
2211                           QualType LoadTy)
2212 {
2213   assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2214
2215   // Are we loading from a region?  This actually results in two loads; one
2216   // to fetch the address of the referenced value and one to fetch the
2217   // referenced value.
2218   if (const TypedValueRegion *TR =
2219         dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
2220
2221     QualType ValTy = TR->getValueType();
2222     if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
2223       static SimpleProgramPointTag
2224              loadReferenceTag(TagProviderName, "Load Reference");
2225       ExplodedNodeSet Tmp;
2226       evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
2227                      location, &loadReferenceTag,
2228                      getContext().getPointerType(RT->getPointeeType()));
2229
2230       // Perform the load from the referenced value.
2231       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
2232         state = (*I)->getState();
2233         location = state->getSVal(BoundEx, (*I)->getLocationContext());
2234         evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
2235       }
2236       return;
2237     }
2238   }
2239
2240   evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
2241 }
2242
2243 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
2244                                 const Expr *NodeEx,
2245                                 const Expr *BoundEx,
2246                                 ExplodedNode *Pred,
2247                                 ProgramStateRef state,
2248                                 SVal location,
2249                                 const ProgramPointTag *tag,
2250                                 QualType LoadTy) {
2251   assert(NodeEx);
2252   assert(BoundEx);
2253   // Evaluate the location (checks for bad dereferences).
2254   ExplodedNodeSet Tmp;
2255   evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
2256   if (Tmp.empty())
2257     return;
2258
2259   StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2260   if (location.isUndef())
2261     return;
2262
2263   // Proceed with the load.
2264   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
2265     state = (*NI)->getState();
2266     const LocationContext *LCtx = (*NI)->getLocationContext();
2267
2268     SVal V = UnknownVal();
2269     if (location.isValid()) {
2270       if (LoadTy.isNull())
2271         LoadTy = BoundEx->getType();
2272       V = state->getSVal(location.castAs<Loc>(), LoadTy);
2273     }
2274
2275     Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
2276                       ProgramPoint::PostLoadKind);
2277   }
2278 }
2279
2280 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2281                               const Stmt *NodeEx,
2282                               const Stmt *BoundEx,
2283                               ExplodedNode *Pred,
2284                               ProgramStateRef state,
2285                               SVal location,
2286                               const ProgramPointTag *tag,
2287                               bool isLoad) {
2288   StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2289   // Early checks for performance reason.
2290   if (location.isUnknown()) {
2291     return;
2292   }
2293
2294   ExplodedNodeSet Src;
2295   BldrTop.takeNodes(Pred);
2296   StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2297   if (Pred->getState() != state) {
2298     // Associate this new state with an ExplodedNode.
2299     // FIXME: If I pass null tag, the graph is incorrect, e.g for
2300     //   int *p;
2301     //   p = 0;
2302     //   *p = 0xDEADBEEF;
2303     // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2304     // instead "int *p" is noted as
2305     // "Variable 'p' initialized to a null pointer value"
2306
2307     static SimpleProgramPointTag tag(TagProviderName, "Location");
2308     Bldr.generateNode(NodeEx, Pred, state, &tag);
2309   }
2310   ExplodedNodeSet Tmp;
2311   getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2312                                              NodeEx, BoundEx, *this);
2313   BldrTop.addNodes(Tmp);
2314 }
2315
2316 std::pair<const ProgramPointTag *, const ProgramPointTag*>
2317 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
2318   static SimpleProgramPointTag
2319          eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
2320                                            "Eagerly Assume True"),
2321          eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
2322                                             "Eagerly Assume False");
2323   return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2324                         &eagerlyAssumeBinOpBifurcationFalse);
2325 }
2326
2327 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
2328                                                    ExplodedNodeSet &Src,
2329                                                    const Expr *Ex) {
2330   StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2331
2332   for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
2333     ExplodedNode *Pred = *I;
2334     // Test if the previous node was as the same expression.  This can happen
2335     // when the expression fails to evaluate to anything meaningful and
2336     // (as an optimization) we don't generate a node.
2337     ProgramPoint P = Pred->getLocation();
2338     if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2339       continue;
2340     }
2341
2342     ProgramStateRef state = Pred->getState();
2343     SVal V = state->getSVal(Ex, Pred->getLocationContext());
2344     Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
2345     if (SEV && SEV->isExpression()) {
2346       const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2347         geteagerlyAssumeBinOpBifurcationTags();
2348
2349       ProgramStateRef StateTrue, StateFalse;
2350       std::tie(StateTrue, StateFalse) = state->assume(*SEV);
2351
2352       // First assume that the condition is true.
2353       if (StateTrue) {
2354         SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2355         StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2356         Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2357       }
2358
2359       // Next, assume that the condition is false.
2360       if (StateFalse) {
2361         SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2362         StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2363         Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2364       }
2365     }
2366   }
2367 }
2368
2369 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
2370                                  ExplodedNodeSet &Dst) {
2371   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2372   // We have processed both the inputs and the outputs.  All of the outputs
2373   // should evaluate to Locs.  Nuke all of their values.
2374
2375   // FIXME: Some day in the future it would be nice to allow a "plug-in"
2376   // which interprets the inline asm and stores proper results in the
2377   // outputs.
2378
2379   ProgramStateRef state = Pred->getState();
2380
2381   for (const Expr *O : A->outputs()) {
2382     SVal X = state->getSVal(O, Pred->getLocationContext());
2383     assert (!X.getAs<NonLoc>());  // Should be an Lval, or unknown, undef.
2384
2385     if (Optional<Loc> LV = X.getAs<Loc>())
2386       state = state->bindLoc(*LV, UnknownVal());
2387   }
2388
2389   Bldr.generateNode(A, Pred, state);
2390 }
2391
2392 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
2393                                 ExplodedNodeSet &Dst) {
2394   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2395   Bldr.generateNode(A, Pred, Pred->getState());
2396 }
2397
2398 //===----------------------------------------------------------------------===//
2399 // Visualization.
2400 //===----------------------------------------------------------------------===//
2401
2402 #ifndef NDEBUG
2403 static ExprEngine* GraphPrintCheckerState;
2404 static SourceManager* GraphPrintSourceManager;
2405
2406 namespace llvm {
2407 template<>
2408 struct DOTGraphTraits<ExplodedNode*> :
2409   public DefaultDOTGraphTraits {
2410
2411   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2412
2413   // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
2414   // work.
2415   static std::string getNodeAttributes(const ExplodedNode *N, void*) {
2416
2417 #if 0
2418       // FIXME: Replace with a general scheme to tell if the node is
2419       // an error node.
2420     if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
2421         GraphPrintCheckerState->isExplicitNullDeref(N) ||
2422         GraphPrintCheckerState->isUndefDeref(N) ||
2423         GraphPrintCheckerState->isUndefStore(N) ||
2424         GraphPrintCheckerState->isUndefControlFlow(N) ||
2425         GraphPrintCheckerState->isUndefResult(N) ||
2426         GraphPrintCheckerState->isBadCall(N) ||
2427         GraphPrintCheckerState->isUndefArg(N))
2428       return "color=\"red\",style=\"filled\"";
2429
2430     if (GraphPrintCheckerState->isNoReturnCall(N))
2431       return "color=\"blue\",style=\"filled\"";
2432 #endif
2433     return "";
2434   }
2435
2436   static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
2437     if (SLoc.isFileID()) {
2438       Out << "\\lline="
2439         << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2440         << " col="
2441         << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
2442         << "\\l";
2443     }
2444   }
2445
2446   static std::string getNodeLabel(const ExplodedNode *N, void*){
2447
2448     std::string sbuf;
2449     llvm::raw_string_ostream Out(sbuf);
2450
2451     // Program Location.
2452     ProgramPoint Loc = N->getLocation();
2453
2454     switch (Loc.getKind()) {
2455       case ProgramPoint::BlockEntranceKind: {
2456         Out << "Block Entrance: B"
2457             << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
2458         if (const NamedDecl *ND =
2459                     dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) {
2460           Out << " (";
2461           ND->printName(Out);
2462           Out << ")";
2463         }
2464         break;
2465       }
2466
2467       case ProgramPoint::BlockExitKind:
2468         assert (false);
2469         break;
2470
2471       case ProgramPoint::CallEnterKind:
2472         Out << "CallEnter";
2473         break;
2474
2475       case ProgramPoint::CallExitBeginKind:
2476         Out << "CallExitBegin";
2477         break;
2478
2479       case ProgramPoint::CallExitEndKind:
2480         Out << "CallExitEnd";
2481         break;
2482
2483       case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
2484         Out << "PostStmtPurgeDeadSymbols";
2485         break;
2486
2487       case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
2488         Out << "PreStmtPurgeDeadSymbols";
2489         break;
2490
2491       case ProgramPoint::EpsilonKind:
2492         Out << "Epsilon Point";
2493         break;
2494
2495       case ProgramPoint::PreImplicitCallKind: {
2496         ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2497         Out << "PreCall: ";
2498
2499         // FIXME: Get proper printing options.
2500         PC.getDecl()->print(Out, LangOptions());
2501         printLocation(Out, PC.getLocation());
2502         break;
2503       }
2504
2505       case ProgramPoint::PostImplicitCallKind: {
2506         ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2507         Out << "PostCall: ";
2508
2509         // FIXME: Get proper printing options.
2510         PC.getDecl()->print(Out, LangOptions());
2511         printLocation(Out, PC.getLocation());
2512         break;
2513       }
2514
2515       case ProgramPoint::PostInitializerKind: {
2516         Out << "PostInitializer: ";
2517         const CXXCtorInitializer *Init =
2518           Loc.castAs<PostInitializer>().getInitializer();
2519         if (const FieldDecl *FD = Init->getAnyMember())
2520           Out << *FD;
2521         else {
2522           QualType Ty = Init->getTypeSourceInfo()->getType();
2523           Ty = Ty.getLocalUnqualifiedType();
2524           LangOptions LO; // FIXME.
2525           Ty.print(Out, LO);
2526         }
2527         break;
2528       }
2529
2530       case ProgramPoint::BlockEdgeKind: {
2531         const BlockEdge &E = Loc.castAs<BlockEdge>();
2532         Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
2533             << E.getDst()->getBlockID()  << ')';
2534
2535         if (const Stmt *T = E.getSrc()->getTerminator()) {
2536           SourceLocation SLoc = T->getLocStart();
2537
2538           Out << "\\|Terminator: ";
2539           LangOptions LO; // FIXME.
2540           E.getSrc()->printTerminator(Out, LO);
2541
2542           if (SLoc.isFileID()) {
2543             Out << "\\lline="
2544               << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2545               << " col="
2546               << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
2547           }
2548
2549           if (isa<SwitchStmt>(T)) {
2550             const Stmt *Label = E.getDst()->getLabel();
2551
2552             if (Label) {
2553               if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
2554                 Out << "\\lcase ";
2555                 LangOptions LO; // FIXME.
2556                 if (C->getLHS())
2557                   C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO));
2558
2559                 if (const Stmt *RHS = C->getRHS()) {
2560                   Out << " .. ";
2561                   RHS->printPretty(Out, nullptr, PrintingPolicy(LO));
2562                 }
2563
2564                 Out << ":";
2565               }
2566               else {
2567                 assert (isa<DefaultStmt>(Label));
2568                 Out << "\\ldefault:";
2569               }
2570             }
2571             else
2572               Out << "\\l(implicit) default:";
2573           }
2574           else if (isa<IndirectGotoStmt>(T)) {
2575             // FIXME
2576           }
2577           else {
2578             Out << "\\lCondition: ";
2579             if (*E.getSrc()->succ_begin() == E.getDst())
2580               Out << "true";
2581             else
2582               Out << "false";
2583           }
2584
2585           Out << "\\l";
2586         }
2587
2588 #if 0
2589           // FIXME: Replace with a general scheme to determine
2590           // the name of the check.
2591         if (GraphPrintCheckerState->isUndefControlFlow(N)) {
2592           Out << "\\|Control-flow based on\\lUndefined value.\\l";
2593         }
2594 #endif
2595         break;
2596       }
2597
2598       default: {
2599         const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
2600         assert(S != nullptr && "Expecting non-null Stmt");
2601
2602         Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
2603         LangOptions LO; // FIXME.
2604         S->printPretty(Out, nullptr, PrintingPolicy(LO));
2605         printLocation(Out, S->getLocStart());
2606
2607         if (Loc.getAs<PreStmt>())
2608           Out << "\\lPreStmt\\l;";
2609         else if (Loc.getAs<PostLoad>())
2610           Out << "\\lPostLoad\\l;";
2611         else if (Loc.getAs<PostStore>())
2612           Out << "\\lPostStore\\l";
2613         else if (Loc.getAs<PostLValue>())
2614           Out << "\\lPostLValue\\l";
2615
2616 #if 0
2617           // FIXME: Replace with a general scheme to determine
2618           // the name of the check.
2619         if (GraphPrintCheckerState->isImplicitNullDeref(N))
2620           Out << "\\|Implicit-Null Dereference.\\l";
2621         else if (GraphPrintCheckerState->isExplicitNullDeref(N))
2622           Out << "\\|Explicit-Null Dereference.\\l";
2623         else if (GraphPrintCheckerState->isUndefDeref(N))
2624           Out << "\\|Dereference of undefialied value.\\l";
2625         else if (GraphPrintCheckerState->isUndefStore(N))
2626           Out << "\\|Store to Undefined Loc.";
2627         else if (GraphPrintCheckerState->isUndefResult(N))
2628           Out << "\\|Result of operation is undefined.";
2629         else if (GraphPrintCheckerState->isNoReturnCall(N))
2630           Out << "\\|Call to function marked \"noreturn\".";
2631         else if (GraphPrintCheckerState->isBadCall(N))
2632           Out << "\\|Call to NULL/Undefined.";
2633         else if (GraphPrintCheckerState->isUndefArg(N))
2634           Out << "\\|Argument in call is undefined";
2635 #endif
2636
2637         break;
2638       }
2639     }
2640
2641     ProgramStateRef state = N->getState();
2642     Out << "\\|StateID: " << (const void*) state.get()
2643         << " NodeID: " << (const void*) N << "\\|";
2644     state->printDOT(Out);
2645
2646     Out << "\\l";
2647
2648     if (const ProgramPointTag *tag = Loc.getTag()) {
2649       Out << "\\|Tag: " << tag->getTagDescription();
2650       Out << "\\l";
2651     }
2652     return Out.str();
2653   }
2654 };
2655 } // end llvm namespace
2656 #endif
2657
2658 void ExprEngine::ViewGraph(bool trim) {
2659 #ifndef NDEBUG
2660   if (trim) {
2661     std::vector<const ExplodedNode*> Src;
2662
2663     // Flush any outstanding reports to make sure we cover all the nodes.
2664     // This does not cause them to get displayed.
2665     for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
2666       const_cast<BugType*>(*I)->FlushReports(BR);
2667
2668     // Iterate through the reports and get their nodes.
2669     for (BugReporter::EQClasses_iterator
2670            EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
2671       ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
2672       if (N) Src.push_back(N);
2673     }
2674
2675     ViewGraph(Src);
2676   }
2677   else {
2678     GraphPrintCheckerState = this;
2679     GraphPrintSourceManager = &getContext().getSourceManager();
2680
2681     llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
2682
2683     GraphPrintCheckerState = nullptr;
2684     GraphPrintSourceManager = nullptr;
2685   }
2686 #endif
2687 }
2688
2689 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
2690 #ifndef NDEBUG
2691   GraphPrintCheckerState = this;
2692   GraphPrintSourceManager = &getContext().getSourceManager();
2693
2694   std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
2695
2696   if (!TrimmedG.get())
2697     llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
2698   else
2699     llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
2700
2701   GraphPrintCheckerState = nullptr;
2702   GraphPrintSourceManager = nullptr;
2703 #endif
2704 }