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