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 "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Support/SaveAndRestore.h"
32 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Support/GraphWriter.h"
38 using namespace clang;
42 #define DEBUG_TYPE "ExprEngine"
44 STATISTIC(NumRemoveDeadBindings,
45 "The # of times RemoveDeadBindings is called");
46 STATISTIC(NumMaxBlockCountReached,
47 "The # of aborted paths due to reaching the maximum block count in "
48 "a top level function");
49 STATISTIC(NumMaxBlockCountReachedInInlined,
50 "The # of aborted paths due to reaching the maximum block count in "
51 "an inlined function");
52 STATISTIC(NumTimesRetriedWithoutInlining,
53 "The # of times we re-evaluated a call without inlining");
55 typedef std::pair<const CXXBindTemporaryExpr *, const StackFrameContext *>
56 CXXBindTemporaryContext;
58 // Keeps track of whether CXXBindTemporaryExpr nodes have been evaluated.
59 // The StackFrameContext assures that nested calls due to inlined recursive
60 // functions do not interfere.
61 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedTemporariesSet,
62 llvm::ImmutableSet<CXXBindTemporaryContext>)
64 //===----------------------------------------------------------------------===//
65 // Engine construction and deletion.
66 //===----------------------------------------------------------------------===//
68 static const char* TagProviderName = "ExprEngine";
70 ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled,
71 SetOfConstDecls *VisitedCalleesIn,
72 FunctionSummariesTy *FS,
73 InliningModes HowToInlineIn)
75 AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
78 StateMgr(getContext(), mgr.getStoreManagerCreator(),
79 mgr.getConstraintManagerCreator(), G.getAllocator(),
81 SymMgr(StateMgr.getSymbolManager()),
82 svalBuilder(StateMgr.getSValBuilder()),
83 currStmtIdx(0), currBldrCtx(nullptr),
84 ObjCNoRet(mgr.getASTContext()),
85 ObjCGCEnabled(gcEnabled), BR(mgr, *this),
86 VisitedCallees(VisitedCalleesIn),
87 HowToInline(HowToInlineIn)
89 unsigned TrimInterval = mgr.options.getGraphTrimInterval();
90 if (TrimInterval != 0) {
91 // Enable eager node reclaimation when constructing the ExplodedGraph.
92 G.enableNodeReclamation(TrimInterval);
96 ExprEngine::~ExprEngine() {
100 //===----------------------------------------------------------------------===//
102 //===----------------------------------------------------------------------===//
104 ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
105 ProgramStateRef state = StateMgr.getInitialState(InitLoc);
106 const Decl *D = InitLoc->getDecl();
109 // FIXME: It would be nice if we had a more general mechanism to add
110 // such preconditions. Some day.
113 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
114 // Precondition: the first argument of 'main' is an integer guaranteed
116 const IdentifierInfo *II = FD->getIdentifier();
117 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
120 const ParmVarDecl *PD = FD->getParamDecl(0);
121 QualType T = PD->getType();
122 const BuiltinType *BT = dyn_cast<BuiltinType>(T);
123 if (!BT || !BT->isInteger())
126 const MemRegion *R = state->getRegion(PD, InitLoc);
130 SVal V = state->getSVal(loc::MemRegionVal(R));
131 SVal Constraint_untested = evalBinOp(state, BO_GT, V,
132 svalBuilder.makeZeroVal(T),
133 svalBuilder.getConditionType());
135 Optional<DefinedOrUnknownSVal> Constraint =
136 Constraint_untested.getAs<DefinedOrUnknownSVal>();
141 if (ProgramStateRef newState = state->assume(*Constraint, true))
148 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
149 // Precondition: 'self' is always non-null upon entry to an Objective-C
151 const ImplicitParamDecl *SelfD = MD->getSelfDecl();
152 const MemRegion *R = state->getRegion(SelfD, InitLoc);
153 SVal V = state->getSVal(loc::MemRegionVal(R));
155 if (Optional<Loc> LV = V.getAs<Loc>()) {
156 // Assume that the pointer value in 'self' is non-null.
157 state = state->assume(*LV, true);
158 assert(state && "'self' cannot be null");
162 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
163 if (!MD->isStatic()) {
164 // Precondition: 'this' is always non-null upon entry to the
165 // top-level function. This is our starting assumption for
166 // analyzing an "open" program.
167 const StackFrameContext *SFC = InitLoc->getCurrentStackFrame();
168 if (SFC->getParent() == nullptr) {
169 loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
170 SVal V = state->getSVal(L);
171 if (Optional<Loc> LV = V.getAs<Loc>()) {
172 state = state->assume(*LV, true);
173 assert(state && "'this' cannot be null");
183 ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State,
184 const LocationContext *LC,
185 const Expr *InitWithAdjustments,
186 const Expr *Result) {
187 // FIXME: This function is a hack that works around the quirky AST
188 // we're often having with respect to C++ temporaries. If only we modelled
189 // the actual execution order of statements properly in the CFG,
190 // all the hassle with adjustments would not be necessary,
191 // and perhaps the whole function would be removed.
192 SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, LC);
194 // If we don't have an explicit result expression, we're in "if needed"
195 // mode. Only create a region if the current value is a NonLoc.
196 if (!InitValWithAdjustments.getAs<NonLoc>())
198 Result = InitWithAdjustments;
200 // We need to create a region no matter what. For sanity, make sure we don't
201 // try to stuff a Loc into a non-pointer temporary region.
202 assert(!InitValWithAdjustments.getAs<Loc>() ||
203 Loc::isLocType(Result->getType()) ||
204 Result->getType()->isMemberPointerType());
207 ProgramStateManager &StateMgr = State->getStateManager();
208 MemRegionManager &MRMgr = StateMgr.getRegionManager();
209 StoreManager &StoreMgr = StateMgr.getStoreManager();
211 // MaterializeTemporaryExpr may appear out of place, after a few field and
212 // base-class accesses have been made to the object, even though semantically
213 // it is the whole object that gets materialized and lifetime-extended.
217 // `-MaterializeTemporaryExpr
219 // `-CXXTemporaryObjectExpr
221 // instead of the more natural
224 // `-MaterializeTemporaryExpr
225 // `-CXXTemporaryObjectExpr
227 // Use the usual methods for obtaining the expression of the base object,
228 // and record the adjustments that we need to make to obtain the sub-object
229 // that the whole expression 'Ex' refers to. This trick is usual,
230 // in the sense that CodeGen takes a similar route.
232 SmallVector<const Expr *, 2> CommaLHSs;
233 SmallVector<SubobjectAdjustment, 2> Adjustments;
235 const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments(
236 CommaLHSs, Adjustments);
238 const TypedValueRegion *TR = nullptr;
239 if (const MaterializeTemporaryExpr *MT =
240 dyn_cast<MaterializeTemporaryExpr>(Result)) {
241 StorageDuration SD = MT->getStorageDuration();
242 // If this object is bound to a reference with static storage duration, we
243 // put it in a different region to prevent "address leakage" warnings.
244 if (SD == SD_Static || SD == SD_Thread)
245 TR = MRMgr.getCXXStaticTempObjectRegion(Init);
248 TR = MRMgr.getCXXTempObjectRegion(Init, LC);
250 SVal Reg = loc::MemRegionVal(TR);
253 // Make the necessary adjustments to obtain the sub-object.
254 for (auto I = Adjustments.rbegin(), E = Adjustments.rend(); I != E; ++I) {
255 const SubobjectAdjustment &Adj = *I;
257 case SubobjectAdjustment::DerivedToBaseAdjustment:
258 Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath);
260 case SubobjectAdjustment::FieldAdjustment:
261 Reg = StoreMgr.getLValueField(Adj.Field, Reg);
263 case SubobjectAdjustment::MemberPointerAdjustment:
264 // FIXME: Unimplemented.
265 State = State->bindDefault(Reg, UnknownVal(), LC);
270 // What remains is to copy the value of the object to the new region.
271 // FIXME: In other words, what we should always do is copy value of the
272 // Init expression (which corresponds to the bigger object) to the whole
273 // temporary region TR. However, this value is often no longer present
274 // in the Environment. If it has disappeared, we instead invalidate TR.
275 // Still, what we can do is assign the value of expression Ex (which
276 // corresponds to the sub-object) to the TR's sub-region Reg. At least,
277 // values inside Reg would be correct.
278 SVal InitVal = State->getSVal(Init, LC);
279 if (InitVal.isUnknown()) {
280 InitVal = getSValBuilder().conjureSymbolVal(Result, LC, Init->getType(),
281 currBldrCtx->blockCount());
282 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
284 // Then we'd need to take the value that certainly exists and bind it over.
285 if (InitValWithAdjustments.isUnknown()) {
286 // Try to recover some path sensitivity in case we couldn't
287 // compute the value.
288 InitValWithAdjustments = getSValBuilder().conjureSymbolVal(
289 Result, LC, InitWithAdjustments->getType(),
290 currBldrCtx->blockCount());
293 State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false);
295 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
298 // The result expression would now point to the correct sub-region of the
299 // newly created temporary region. Do this last in order to getSVal of Init
300 // correctly in case (Result == Init).
301 State = State->BindExpr(Result, LC, Reg);
303 // Notify checkers once for two bindLoc()s.
304 State = processRegionChange(State, TR, LC);
309 //===----------------------------------------------------------------------===//
310 // Top-level transfer function logic (Dispatcher).
311 //===----------------------------------------------------------------------===//
313 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
314 /// logic for handling assumptions on symbolic values.
315 ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
316 SVal cond, bool assumption) {
317 return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
321 ExprEngine::processRegionChanges(ProgramStateRef state,
322 const InvalidatedSymbols *invalidated,
323 ArrayRef<const MemRegion *> Explicits,
324 ArrayRef<const MemRegion *> Regions,
325 const LocationContext *LCtx,
326 const CallEvent *Call) {
327 return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
332 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
333 const char *NL, const char *Sep) {
334 getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
337 void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
338 getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
341 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
342 unsigned StmtIdx, NodeBuilderContext *Ctx) {
343 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
344 currStmtIdx = StmtIdx;
347 switch (E.getKind()) {
348 case CFGElement::Statement:
349 ProcessStmt(const_cast<Stmt*>(E.castAs<CFGStmt>().getStmt()), Pred);
351 case CFGElement::Initializer:
352 ProcessInitializer(E.castAs<CFGInitializer>().getInitializer(), Pred);
354 case CFGElement::NewAllocator:
355 ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(),
358 case CFGElement::AutomaticObjectDtor:
359 case CFGElement::DeleteDtor:
360 case CFGElement::BaseDtor:
361 case CFGElement::MemberDtor:
362 case CFGElement::TemporaryDtor:
363 ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
368 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
370 const ExplodedNode *Pred,
371 const LocationContext *LC) {
373 // Are we never purging state values?
374 if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
377 // Is this the beginning of a basic block?
378 if (Pred->getLocation().getAs<BlockEntrance>())
381 // Is this on a non-expression?
382 if (!isa<Expr>(S.getStmt()))
385 // Run before processing a call.
386 if (CallEvent::isCallStmt(S.getStmt()))
389 // Is this an expression that is consumed by another expression? If so,
390 // postpone cleaning out the state.
391 ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
392 return !PM.isConsumedExpr(cast<Expr>(S.getStmt()));
395 void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
396 const Stmt *ReferenceStmt,
397 const LocationContext *LC,
398 const Stmt *DiagnosticStmt,
399 ProgramPoint::Kind K) {
400 assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
401 ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
402 && "PostStmt is not generally supported by the SymbolReaper yet");
403 assert(LC && "Must pass the current (or expiring) LocationContext");
405 if (!DiagnosticStmt) {
406 DiagnosticStmt = ReferenceStmt;
407 assert(DiagnosticStmt && "Required for clearing a LocationContext");
410 NumRemoveDeadBindings++;
411 ProgramStateRef CleanedState = Pred->getState();
413 // LC is the location context being destroyed, but SymbolReaper wants a
414 // location context that is still live. (If this is the top-level stack
415 // frame, this will be null.)
416 if (!ReferenceStmt) {
417 assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
418 "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
419 LC = LC->getParent();
422 const StackFrameContext *SFC = LC ? LC->getCurrentStackFrame() : nullptr;
423 SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
425 getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
427 // Create a state in which dead bindings are removed from the environment
428 // and the store. TODO: The function should just return new env and store,
430 CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
432 // Process any special transfer function for dead symbols.
433 // A tag to track convenience transitions, which can be removed at cleanup.
434 static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
435 if (!SymReaper.hasDeadSymbols()) {
436 // Generate a CleanedNode that has the environment and store cleaned
437 // up. Since no symbols are dead, we can optimize and not clean out
438 // the constraint manager.
439 StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx);
440 Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K);
443 // Call checkers with the non-cleaned state so that they could query the
444 // values of the soon to be dead symbols.
445 ExplodedNodeSet CheckedSet;
446 getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
447 DiagnosticStmt, *this, K);
449 // For each node in CheckedSet, generate CleanedNodes that have the
450 // environment, the store, and the constraints cleaned up but have the
451 // user-supplied states as the predecessors.
452 StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
453 for (ExplodedNodeSet::const_iterator
454 I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) {
455 ProgramStateRef CheckerState = (*I)->getState();
457 // The constraint manager has not been cleaned up yet, so clean up now.
458 CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
461 assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
462 "Checkers are not allowed to modify the Environment as a part of "
463 "checkDeadSymbols processing.");
464 assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
465 "Checkers are not allowed to modify the Store as a part of "
466 "checkDeadSymbols processing.");
468 // Create a state based on CleanedState with CheckerState GDM and
469 // generate a transition to that state.
470 ProgramStateRef CleanedCheckerSt =
471 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
472 Bldr.generateNode(DiagnosticStmt, *I, CleanedCheckerSt, &cleanupTag, K);
477 void ExprEngine::ProcessStmt(const CFGStmt S,
478 ExplodedNode *Pred) {
479 // Reclaim any unnecessary nodes in the ExplodedGraph.
480 G.reclaimRecentlyAllocatedNodes();
482 const Stmt *currStmt = S.getStmt();
483 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
484 currStmt->getLocStart(),
485 "Error evaluating statement");
487 // Remove dead bindings and symbols.
488 ExplodedNodeSet CleanedStates;
489 if (shouldRemoveDeadBindings(AMgr, S, Pred, Pred->getLocationContext())){
490 removeDead(Pred, CleanedStates, currStmt, Pred->getLocationContext());
492 CleanedStates.Add(Pred);
494 // Visit the statement.
496 for (ExplodedNodeSet::iterator I = CleanedStates.begin(),
497 E = CleanedStates.end(); I != E; ++I) {
498 ExplodedNodeSet DstI;
499 // Visit the statement.
500 Visit(currStmt, *I, DstI);
504 // Enqueue the new nodes onto the work list.
505 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
508 void ExprEngine::ProcessInitializer(const CFGInitializer Init,
509 ExplodedNode *Pred) {
510 const CXXCtorInitializer *BMI = Init.getInitializer();
512 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
513 BMI->getSourceLocation(),
514 "Error evaluating initializer");
516 // We don't clean up dead bindings here.
517 const StackFrameContext *stackFrame =
518 cast<StackFrameContext>(Pred->getLocationContext());
519 const CXXConstructorDecl *decl =
520 cast<CXXConstructorDecl>(stackFrame->getDecl());
522 ProgramStateRef State = Pred->getState();
523 SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
525 ExplodedNodeSet Tmp(Pred);
528 // Evaluate the initializer, if necessary
529 if (BMI->isAnyMemberInitializer()) {
530 // Constructors build the object directly in the field,
531 // but non-objects must be copied in from the initializer.
532 if (auto *CtorExpr = findDirectConstructorForCurrentCFGElement()) {
533 assert(BMI->getInit()->IgnoreImplicit() == CtorExpr);
535 // The field was directly constructed, so there is no need to bind.
537 const Expr *Init = BMI->getInit()->IgnoreImplicit();
538 const ValueDecl *Field;
539 if (BMI->isIndirectMemberInitializer()) {
540 Field = BMI->getIndirectMember();
541 FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
543 Field = BMI->getMember();
544 FieldLoc = State->getLValue(BMI->getMember(), thisVal);
548 if (Init->getType()->isArrayType()) {
549 // Handle arrays of trivial type. We can represent this with a
550 // primitive load/copy from the base array region.
551 const ArraySubscriptExpr *ASE;
552 while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
553 Init = ASE->getBase()->IgnoreImplicit();
555 SVal LValue = State->getSVal(Init, stackFrame);
556 if (!Field->getType()->isReferenceType())
557 if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
558 InitVal = State->getSVal(*LValueLoc);
560 // If we fail to get the value for some reason, use a symbolic value.
561 if (InitVal.isUnknownOrUndef()) {
562 SValBuilder &SVB = getSValBuilder();
563 InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
565 currBldrCtx->blockCount());
568 InitVal = State->getSVal(BMI->getInit(), stackFrame);
571 assert(Tmp.size() == 1 && "have not generated any new nodes yet");
572 assert(*Tmp.begin() == Pred && "have not generated any new nodes yet");
575 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
576 evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
579 assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
580 // We already did all the work when visiting the CXXConstructExpr.
583 // Construct PostInitializer nodes whether the state changed or not,
584 // so that the diagnostics don't get confused.
585 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
587 NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
588 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) {
589 ExplodedNode *N = *I;
590 Bldr.generateNode(PP, N->getState(), N);
593 // Enqueue the new nodes onto the work list.
594 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
597 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
598 ExplodedNode *Pred) {
600 switch (D.getKind()) {
601 case CFGElement::AutomaticObjectDtor:
602 ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
604 case CFGElement::BaseDtor:
605 ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
607 case CFGElement::MemberDtor:
608 ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
610 case CFGElement::TemporaryDtor:
611 ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
613 case CFGElement::DeleteDtor:
614 ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
617 llvm_unreachable("Unexpected dtor kind.");
620 // Enqueue the new nodes onto the work list.
621 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
624 void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE,
625 ExplodedNode *Pred) {
627 AnalysisManager &AMgr = getAnalysisManager();
628 AnalyzerOptions &Opts = AMgr.options;
629 // TODO: We're not evaluating allocators for all cases just yet as
630 // we're not handling the return value correctly, which causes false
631 // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
632 if (Opts.mayInlineCXXAllocator())
633 VisitCXXNewAllocatorCall(NE, Pred, Dst);
635 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
636 const LocationContext *LCtx = Pred->getLocationContext();
637 PostImplicitCall PP(NE->getOperatorNew(), NE->getLocStart(), LCtx);
638 Bldr.generateNode(PP, Pred->getState(), Pred);
640 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
643 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
645 ExplodedNodeSet &Dst) {
646 const VarDecl *varDecl = Dtor.getVarDecl();
647 QualType varType = varDecl->getType();
649 ProgramStateRef state = Pred->getState();
650 SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
651 const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
653 if (varType->isReferenceType()) {
654 const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion();
656 // FIXME: This should not happen. The language guarantees a presence
657 // of a valid initializer here, so the reference shall not be undefined.
658 // It seems that we're calling destructors over variables that
659 // were not initialized yet.
662 Region = ValueRegion->getBaseRegion();
663 varType = cast<TypedValueRegion>(Region)->getValueType();
666 VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
670 void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor,
672 ExplodedNodeSet &Dst) {
673 ProgramStateRef State = Pred->getState();
674 const LocationContext *LCtx = Pred->getLocationContext();
675 const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
676 const Stmt *Arg = DE->getArgument();
677 SVal ArgVal = State->getSVal(Arg, LCtx);
679 // If the argument to delete is known to be a null value,
680 // don't run destructor.
681 if (State->isNull(ArgVal).isConstrainedTrue()) {
682 QualType DTy = DE->getDestroyedType();
683 QualType BTy = getContext().getBaseElementType(DTy);
684 const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
685 const CXXDestructorDecl *Dtor = RD->getDestructor();
687 PostImplicitCall PP(Dtor, DE->getLocStart(), LCtx);
688 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
689 Bldr.generateNode(PP, Pred->getState(), Pred);
693 VisitCXXDestructor(DE->getDestroyedType(),
694 ArgVal.getAsRegion(),
695 DE, /*IsBase=*/ false,
699 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
700 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
701 const LocationContext *LCtx = Pred->getLocationContext();
703 const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
704 Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
705 LCtx->getCurrentStackFrame());
706 SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
708 // Create the base object region.
709 const CXXBaseSpecifier *Base = D.getBaseSpecifier();
710 QualType BaseTy = Base->getType();
711 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
714 VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
715 CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst);
718 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
719 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
720 const FieldDecl *Member = D.getFieldDecl();
721 ProgramStateRef State = Pred->getState();
722 const LocationContext *LCtx = Pred->getLocationContext();
724 const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
725 Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
726 LCtx->getCurrentStackFrame());
728 State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
730 VisitCXXDestructor(Member->getType(),
731 FieldVal.castAs<loc::MemRegionVal>().getRegion(),
732 CurDtor->getBody(), /*IsBase=*/false, Pred, Dst);
735 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
737 ExplodedNodeSet &Dst) {
738 ExplodedNodeSet CleanDtorState;
739 StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx);
740 ProgramStateRef State = Pred->getState();
741 if (State->contains<InitializedTemporariesSet>(
742 std::make_pair(D.getBindTemporaryExpr(), Pred->getStackFrame()))) {
743 // FIXME: Currently we insert temporary destructors for default parameters,
744 // but we don't insert the constructors.
745 State = State->remove<InitializedTemporariesSet>(
746 std::make_pair(D.getBindTemporaryExpr(), Pred->getStackFrame()));
748 StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
750 QualType varType = D.getBindTemporaryExpr()->getSubExpr()->getType();
751 // FIXME: Currently CleanDtorState can be empty here due to temporaries being
752 // bound to default parameters.
753 assert(CleanDtorState.size() <= 1);
754 ExplodedNode *CleanPred =
755 CleanDtorState.empty() ? Pred : *CleanDtorState.begin();
756 // FIXME: Inlining of temporary destructors is not supported yet anyway, so
757 // we just put a NULL region for now. This will need to be changed later.
758 VisitCXXDestructor(varType, nullptr, D.getBindTemporaryExpr(),
759 /*IsBase=*/false, CleanPred, Dst);
762 void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
763 NodeBuilderContext &BldCtx,
765 ExplodedNodeSet &Dst,
766 const CFGBlock *DstT,
767 const CFGBlock *DstF) {
768 BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF);
769 if (Pred->getState()->contains<InitializedTemporariesSet>(
770 std::make_pair(BTE, Pred->getStackFrame()))) {
771 TempDtorBuilder.markInfeasible(false);
772 TempDtorBuilder.generateNode(Pred->getState(), true, Pred);
774 TempDtorBuilder.markInfeasible(true);
775 TempDtorBuilder.generateNode(Pred->getState(), false, Pred);
779 void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE,
780 ExplodedNodeSet &PreVisit,
781 ExplodedNodeSet &Dst) {
782 if (!getAnalysisManager().options.includeTemporaryDtorsInCFG()) {
783 // In case we don't have temporary destructors in the CFG, do not mark
784 // the initialization - we would otherwise never clean it up.
788 StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
789 for (ExplodedNode *Node : PreVisit) {
790 ProgramStateRef State = Node->getState();
792 if (!State->contains<InitializedTemporariesSet>(
793 std::make_pair(BTE, Node->getStackFrame()))) {
794 // FIXME: Currently the state might already contain the marker due to
795 // incorrect handling of temporaries bound to default parameters; for
796 // those, we currently skip the CXXBindTemporaryExpr but rely on adding
797 // temporary destructor nodes.
798 State = State->add<InitializedTemporariesSet>(
799 std::make_pair(BTE, Node->getStackFrame()));
801 StmtBldr.generateNode(BTE, Node, State);
805 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
806 ExplodedNodeSet &DstTop) {
807 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
809 "Error evaluating statement");
811 StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
813 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
815 switch (S->getStmtClass()) {
816 // C++, OpenMP and ARC stuff we don't support yet.
817 case Expr::ObjCIndirectCopyRestoreExprClass:
818 case Stmt::CXXDependentScopeMemberExprClass:
819 case Stmt::CXXInheritedCtorInitExprClass:
820 case Stmt::CXXTryStmtClass:
821 case Stmt::CXXTypeidExprClass:
822 case Stmt::CXXUuidofExprClass:
823 case Stmt::CXXFoldExprClass:
824 case Stmt::MSPropertyRefExprClass:
825 case Stmt::MSPropertySubscriptExprClass:
826 case Stmt::CXXUnresolvedConstructExprClass:
827 case Stmt::DependentScopeDeclRefExprClass:
828 case Stmt::ArrayTypeTraitExprClass:
829 case Stmt::ExpressionTraitExprClass:
830 case Stmt::UnresolvedLookupExprClass:
831 case Stmt::UnresolvedMemberExprClass:
832 case Stmt::TypoExprClass:
833 case Stmt::CXXNoexceptExprClass:
834 case Stmt::PackExpansionExprClass:
835 case Stmt::SubstNonTypeTemplateParmPackExprClass:
836 case Stmt::FunctionParmPackExprClass:
837 case Stmt::CoroutineBodyStmtClass:
838 case Stmt::CoawaitExprClass:
839 case Stmt::DependentCoawaitExprClass:
840 case Stmt::CoreturnStmtClass:
841 case Stmt::CoyieldExprClass:
842 case Stmt::SEHTryStmtClass:
843 case Stmt::SEHExceptStmtClass:
844 case Stmt::SEHLeaveStmtClass:
845 case Stmt::SEHFinallyStmtClass:
846 case Stmt::OMPParallelDirectiveClass:
847 case Stmt::OMPSimdDirectiveClass:
848 case Stmt::OMPForDirectiveClass:
849 case Stmt::OMPForSimdDirectiveClass:
850 case Stmt::OMPSectionsDirectiveClass:
851 case Stmt::OMPSectionDirectiveClass:
852 case Stmt::OMPSingleDirectiveClass:
853 case Stmt::OMPMasterDirectiveClass:
854 case Stmt::OMPCriticalDirectiveClass:
855 case Stmt::OMPParallelForDirectiveClass:
856 case Stmt::OMPParallelForSimdDirectiveClass:
857 case Stmt::OMPParallelSectionsDirectiveClass:
858 case Stmt::OMPTaskDirectiveClass:
859 case Stmt::OMPTaskyieldDirectiveClass:
860 case Stmt::OMPBarrierDirectiveClass:
861 case Stmt::OMPTaskwaitDirectiveClass:
862 case Stmt::OMPTaskgroupDirectiveClass:
863 case Stmt::OMPFlushDirectiveClass:
864 case Stmt::OMPOrderedDirectiveClass:
865 case Stmt::OMPAtomicDirectiveClass:
866 case Stmt::OMPTargetDirectiveClass:
867 case Stmt::OMPTargetDataDirectiveClass:
868 case Stmt::OMPTargetEnterDataDirectiveClass:
869 case Stmt::OMPTargetExitDataDirectiveClass:
870 case Stmt::OMPTargetParallelDirectiveClass:
871 case Stmt::OMPTargetParallelForDirectiveClass:
872 case Stmt::OMPTargetUpdateDirectiveClass:
873 case Stmt::OMPTeamsDirectiveClass:
874 case Stmt::OMPCancellationPointDirectiveClass:
875 case Stmt::OMPCancelDirectiveClass:
876 case Stmt::OMPTaskLoopDirectiveClass:
877 case Stmt::OMPTaskLoopSimdDirectiveClass:
878 case Stmt::OMPDistributeDirectiveClass:
879 case Stmt::OMPDistributeParallelForDirectiveClass:
880 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
881 case Stmt::OMPDistributeSimdDirectiveClass:
882 case Stmt::OMPTargetParallelForSimdDirectiveClass:
883 case Stmt::OMPTargetSimdDirectiveClass:
884 case Stmt::OMPTeamsDistributeDirectiveClass:
885 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
886 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
887 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
888 case Stmt::OMPTargetTeamsDirectiveClass:
889 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
890 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
891 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
892 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
893 case Stmt::CapturedStmtClass:
895 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
896 Engine.addAbortedBlock(node, currBldrCtx->getBlock());
900 case Stmt::ParenExprClass:
901 llvm_unreachable("ParenExprs already handled.");
902 case Stmt::GenericSelectionExprClass:
903 llvm_unreachable("GenericSelectionExprs already handled.");
904 // Cases that should never be evaluated simply because they shouldn't
905 // appear in the CFG.
906 case Stmt::BreakStmtClass:
907 case Stmt::CaseStmtClass:
908 case Stmt::CompoundStmtClass:
909 case Stmt::ContinueStmtClass:
910 case Stmt::CXXForRangeStmtClass:
911 case Stmt::DefaultStmtClass:
912 case Stmt::DoStmtClass:
913 case Stmt::ForStmtClass:
914 case Stmt::GotoStmtClass:
915 case Stmt::IfStmtClass:
916 case Stmt::IndirectGotoStmtClass:
917 case Stmt::LabelStmtClass:
918 case Stmt::NoStmtClass:
919 case Stmt::NullStmtClass:
920 case Stmt::SwitchStmtClass:
921 case Stmt::WhileStmtClass:
922 case Expr::MSDependentExistsStmtClass:
923 llvm_unreachable("Stmt should not be in analyzer evaluation loop");
925 case Stmt::ObjCSubscriptRefExprClass:
926 case Stmt::ObjCPropertyRefExprClass:
927 llvm_unreachable("These are handled by PseudoObjectExpr");
929 case Stmt::GNUNullExprClass: {
930 // GNU __null is a pointer-width integer, not an actual pointer.
931 ProgramStateRef state = Pred->getState();
932 state = state->BindExpr(S, Pred->getLocationContext(),
933 svalBuilder.makeIntValWithPtrWidth(0, false));
934 Bldr.generateNode(S, Pred, state);
938 case Stmt::ObjCAtSynchronizedStmtClass:
939 Bldr.takeNodes(Pred);
940 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
944 case Stmt::ExprWithCleanupsClass:
945 // Handled due to fully linearised CFG.
948 case Stmt::CXXBindTemporaryExprClass: {
949 Bldr.takeNodes(Pred);
950 ExplodedNodeSet PreVisit;
951 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
952 ExplodedNodeSet Next;
953 VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
954 getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
959 // Cases not handled yet; but will handle some day.
960 case Stmt::DesignatedInitExprClass:
961 case Stmt::DesignatedInitUpdateExprClass:
962 case Stmt::ArrayInitLoopExprClass:
963 case Stmt::ArrayInitIndexExprClass:
964 case Stmt::ExtVectorElementExprClass:
965 case Stmt::ImaginaryLiteralClass:
966 case Stmt::ObjCAtCatchStmtClass:
967 case Stmt::ObjCAtFinallyStmtClass:
968 case Stmt::ObjCAtTryStmtClass:
969 case Stmt::ObjCAutoreleasePoolStmtClass:
970 case Stmt::ObjCEncodeExprClass:
971 case Stmt::ObjCIsaExprClass:
972 case Stmt::ObjCProtocolExprClass:
973 case Stmt::ObjCSelectorExprClass:
974 case Stmt::ParenListExprClass:
975 case Stmt::ShuffleVectorExprClass:
976 case Stmt::ConvertVectorExprClass:
977 case Stmt::VAArgExprClass:
978 case Stmt::CUDAKernelCallExprClass:
979 case Stmt::OpaqueValueExprClass:
980 case Stmt::AsTypeExprClass:
983 // Cases we intentionally don't evaluate, since they don't need
984 // to be explicitly evaluated.
985 case Stmt::PredefinedExprClass:
986 case Stmt::AddrLabelExprClass:
987 case Stmt::AttributedStmtClass:
988 case Stmt::IntegerLiteralClass:
989 case Stmt::CharacterLiteralClass:
990 case Stmt::ImplicitValueInitExprClass:
991 case Stmt::CXXScalarValueInitExprClass:
992 case Stmt::CXXBoolLiteralExprClass:
993 case Stmt::ObjCBoolLiteralExprClass:
994 case Stmt::ObjCAvailabilityCheckExprClass:
995 case Stmt::FloatingLiteralClass:
996 case Stmt::NoInitExprClass:
997 case Stmt::SizeOfPackExprClass:
998 case Stmt::StringLiteralClass:
999 case Stmt::ObjCStringLiteralClass:
1000 case Stmt::CXXPseudoDestructorExprClass:
1001 case Stmt::SubstNonTypeTemplateParmExprClass:
1002 case Stmt::CXXNullPtrLiteralExprClass:
1003 case Stmt::OMPArraySectionExprClass:
1004 case Stmt::TypeTraitExprClass: {
1005 Bldr.takeNodes(Pred);
1006 ExplodedNodeSet preVisit;
1007 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1008 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
1013 case Stmt::CXXDefaultArgExprClass:
1014 case Stmt::CXXDefaultInitExprClass: {
1015 Bldr.takeNodes(Pred);
1016 ExplodedNodeSet PreVisit;
1017 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1019 ExplodedNodeSet Tmp;
1020 StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
1023 if (const CXXDefaultArgExpr *DefE = dyn_cast<CXXDefaultArgExpr>(S))
1024 ArgE = DefE->getExpr();
1025 else if (const CXXDefaultInitExpr *DefE = dyn_cast<CXXDefaultInitExpr>(S))
1026 ArgE = DefE->getExpr();
1028 llvm_unreachable("unknown constant wrapper kind");
1030 bool IsTemporary = false;
1031 if (const MaterializeTemporaryExpr *MTE =
1032 dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
1033 ArgE = MTE->GetTemporaryExpr();
1037 Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
1039 ConstantVal = UnknownVal();
1041 const LocationContext *LCtx = Pred->getLocationContext();
1042 for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end();
1044 ProgramStateRef State = (*I)->getState();
1045 State = State->BindExpr(S, LCtx, *ConstantVal);
1047 State = createTemporaryRegionIfNeeded(State, LCtx,
1050 Bldr2.generateNode(S, *I, State);
1053 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1058 // Cases we evaluate as opaque expressions, conjuring a symbol.
1059 case Stmt::CXXStdInitializerListExprClass:
1060 case Expr::ObjCArrayLiteralClass:
1061 case Expr::ObjCDictionaryLiteralClass:
1062 case Expr::ObjCBoxedExprClass: {
1063 Bldr.takeNodes(Pred);
1065 ExplodedNodeSet preVisit;
1066 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1068 ExplodedNodeSet Tmp;
1069 StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
1071 const Expr *Ex = cast<Expr>(S);
1072 QualType resultType = Ex->getType();
1074 for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end();
1076 ExplodedNode *N = *it;
1077 const LocationContext *LCtx = N->getLocationContext();
1078 SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
1080 currBldrCtx->blockCount());
1081 ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result);
1082 Bldr2.generateNode(S, N, state);
1085 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1090 case Stmt::ArraySubscriptExprClass:
1091 Bldr.takeNodes(Pred);
1092 VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
1096 case Stmt::GCCAsmStmtClass:
1097 Bldr.takeNodes(Pred);
1098 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
1102 case Stmt::MSAsmStmtClass:
1103 Bldr.takeNodes(Pred);
1104 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
1108 case Stmt::BlockExprClass:
1109 Bldr.takeNodes(Pred);
1110 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
1114 case Stmt::LambdaExprClass:
1115 if (AMgr.options.shouldInlineLambdas()) {
1116 Bldr.takeNodes(Pred);
1117 VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
1120 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1121 Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1125 case Stmt::BinaryOperatorClass: {
1126 const BinaryOperator* B = cast<BinaryOperator>(S);
1127 if (B->isLogicalOp()) {
1128 Bldr.takeNodes(Pred);
1129 VisitLogicalExpr(B, Pred, Dst);
1133 else if (B->getOpcode() == BO_Comma) {
1134 ProgramStateRef state = Pred->getState();
1135 Bldr.generateNode(B, Pred,
1136 state->BindExpr(B, Pred->getLocationContext(),
1137 state->getSVal(B->getRHS(),
1138 Pred->getLocationContext())));
1142 Bldr.takeNodes(Pred);
1144 if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
1145 (B->isRelationalOp() || B->isEqualityOp())) {
1146 ExplodedNodeSet Tmp;
1147 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
1148 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
1151 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1157 case Stmt::CXXOperatorCallExprClass: {
1158 const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S);
1160 // For instance method operators, make sure the 'this' argument has a
1162 const Decl *Callee = OCE->getCalleeDecl();
1163 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
1164 if (MD->isInstance()) {
1165 ProgramStateRef State = Pred->getState();
1166 const LocationContext *LCtx = Pred->getLocationContext();
1167 ProgramStateRef NewState =
1168 createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
1169 if (NewState != State) {
1170 Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
1171 ProgramPoint::PreStmtKind);
1172 // Did we cache out?
1180 case Stmt::CallExprClass:
1181 case Stmt::CXXMemberCallExprClass:
1182 case Stmt::UserDefinedLiteralClass: {
1183 Bldr.takeNodes(Pred);
1184 VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
1189 case Stmt::CXXCatchStmtClass: {
1190 Bldr.takeNodes(Pred);
1191 VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
1196 case Stmt::CXXTemporaryObjectExprClass:
1197 case Stmt::CXXConstructExprClass: {
1198 Bldr.takeNodes(Pred);
1199 VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
1204 case Stmt::CXXNewExprClass: {
1205 Bldr.takeNodes(Pred);
1206 ExplodedNodeSet PostVisit;
1207 VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit);
1208 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1213 case Stmt::CXXDeleteExprClass: {
1214 Bldr.takeNodes(Pred);
1215 ExplodedNodeSet PreVisit;
1216 const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
1217 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1219 for (ExplodedNodeSet::iterator i = PreVisit.begin(),
1220 e = PreVisit.end(); i != e ; ++i)
1221 VisitCXXDeleteExpr(CDE, *i, Dst);
1226 // FIXME: ChooseExpr is really a constant. We need to fix
1227 // the CFG do not model them as explicit control-flow.
1229 case Stmt::ChooseExprClass: { // __builtin_choose_expr
1230 Bldr.takeNodes(Pred);
1231 const ChooseExpr *C = cast<ChooseExpr>(S);
1232 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
1237 case Stmt::CompoundAssignOperatorClass:
1238 Bldr.takeNodes(Pred);
1239 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1243 case Stmt::CompoundLiteralExprClass:
1244 Bldr.takeNodes(Pred);
1245 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
1249 case Stmt::BinaryConditionalOperatorClass:
1250 case Stmt::ConditionalOperatorClass: { // '?' operator
1251 Bldr.takeNodes(Pred);
1252 const AbstractConditionalOperator *C
1253 = cast<AbstractConditionalOperator>(S);
1254 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
1259 case Stmt::CXXThisExprClass:
1260 Bldr.takeNodes(Pred);
1261 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
1265 case Stmt::DeclRefExprClass: {
1266 Bldr.takeNodes(Pred);
1267 const DeclRefExpr *DE = cast<DeclRefExpr>(S);
1268 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
1273 case Stmt::DeclStmtClass:
1274 Bldr.takeNodes(Pred);
1275 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
1279 case Stmt::ImplicitCastExprClass:
1280 case Stmt::CStyleCastExprClass:
1281 case Stmt::CXXStaticCastExprClass:
1282 case Stmt::CXXDynamicCastExprClass:
1283 case Stmt::CXXReinterpretCastExprClass:
1284 case Stmt::CXXConstCastExprClass:
1285 case Stmt::CXXFunctionalCastExprClass:
1286 case Stmt::ObjCBridgedCastExprClass: {
1287 Bldr.takeNodes(Pred);
1288 const CastExpr *C = cast<CastExpr>(S);
1289 ExplodedNodeSet dstExpr;
1290 VisitCast(C, C->getSubExpr(), Pred, dstExpr);
1292 // Handle the postvisit checks.
1293 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1298 case Expr::MaterializeTemporaryExprClass: {
1299 Bldr.takeNodes(Pred);
1300 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
1301 ExplodedNodeSet dstPrevisit;
1302 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this);
1303 ExplodedNodeSet dstExpr;
1304 for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
1305 e = dstPrevisit.end(); i != e ; ++i) {
1306 CreateCXXTemporaryObject(MTE, *i, dstExpr);
1308 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this);
1313 case Stmt::InitListExprClass:
1314 Bldr.takeNodes(Pred);
1315 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1319 case Stmt::MemberExprClass:
1320 Bldr.takeNodes(Pred);
1321 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1325 case Stmt::AtomicExprClass:
1326 Bldr.takeNodes(Pred);
1327 VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
1331 case Stmt::ObjCIvarRefExprClass:
1332 Bldr.takeNodes(Pred);
1333 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1337 case Stmt::ObjCForCollectionStmtClass:
1338 Bldr.takeNodes(Pred);
1339 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1343 case Stmt::ObjCMessageExprClass:
1344 Bldr.takeNodes(Pred);
1345 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1349 case Stmt::ObjCAtThrowStmtClass:
1350 case Stmt::CXXThrowExprClass:
1351 // FIXME: This is not complete. We basically treat @throw as
1353 Bldr.generateSink(S, Pred, Pred->getState());
1356 case Stmt::ReturnStmtClass:
1357 Bldr.takeNodes(Pred);
1358 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1362 case Stmt::OffsetOfExprClass:
1363 Bldr.takeNodes(Pred);
1364 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
1368 case Stmt::UnaryExprOrTypeTraitExprClass:
1369 Bldr.takeNodes(Pred);
1370 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1375 case Stmt::StmtExprClass: {
1376 const StmtExpr *SE = cast<StmtExpr>(S);
1378 if (SE->getSubStmt()->body_empty()) {
1379 // Empty statement expression.
1380 assert(SE->getType() == getContext().VoidTy
1381 && "Empty statement expression must have void type.");
1385 if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1386 ProgramStateRef state = Pred->getState();
1387 Bldr.generateNode(SE, Pred,
1388 state->BindExpr(SE, Pred->getLocationContext(),
1389 state->getSVal(LastExpr,
1390 Pred->getLocationContext())));
1395 case Stmt::UnaryOperatorClass: {
1396 Bldr.takeNodes(Pred);
1397 const UnaryOperator *U = cast<UnaryOperator>(S);
1398 if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
1399 ExplodedNodeSet Tmp;
1400 VisitUnaryOperator(U, Pred, Tmp);
1401 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1404 VisitUnaryOperator(U, Pred, Dst);
1409 case Stmt::PseudoObjectExprClass: {
1410 Bldr.takeNodes(Pred);
1411 ProgramStateRef state = Pred->getState();
1412 const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
1413 if (const Expr *Result = PE->getResultExpr()) {
1414 SVal V = state->getSVal(Result, Pred->getLocationContext());
1415 Bldr.generateNode(S, Pred,
1416 state->BindExpr(S, Pred->getLocationContext(), V));
1419 Bldr.generateNode(S, Pred,
1420 state->BindExpr(S, Pred->getLocationContext(),
1429 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1430 const LocationContext *CalleeLC) {
1431 const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1432 const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
1433 assert(CalleeSF && CallerSF);
1434 ExplodedNode *BeforeProcessingCall = nullptr;
1435 const Stmt *CE = CalleeSF->getCallSite();
1437 // Find the first node before we started processing the call expression.
1439 ProgramPoint L = N->getLocation();
1440 BeforeProcessingCall = N;
1441 N = N->pred_empty() ? nullptr : *(N->pred_begin());
1443 // Skip the nodes corresponding to the inlined code.
1444 if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
1446 // We reached the caller. Find the node right before we started
1447 // processing the call.
1448 if (L.isPurgeKind())
1450 if (L.getAs<PreImplicitCall>())
1452 if (L.getAs<CallEnter>())
1454 if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1455 if (SP->getStmt() == CE)
1460 if (!BeforeProcessingCall)
1463 // TODO: Clean up the unneeded nodes.
1465 // Build an Epsilon node from which we will restart the analyzes.
1466 // Note that CE is permitted to be NULL!
1467 ProgramPoint NewNodeLoc =
1468 EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1469 // Add the special flag to GDM to signal retrying with no inlining.
1470 // Note, changing the state ensures that we are not going to cache out.
1471 ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1473 NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1475 // Make the new node a successor of BeforeProcessingCall.
1477 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1478 // We cached out at this point. Caching out is common due to us backtracking
1479 // from the inlined function, which might spawn several paths.
1483 NewNode->addPredecessor(BeforeProcessingCall, G);
1485 // Add the new node to the work list.
1486 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1487 CalleeSF->getIndex());
1488 NumTimesRetriedWithoutInlining++;
1492 /// Block entrance. (Update counters).
1493 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
1494 NodeBuilderWithSinks &nodeBuilder,
1495 ExplodedNode *Pred) {
1496 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1498 // If this block is terminated by a loop and it has already been visited the
1499 // maximum number of times, widen the loop.
1500 unsigned int BlockCount = nodeBuilder.getContext().blockCount();
1501 if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
1502 AMgr.options.shouldWidenLoops()) {
1503 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
1505 (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
1508 const LocationContext *LCtx = Pred->getLocationContext();
1509 ProgramStateRef WidenedState =
1510 getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
1511 nodeBuilder.generateNode(WidenedState, Pred);
1515 // FIXME: Refactor this into a checker.
1516 if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
1517 static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
1518 const ExplodedNode *Sink =
1519 nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1521 // Check if we stopped at the top level function or not.
1522 // Root node should have the location context of the top most function.
1523 const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1524 const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1525 const LocationContext *RootLC =
1526 (*G.roots_begin())->getLocation().getLocationContext();
1527 if (RootLC->getCurrentStackFrame() != CalleeSF) {
1528 Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1530 // Re-run the call evaluation without inlining it, by storing the
1531 // no-inlining policy in the state and enqueuing the new work item on
1532 // the list. Replay should almost never fail. Use the stats to catch it
1534 if ((!AMgr.options.NoRetryExhausted &&
1535 replayWithoutInlining(Pred, CalleeLC)))
1537 NumMaxBlockCountReachedInInlined++;
1539 NumMaxBlockCountReached++;
1541 // Make sink nodes as exhausted(for stats) only if retry failed.
1542 Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1546 //===----------------------------------------------------------------------===//
1547 // Branch processing.
1548 //===----------------------------------------------------------------------===//
1550 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1551 /// to try to recover some path-sensitivity for casts of symbolic
1552 /// integers that promote their values (which are currently not tracked well).
1553 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1554 // cast(s) did was sign-extend the original value.
1555 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
1556 ProgramStateRef state,
1557 const Stmt *Condition,
1558 const LocationContext *LCtx,
1561 const Expr *Ex = dyn_cast<Expr>(Condition);
1563 return UnknownVal();
1566 bool bitsInit = false;
1568 while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
1569 QualType T = CE->getType();
1571 if (!T->isIntegralOrEnumerationType())
1572 return UnknownVal();
1574 uint64_t newBits = Ctx.getTypeSize(T);
1575 if (!bitsInit || newBits < bits) {
1580 Ex = CE->getSubExpr();
1583 // We reached a non-cast. Is it a symbolic value?
1584 QualType T = Ex->getType();
1586 if (!bitsInit || !T->isIntegralOrEnumerationType() ||
1587 Ctx.getTypeSize(T) > bits)
1588 return UnknownVal();
1590 return state->getSVal(Ex, LCtx);
1594 static const Stmt *getRightmostLeaf(const Stmt *Condition) {
1596 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1597 if (!BO || !BO->isLogicalOp()) {
1600 Condition = BO->getRHS()->IgnoreParens();
1606 // Returns the condition the branch at the end of 'B' depends on and whose value
1607 // has been evaluated within 'B'.
1608 // In most cases, the terminator condition of 'B' will be evaluated fully in
1609 // the last statement of 'B'; in those cases, the resolved condition is the
1610 // given 'Condition'.
1611 // If the condition of the branch is a logical binary operator tree, the CFG is
1612 // optimized: in that case, we know that the expression formed by all but the
1613 // rightmost leaf of the logical binary operator tree must be true, and thus
1614 // the branch condition is at this point equivalent to the truth value of that
1615 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
1616 // expression in its final statement. As the full condition in that case was
1617 // not evaluated, and is thus not in the SVal cache, we need to use that leaf
1618 // expression to evaluate the truth value of the condition in the current state
1620 static const Stmt *ResolveCondition(const Stmt *Condition,
1621 const CFGBlock *B) {
1622 if (const Expr *Ex = dyn_cast<Expr>(Condition))
1623 Condition = Ex->IgnoreParens();
1625 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1626 if (!BO || !BO->isLogicalOp())
1629 assert(!B->getTerminator().isTemporaryDtorsBranch() &&
1630 "Temporary destructor branches handled by processBindTemporary.");
1632 // For logical operations, we still have the case where some branches
1633 // use the traditional "merge" approach and others sink the branch
1634 // directly into the basic blocks representing the logical operation.
1635 // We need to distinguish between those two cases here.
1637 // The invariants are still shifting, but it is possible that the
1638 // last element in a CFGBlock is not a CFGStmt. Look for the last
1639 // CFGStmt as the value of the condition.
1640 CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
1641 for (; I != E; ++I) {
1642 CFGElement Elem = *I;
1643 Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
1646 const Stmt *LastStmt = CS->getStmt();
1647 assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
1650 llvm_unreachable("could not resolve condition");
1653 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
1654 NodeBuilderContext& BldCtx,
1656 ExplodedNodeSet &Dst,
1657 const CFGBlock *DstT,
1658 const CFGBlock *DstF) {
1659 assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
1660 "CXXBindTemporaryExprs are handled by processBindTemporary.");
1661 const LocationContext *LCtx = Pred->getLocationContext();
1662 PrettyStackTraceLocationContext StackCrashInfo(LCtx);
1663 currBldrCtx = &BldCtx;
1665 // Check for NULL conditions; e.g. "for(;;)"
1667 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
1668 NullCondBldr.markInfeasible(false);
1669 NullCondBldr.generateNode(Pred->getState(), true, Pred);
1673 if (const Expr *Ex = dyn_cast<Expr>(Condition))
1674 Condition = Ex->IgnoreParens();
1676 Condition = ResolveCondition(Condition, BldCtx.getBlock());
1677 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1678 Condition->getLocStart(),
1679 "Error evaluating branch");
1681 ExplodedNodeSet CheckersOutSet;
1682 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
1684 // We generated only sinks.
1685 if (CheckersOutSet.empty())
1688 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
1689 for (NodeBuilder::iterator I = CheckersOutSet.begin(),
1690 E = CheckersOutSet.end(); E != I; ++I) {
1691 ExplodedNode *PredI = *I;
1693 if (PredI->isSink())
1696 ProgramStateRef PrevState = PredI->getState();
1697 SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
1699 if (X.isUnknownOrUndef()) {
1700 // Give it a chance to recover from unknown.
1701 if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
1702 if (Ex->getType()->isIntegralOrEnumerationType()) {
1703 // Try to recover some path-sensitivity. Right now casts of symbolic
1704 // integers that promote their values are currently not tracked well.
1705 // If 'Condition' is such an expression, try and recover the
1706 // underlying value and use that instead.
1707 SVal recovered = RecoverCastedSymbol(getStateManager(),
1708 PrevState, Condition,
1709 PredI->getLocationContext(),
1712 if (!recovered.isUnknown()) {
1719 // If the condition is still unknown, give up.
1720 if (X.isUnknownOrUndef()) {
1721 builder.generateNode(PrevState, true, PredI);
1722 builder.generateNode(PrevState, false, PredI);
1726 DefinedSVal V = X.castAs<DefinedSVal>();
1728 ProgramStateRef StTrue, StFalse;
1729 std::tie(StTrue, StFalse) = PrevState->assume(V);
1731 // Process the true branch.
1732 if (builder.isFeasible(true)) {
1734 builder.generateNode(StTrue, true, PredI);
1736 builder.markInfeasible(true);
1739 // Process the false branch.
1740 if (builder.isFeasible(false)) {
1742 builder.generateNode(StFalse, false, PredI);
1744 builder.markInfeasible(false);
1747 currBldrCtx = nullptr;
1750 /// The GDM component containing the set of global variables which have been
1751 /// previously initialized with explicit initializers.
1752 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
1753 llvm::ImmutableSet<const VarDecl *>)
1755 void ExprEngine::processStaticInitializer(const DeclStmt *DS,
1756 NodeBuilderContext &BuilderCtx,
1758 clang::ento::ExplodedNodeSet &Dst,
1759 const CFGBlock *DstT,
1760 const CFGBlock *DstF) {
1761 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1762 currBldrCtx = &BuilderCtx;
1764 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
1765 ProgramStateRef state = Pred->getState();
1766 bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
1767 BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
1770 state = state->add<InitializedGlobalsSet>(VD);
1773 builder.generateNode(state, initHasRun, Pred);
1774 builder.markInfeasible(!initHasRun);
1776 currBldrCtx = nullptr;
1779 /// processIndirectGoto - Called by CoreEngine. Used to generate successor
1780 /// nodes by processing the 'effects' of a computed goto jump.
1781 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
1783 ProgramStateRef state = builder.getState();
1784 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
1786 // Three possibilities:
1788 // (1) We know the computed label.
1789 // (2) The label is NULL (or some other constant), or Undefined.
1790 // (3) We have no clue about the label. Dispatch to all targets.
1793 typedef IndirectGotoNodeBuilder::iterator iterator;
1795 if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
1796 const LabelDecl *L = LV->getLabel();
1798 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
1799 if (I.getLabel() == L) {
1800 builder.generateNode(I, state);
1805 llvm_unreachable("No block with label.");
1808 if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
1809 // Dispatch to the first target and mark it as a sink.
1810 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
1811 // FIXME: add checker visit.
1812 // UndefBranches.insert(N);
1816 // This is really a catch-all. We don't support symbolics yet.
1817 // FIXME: Implement dispatch for symbolic pointers.
1819 for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
1820 builder.generateNode(I, state);
1824 static bool stackFrameDoesNotContainInitializedTemporaries(ExplodedNode &Pred) {
1825 const StackFrameContext* Frame = Pred.getStackFrame();
1826 const llvm::ImmutableSet<CXXBindTemporaryContext> &Set =
1827 Pred.getState()->get<InitializedTemporariesSet>();
1828 return std::find_if(Set.begin(), Set.end(),
1829 [&](const CXXBindTemporaryContext &Ctx) {
1830 if (Ctx.second == Frame) {
1832 llvm::errs() << "\n";
1834 return Ctx.second == Frame;
1839 void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC,
1841 ExplodedNodeSet &Dst,
1842 const BlockEdge &L) {
1843 SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
1844 getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
1847 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
1848 /// nodes when the control reaches the end of a function.
1849 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
1851 const ReturnStmt *RS) {
1852 // FIXME: Assert that stackFrameDoesNotContainInitializedTemporaries(*Pred)).
1853 // We currently cannot enable this assert, as lifetime extended temporaries
1854 // are not modelled correctly.
1855 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1856 StateMgr.EndPath(Pred->getState());
1858 ExplodedNodeSet Dst;
1859 if (Pred->getLocationContext()->inTopFrame()) {
1860 // Remove dead symbols.
1861 ExplodedNodeSet AfterRemovedDead;
1862 removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
1865 for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(),
1866 E = AfterRemovedDead.end(); I != E; ++I) {
1867 getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this);
1870 getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
1873 Engine.enqueueEndOfFunction(Dst, RS);
1876 /// ProcessSwitch - Called by CoreEngine. Used to generate successor
1877 /// nodes by processing the 'effects' of a switch statement.
1878 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
1879 typedef SwitchNodeBuilder::iterator iterator;
1880 ProgramStateRef state = builder.getState();
1881 const Expr *CondE = builder.getCondition();
1882 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
1884 if (CondV_untested.isUndef()) {
1885 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
1886 // FIXME: add checker
1887 //UndefBranches.insert(N);
1891 DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
1893 ProgramStateRef DefaultSt = state;
1895 iterator I = builder.begin(), EI = builder.end();
1896 bool defaultIsFeasible = I == EI;
1898 for ( ; I != EI; ++I) {
1899 // Successor may be pruned out during CFG construction.
1903 const CaseStmt *Case = I.getCase();
1905 // Evaluate the LHS of the case value.
1906 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
1907 assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType()));
1909 // Get the RHS of the case, if it exists.
1911 if (const Expr *E = Case->getRHS())
1912 V2 = E->EvaluateKnownConstInt(getContext());
1916 ProgramStateRef StateCase;
1917 if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
1918 std::tie(StateCase, DefaultSt) =
1919 DefaultSt->assumeInclusiveRange(*NL, V1, V2);
1921 StateCase = DefaultSt;
1924 builder.generateCaseStmtNode(I, StateCase);
1926 // Now "assume" that the case doesn't match. Add this state
1927 // to the default state (if it is feasible).
1929 defaultIsFeasible = true;
1931 defaultIsFeasible = false;
1936 if (!defaultIsFeasible)
1939 // If we have switch(enum value), the default branch is not
1940 // feasible if all of the enum constants not covered by 'case:' statements
1941 // are not feasible values for the switch condition.
1943 // Note that this isn't as accurate as it could be. Even if there isn't
1944 // a case for a particular enum value as long as that enum value isn't
1945 // feasible then it shouldn't be considered for making 'default:' reachable.
1946 const SwitchStmt *SS = builder.getSwitch();
1947 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
1948 if (CondExpr->getType()->getAs<EnumType>()) {
1949 if (SS->isAllEnumCasesCovered())
1953 builder.generateDefaultCaseNode(DefaultSt);
1956 //===----------------------------------------------------------------------===//
1957 // Transfer functions: Loads and stores.
1958 //===----------------------------------------------------------------------===//
1960 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
1962 ExplodedNodeSet &Dst) {
1963 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1965 ProgramStateRef state = Pred->getState();
1966 const LocationContext *LCtx = Pred->getLocationContext();
1968 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1969 // C permits "extern void v", and if you cast the address to a valid type,
1970 // you can even do things with it. We simply pretend
1971 assert(Ex->isGLValue() || VD->getType()->isVoidType());
1972 const LocationContext *LocCtxt = Pred->getLocationContext();
1973 const Decl *D = LocCtxt->getDecl();
1974 const auto *MD = D ? dyn_cast<CXXMethodDecl>(D) : nullptr;
1975 const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
1978 if (AMgr.options.shouldInlineLambdas() && DeclRefEx &&
1979 DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
1980 MD->getParent()->isLambda()) {
1981 // Lookup the field of the lambda.
1982 const CXXRecordDecl *CXXRec = MD->getParent();
1983 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
1984 FieldDecl *LambdaThisCaptureField;
1985 CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
1986 const FieldDecl *FD = LambdaCaptureFields[VD];
1988 // When a constant is captured, sometimes no corresponding field is
1989 // created in the lambda object.
1990 assert(VD->getType().isConstQualified());
1991 V = state->getLValue(VD, LocCtxt);
1992 IsReference = false;
1995 svalBuilder.getCXXThis(MD, LocCtxt->getCurrentStackFrame());
1996 SVal CXXThisVal = state->getSVal(CXXThis);
1997 V = state->getLValue(FD, CXXThisVal);
1998 IsReference = FD->getType()->isReferenceType();
2001 V = state->getLValue(VD, LocCtxt);
2002 IsReference = VD->getType()->isReferenceType();
2005 // For references, the 'lvalue' is the pointer address stored in the
2006 // reference region.
2008 if (const MemRegion *R = V.getAsRegion())
2009 V = state->getSVal(R);
2014 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2015 ProgramPoint::PostLValueKind);
2018 if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
2019 assert(!Ex->isGLValue());
2020 SVal V = svalBuilder.makeIntVal(ED->getInitVal());
2021 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
2024 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2025 SVal V = svalBuilder.getFunctionPointer(FD);
2026 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2027 ProgramPoint::PostLValueKind);
2030 if (isa<FieldDecl>(D)) {
2031 // FIXME: Compute lvalue of field pointers-to-member.
2032 // Right now we just use a non-null void pointer, so that it gives proper
2033 // results in boolean contexts.
2034 SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
2035 currBldrCtx->blockCount());
2036 state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
2037 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2038 ProgramPoint::PostLValueKind);
2042 llvm_unreachable("Support for this Decl not implemented.");
2045 /// VisitArraySubscriptExpr - Transfer function for array accesses
2046 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A,
2048 ExplodedNodeSet &Dst){
2050 const Expr *Base = A->getBase()->IgnoreParens();
2051 const Expr *Idx = A->getIdx()->IgnoreParens();
2053 ExplodedNodeSet CheckerPreStmt;
2054 getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this);
2056 ExplodedNodeSet EvalSet;
2057 StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx);
2058 assert(A->isGLValue() ||
2059 (!AMgr.getLangOpts().CPlusPlus &&
2060 A->getType().isCForbiddenLValueType()));
2062 for (auto *Node : CheckerPreStmt) {
2063 const LocationContext *LCtx = Node->getLocationContext();
2064 ProgramStateRef state = Node->getState();
2065 SVal V = state->getLValue(A->getType(),
2066 state->getSVal(Idx, LCtx),
2067 state->getSVal(Base, LCtx));
2068 Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr,
2069 ProgramPoint::PostLValueKind);
2072 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
2075 /// VisitMemberExpr - Transfer function for member expressions.
2076 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
2077 ExplodedNodeSet &Dst) {
2079 // FIXME: Prechecks eventually go in ::Visit().
2080 ExplodedNodeSet CheckedSet;
2081 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
2083 ExplodedNodeSet EvalSet;
2084 ValueDecl *Member = M->getMemberDecl();
2086 // Handle static member variables and enum constants accessed via
2088 if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
2089 ExplodedNodeSet Dst;
2090 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2092 VisitCommonDeclRefExpr(M, Member, Pred, EvalSet);
2095 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
2096 ExplodedNodeSet Tmp;
2098 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2100 ProgramStateRef state = (*I)->getState();
2101 const LocationContext *LCtx = (*I)->getLocationContext();
2102 Expr *BaseExpr = M->getBase();
2104 // Handle C++ method calls.
2105 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
2106 if (MD->isInstance())
2107 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2109 SVal MDVal = svalBuilder.getFunctionPointer(MD);
2110 state = state->BindExpr(M, LCtx, MDVal);
2112 Bldr.generateNode(M, *I, state);
2116 // Handle regular struct fields / member variables.
2117 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2118 SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
2120 FieldDecl *field = cast<FieldDecl>(Member);
2121 SVal L = state->getLValue(field, baseExprVal);
2123 if (M->isGLValue() || M->getType()->isArrayType()) {
2124 // We special-case rvalues of array type because the analyzer cannot
2125 // reason about them, since we expect all regions to be wrapped in Locs.
2126 // We instead treat these as lvalues and assume that they will decay to
2127 // pointers as soon as they are used.
2128 if (!M->isGLValue()) {
2129 assert(M->getType()->isArrayType());
2130 const ImplicitCastExpr *PE =
2131 dyn_cast<ImplicitCastExpr>((*I)->getParentMap().getParentIgnoreParens(M));
2132 if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
2133 llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
2137 if (field->getType()->isReferenceType()) {
2138 if (const MemRegion *R = L.getAsRegion())
2139 L = state->getSVal(R);
2144 Bldr.generateNode(M, *I, state->BindExpr(M, LCtx, L), nullptr,
2145 ProgramPoint::PostLValueKind);
2148 evalLoad(Tmp, M, M, *I, state, L);
2154 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
2157 void ExprEngine::VisitAtomicExpr(const AtomicExpr *AE, ExplodedNode *Pred,
2158 ExplodedNodeSet &Dst) {
2159 ExplodedNodeSet AfterPreSet;
2160 getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this);
2162 // For now, treat all the arguments to C11 atomics as escaping.
2163 // FIXME: Ideally we should model the behavior of the atomics precisely here.
2165 ExplodedNodeSet AfterInvalidateSet;
2166 StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx);
2168 for (ExplodedNodeSet::iterator I = AfterPreSet.begin(), E = AfterPreSet.end();
2170 ProgramStateRef State = (*I)->getState();
2171 const LocationContext *LCtx = (*I)->getLocationContext();
2173 SmallVector<SVal, 8> ValuesToInvalidate;
2174 for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) {
2175 const Expr *SubExpr = AE->getSubExprs()[SI];
2176 SVal SubExprVal = State->getSVal(SubExpr, LCtx);
2177 ValuesToInvalidate.push_back(SubExprVal);
2180 State = State->invalidateRegions(ValuesToInvalidate, AE,
2181 currBldrCtx->blockCount(),
2183 /*CausedByPointerEscape*/true,
2184 /*Symbols=*/nullptr);
2186 SVal ResultVal = UnknownVal();
2187 State = State->BindExpr(AE, LCtx, ResultVal);
2188 Bldr.generateNode(AE, *I, State, nullptr,
2189 ProgramPoint::PostStmtKind);
2192 getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this);
2196 class CollectReachableSymbolsCallback final : public SymbolVisitor {
2197 InvalidatedSymbols Symbols;
2200 CollectReachableSymbolsCallback(ProgramStateRef State) {}
2201 const InvalidatedSymbols &getSymbols() const { return Symbols; }
2203 bool VisitSymbol(SymbolRef Sym) override {
2204 Symbols.insert(Sym);
2208 } // end anonymous namespace
2210 // A value escapes in three possible cases:
2211 // (1) We are binding to something that is not a memory region.
2212 // (2) We are binding to a MemrRegion that does not have stack storage.
2213 // (3) We are binding to a MemRegion with stack storage that the store
2214 // does not understand.
2215 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
2218 const LocationContext *LCtx) {
2219 // Are we storing to something that causes the value to "escape"?
2220 bool escapes = true;
2222 // TODO: Move to StoreManager.
2223 if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
2224 escapes = !regionLoc->getRegion()->hasStackStorage();
2227 // To test (3), generate a new state with the binding added. If it is
2228 // the same state, then it escapes (since the store cannot represent
2230 // Do this only if we know that the store is not supposed to generate the
2232 SVal StoredVal = State->getSVal(regionLoc->getRegion());
2233 if (StoredVal != Val)
2234 escapes = (State == (State->bindLoc(*regionLoc, Val, LCtx)));
2238 // If our store can represent the binding and we aren't storing to something
2239 // that doesn't have local storage then just return and have the simulation
2240 // state continue as is.
2244 // Otherwise, find all symbols referenced by 'val' that we are tracking
2245 // and stop tracking them.
2246 CollectReachableSymbolsCallback Scanner =
2247 State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val);
2248 const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
2249 State = getCheckerManager().runCheckersForPointerEscape(State,
2251 /*CallEvent*/ nullptr,
2259 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
2260 const InvalidatedSymbols *Invalidated,
2261 ArrayRef<const MemRegion *> ExplicitRegions,
2262 ArrayRef<const MemRegion *> Regions,
2263 const CallEvent *Call,
2264 RegionAndSymbolInvalidationTraits &ITraits) {
2266 if (!Invalidated || Invalidated->empty())
2270 return getCheckerManager().runCheckersForPointerEscape(State,
2276 // If the symbols were invalidated by a call, we want to find out which ones
2277 // were invalidated directly due to being arguments to the call.
2278 InvalidatedSymbols SymbolsDirectlyInvalidated;
2279 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
2280 E = ExplicitRegions.end(); I != E; ++I) {
2281 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
2282 SymbolsDirectlyInvalidated.insert(R->getSymbol());
2285 InvalidatedSymbols SymbolsIndirectlyInvalidated;
2286 for (InvalidatedSymbols::const_iterator I=Invalidated->begin(),
2287 E = Invalidated->end(); I!=E; ++I) {
2289 if (SymbolsDirectlyInvalidated.count(sym))
2291 SymbolsIndirectlyInvalidated.insert(sym);
2294 if (!SymbolsDirectlyInvalidated.empty())
2295 State = getCheckerManager().runCheckersForPointerEscape(State,
2296 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
2298 // Notify about the symbols that get indirectly invalidated by the call.
2299 if (!SymbolsIndirectlyInvalidated.empty())
2300 State = getCheckerManager().runCheckersForPointerEscape(State,
2301 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
2306 /// evalBind - Handle the semantics of binding a value to a specific location.
2307 /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
2308 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
2310 SVal location, SVal Val,
2311 bool atDeclInit, const ProgramPoint *PP) {
2313 const LocationContext *LC = Pred->getLocationContext();
2314 PostStmt PS(StoreE, LC);
2318 // Do a previsit of the bind.
2319 ExplodedNodeSet CheckedSet;
2320 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
2321 StoreE, *this, *PP);
2323 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
2325 // If the location is not a 'Loc', it will already be handled by
2326 // the checkers. There is nothing left to do.
2327 if (!location.getAs<Loc>()) {
2328 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
2330 ProgramStateRef state = Pred->getState();
2331 state = processPointerEscapedOnBind(state, location, Val, LC);
2332 Bldr.generateNode(L, state, Pred);
2336 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2338 ExplodedNode *PredI = *I;
2339 ProgramStateRef state = PredI->getState();
2341 state = processPointerEscapedOnBind(state, location, Val, LC);
2343 // When binding the value, pass on the hint that this is a initialization.
2344 // For initializations, we do not need to inform clients of region
2346 state = state->bindLoc(location.castAs<Loc>(),
2347 Val, LC, /* notifyChanges = */ !atDeclInit);
2349 const MemRegion *LocReg = nullptr;
2350 if (Optional<loc::MemRegionVal> LocRegVal =
2351 location.getAs<loc::MemRegionVal>()) {
2352 LocReg = LocRegVal->getRegion();
2355 const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
2356 Bldr.generateNode(L, state, PredI);
2360 /// evalStore - Handle the semantics of a store via an assignment.
2361 /// @param Dst The node set to store generated state nodes
2362 /// @param AssignE The assignment expression if the store happens in an
2364 /// @param LocationE The location expression that is stored to.
2365 /// @param state The current simulation state
2366 /// @param location The location to store the value
2367 /// @param Val The value to be stored
2368 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
2369 const Expr *LocationE,
2371 ProgramStateRef state, SVal location, SVal Val,
2372 const ProgramPointTag *tag) {
2373 // Proceed with the store. We use AssignE as the anchor for the PostStore
2374 // ProgramPoint if it is non-NULL, and LocationE otherwise.
2375 const Expr *StoreE = AssignE ? AssignE : LocationE;
2377 // Evaluate the location (checks for bad dereferences).
2378 ExplodedNodeSet Tmp;
2379 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
2384 if (location.isUndef())
2387 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
2388 evalBind(Dst, StoreE, *NI, location, Val, false);
2391 void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
2393 const Expr *BoundEx,
2395 ProgramStateRef state,
2397 const ProgramPointTag *tag,
2400 assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2402 // Are we loading from a region? This actually results in two loads; one
2403 // to fetch the address of the referenced value and one to fetch the
2404 // referenced value.
2405 if (const TypedValueRegion *TR =
2406 dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
2408 QualType ValTy = TR->getValueType();
2409 if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
2410 static SimpleProgramPointTag
2411 loadReferenceTag(TagProviderName, "Load Reference");
2412 ExplodedNodeSet Tmp;
2413 evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
2414 location, &loadReferenceTag,
2415 getContext().getPointerType(RT->getPointeeType()));
2417 // Perform the load from the referenced value.
2418 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
2419 state = (*I)->getState();
2420 location = state->getSVal(BoundEx, (*I)->getLocationContext());
2421 evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
2427 evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
2430 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
2432 const Expr *BoundEx,
2434 ProgramStateRef state,
2436 const ProgramPointTag *tag,
2440 // Evaluate the location (checks for bad dereferences).
2441 ExplodedNodeSet Tmp;
2442 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
2446 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2447 if (location.isUndef())
2450 // Proceed with the load.
2451 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
2452 state = (*NI)->getState();
2453 const LocationContext *LCtx = (*NI)->getLocationContext();
2455 SVal V = UnknownVal();
2456 if (location.isValid()) {
2457 if (LoadTy.isNull())
2458 LoadTy = BoundEx->getType();
2459 V = state->getSVal(location.castAs<Loc>(), LoadTy);
2462 Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
2463 ProgramPoint::PostLoadKind);
2467 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2469 const Stmt *BoundEx,
2471 ProgramStateRef state,
2473 const ProgramPointTag *tag,
2475 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2476 // Early checks for performance reason.
2477 if (location.isUnknown()) {
2481 ExplodedNodeSet Src;
2482 BldrTop.takeNodes(Pred);
2483 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2484 if (Pred->getState() != state) {
2485 // Associate this new state with an ExplodedNode.
2486 // FIXME: If I pass null tag, the graph is incorrect, e.g for
2490 // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2491 // instead "int *p" is noted as
2492 // "Variable 'p' initialized to a null pointer value"
2494 static SimpleProgramPointTag tag(TagProviderName, "Location");
2495 Bldr.generateNode(NodeEx, Pred, state, &tag);
2497 ExplodedNodeSet Tmp;
2498 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2499 NodeEx, BoundEx, *this);
2500 BldrTop.addNodes(Tmp);
2503 std::pair<const ProgramPointTag *, const ProgramPointTag*>
2504 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
2505 static SimpleProgramPointTag
2506 eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
2507 "Eagerly Assume True"),
2508 eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
2509 "Eagerly Assume False");
2510 return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2511 &eagerlyAssumeBinOpBifurcationFalse);
2514 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
2515 ExplodedNodeSet &Src,
2517 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2519 for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
2520 ExplodedNode *Pred = *I;
2521 // Test if the previous node was as the same expression. This can happen
2522 // when the expression fails to evaluate to anything meaningful and
2523 // (as an optimization) we don't generate a node.
2524 ProgramPoint P = Pred->getLocation();
2525 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2529 ProgramStateRef state = Pred->getState();
2530 SVal V = state->getSVal(Ex, Pred->getLocationContext());
2531 Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
2532 if (SEV && SEV->isExpression()) {
2533 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2534 geteagerlyAssumeBinOpBifurcationTags();
2536 ProgramStateRef StateTrue, StateFalse;
2537 std::tie(StateTrue, StateFalse) = state->assume(*SEV);
2539 // First assume that the condition is true.
2541 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2542 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2543 Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2546 // Next, assume that the condition is false.
2548 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2549 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2550 Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2556 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
2557 ExplodedNodeSet &Dst) {
2558 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2559 // We have processed both the inputs and the outputs. All of the outputs
2560 // should evaluate to Locs. Nuke all of their values.
2562 // FIXME: Some day in the future it would be nice to allow a "plug-in"
2563 // which interprets the inline asm and stores proper results in the
2566 ProgramStateRef state = Pred->getState();
2568 for (const Expr *O : A->outputs()) {
2569 SVal X = state->getSVal(O, Pred->getLocationContext());
2570 assert (!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
2572 if (Optional<Loc> LV = X.getAs<Loc>())
2573 state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext());
2576 Bldr.generateNode(A, Pred, state);
2579 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
2580 ExplodedNodeSet &Dst) {
2581 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2582 Bldr.generateNode(A, Pred, Pred->getState());
2585 //===----------------------------------------------------------------------===//
2587 //===----------------------------------------------------------------------===//
2590 static ExprEngine* GraphPrintCheckerState;
2591 static SourceManager* GraphPrintSourceManager;
2595 struct DOTGraphTraits<ExplodedNode*> :
2596 public DefaultDOTGraphTraits {
2598 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2600 // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
2602 static std::string getNodeAttributes(const ExplodedNode *N, void*) {
2606 // De-duplicate some source location pretty-printing.
2607 static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
2608 if (SLoc.isFileID()) {
2610 << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2612 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
2616 static void printLocation2(raw_ostream &Out, SourceLocation SLoc) {
2617 if (SLoc.isFileID() && GraphPrintSourceManager->isInMainFile(SLoc))
2618 Out << "line " << GraphPrintSourceManager->getExpansionLineNumber(SLoc);
2620 SLoc.print(Out, *GraphPrintSourceManager);
2623 static std::string getNodeLabel(const ExplodedNode *N, void*){
2626 llvm::raw_string_ostream Out(sbuf);
2628 // Program Location.
2629 ProgramPoint Loc = N->getLocation();
2631 switch (Loc.getKind()) {
2632 case ProgramPoint::BlockEntranceKind: {
2633 Out << "Block Entrance: B"
2634 << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
2638 case ProgramPoint::BlockExitKind:
2642 case ProgramPoint::CallEnterKind:
2646 case ProgramPoint::CallExitBeginKind:
2647 Out << "CallExitBegin";
2650 case ProgramPoint::CallExitEndKind:
2651 Out << "CallExitEnd";
2654 case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
2655 Out << "PostStmtPurgeDeadSymbols";
2658 case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
2659 Out << "PreStmtPurgeDeadSymbols";
2662 case ProgramPoint::EpsilonKind:
2663 Out << "Epsilon Point";
2666 case ProgramPoint::PreImplicitCallKind: {
2667 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2670 // FIXME: Get proper printing options.
2671 PC.getDecl()->print(Out, LangOptions());
2672 printLocation(Out, PC.getLocation());
2676 case ProgramPoint::PostImplicitCallKind: {
2677 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
2678 Out << "PostCall: ";
2680 // FIXME: Get proper printing options.
2681 PC.getDecl()->print(Out, LangOptions());
2682 printLocation(Out, PC.getLocation());
2686 case ProgramPoint::PostInitializerKind: {
2687 Out << "PostInitializer: ";
2688 const CXXCtorInitializer *Init =
2689 Loc.castAs<PostInitializer>().getInitializer();
2690 if (const FieldDecl *FD = Init->getAnyMember())
2693 QualType Ty = Init->getTypeSourceInfo()->getType();
2694 Ty = Ty.getLocalUnqualifiedType();
2695 LangOptions LO; // FIXME.
2701 case ProgramPoint::BlockEdgeKind: {
2702 const BlockEdge &E = Loc.castAs<BlockEdge>();
2703 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
2704 << E.getDst()->getBlockID() << ')';
2706 if (const Stmt *T = E.getSrc()->getTerminator()) {
2707 SourceLocation SLoc = T->getLocStart();
2709 Out << "\\|Terminator: ";
2710 LangOptions LO; // FIXME.
2711 E.getSrc()->printTerminator(Out, LO);
2713 if (SLoc.isFileID()) {
2715 << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2717 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
2720 if (isa<SwitchStmt>(T)) {
2721 const Stmt *Label = E.getDst()->getLabel();
2724 if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
2726 LangOptions LO; // FIXME.
2728 C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO));
2730 if (const Stmt *RHS = C->getRHS()) {
2732 RHS->printPretty(Out, nullptr, PrintingPolicy(LO));
2738 assert (isa<DefaultStmt>(Label));
2739 Out << "\\ldefault:";
2743 Out << "\\l(implicit) default:";
2745 else if (isa<IndirectGotoStmt>(T)) {
2749 Out << "\\lCondition: ";
2750 if (*E.getSrc()->succ_begin() == E.getDst())
2763 const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
2764 assert(S != nullptr && "Expecting non-null Stmt");
2766 Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
2767 LangOptions LO; // FIXME.
2768 S->printPretty(Out, nullptr, PrintingPolicy(LO));
2769 printLocation(Out, S->getLocStart());
2771 if (Loc.getAs<PreStmt>())
2772 Out << "\\lPreStmt\\l;";
2773 else if (Loc.getAs<PostLoad>())
2774 Out << "\\lPostLoad\\l;";
2775 else if (Loc.getAs<PostStore>())
2776 Out << "\\lPostStore\\l";
2777 else if (Loc.getAs<PostLValue>())
2778 Out << "\\lPostLValue\\l";
2784 ProgramStateRef state = N->getState();
2785 Out << "\\|StateID: " << (const void*) state.get()
2786 << " NodeID: " << (const void*) N << "\\|";
2788 // Analysis stack backtrace.
2789 Out << "Location context stack (from current to outer):\\l";
2790 const LocationContext *LC = Loc.getLocationContext();
2792 for (; LC; LC = LC->getParent(), ++Idx) {
2793 Out << Idx << ". (" << (const void *)LC << ") ";
2794 switch (LC->getKind()) {
2795 case LocationContext::StackFrame:
2796 if (const NamedDecl *D = dyn_cast<NamedDecl>(LC->getDecl()))
2797 Out << "Calling " << D->getQualifiedNameAsString();
2799 Out << "Calling anonymous code";
2800 if (const Stmt *S = cast<StackFrameContext>(LC)->getCallSite()) {
2802 printLocation2(Out, S->getLocStart());
2805 case LocationContext::Block:
2806 Out << "Invoking block";
2807 if (const Decl *D = cast<BlockInvocationContext>(LC)->getBlockDecl()) {
2808 Out << " defined at ";
2809 printLocation2(Out, D->getLocStart());
2812 case LocationContext::Scope:
2813 Out << "Entering scope";
2814 // FIXME: Add more info once ScopeContext is activated.
2821 state->printDOT(Out);
2825 if (const ProgramPointTag *tag = Loc.getTag()) {
2826 Out << "\\|Tag: " << tag->getTagDescription();
2832 } // end llvm namespace
2835 void ExprEngine::ViewGraph(bool trim) {
2838 std::vector<const ExplodedNode*> Src;
2840 // Flush any outstanding reports to make sure we cover all the nodes.
2841 // This does not cause them to get displayed.
2842 for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
2843 const_cast<BugType*>(*I)->FlushReports(BR);
2845 // Iterate through the reports and get their nodes.
2846 for (BugReporter::EQClasses_iterator
2847 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
2848 ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
2849 if (N) Src.push_back(N);
2855 GraphPrintCheckerState = this;
2856 GraphPrintSourceManager = &getContext().getSourceManager();
2858 llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
2860 GraphPrintCheckerState = nullptr;
2861 GraphPrintSourceManager = nullptr;
2866 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
2868 GraphPrintCheckerState = this;
2869 GraphPrintSourceManager = &getContext().getSourceManager();
2871 std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
2873 if (!TrimmedG.get())
2874 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
2876 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
2878 GraphPrintCheckerState = nullptr;
2879 GraphPrintSourceManager = nullptr;