1 //=-- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- C++ -*-=
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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"
34 #include "llvm/Support/GraphWriter.h"
37 using namespace clang;
41 #define DEBUG_TYPE "ExprEngine"
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");
54 typedef std::pair<const CXXBindTemporaryExpr *, const StackFrameContext *>
55 CXXBindTemporaryContext;
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>)
63 //===----------------------------------------------------------------------===//
64 // Engine construction and deletion.
65 //===----------------------------------------------------------------------===//
67 static const char* TagProviderName = "ExprEngine";
69 ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled,
70 SetOfConstDecls *VisitedCalleesIn,
71 FunctionSummariesTy *FS,
72 InliningModes HowToInlineIn)
74 AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
77 StateMgr(getContext(), mgr.getStoreManagerCreator(),
78 mgr.getConstraintManagerCreator(), G.getAllocator(),
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)
88 unsigned TrimInterval = mgr.options.getGraphTrimInterval();
89 if (TrimInterval != 0) {
90 // Enable eager node reclaimation when constructing the ExplodedGraph.
91 G.enableNodeReclamation(TrimInterval);
95 ExprEngine::~ExprEngine() {
99 //===----------------------------------------------------------------------===//
101 //===----------------------------------------------------------------------===//
103 ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
104 ProgramStateRef state = StateMgr.getInitialState(InitLoc);
105 const Decl *D = InitLoc->getDecl();
108 // FIXME: It would be nice if we had a more general mechanism to add
109 // such preconditions. Some day.
112 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
113 // Precondition: the first argument of 'main' is an integer guaranteed
115 const IdentifierInfo *II = FD->getIdentifier();
116 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
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())
125 const MemRegion *R = state->getRegion(PD, InitLoc);
129 SVal V = state->getSVal(loc::MemRegionVal(R));
130 SVal Constraint_untested = evalBinOp(state, BO_GT, V,
131 svalBuilder.makeZeroVal(T),
132 svalBuilder.getConditionType());
134 Optional<DefinedOrUnknownSVal> Constraint =
135 Constraint_untested.getAs<DefinedOrUnknownSVal>();
140 if (ProgramStateRef newState = state->assume(*Constraint, true))
147 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
148 // Precondition: 'self' is always non-null upon entry to an Objective-C
150 const ImplicitParamDecl *SelfD = MD->getSelfDecl();
151 const MemRegion *R = state->getRegion(SelfD, InitLoc);
152 SVal V = state->getSVal(loc::MemRegionVal(R));
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");
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");
182 ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State,
183 const LocationContext *LC,
185 const Expr *Result) {
186 SVal V = State->getSVal(Ex, LC);
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>())
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());
200 ProgramStateManager &StateMgr = State->getStateManager();
201 MemRegionManager &MRMgr = StateMgr.getRegionManager();
202 StoreManager &StoreMgr = StateMgr.getStoreManager();
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)
214 else if (CE->getCastKind() != CK_NoOp)
217 Inner = CE->getSubExpr()->IgnoreParens();
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);
233 TR = MRMgr.getCXXTempObjectRegion(Inner, LC);
235 SVal Reg = loc::MemRegionVal(TR);
238 V = getSValBuilder().conjureSymbolVal(Result, LC, TR->getValueType(),
239 currBldrCtx->blockCount());
240 State = State->bindLoc(Reg, V);
242 // Re-apply the casts (from innermost to outermost) for type sanity.
243 for (SmallVectorImpl<const CastExpr *>::reverse_iterator I = Casts.rbegin(),
246 Reg = StoreMgr.evalDerivedToBase(Reg, *I);
249 State = State->BindExpr(Result, LC, Reg);
253 //===----------------------------------------------------------------------===//
254 // Top-level transfer function logic (Dispatcher).
255 //===----------------------------------------------------------------------===//
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);
264 bool ExprEngine::wantsRegionChangeUpdate(ProgramStateRef state) {
265 return getCheckerManager().wantsRegionChangeUpdate(state);
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);
278 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
279 const char *NL, const char *Sep) {
280 getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
283 void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
284 getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
287 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
288 unsigned StmtIdx, NodeBuilderContext *Ctx) {
289 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
290 currStmtIdx = StmtIdx;
293 switch (E.getKind()) {
294 case CFGElement::Statement:
295 ProcessStmt(const_cast<Stmt*>(E.castAs<CFGStmt>().getStmt()), Pred);
297 case CFGElement::Initializer:
298 ProcessInitializer(E.castAs<CFGInitializer>().getInitializer(), Pred);
300 case CFGElement::NewAllocator:
301 ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(),
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);
314 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
316 const ExplodedNode *Pred,
317 const LocationContext *LC) {
319 // Are we never purging state values?
320 if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
323 // Is this the beginning of a basic block?
324 if (Pred->getLocation().getAs<BlockEntrance>())
327 // Is this on a non-expression?
328 if (!isa<Expr>(S.getStmt()))
331 // Run before processing a call.
332 if (CallEvent::isCallStmt(S.getStmt()))
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()));
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");
351 if (!DiagnosticStmt) {
352 DiagnosticStmt = ReferenceStmt;
353 assert(DiagnosticStmt && "Required for clearing a LocationContext");
356 NumRemoveDeadBindings++;
357 ProgramStateRef CleanedState = Pred->getState();
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();
368 const StackFrameContext *SFC = LC ? LC->getCurrentStackFrame() : nullptr;
369 SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
371 getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
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,
376 CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
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);
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);
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();
403 // The constraint manager has not been cleaned up yet, so clean up now.
404 CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
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.");
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);
423 void ExprEngine::ProcessStmt(const CFGStmt S,
424 ExplodedNode *Pred) {
425 // Reclaim any unnecessary nodes in the ExplodedGraph.
426 G.reclaimRecentlyAllocatedNodes();
428 const Stmt *currStmt = S.getStmt();
429 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
430 currStmt->getLocStart(),
431 "Error evaluating statement");
433 // Remove dead bindings and symbols.
434 ExplodedNodeSet CleanedStates;
435 if (shouldRemoveDeadBindings(AMgr, S, Pred, Pred->getLocationContext())){
436 removeDead(Pred, CleanedStates, currStmt, Pred->getLocationContext());
438 CleanedStates.Add(Pred);
440 // Visit the statement.
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);
450 // Enqueue the new nodes onto the work list.
451 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
454 void ExprEngine::ProcessInitializer(const CFGInitializer Init,
455 ExplodedNode *Pred) {
456 const CXXCtorInitializer *BMI = Init.getInitializer();
458 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
459 BMI->getSourceLocation(),
460 "Error evaluating initializer");
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());
468 ProgramStateRef State = Pred->getState();
469 SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
471 ExplodedNodeSet Tmp(Pred);
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);
485 Field = BMI->getMember();
486 FieldLoc = State->getLValue(BMI->getMember(), thisVal);
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();
497 SVal LValue = State->getSVal(Init, stackFrame);
498 if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
499 InitVal = State->getSVal(*LValueLoc);
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,
506 currBldrCtx->blockCount());
509 InitVal = State->getSVal(BMI->getInit(), stackFrame);
512 assert(Tmp.size() == 1 && "have not generated any new nodes yet");
513 assert(*Tmp.begin() == Pred && "have not generated any new nodes yet");
516 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
517 evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
520 assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
521 // We already did all the work when visiting the CXXConstructExpr.
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);
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);
534 // Enqueue the new nodes onto the work list.
535 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
538 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
539 ExplodedNode *Pred) {
541 switch (D.getKind()) {
542 case CFGElement::AutomaticObjectDtor:
543 ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
545 case CFGElement::BaseDtor:
546 ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
548 case CFGElement::MemberDtor:
549 ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
551 case CFGElement::TemporaryDtor:
552 ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
554 case CFGElement::DeleteDtor:
555 ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
558 llvm_unreachable("Unexpected dtor kind.");
561 // Enqueue the new nodes onto the work list.
562 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
565 void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE,
566 ExplodedNode *Pred) {
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);
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);
581 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
584 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
586 ExplodedNodeSet &Dst) {
587 const VarDecl *varDecl = Dtor.getVarDecl();
588 QualType varType = varDecl->getType();
590 ProgramStateRef state = Pred->getState();
591 SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
592 const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
594 if (const ReferenceType *refType = varType->getAs<ReferenceType>()) {
595 varType = refType->getPointeeType();
596 Region = state->getSVal(Region).getAsRegion();
599 VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
603 void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor,
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);
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();
620 PostImplicitCall PP(Dtor, DE->getLocStart(), LCtx);
621 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
622 Bldr.generateNode(PP, Pred->getState(), Pred);
626 VisitCXXDestructor(DE->getDestroyedType(),
627 ArgVal.getAsRegion(),
628 DE, /*IsBase=*/ false,
632 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
633 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
634 const LocationContext *LCtx = Pred->getLocationContext();
636 const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
637 Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
638 LCtx->getCurrentStackFrame());
639 SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
641 // Create the base object region.
642 const CXXBaseSpecifier *Base = D.getBaseSpecifier();
643 QualType BaseTy = Base->getType();
644 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
647 VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
648 CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst);
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();
657 const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
658 Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
659 LCtx->getCurrentStackFrame());
661 State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
663 VisitCXXDestructor(Member->getType(),
664 FieldVal.castAs<loc::MemRegionVal>().getRegion(),
665 CurDtor->getBody(), /*IsBase=*/false, Pred, Dst);
668 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
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()));
681 StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
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);
695 void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
696 NodeBuilderContext &BldCtx,
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);
707 TempDtorBuilder.markInfeasible(true);
708 TempDtorBuilder.generateNode(Pred->getState(), false, Pred);
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.
721 StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
722 for (ExplodedNode *Node : PreVisit) {
723 ProgramStateRef State = Node->getState();
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()));
734 StmtBldr.generateNode(BTE, Node, State);
738 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
739 ExplodedNodeSet &DstTop) {
740 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
742 "Error evaluating statement");
744 StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
746 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
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());
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::OMPTeamsDirectiveClass:
825 llvm_unreachable("Stmt should not be in analyzer evaluation loop");
827 case Stmt::ObjCSubscriptRefExprClass:
828 case Stmt::ObjCPropertyRefExprClass:
829 llvm_unreachable("These are handled by PseudoObjectExpr");
831 case Stmt::GNUNullExprClass: {
832 // GNU __null is a pointer-width integer, not an actual pointer.
833 ProgramStateRef state = Pred->getState();
834 state = state->BindExpr(S, Pred->getLocationContext(),
835 svalBuilder.makeIntValWithPtrWidth(0, false));
836 Bldr.generateNode(S, Pred, state);
840 case Stmt::ObjCAtSynchronizedStmtClass:
841 Bldr.takeNodes(Pred);
842 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
846 case Stmt::ExprWithCleanupsClass:
847 // Handled due to fully linearised CFG.
850 case Stmt::CXXBindTemporaryExprClass: {
851 Bldr.takeNodes(Pred);
852 ExplodedNodeSet PreVisit;
853 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
854 ExplodedNodeSet Next;
855 VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
856 getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
861 // Cases not handled yet; but will handle some day.
862 case Stmt::DesignatedInitExprClass:
863 case Stmt::DesignatedInitUpdateExprClass:
864 case Stmt::ExtVectorElementExprClass:
865 case Stmt::ImaginaryLiteralClass:
866 case Stmt::ObjCAtCatchStmtClass:
867 case Stmt::ObjCAtFinallyStmtClass:
868 case Stmt::ObjCAtTryStmtClass:
869 case Stmt::ObjCAutoreleasePoolStmtClass:
870 case Stmt::ObjCEncodeExprClass:
871 case Stmt::ObjCIsaExprClass:
872 case Stmt::ObjCProtocolExprClass:
873 case Stmt::ObjCSelectorExprClass:
874 case Stmt::ParenListExprClass:
875 case Stmt::ShuffleVectorExprClass:
876 case Stmt::ConvertVectorExprClass:
877 case Stmt::VAArgExprClass:
878 case Stmt::CUDAKernelCallExprClass:
879 case Stmt::OpaqueValueExprClass:
880 case Stmt::AsTypeExprClass:
881 case Stmt::AtomicExprClass:
884 // Cases we intentionally don't evaluate, since they don't need
885 // to be explicitly evaluated.
886 case Stmt::PredefinedExprClass:
887 case Stmt::AddrLabelExprClass:
888 case Stmt::AttributedStmtClass:
889 case Stmt::IntegerLiteralClass:
890 case Stmt::CharacterLiteralClass:
891 case Stmt::ImplicitValueInitExprClass:
892 case Stmt::CXXScalarValueInitExprClass:
893 case Stmt::CXXBoolLiteralExprClass:
894 case Stmt::ObjCBoolLiteralExprClass:
895 case Stmt::FloatingLiteralClass:
896 case Stmt::NoInitExprClass:
897 case Stmt::SizeOfPackExprClass:
898 case Stmt::StringLiteralClass:
899 case Stmt::ObjCStringLiteralClass:
900 case Stmt::CXXPseudoDestructorExprClass:
901 case Stmt::SubstNonTypeTemplateParmExprClass:
902 case Stmt::CXXNullPtrLiteralExprClass: {
903 Bldr.takeNodes(Pred);
904 ExplodedNodeSet preVisit;
905 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
906 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
911 case Stmt::CXXDefaultArgExprClass:
912 case Stmt::CXXDefaultInitExprClass: {
913 Bldr.takeNodes(Pred);
914 ExplodedNodeSet PreVisit;
915 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
918 StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
921 if (const CXXDefaultArgExpr *DefE = dyn_cast<CXXDefaultArgExpr>(S))
922 ArgE = DefE->getExpr();
923 else if (const CXXDefaultInitExpr *DefE = dyn_cast<CXXDefaultInitExpr>(S))
924 ArgE = DefE->getExpr();
926 llvm_unreachable("unknown constant wrapper kind");
928 bool IsTemporary = false;
929 if (const MaterializeTemporaryExpr *MTE =
930 dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
931 ArgE = MTE->GetTemporaryExpr();
935 Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
937 ConstantVal = UnknownVal();
939 const LocationContext *LCtx = Pred->getLocationContext();
940 for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end();
942 ProgramStateRef State = (*I)->getState();
943 State = State->BindExpr(S, LCtx, *ConstantVal);
945 State = createTemporaryRegionIfNeeded(State, LCtx,
948 Bldr2.generateNode(S, *I, State);
951 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
956 // Cases we evaluate as opaque expressions, conjuring a symbol.
957 case Stmt::CXXStdInitializerListExprClass:
958 case Expr::ObjCArrayLiteralClass:
959 case Expr::ObjCDictionaryLiteralClass:
960 case Expr::ObjCBoxedExprClass: {
961 Bldr.takeNodes(Pred);
963 ExplodedNodeSet preVisit;
964 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
967 StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
969 const Expr *Ex = cast<Expr>(S);
970 QualType resultType = Ex->getType();
972 for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end();
974 ExplodedNode *N = *it;
975 const LocationContext *LCtx = N->getLocationContext();
976 SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
978 currBldrCtx->blockCount());
979 ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result);
980 Bldr2.generateNode(S, N, state);
983 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
988 case Stmt::ArraySubscriptExprClass:
989 Bldr.takeNodes(Pred);
990 VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
994 case Stmt::GCCAsmStmtClass:
995 Bldr.takeNodes(Pred);
996 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
1000 case Stmt::MSAsmStmtClass:
1001 Bldr.takeNodes(Pred);
1002 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
1006 case Stmt::BlockExprClass:
1007 Bldr.takeNodes(Pred);
1008 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
1012 case Stmt::BinaryOperatorClass: {
1013 const BinaryOperator* B = cast<BinaryOperator>(S);
1014 if (B->isLogicalOp()) {
1015 Bldr.takeNodes(Pred);
1016 VisitLogicalExpr(B, Pred, Dst);
1020 else if (B->getOpcode() == BO_Comma) {
1021 ProgramStateRef state = Pred->getState();
1022 Bldr.generateNode(B, Pred,
1023 state->BindExpr(B, Pred->getLocationContext(),
1024 state->getSVal(B->getRHS(),
1025 Pred->getLocationContext())));
1029 Bldr.takeNodes(Pred);
1031 if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
1032 (B->isRelationalOp() || B->isEqualityOp())) {
1033 ExplodedNodeSet Tmp;
1034 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
1035 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
1038 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1044 case Stmt::CXXOperatorCallExprClass: {
1045 const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S);
1047 // For instance method operators, make sure the 'this' argument has a
1049 const Decl *Callee = OCE->getCalleeDecl();
1050 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
1051 if (MD->isInstance()) {
1052 ProgramStateRef State = Pred->getState();
1053 const LocationContext *LCtx = Pred->getLocationContext();
1054 ProgramStateRef NewState =
1055 createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
1056 if (NewState != State) {
1057 Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
1058 ProgramPoint::PreStmtKind);
1059 // Did we cache out?
1067 case Stmt::CallExprClass:
1068 case Stmt::CXXMemberCallExprClass:
1069 case Stmt::UserDefinedLiteralClass: {
1070 Bldr.takeNodes(Pred);
1071 VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
1076 case Stmt::CXXCatchStmtClass: {
1077 Bldr.takeNodes(Pred);
1078 VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
1083 case Stmt::CXXTemporaryObjectExprClass:
1084 case Stmt::CXXConstructExprClass: {
1085 Bldr.takeNodes(Pred);
1086 VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
1091 case Stmt::CXXNewExprClass: {
1092 Bldr.takeNodes(Pred);
1093 ExplodedNodeSet PostVisit;
1094 VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit);
1095 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1100 case Stmt::CXXDeleteExprClass: {
1101 Bldr.takeNodes(Pred);
1102 ExplodedNodeSet PreVisit;
1103 const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
1104 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1106 for (ExplodedNodeSet::iterator i = PreVisit.begin(),
1107 e = PreVisit.end(); i != e ; ++i)
1108 VisitCXXDeleteExpr(CDE, *i, Dst);
1113 // FIXME: ChooseExpr is really a constant. We need to fix
1114 // the CFG do not model them as explicit control-flow.
1116 case Stmt::ChooseExprClass: { // __builtin_choose_expr
1117 Bldr.takeNodes(Pred);
1118 const ChooseExpr *C = cast<ChooseExpr>(S);
1119 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
1124 case Stmt::CompoundAssignOperatorClass:
1125 Bldr.takeNodes(Pred);
1126 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1130 case Stmt::CompoundLiteralExprClass:
1131 Bldr.takeNodes(Pred);
1132 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
1136 case Stmt::BinaryConditionalOperatorClass:
1137 case Stmt::ConditionalOperatorClass: { // '?' operator
1138 Bldr.takeNodes(Pred);
1139 const AbstractConditionalOperator *C
1140 = cast<AbstractConditionalOperator>(S);
1141 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
1146 case Stmt::CXXThisExprClass:
1147 Bldr.takeNodes(Pred);
1148 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
1152 case Stmt::DeclRefExprClass: {
1153 Bldr.takeNodes(Pred);
1154 const DeclRefExpr *DE = cast<DeclRefExpr>(S);
1155 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
1160 case Stmt::DeclStmtClass:
1161 Bldr.takeNodes(Pred);
1162 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
1166 case Stmt::ImplicitCastExprClass:
1167 case Stmt::CStyleCastExprClass:
1168 case Stmt::CXXStaticCastExprClass:
1169 case Stmt::CXXDynamicCastExprClass:
1170 case Stmt::CXXReinterpretCastExprClass:
1171 case Stmt::CXXConstCastExprClass:
1172 case Stmt::CXXFunctionalCastExprClass:
1173 case Stmt::ObjCBridgedCastExprClass: {
1174 Bldr.takeNodes(Pred);
1175 const CastExpr *C = cast<CastExpr>(S);
1176 // Handle the previsit checks.
1177 ExplodedNodeSet dstPrevisit;
1178 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this);
1180 // Handle the expression itself.
1181 ExplodedNodeSet dstExpr;
1182 for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
1183 e = dstPrevisit.end(); i != e ; ++i) {
1184 VisitCast(C, C->getSubExpr(), *i, dstExpr);
1187 // Handle the postvisit checks.
1188 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1193 case Expr::MaterializeTemporaryExprClass: {
1194 Bldr.takeNodes(Pred);
1195 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
1196 CreateCXXTemporaryObject(MTE, Pred, Dst);
1201 case Stmt::InitListExprClass:
1202 Bldr.takeNodes(Pred);
1203 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1207 case Stmt::MemberExprClass:
1208 Bldr.takeNodes(Pred);
1209 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1213 case Stmt::ObjCIvarRefExprClass:
1214 Bldr.takeNodes(Pred);
1215 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1219 case Stmt::ObjCForCollectionStmtClass:
1220 Bldr.takeNodes(Pred);
1221 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1225 case Stmt::ObjCMessageExprClass:
1226 Bldr.takeNodes(Pred);
1227 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1231 case Stmt::ObjCAtThrowStmtClass:
1232 case Stmt::CXXThrowExprClass:
1233 // FIXME: This is not complete. We basically treat @throw as
1235 Bldr.generateSink(S, Pred, Pred->getState());
1238 case Stmt::ReturnStmtClass:
1239 Bldr.takeNodes(Pred);
1240 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1244 case Stmt::OffsetOfExprClass:
1245 Bldr.takeNodes(Pred);
1246 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
1250 case Stmt::UnaryExprOrTypeTraitExprClass:
1251 Bldr.takeNodes(Pred);
1252 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1257 case Stmt::StmtExprClass: {
1258 const StmtExpr *SE = cast<StmtExpr>(S);
1260 if (SE->getSubStmt()->body_empty()) {
1261 // Empty statement expression.
1262 assert(SE->getType() == getContext().VoidTy
1263 && "Empty statement expression must have void type.");
1267 if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1268 ProgramStateRef state = Pred->getState();
1269 Bldr.generateNode(SE, Pred,
1270 state->BindExpr(SE, Pred->getLocationContext(),
1271 state->getSVal(LastExpr,
1272 Pred->getLocationContext())));
1277 case Stmt::UnaryOperatorClass: {
1278 Bldr.takeNodes(Pred);
1279 const UnaryOperator *U = cast<UnaryOperator>(S);
1280 if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
1281 ExplodedNodeSet Tmp;
1282 VisitUnaryOperator(U, Pred, Tmp);
1283 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1286 VisitUnaryOperator(U, Pred, Dst);
1291 case Stmt::PseudoObjectExprClass: {
1292 Bldr.takeNodes(Pred);
1293 ProgramStateRef state = Pred->getState();
1294 const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
1295 if (const Expr *Result = PE->getResultExpr()) {
1296 SVal V = state->getSVal(Result, Pred->getLocationContext());
1297 Bldr.generateNode(S, Pred,
1298 state->BindExpr(S, Pred->getLocationContext(), V));
1301 Bldr.generateNode(S, Pred,
1302 state->BindExpr(S, Pred->getLocationContext(),
1311 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1312 const LocationContext *CalleeLC) {
1313 const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1314 const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
1315 assert(CalleeSF && CallerSF);
1316 ExplodedNode *BeforeProcessingCall = nullptr;
1317 const Stmt *CE = CalleeSF->getCallSite();
1319 // Find the first node before we started processing the call expression.
1321 ProgramPoint L = N->getLocation();
1322 BeforeProcessingCall = N;
1323 N = N->pred_empty() ? nullptr : *(N->pred_begin());
1325 // Skip the nodes corresponding to the inlined code.
1326 if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
1328 // We reached the caller. Find the node right before we started
1329 // processing the call.
1330 if (L.isPurgeKind())
1332 if (L.getAs<PreImplicitCall>())
1334 if (L.getAs<CallEnter>())
1336 if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1337 if (SP->getStmt() == CE)
1342 if (!BeforeProcessingCall)
1345 // TODO: Clean up the unneeded nodes.
1347 // Build an Epsilon node from which we will restart the analyzes.
1348 // Note that CE is permitted to be NULL!
1349 ProgramPoint NewNodeLoc =
1350 EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1351 // Add the special flag to GDM to signal retrying with no inlining.
1352 // Note, changing the state ensures that we are not going to cache out.
1353 ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1355 NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1357 // Make the new node a successor of BeforeProcessingCall.
1359 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1360 // We cached out at this point. Caching out is common due to us backtracking
1361 // from the inlined function, which might spawn several paths.
1365 NewNode->addPredecessor(BeforeProcessingCall, G);
1367 // Add the new node to the work list.
1368 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1369 CalleeSF->getIndex());
1370 NumTimesRetriedWithoutInlining++;
1374 /// Block entrance. (Update counters).
1375 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
1376 NodeBuilderWithSinks &nodeBuilder,
1377 ExplodedNode *Pred) {
1378 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1380 // FIXME: Refactor this into a checker.
1381 if (nodeBuilder.getContext().blockCount() >= AMgr.options.maxBlockVisitOnPath) {
1382 static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
1383 const ExplodedNode *Sink =
1384 nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1386 // Check if we stopped at the top level function or not.
1387 // Root node should have the location context of the top most function.
1388 const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1389 const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1390 const LocationContext *RootLC =
1391 (*G.roots_begin())->getLocation().getLocationContext();
1392 if (RootLC->getCurrentStackFrame() != CalleeSF) {
1393 Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1395 // Re-run the call evaluation without inlining it, by storing the
1396 // no-inlining policy in the state and enqueuing the new work item on
1397 // the list. Replay should almost never fail. Use the stats to catch it
1399 if ((!AMgr.options.NoRetryExhausted &&
1400 replayWithoutInlining(Pred, CalleeLC)))
1402 NumMaxBlockCountReachedInInlined++;
1404 NumMaxBlockCountReached++;
1406 // Make sink nodes as exhausted(for stats) only if retry failed.
1407 Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1411 //===----------------------------------------------------------------------===//
1412 // Branch processing.
1413 //===----------------------------------------------------------------------===//
1415 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1416 /// to try to recover some path-sensitivity for casts of symbolic
1417 /// integers that promote their values (which are currently not tracked well).
1418 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1419 // cast(s) did was sign-extend the original value.
1420 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
1421 ProgramStateRef state,
1422 const Stmt *Condition,
1423 const LocationContext *LCtx,
1426 const Expr *Ex = dyn_cast<Expr>(Condition);
1428 return UnknownVal();
1431 bool bitsInit = false;
1433 while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
1434 QualType T = CE->getType();
1436 if (!T->isIntegralOrEnumerationType())
1437 return UnknownVal();
1439 uint64_t newBits = Ctx.getTypeSize(T);
1440 if (!bitsInit || newBits < bits) {
1445 Ex = CE->getSubExpr();
1448 // We reached a non-cast. Is it a symbolic value?
1449 QualType T = Ex->getType();
1451 if (!bitsInit || !T->isIntegralOrEnumerationType() ||
1452 Ctx.getTypeSize(T) > bits)
1453 return UnknownVal();
1455 return state->getSVal(Ex, LCtx);
1459 static const Stmt *getRightmostLeaf(const Stmt *Condition) {
1461 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1462 if (!BO || !BO->isLogicalOp()) {
1465 Condition = BO->getRHS()->IgnoreParens();
1471 // Returns the condition the branch at the end of 'B' depends on and whose value
1472 // has been evaluated within 'B'.
1473 // In most cases, the terminator condition of 'B' will be evaluated fully in
1474 // the last statement of 'B'; in those cases, the resolved condition is the
1475 // given 'Condition'.
1476 // If the condition of the branch is a logical binary operator tree, the CFG is
1477 // optimized: in that case, we know that the expression formed by all but the
1478 // rightmost leaf of the logical binary operator tree must be true, and thus
1479 // the branch condition is at this point equivalent to the truth value of that
1480 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
1481 // expression in its final statement. As the full condition in that case was
1482 // not evaluated, and is thus not in the SVal cache, we need to use that leaf
1483 // expression to evaluate the truth value of the condition in the current state
1485 static const Stmt *ResolveCondition(const Stmt *Condition,
1486 const CFGBlock *B) {
1487 if (const Expr *Ex = dyn_cast<Expr>(Condition))
1488 Condition = Ex->IgnoreParens();
1490 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1491 if (!BO || !BO->isLogicalOp())
1494 assert(!B->getTerminator().isTemporaryDtorsBranch() &&
1495 "Temporary destructor branches handled by processBindTemporary.");
1497 // For logical operations, we still have the case where some branches
1498 // use the traditional "merge" approach and others sink the branch
1499 // directly into the basic blocks representing the logical operation.
1500 // We need to distinguish between those two cases here.
1502 // The invariants are still shifting, but it is possible that the
1503 // last element in a CFGBlock is not a CFGStmt. Look for the last
1504 // CFGStmt as the value of the condition.
1505 CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
1506 for (; I != E; ++I) {
1507 CFGElement Elem = *I;
1508 Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
1511 const Stmt *LastStmt = CS->getStmt();
1512 assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
1515 llvm_unreachable("could not resolve condition");
1518 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
1519 NodeBuilderContext& BldCtx,
1521 ExplodedNodeSet &Dst,
1522 const CFGBlock *DstT,
1523 const CFGBlock *DstF) {
1524 assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
1525 "CXXBindTemporaryExprs are handled by processBindTemporary.");
1526 const LocationContext *LCtx = Pred->getLocationContext();
1527 PrettyStackTraceLocationContext StackCrashInfo(LCtx);
1528 currBldrCtx = &BldCtx;
1530 // Check for NULL conditions; e.g. "for(;;)"
1532 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
1533 NullCondBldr.markInfeasible(false);
1534 NullCondBldr.generateNode(Pred->getState(), true, Pred);
1539 if (const Expr *Ex = dyn_cast<Expr>(Condition))
1540 Condition = Ex->IgnoreParens();
1542 Condition = ResolveCondition(Condition, BldCtx.getBlock());
1543 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1544 Condition->getLocStart(),
1545 "Error evaluating branch");
1547 ExplodedNodeSet CheckersOutSet;
1548 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
1550 // We generated only sinks.
1551 if (CheckersOutSet.empty())
1554 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
1555 for (NodeBuilder::iterator I = CheckersOutSet.begin(),
1556 E = CheckersOutSet.end(); E != I; ++I) {
1557 ExplodedNode *PredI = *I;
1559 if (PredI->isSink())
1562 ProgramStateRef PrevState = PredI->getState();
1563 SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
1565 if (X.isUnknownOrUndef()) {
1566 // Give it a chance to recover from unknown.
1567 if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
1568 if (Ex->getType()->isIntegralOrEnumerationType()) {
1569 // Try to recover some path-sensitivity. Right now casts of symbolic
1570 // integers that promote their values are currently not tracked well.
1571 // If 'Condition' is such an expression, try and recover the
1572 // underlying value and use that instead.
1573 SVal recovered = RecoverCastedSymbol(getStateManager(),
1574 PrevState, Condition,
1575 PredI->getLocationContext(),
1578 if (!recovered.isUnknown()) {
1585 // If the condition is still unknown, give up.
1586 if (X.isUnknownOrUndef()) {
1587 builder.generateNode(PrevState, true, PredI);
1588 builder.generateNode(PrevState, false, PredI);
1592 DefinedSVal V = X.castAs<DefinedSVal>();
1594 ProgramStateRef StTrue, StFalse;
1595 std::tie(StTrue, StFalse) = PrevState->assume(V);
1597 // Process the true branch.
1598 if (builder.isFeasible(true)) {
1600 builder.generateNode(StTrue, true, PredI);
1602 builder.markInfeasible(true);
1605 // Process the false branch.
1606 if (builder.isFeasible(false)) {
1608 builder.generateNode(StFalse, false, PredI);
1610 builder.markInfeasible(false);
1613 currBldrCtx = nullptr;
1616 /// The GDM component containing the set of global variables which have been
1617 /// previously initialized with explicit initializers.
1618 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
1619 llvm::ImmutableSet<const VarDecl *>)
1621 void ExprEngine::processStaticInitializer(const DeclStmt *DS,
1622 NodeBuilderContext &BuilderCtx,
1624 clang::ento::ExplodedNodeSet &Dst,
1625 const CFGBlock *DstT,
1626 const CFGBlock *DstF) {
1627 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1628 currBldrCtx = &BuilderCtx;
1630 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
1631 ProgramStateRef state = Pred->getState();
1632 bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
1633 BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
1636 state = state->add<InitializedGlobalsSet>(VD);
1639 builder.generateNode(state, initHasRun, Pred);
1640 builder.markInfeasible(!initHasRun);
1642 currBldrCtx = nullptr;
1645 /// processIndirectGoto - Called by CoreEngine. Used to generate successor
1646 /// nodes by processing the 'effects' of a computed goto jump.
1647 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
1649 ProgramStateRef state = builder.getState();
1650 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
1652 // Three possibilities:
1654 // (1) We know the computed label.
1655 // (2) The label is NULL (or some other constant), or Undefined.
1656 // (3) We have no clue about the label. Dispatch to all targets.
1659 typedef IndirectGotoNodeBuilder::iterator iterator;
1661 if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
1662 const LabelDecl *L = LV->getLabel();
1664 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
1665 if (I.getLabel() == L) {
1666 builder.generateNode(I, state);
1671 llvm_unreachable("No block with label.");
1674 if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
1675 // Dispatch to the first target and mark it as a sink.
1676 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
1677 // FIXME: add checker visit.
1678 // UndefBranches.insert(N);
1682 // This is really a catch-all. We don't support symbolics yet.
1683 // FIXME: Implement dispatch for symbolic pointers.
1685 for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
1686 builder.generateNode(I, state);
1690 static bool stackFrameDoesNotContainInitializedTemporaries(ExplodedNode &Pred) {
1691 const StackFrameContext* Frame = Pred.getStackFrame();
1692 const llvm::ImmutableSet<CXXBindTemporaryContext> &Set =
1693 Pred.getState()->get<InitializedTemporariesSet>();
1694 return std::find_if(Set.begin(), Set.end(),
1695 [&](const CXXBindTemporaryContext &Ctx) {
1696 if (Ctx.second == Frame) {
1698 llvm::errs() << "\n";
1700 return Ctx.second == Frame;
1705 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
1706 /// nodes when the control reaches the end of a function.
1707 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
1708 ExplodedNode *Pred) {
1709 // FIXME: Assert that stackFrameDoesNotContainInitializedTemporaries(*Pred)).
1710 // We currently cannot enable this assert, as lifetime extended temporaries
1711 // are not modelled correctly.
1712 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1713 StateMgr.EndPath(Pred->getState());
1715 ExplodedNodeSet Dst;
1716 if (Pred->getLocationContext()->inTopFrame()) {
1717 // Remove dead symbols.
1718 ExplodedNodeSet AfterRemovedDead;
1719 removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
1722 for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(),
1723 E = AfterRemovedDead.end(); I != E; ++I) {
1724 getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this);
1727 getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
1730 Engine.enqueueEndOfFunction(Dst);
1733 /// ProcessSwitch - Called by CoreEngine. Used to generate successor
1734 /// nodes by processing the 'effects' of a switch statement.
1735 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
1736 typedef SwitchNodeBuilder::iterator iterator;
1737 ProgramStateRef state = builder.getState();
1738 const Expr *CondE = builder.getCondition();
1739 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
1741 if (CondV_untested.isUndef()) {
1742 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
1743 // FIXME: add checker
1744 //UndefBranches.insert(N);
1748 DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
1750 ProgramStateRef DefaultSt = state;
1752 iterator I = builder.begin(), EI = builder.end();
1753 bool defaultIsFeasible = I == EI;
1755 for ( ; I != EI; ++I) {
1756 // Successor may be pruned out during CFG construction.
1760 const CaseStmt *Case = I.getCase();
1762 // Evaluate the LHS of the case value.
1763 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
1764 assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType()));
1766 // Get the RHS of the case, if it exists.
1768 if (const Expr *E = Case->getRHS())
1769 V2 = E->EvaluateKnownConstInt(getContext());
1773 // FIXME: Eventually we should replace the logic below with a range
1774 // comparison, rather than concretize the values within the range.
1775 // This should be easy once we have "ranges" for NonLVals.
1778 nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1));
1779 DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state,
1782 // Now "assume" that the case matches.
1783 if (ProgramStateRef stateNew = state->assume(Res, true)) {
1784 builder.generateCaseStmtNode(I, stateNew);
1786 // If CondV evaluates to a constant, then we know that this
1787 // is the *only* case that we can take, so stop evaluating the
1789 if (CondV.getAs<nonloc::ConcreteInt>())
1793 // Now "assume" that the case doesn't match. Add this state
1794 // to the default state (if it is feasible).
1796 if (ProgramStateRef stateNew = DefaultSt->assume(Res, false)) {
1797 defaultIsFeasible = true;
1798 DefaultSt = stateNew;
1801 defaultIsFeasible = false;
1802 DefaultSt = nullptr;
1806 // Concretize the next value in the range.
1816 if (!defaultIsFeasible)
1819 // If we have switch(enum value), the default branch is not
1820 // feasible if all of the enum constants not covered by 'case:' statements
1821 // are not feasible values for the switch condition.
1823 // Note that this isn't as accurate as it could be. Even if there isn't
1824 // a case for a particular enum value as long as that enum value isn't
1825 // feasible then it shouldn't be considered for making 'default:' reachable.
1826 const SwitchStmt *SS = builder.getSwitch();
1827 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
1828 if (CondExpr->getType()->getAs<EnumType>()) {
1829 if (SS->isAllEnumCasesCovered())
1833 builder.generateDefaultCaseNode(DefaultSt);
1836 //===----------------------------------------------------------------------===//
1837 // Transfer functions: Loads and stores.
1838 //===----------------------------------------------------------------------===//
1840 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
1842 ExplodedNodeSet &Dst) {
1843 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1845 ProgramStateRef state = Pred->getState();
1846 const LocationContext *LCtx = Pred->getLocationContext();
1848 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1849 // C permits "extern void v", and if you cast the address to a valid type,
1850 // you can even do things with it. We simply pretend
1851 assert(Ex->isGLValue() || VD->getType()->isVoidType());
1852 SVal V = state->getLValue(VD, Pred->getLocationContext());
1854 // For references, the 'lvalue' is the pointer address stored in the
1855 // reference region.
1856 if (VD->getType()->isReferenceType()) {
1857 if (const MemRegion *R = V.getAsRegion())
1858 V = state->getSVal(R);
1863 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1864 ProgramPoint::PostLValueKind);
1867 if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
1868 assert(!Ex->isGLValue());
1869 SVal V = svalBuilder.makeIntVal(ED->getInitVal());
1870 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
1873 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1874 SVal V = svalBuilder.getFunctionPointer(FD);
1875 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1876 ProgramPoint::PostLValueKind);
1879 if (isa<FieldDecl>(D)) {
1880 // FIXME: Compute lvalue of field pointers-to-member.
1881 // Right now we just use a non-null void pointer, so that it gives proper
1882 // results in boolean contexts.
1883 SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
1884 currBldrCtx->blockCount());
1885 state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
1886 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1887 ProgramPoint::PostLValueKind);
1891 llvm_unreachable("Support for this Decl not implemented.");
1894 /// VisitArraySubscriptExpr - Transfer function for array accesses
1895 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A,
1897 ExplodedNodeSet &Dst){
1899 const Expr *Base = A->getBase()->IgnoreParens();
1900 const Expr *Idx = A->getIdx()->IgnoreParens();
1903 ExplodedNodeSet checkerPreStmt;
1904 getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this);
1906 StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currBldrCtx);
1907 assert(A->isGLValue() ||
1908 (!AMgr.getLangOpts().CPlusPlus &&
1909 A->getType().isCForbiddenLValueType()));
1911 for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(),
1912 ei = checkerPreStmt.end(); it != ei; ++it) {
1913 const LocationContext *LCtx = (*it)->getLocationContext();
1914 ProgramStateRef state = (*it)->getState();
1915 SVal V = state->getLValue(A->getType(),
1916 state->getSVal(Idx, LCtx),
1917 state->getSVal(Base, LCtx));
1918 Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), nullptr,
1919 ProgramPoint::PostLValueKind);
1923 /// VisitMemberExpr - Transfer function for member expressions.
1924 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
1925 ExplodedNodeSet &Dst) {
1927 // FIXME: Prechecks eventually go in ::Visit().
1928 ExplodedNodeSet CheckedSet;
1929 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
1931 ExplodedNodeSet EvalSet;
1932 ValueDecl *Member = M->getMemberDecl();
1934 // Handle static member variables and enum constants accessed via
1936 if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
1937 ExplodedNodeSet Dst;
1938 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
1940 VisitCommonDeclRefExpr(M, Member, Pred, EvalSet);
1943 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
1944 ExplodedNodeSet Tmp;
1946 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
1948 ProgramStateRef state = (*I)->getState();
1949 const LocationContext *LCtx = (*I)->getLocationContext();
1950 Expr *BaseExpr = M->getBase();
1952 // Handle C++ method calls.
1953 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
1954 if (MD->isInstance())
1955 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
1957 SVal MDVal = svalBuilder.getFunctionPointer(MD);
1958 state = state->BindExpr(M, LCtx, MDVal);
1960 Bldr.generateNode(M, *I, state);
1964 // Handle regular struct fields / member variables.
1965 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
1966 SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
1968 FieldDecl *field = cast<FieldDecl>(Member);
1969 SVal L = state->getLValue(field, baseExprVal);
1971 if (M->isGLValue() || M->getType()->isArrayType()) {
1972 // We special-case rvalues of array type because the analyzer cannot
1973 // reason about them, since we expect all regions to be wrapped in Locs.
1974 // We instead treat these as lvalues and assume that they will decay to
1975 // pointers as soon as they are used.
1976 if (!M->isGLValue()) {
1977 assert(M->getType()->isArrayType());
1978 const ImplicitCastExpr *PE =
1979 dyn_cast<ImplicitCastExpr>((*I)->getParentMap().getParent(M));
1980 if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
1981 llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
1985 if (field->getType()->isReferenceType()) {
1986 if (const MemRegion *R = L.getAsRegion())
1987 L = state->getSVal(R);
1992 Bldr.generateNode(M, *I, state->BindExpr(M, LCtx, L), nullptr,
1993 ProgramPoint::PostLValueKind);
1996 evalLoad(Tmp, M, M, *I, state, L);
2002 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
2006 class CollectReachableSymbolsCallback : public SymbolVisitor {
2007 InvalidatedSymbols Symbols;
2009 CollectReachableSymbolsCallback(ProgramStateRef State) {}
2010 const InvalidatedSymbols &getSymbols() const { return Symbols; }
2012 bool VisitSymbol(SymbolRef Sym) override {
2013 Symbols.insert(Sym);
2017 } // end anonymous namespace
2019 // A value escapes in three possible cases:
2020 // (1) We are binding to something that is not a memory region.
2021 // (2) We are binding to a MemrRegion that does not have stack storage.
2022 // (3) We are binding to a MemRegion with stack storage that the store
2023 // does not understand.
2024 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
2025 SVal Loc, SVal Val) {
2026 // Are we storing to something that causes the value to "escape"?
2027 bool escapes = true;
2029 // TODO: Move to StoreManager.
2030 if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
2031 escapes = !regionLoc->getRegion()->hasStackStorage();
2034 // To test (3), generate a new state with the binding added. If it is
2035 // the same state, then it escapes (since the store cannot represent
2037 // Do this only if we know that the store is not supposed to generate the
2039 SVal StoredVal = State->getSVal(regionLoc->getRegion());
2040 if (StoredVal != Val)
2041 escapes = (State == (State->bindLoc(*regionLoc, Val)));
2045 // If our store can represent the binding and we aren't storing to something
2046 // that doesn't have local storage then just return and have the simulation
2047 // state continue as is.
2051 // Otherwise, find all symbols referenced by 'val' that we are tracking
2052 // and stop tracking them.
2053 CollectReachableSymbolsCallback Scanner =
2054 State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val);
2055 const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
2056 State = getCheckerManager().runCheckersForPointerEscape(State,
2058 /*CallEvent*/ nullptr,
2066 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
2067 const InvalidatedSymbols *Invalidated,
2068 ArrayRef<const MemRegion *> ExplicitRegions,
2069 ArrayRef<const MemRegion *> Regions,
2070 const CallEvent *Call,
2071 RegionAndSymbolInvalidationTraits &ITraits) {
2073 if (!Invalidated || Invalidated->empty())
2077 return getCheckerManager().runCheckersForPointerEscape(State,
2083 // If the symbols were invalidated by a call, we want to find out which ones
2084 // were invalidated directly due to being arguments to the call.
2085 InvalidatedSymbols SymbolsDirectlyInvalidated;
2086 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
2087 E = ExplicitRegions.end(); I != E; ++I) {
2088 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
2089 SymbolsDirectlyInvalidated.insert(R->getSymbol());
2092 InvalidatedSymbols SymbolsIndirectlyInvalidated;
2093 for (InvalidatedSymbols::const_iterator I=Invalidated->begin(),
2094 E = Invalidated->end(); I!=E; ++I) {
2096 if (SymbolsDirectlyInvalidated.count(sym))
2098 SymbolsIndirectlyInvalidated.insert(sym);
2101 if (!SymbolsDirectlyInvalidated.empty())
2102 State = getCheckerManager().runCheckersForPointerEscape(State,
2103 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
2105 // Notify about the symbols that get indirectly invalidated by the call.
2106 if (!SymbolsIndirectlyInvalidated.empty())
2107 State = getCheckerManager().runCheckersForPointerEscape(State,
2108 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
2113 /// evalBind - Handle the semantics of binding a value to a specific location.
2114 /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
2115 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
2117 SVal location, SVal Val,
2118 bool atDeclInit, const ProgramPoint *PP) {
2120 const LocationContext *LC = Pred->getLocationContext();
2121 PostStmt PS(StoreE, LC);
2125 // Do a previsit of the bind.
2126 ExplodedNodeSet CheckedSet;
2127 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
2128 StoreE, *this, *PP);
2131 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
2133 // If the location is not a 'Loc', it will already be handled by
2134 // the checkers. There is nothing left to do.
2135 if (!location.getAs<Loc>()) {
2136 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
2138 ProgramStateRef state = Pred->getState();
2139 state = processPointerEscapedOnBind(state, location, Val);
2140 Bldr.generateNode(L, state, Pred);
2145 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2147 ExplodedNode *PredI = *I;
2148 ProgramStateRef state = PredI->getState();
2150 state = processPointerEscapedOnBind(state, location, Val);
2152 // When binding the value, pass on the hint that this is a initialization.
2153 // For initializations, we do not need to inform clients of region
2155 state = state->bindLoc(location.castAs<Loc>(),
2156 Val, /* notifyChanges = */ !atDeclInit);
2158 const MemRegion *LocReg = nullptr;
2159 if (Optional<loc::MemRegionVal> LocRegVal =
2160 location.getAs<loc::MemRegionVal>()) {
2161 LocReg = LocRegVal->getRegion();
2164 const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
2165 Bldr.generateNode(L, state, PredI);
2169 /// evalStore - Handle the semantics of a store via an assignment.
2170 /// @param Dst The node set to store generated state nodes
2171 /// @param AssignE The assignment expression if the store happens in an
2173 /// @param LocationE The location expression that is stored to.
2174 /// @param state The current simulation state
2175 /// @param location The location to store the value
2176 /// @param Val The value to be stored
2177 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
2178 const Expr *LocationE,
2180 ProgramStateRef state, SVal location, SVal Val,
2181 const ProgramPointTag *tag) {
2182 // Proceed with the store. We use AssignE as the anchor for the PostStore
2183 // ProgramPoint if it is non-NULL, and LocationE otherwise.
2184 const Expr *StoreE = AssignE ? AssignE : LocationE;
2186 // Evaluate the location (checks for bad dereferences).
2187 ExplodedNodeSet Tmp;
2188 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
2193 if (location.isUndef())
2196 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
2197 evalBind(Dst, StoreE, *NI, location, Val, false);
2200 void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
2202 const Expr *BoundEx,
2204 ProgramStateRef state,
2206 const ProgramPointTag *tag,
2209 assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2211 // Are we loading from a region? This actually results in two loads; one
2212 // to fetch the address of the referenced value and one to fetch the
2213 // referenced value.
2214 if (const TypedValueRegion *TR =
2215 dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
2217 QualType ValTy = TR->getValueType();
2218 if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
2219 static SimpleProgramPointTag
2220 loadReferenceTag(TagProviderName, "Load Reference");
2221 ExplodedNodeSet Tmp;
2222 evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
2223 location, &loadReferenceTag,
2224 getContext().getPointerType(RT->getPointeeType()));
2226 // Perform the load from the referenced value.
2227 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
2228 state = (*I)->getState();
2229 location = state->getSVal(BoundEx, (*I)->getLocationContext());
2230 evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
2236 evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
2239 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
2241 const Expr *BoundEx,
2243 ProgramStateRef state,
2245 const ProgramPointTag *tag,
2249 // Evaluate the location (checks for bad dereferences).
2250 ExplodedNodeSet Tmp;
2251 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
2255 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2256 if (location.isUndef())
2259 // Proceed with the load.
2260 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
2261 state = (*NI)->getState();
2262 const LocationContext *LCtx = (*NI)->getLocationContext();
2264 SVal V = UnknownVal();
2265 if (location.isValid()) {
2266 if (LoadTy.isNull())
2267 LoadTy = BoundEx->getType();
2268 V = state->getSVal(location.castAs<Loc>(), LoadTy);
2271 Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
2272 ProgramPoint::PostLoadKind);
2276 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2278 const Stmt *BoundEx,
2280 ProgramStateRef state,
2282 const ProgramPointTag *tag,
2284 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2285 // Early checks for performance reason.
2286 if (location.isUnknown()) {
2290 ExplodedNodeSet Src;
2291 BldrTop.takeNodes(Pred);
2292 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2293 if (Pred->getState() != state) {
2294 // Associate this new state with an ExplodedNode.
2295 // FIXME: If I pass null tag, the graph is incorrect, e.g for
2299 // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2300 // instead "int *p" is noted as
2301 // "Variable 'p' initialized to a null pointer value"
2303 static SimpleProgramPointTag tag(TagProviderName, "Location");
2304 Bldr.generateNode(NodeEx, Pred, state, &tag);
2306 ExplodedNodeSet Tmp;
2307 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2308 NodeEx, BoundEx, *this);
2309 BldrTop.addNodes(Tmp);
2312 std::pair<const ProgramPointTag *, const ProgramPointTag*>
2313 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
2314 static SimpleProgramPointTag
2315 eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
2316 "Eagerly Assume True"),
2317 eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
2318 "Eagerly Assume False");
2319 return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2320 &eagerlyAssumeBinOpBifurcationFalse);
2323 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
2324 ExplodedNodeSet &Src,
2326 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2328 for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
2329 ExplodedNode *Pred = *I;
2330 // Test if the previous node was as the same expression. This can happen
2331 // when the expression fails to evaluate to anything meaningful and
2332 // (as an optimization) we don't generate a node.
2333 ProgramPoint P = Pred->getLocation();
2334 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2338 ProgramStateRef state = Pred->getState();
2339 SVal V = state->getSVal(Ex, Pred->getLocationContext());
2340 Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
2341 if (SEV && SEV->isExpression()) {
2342 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2343 geteagerlyAssumeBinOpBifurcationTags();
2345 ProgramStateRef StateTrue, StateFalse;
2346 std::tie(StateTrue, StateFalse) = state->assume(*SEV);
2348 // First assume that the condition is true.
2350 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2351 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2352 Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2355 // Next, assume that the condition is false.
2357 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2358 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2359 Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2365 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
2366 ExplodedNodeSet &Dst) {
2367 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2368 // We have processed both the inputs and the outputs. All of the outputs
2369 // should evaluate to Locs. Nuke all of their values.
2371 // FIXME: Some day in the future it would be nice to allow a "plug-in"
2372 // which interprets the inline asm and stores proper results in the
2375 ProgramStateRef state = Pred->getState();
2377 for (const Expr *O : A->outputs()) {
2378 SVal X = state->getSVal(O, Pred->getLocationContext());
2379 assert (!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
2381 if (Optional<Loc> LV = X.getAs<Loc>())
2382 state = state->bindLoc(*LV, UnknownVal());
2385 Bldr.generateNode(A, Pred, state);
2388 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
2389 ExplodedNodeSet &Dst) {
2390 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2391 Bldr.generateNode(A, Pred, Pred->getState());
2394 //===----------------------------------------------------------------------===//
2396 //===----------------------------------------------------------------------===//
2399 static ExprEngine* GraphPrintCheckerState;
2400 static SourceManager* GraphPrintSourceManager;
2404 struct DOTGraphTraits<ExplodedNode*> :
2405 public DefaultDOTGraphTraits {
2407 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2409 // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
2411 static std::string getNodeAttributes(const ExplodedNode *N, void*) {
2414 // FIXME: Replace with a general scheme to tell if the node is
2416 if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
2417 GraphPrintCheckerState->isExplicitNullDeref(N) ||
2418 GraphPrintCheckerState->isUndefDeref(N) ||
2419 GraphPrintCheckerState->isUndefStore(N) ||
2420 GraphPrintCheckerState->isUndefControlFlow(N) ||
2421 GraphPrintCheckerState->isUndefResult(N) ||
2422 GraphPrintCheckerState->isBadCall(N) ||
2423 GraphPrintCheckerState->isUndefArg(N))
2424 return "color=\"red\",style=\"filled\"";
2426 if (GraphPrintCheckerState->isNoReturnCall(N))
2427 return "color=\"blue\",style=\"filled\"";
2432 static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
2433 if (SLoc.isFileID()) {
2435 << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2437 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
2442 static std::string getNodeLabel(const ExplodedNode *N, void*){
2445 llvm::raw_string_ostream Out(sbuf);
2447 // Program Location.
2448 ProgramPoint Loc = N->getLocation();
2450 switch (Loc.getKind()) {
2451 case ProgramPoint::BlockEntranceKind: {
2452 Out << "Block Entrance: B"
2453 << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
2454 if (const NamedDecl *ND =
2455 dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) {
2463 case ProgramPoint::BlockExitKind:
2467 case ProgramPoint::CallEnterKind:
2471 case ProgramPoint::CallExitBeginKind:
2472 Out << "CallExitBegin";
2475 case ProgramPoint::CallExitEndKind:
2476 Out << "CallExitEnd";
2479 case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
2480 Out << "PostStmtPurgeDeadSymbols";
2483 case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
2484 Out << "PreStmtPurgeDeadSymbols";
2487 case ProgramPoint::EpsilonKind:
2488 Out << "Epsilon Point";
2491 case ProgramPoint::PreImplicitCallKind: {
2492 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2495 // FIXME: Get proper printing options.
2496 PC.getDecl()->print(Out, LangOptions());
2497 printLocation(Out, PC.getLocation());
2501 case ProgramPoint::PostImplicitCallKind: {
2502 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2503 Out << "PostCall: ";
2505 // FIXME: Get proper printing options.
2506 PC.getDecl()->print(Out, LangOptions());
2507 printLocation(Out, PC.getLocation());
2511 case ProgramPoint::PostInitializerKind: {
2512 Out << "PostInitializer: ";
2513 const CXXCtorInitializer *Init =
2514 Loc.castAs<PostInitializer>().getInitializer();
2515 if (const FieldDecl *FD = Init->getAnyMember())
2518 QualType Ty = Init->getTypeSourceInfo()->getType();
2519 Ty = Ty.getLocalUnqualifiedType();
2520 LangOptions LO; // FIXME.
2526 case ProgramPoint::BlockEdgeKind: {
2527 const BlockEdge &E = Loc.castAs<BlockEdge>();
2528 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
2529 << E.getDst()->getBlockID() << ')';
2531 if (const Stmt *T = E.getSrc()->getTerminator()) {
2532 SourceLocation SLoc = T->getLocStart();
2534 Out << "\\|Terminator: ";
2535 LangOptions LO; // FIXME.
2536 E.getSrc()->printTerminator(Out, LO);
2538 if (SLoc.isFileID()) {
2540 << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2542 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
2545 if (isa<SwitchStmt>(T)) {
2546 const Stmt *Label = E.getDst()->getLabel();
2549 if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
2551 LangOptions LO; // FIXME.
2553 C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO));
2555 if (const Stmt *RHS = C->getRHS()) {
2557 RHS->printPretty(Out, nullptr, PrintingPolicy(LO));
2563 assert (isa<DefaultStmt>(Label));
2564 Out << "\\ldefault:";
2568 Out << "\\l(implicit) default:";
2570 else if (isa<IndirectGotoStmt>(T)) {
2574 Out << "\\lCondition: ";
2575 if (*E.getSrc()->succ_begin() == E.getDst())
2585 // FIXME: Replace with a general scheme to determine
2586 // the name of the check.
2587 if (GraphPrintCheckerState->isUndefControlFlow(N)) {
2588 Out << "\\|Control-flow based on\\lUndefined value.\\l";
2595 const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
2596 assert(S != nullptr && "Expecting non-null Stmt");
2598 Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
2599 LangOptions LO; // FIXME.
2600 S->printPretty(Out, nullptr, PrintingPolicy(LO));
2601 printLocation(Out, S->getLocStart());
2603 if (Loc.getAs<PreStmt>())
2604 Out << "\\lPreStmt\\l;";
2605 else if (Loc.getAs<PostLoad>())
2606 Out << "\\lPostLoad\\l;";
2607 else if (Loc.getAs<PostStore>())
2608 Out << "\\lPostStore\\l";
2609 else if (Loc.getAs<PostLValue>())
2610 Out << "\\lPostLValue\\l";
2613 // FIXME: Replace with a general scheme to determine
2614 // the name of the check.
2615 if (GraphPrintCheckerState->isImplicitNullDeref(N))
2616 Out << "\\|Implicit-Null Dereference.\\l";
2617 else if (GraphPrintCheckerState->isExplicitNullDeref(N))
2618 Out << "\\|Explicit-Null Dereference.\\l";
2619 else if (GraphPrintCheckerState->isUndefDeref(N))
2620 Out << "\\|Dereference of undefialied value.\\l";
2621 else if (GraphPrintCheckerState->isUndefStore(N))
2622 Out << "\\|Store to Undefined Loc.";
2623 else if (GraphPrintCheckerState->isUndefResult(N))
2624 Out << "\\|Result of operation is undefined.";
2625 else if (GraphPrintCheckerState->isNoReturnCall(N))
2626 Out << "\\|Call to function marked \"noreturn\".";
2627 else if (GraphPrintCheckerState->isBadCall(N))
2628 Out << "\\|Call to NULL/Undefined.";
2629 else if (GraphPrintCheckerState->isUndefArg(N))
2630 Out << "\\|Argument in call is undefined";
2637 ProgramStateRef state = N->getState();
2638 Out << "\\|StateID: " << (const void*) state.get()
2639 << " NodeID: " << (const void*) N << "\\|";
2640 state->printDOT(Out);
2644 if (const ProgramPointTag *tag = Loc.getTag()) {
2645 Out << "\\|Tag: " << tag->getTagDescription();
2651 } // end llvm namespace
2654 void ExprEngine::ViewGraph(bool trim) {
2657 std::vector<const ExplodedNode*> Src;
2659 // Flush any outstanding reports to make sure we cover all the nodes.
2660 // This does not cause them to get displayed.
2661 for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
2662 const_cast<BugType*>(*I)->FlushReports(BR);
2664 // Iterate through the reports and get their nodes.
2665 for (BugReporter::EQClasses_iterator
2666 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
2667 ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
2668 if (N) Src.push_back(N);
2674 GraphPrintCheckerState = this;
2675 GraphPrintSourceManager = &getContext().getSourceManager();
2677 llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
2679 GraphPrintCheckerState = nullptr;
2680 GraphPrintSourceManager = nullptr;
2685 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
2687 GraphPrintCheckerState = this;
2688 GraphPrintSourceManager = &getContext().getSourceManager();
2690 std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
2692 if (!TrimmedG.get())
2693 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
2695 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
2697 GraphPrintCheckerState = nullptr;
2698 GraphPrintSourceManager = nullptr;