1//= ProgramState.cpp - Path-Sensitive "State" for tracking values --*- C++ -*--=
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements ProgramState and ProgramStateManager.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
14#include "clang/Analysis/CFG.h"
15#include "clang/Basic/JsonSupport.h"
16#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
17#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
20#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
21#include "llvm/Support/raw_ostream.h"
22#include <optional>
23
24using namespace clang;
25using namespace ento;
26
27namespace clang { namespace ento {
28/// Increments the number of times this state is referenced.
29
30void ProgramStateRetain(const ProgramState *state) {
31 ++const_cast<ProgramState*>(state)->refCount;
32}
33
34/// Decrement the number of times this state is referenced.
35void ProgramStateRelease(const ProgramState *state) {
36 assert(state->refCount > 0);
37 ProgramState *s = const_cast<ProgramState*>(state);
38 if (--s->refCount == 0) {
39 ProgramStateManager &Mgr = s->getStateManager();
40 Mgr.StateSet.RemoveNode(N: s);
41 s->~ProgramState();
42 Mgr.freeStates.push_back(x: s);
43 }
44}
45}}
46
47ProgramState::ProgramState(ProgramStateManager *mgr, const Environment& env,
48 StoreRef st, GenericDataMap gdm)
49 : stateMgr(mgr),
50 Env(env),
51 store(st.getStore()),
52 GDM(gdm),
53 refCount(0) {
54 stateMgr->getStoreManager().incrementReferenceCount(store);
55}
56
57ProgramState::ProgramState(const ProgramState &RHS)
58 : stateMgr(RHS.stateMgr), Env(RHS.Env), store(RHS.store), GDM(RHS.GDM),
59 PosteriorlyOverconstrained(RHS.PosteriorlyOverconstrained), refCount(0) {
60 stateMgr->getStoreManager().incrementReferenceCount(store);
61}
62
63ProgramState::~ProgramState() {
64 if (store)
65 stateMgr->getStoreManager().decrementReferenceCount(store);
66}
67
68int64_t ProgramState::getID() const {
69 return getStateManager().Alloc.identifyKnownAlignedObject<ProgramState>(Ptr: this);
70}
71
72ProgramStateManager::ProgramStateManager(ASTContext &Ctx,
73 StoreManagerCreator CreateSMgr,
74 ConstraintManagerCreator CreateCMgr,
75 llvm::BumpPtrAllocator &alloc,
76 ExprEngine *ExprEng)
77 : Eng(ExprEng), EnvMgr(alloc), GDMFactory(alloc),
78 svalBuilder(createSimpleSValBuilder(alloc, context&: Ctx, stateMgr&: *this)),
79 CallEventMgr(new CallEventManager(alloc)), Alloc(alloc) {
80 StoreMgr = (*CreateSMgr)(*this);
81 ConstraintMgr = (*CreateCMgr)(*this, ExprEng);
82}
83
84
85ProgramStateManager::~ProgramStateManager() {
86 for (GDMContextsTy::iterator I=GDMContexts.begin(), E=GDMContexts.end();
87 I!=E; ++I)
88 I->second.second(I->second.first);
89}
90
91ProgramStateRef ProgramStateManager::removeDeadBindingsFromEnvironmentAndStore(
92 ProgramStateRef state, const StackFrameContext *LCtx,
93 SymbolReaper &SymReaper) {
94
95 // This code essentially performs a "mark-and-sweep" of the VariableBindings.
96 // The roots are any Block-level exprs and Decls that our liveness algorithm
97 // tells us are live. We then see what Decls they may reference, and keep
98 // those around. This code more than likely can be made faster, and the
99 // frequency of which this method is called should be experimented with
100 // for optimum performance.
101 ProgramState NewState = *state;
102
103 NewState.Env = EnvMgr.removeDeadBindings(Env: NewState.Env, SymReaper, state);
104
105 // Clean up the store.
106 StoreRef newStore = StoreMgr->removeDeadBindings(store: NewState.getStore(), LCtx,
107 SymReaper);
108 NewState.setStore(newStore);
109 SymReaper.setReapedStore(newStore);
110
111 return getPersistentState(Impl&: NewState);
112}
113
114ProgramStateRef ProgramState::bindLoc(Loc LV,
115 SVal V,
116 const LocationContext *LCtx,
117 bool notifyChanges) const {
118 ProgramStateManager &Mgr = getStateManager();
119 ProgramStateRef newState = makeWithStore(store: Mgr.StoreMgr->Bind(store: getStore(),
120 loc: LV, val: V));
121 const MemRegion *MR = LV.getAsRegion();
122 if (MR && notifyChanges)
123 return Mgr.getOwningEngine().processRegionChange(state: newState, MR, LCtx);
124
125 return newState;
126}
127
128ProgramStateRef
129ProgramState::bindDefaultInitial(SVal loc, SVal V,
130 const LocationContext *LCtx) const {
131 ProgramStateManager &Mgr = getStateManager();
132 const MemRegion *R = loc.castAs<loc::MemRegionVal>().getRegion();
133 const StoreRef &newStore = Mgr.StoreMgr->BindDefaultInitial(store: getStore(), R, V);
134 ProgramStateRef new_state = makeWithStore(store: newStore);
135 return Mgr.getOwningEngine().processRegionChange(state: new_state, MR: R, LCtx);
136}
137
138ProgramStateRef
139ProgramState::bindDefaultZero(SVal loc, const LocationContext *LCtx) const {
140 ProgramStateManager &Mgr = getStateManager();
141 const MemRegion *R = loc.castAs<loc::MemRegionVal>().getRegion();
142 const StoreRef &newStore = Mgr.StoreMgr->BindDefaultZero(store: getStore(), R);
143 ProgramStateRef new_state = makeWithStore(store: newStore);
144 return Mgr.getOwningEngine().processRegionChange(state: new_state, MR: R, LCtx);
145}
146
147typedef ArrayRef<const MemRegion *> RegionList;
148typedef ArrayRef<SVal> ValueList;
149
150ProgramStateRef
151ProgramState::invalidateRegions(RegionList Regions,
152 const Expr *E, unsigned Count,
153 const LocationContext *LCtx,
154 bool CausedByPointerEscape,
155 InvalidatedSymbols *IS,
156 const CallEvent *Call,
157 RegionAndSymbolInvalidationTraits *ITraits) const {
158 SmallVector<SVal, 8> Values;
159 for (const MemRegion *Reg : Regions)
160 Values.push_back(Elt: loc::MemRegionVal(Reg));
161
162 return invalidateRegionsImpl(Values, E, BlockCount: Count, LCtx, ResultsInSymbolEscape: CausedByPointerEscape,
163 IS, HTraits: ITraits, Call);
164}
165
166ProgramStateRef
167ProgramState::invalidateRegions(ValueList Values,
168 const Expr *E, unsigned Count,
169 const LocationContext *LCtx,
170 bool CausedByPointerEscape,
171 InvalidatedSymbols *IS,
172 const CallEvent *Call,
173 RegionAndSymbolInvalidationTraits *ITraits) const {
174
175 return invalidateRegionsImpl(Values, E, BlockCount: Count, LCtx, ResultsInSymbolEscape: CausedByPointerEscape,
176 IS, HTraits: ITraits, Call);
177}
178
179ProgramStateRef
180ProgramState::invalidateRegionsImpl(ValueList Values,
181 const Expr *E, unsigned Count,
182 const LocationContext *LCtx,
183 bool CausedByPointerEscape,
184 InvalidatedSymbols *IS,
185 RegionAndSymbolInvalidationTraits *ITraits,
186 const CallEvent *Call) const {
187 ProgramStateManager &Mgr = getStateManager();
188 ExprEngine &Eng = Mgr.getOwningEngine();
189
190 InvalidatedSymbols InvalidatedSyms;
191 if (!IS)
192 IS = &InvalidatedSyms;
193
194 RegionAndSymbolInvalidationTraits ITraitsLocal;
195 if (!ITraits)
196 ITraits = &ITraitsLocal;
197
198 StoreManager::InvalidatedRegions TopLevelInvalidated;
199 StoreManager::InvalidatedRegions Invalidated;
200 const StoreRef &newStore
201 = Mgr.StoreMgr->invalidateRegions(store: getStore(), Values, Ex: E, Count, LCtx, Call,
202 IS&: *IS, ITraits&: *ITraits, TopLevelRegions: &TopLevelInvalidated,
203 Invalidated: &Invalidated);
204
205 ProgramStateRef newState = makeWithStore(store: newStore);
206
207 if (CausedByPointerEscape) {
208 newState = Eng.notifyCheckersOfPointerEscape(State: newState, Invalidated: IS,
209 ExplicitRegions: TopLevelInvalidated,
210 Call,
211 ITraits&: *ITraits);
212 }
213
214 return Eng.processRegionChanges(state: newState, invalidated: IS, ExplicitRegions: TopLevelInvalidated,
215 Regions: Invalidated, LCtx, Call);
216}
217
218ProgramStateRef ProgramState::killBinding(Loc LV) const {
219 Store OldStore = getStore();
220 const StoreRef &newStore =
221 getStateManager().StoreMgr->killBinding(ST: OldStore, L: LV);
222
223 if (newStore.getStore() == OldStore)
224 return this;
225
226 return makeWithStore(store: newStore);
227}
228
229/// SymbolicRegions are expected to be wrapped by an ElementRegion as a
230/// canonical representation. As a canonical representation, SymbolicRegions
231/// should be wrapped by ElementRegions before getting a FieldRegion.
232/// See f8643a9b31c4029942f67d4534c9139b45173504 why.
233SVal ProgramState::wrapSymbolicRegion(SVal Val) const {
234 const auto *BaseReg = dyn_cast_or_null<SymbolicRegion>(Val: Val.getAsRegion());
235 if (!BaseReg)
236 return Val;
237
238 StoreManager &SM = getStateManager().getStoreManager();
239 QualType ElemTy = BaseReg->getPointeeStaticType();
240 return loc::MemRegionVal{SM.GetElementZeroRegion(R: BaseReg, T: ElemTy)};
241}
242
243ProgramStateRef
244ProgramState::enterStackFrame(const CallEvent &Call,
245 const StackFrameContext *CalleeCtx) const {
246 const StoreRef &NewStore =
247 getStateManager().StoreMgr->enterStackFrame(store: getStore(), Call, CalleeCtx);
248 return makeWithStore(store: NewStore);
249}
250
251SVal ProgramState::getSelfSVal(const LocationContext *LCtx) const {
252 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
253 if (!SelfDecl)
254 return SVal();
255 return getSVal(R: getRegion(D: SelfDecl, LC: LCtx));
256}
257
258SVal ProgramState::getSValAsScalarOrLoc(const MemRegion *R) const {
259 // We only want to do fetches from regions that we can actually bind
260 // values. For example, SymbolicRegions of type 'id<...>' cannot
261 // have direct bindings (but their can be bindings on their subregions).
262 if (!R->isBoundable())
263 return UnknownVal();
264
265 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(Val: R)) {
266 QualType T = TR->getValueType();
267 if (Loc::isLocType(T) || T->isIntegralOrEnumerationType())
268 return getSVal(R);
269 }
270
271 return UnknownVal();
272}
273
274SVal ProgramState::getSVal(Loc location, QualType T) const {
275 SVal V = getRawSVal(LV: location, T);
276
277 // If 'V' is a symbolic value that is *perfectly* constrained to
278 // be a constant value, use that value instead to lessen the burden
279 // on later analysis stages (so we have less symbolic values to reason
280 // about).
281 // We only go into this branch if we can convert the APSInt value we have
282 // to the type of T, which is not always the case (e.g. for void).
283 if (!T.isNull() && (T->isIntegralOrEnumerationType() || Loc::isLocType(T))) {
284 if (SymbolRef sym = V.getAsSymbol()) {
285 if (const llvm::APSInt *Int = getStateManager()
286 .getConstraintManager()
287 .getSymVal(state: this, sym)) {
288 // FIXME: Because we don't correctly model (yet) sign-extension
289 // and truncation of symbolic values, we need to convert
290 // the integer value to the correct signedness and bitwidth.
291 //
292 // This shows up in the following:
293 //
294 // char foo();
295 // unsigned x = foo();
296 // if (x == 54)
297 // ...
298 //
299 // The symbolic value stored to 'x' is actually the conjured
300 // symbol for the call to foo(); the type of that symbol is 'char',
301 // not unsigned.
302 const llvm::APSInt &NewV = getBasicVals().Convert(T, From: *Int);
303
304 if (V.getAs<Loc>())
305 return loc::ConcreteInt(NewV);
306 else
307 return nonloc::ConcreteInt(NewV);
308 }
309 }
310 }
311
312 return V;
313}
314
315ProgramStateRef ProgramState::BindExpr(const Stmt *S,
316 const LocationContext *LCtx,
317 SVal V, bool Invalidate) const{
318 Environment NewEnv =
319 getStateManager().EnvMgr.bindExpr(Env, E: EnvironmentEntry(S, LCtx), V,
320 Invalidate);
321 if (NewEnv == Env)
322 return this;
323
324 ProgramState NewSt = *this;
325 NewSt.Env = NewEnv;
326 return getStateManager().getPersistentState(Impl&: NewSt);
327}
328
329[[nodiscard]] std::pair<ProgramStateRef, ProgramStateRef>
330ProgramState::assumeInBoundDual(DefinedOrUnknownSVal Idx,
331 DefinedOrUnknownSVal UpperBound,
332 QualType indexTy) const {
333 if (Idx.isUnknown() || UpperBound.isUnknown())
334 return {this, this};
335
336 // Build an expression for 0 <= Idx < UpperBound.
337 // This is the same as Idx + MIN < UpperBound + MIN, if overflow is allowed.
338 // FIXME: This should probably be part of SValBuilder.
339 ProgramStateManager &SM = getStateManager();
340 SValBuilder &svalBuilder = SM.getSValBuilder();
341 ASTContext &Ctx = svalBuilder.getContext();
342
343 // Get the offset: the minimum value of the array index type.
344 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
345 if (indexTy.isNull())
346 indexTy = svalBuilder.getArrayIndexType();
347 nonloc::ConcreteInt Min(BVF.getMinValue(T: indexTy));
348
349 // Adjust the index.
350 SVal newIdx = svalBuilder.evalBinOpNN(state: this, op: BO_Add,
351 lhs: Idx.castAs<NonLoc>(), rhs: Min, resultTy: indexTy);
352 if (newIdx.isUnknownOrUndef())
353 return {this, this};
354
355 // Adjust the upper bound.
356 SVal newBound =
357 svalBuilder.evalBinOpNN(state: this, op: BO_Add, lhs: UpperBound.castAs<NonLoc>(),
358 rhs: Min, resultTy: indexTy);
359
360 if (newBound.isUnknownOrUndef())
361 return {this, this};
362
363 // Build the actual comparison.
364 SVal inBound = svalBuilder.evalBinOpNN(state: this, op: BO_LT, lhs: newIdx.castAs<NonLoc>(),
365 rhs: newBound.castAs<NonLoc>(), resultTy: Ctx.IntTy);
366 if (inBound.isUnknownOrUndef())
367 return {this, this};
368
369 // Finally, let the constraint manager take care of it.
370 ConstraintManager &CM = SM.getConstraintManager();
371 return CM.assumeDual(State: this, Cond: inBound.castAs<DefinedSVal>());
372}
373
374ProgramStateRef ProgramState::assumeInBound(DefinedOrUnknownSVal Idx,
375 DefinedOrUnknownSVal UpperBound,
376 bool Assumption,
377 QualType indexTy) const {
378 std::pair<ProgramStateRef, ProgramStateRef> R =
379 assumeInBoundDual(Idx, UpperBound, indexTy);
380 return Assumption ? R.first : R.second;
381}
382
383ConditionTruthVal ProgramState::isNonNull(SVal V) const {
384 ConditionTruthVal IsNull = isNull(V);
385 if (IsNull.isUnderconstrained())
386 return IsNull;
387 return ConditionTruthVal(!IsNull.getValue());
388}
389
390ConditionTruthVal ProgramState::areEqual(SVal Lhs, SVal Rhs) const {
391 return stateMgr->getSValBuilder().areEqual(state: this, lhs: Lhs, rhs: Rhs);
392}
393
394ConditionTruthVal ProgramState::isNull(SVal V) const {
395 if (V.isZeroConstant())
396 return true;
397
398 if (V.isConstant())
399 return false;
400
401 SymbolRef Sym = V.getAsSymbol(/* IncludeBaseRegion */ IncludeBaseRegions: true);
402 if (!Sym)
403 return ConditionTruthVal();
404
405 return getStateManager().ConstraintMgr->isNull(State: this, Sym);
406}
407
408ProgramStateRef ProgramStateManager::getInitialState(const LocationContext *InitLoc) {
409 ProgramState State(this,
410 EnvMgr.getInitialEnvironment(),
411 StoreMgr->getInitialStore(InitLoc),
412 GDMFactory.getEmptyMap());
413
414 return getPersistentState(Impl&: State);
415}
416
417ProgramStateRef ProgramStateManager::getPersistentStateWithGDM(
418 ProgramStateRef FromState,
419 ProgramStateRef GDMState) {
420 ProgramState NewState(*FromState);
421 NewState.GDM = GDMState->GDM;
422 return getPersistentState(Impl&: NewState);
423}
424
425ProgramStateRef ProgramStateManager::getPersistentState(ProgramState &State) {
426
427 llvm::FoldingSetNodeID ID;
428 State.Profile(ID);
429 void *InsertPos;
430
431 if (ProgramState *I = StateSet.FindNodeOrInsertPos(ID, InsertPos))
432 return I;
433
434 ProgramState *newState = nullptr;
435 if (!freeStates.empty()) {
436 newState = freeStates.back();
437 freeStates.pop_back();
438 }
439 else {
440 newState = Alloc.Allocate<ProgramState>();
441 }
442 new (newState) ProgramState(State);
443 StateSet.InsertNode(N: newState, InsertPos);
444 return newState;
445}
446
447ProgramStateRef ProgramState::makeWithStore(const StoreRef &store) const {
448 ProgramState NewSt(*this);
449 NewSt.setStore(store);
450 return getStateManager().getPersistentState(State&: NewSt);
451}
452
453ProgramStateRef ProgramState::cloneAsPosteriorlyOverconstrained() const {
454 ProgramState NewSt(*this);
455 NewSt.PosteriorlyOverconstrained = true;
456 return getStateManager().getPersistentState(State&: NewSt);
457}
458
459void ProgramState::setStore(const StoreRef &newStore) {
460 Store newStoreStore = newStore.getStore();
461 if (newStoreStore)
462 stateMgr->getStoreManager().incrementReferenceCount(store: newStoreStore);
463 if (store)
464 stateMgr->getStoreManager().decrementReferenceCount(store);
465 store = newStoreStore;
466}
467
468SVal ProgramState::getLValue(const FieldDecl *D, SVal Base) const {
469 Base = wrapSymbolicRegion(Val: Base);
470 return getStateManager().StoreMgr->getLValueField(D, Base);
471}
472
473SVal ProgramState::getLValue(const IndirectFieldDecl *D, SVal Base) const {
474 StoreManager &SM = *getStateManager().StoreMgr;
475 Base = wrapSymbolicRegion(Val: Base);
476
477 // FIXME: This should work with `SM.getLValueField(D->getAnonField(), Base)`,
478 // but that would break some tests. There is probably a bug somewhere that it
479 // would expose.
480 for (const auto *I : D->chain()) {
481 Base = SM.getLValueField(D: cast<FieldDecl>(Val: I), Base);
482 }
483 return Base;
484}
485
486//===----------------------------------------------------------------------===//
487// State pretty-printing.
488//===----------------------------------------------------------------------===//
489
490void ProgramState::printJson(raw_ostream &Out, const LocationContext *LCtx,
491 const char *NL, unsigned int Space,
492 bool IsDot) const {
493 Indent(Out, Space, IsDot) << "\"program_state\": {" << NL;
494 ++Space;
495
496 ProgramStateManager &Mgr = getStateManager();
497
498 // Print the store.
499 Mgr.getStoreManager().printJson(Out, S: getStore(), NL, Space, IsDot);
500
501 // Print out the environment.
502 Env.printJson(Out, Ctx: Mgr.getContext(), LCtx, NL, Space, IsDot);
503
504 // Print out the constraints.
505 Mgr.getConstraintManager().printJson(Out, State: this, NL, Space, IsDot);
506
507 // Print out the tracked dynamic types.
508 printDynamicTypeInfoJson(Out, State: this, NL, Space, IsDot);
509
510 // Print checker-specific data.
511 Mgr.getOwningEngine().printJson(Out, State: this, LCtx, NL, Space, IsDot);
512
513 --Space;
514 Indent(Out, Space, IsDot) << '}';
515}
516
517void ProgramState::printDOT(raw_ostream &Out, const LocationContext *LCtx,
518 unsigned int Space) const {
519 printJson(Out, LCtx, /*NL=*/"\\l", Space, /*IsDot=*/true);
520}
521
522LLVM_DUMP_METHOD void ProgramState::dump() const {
523 printJson(Out&: llvm::errs());
524}
525
526AnalysisManager& ProgramState::getAnalysisManager() const {
527 return stateMgr->getOwningEngine().getAnalysisManager();
528}
529
530//===----------------------------------------------------------------------===//
531// Generic Data Map.
532//===----------------------------------------------------------------------===//
533
534void *const* ProgramState::FindGDM(void *K) const {
535 return GDM.lookup(K);
536}
537
538void*
539ProgramStateManager::FindGDMContext(void *K,
540 void *(*CreateContext)(llvm::BumpPtrAllocator&),
541 void (*DeleteContext)(void*)) {
542
543 std::pair<void*, void (*)(void*)>& p = GDMContexts[K];
544 if (!p.first) {
545 p.first = CreateContext(Alloc);
546 p.second = DeleteContext;
547 }
548
549 return p.first;
550}
551
552ProgramStateRef ProgramStateManager::addGDM(ProgramStateRef St, void *Key, void *Data){
553 ProgramState::GenericDataMap M1 = St->getGDM();
554 ProgramState::GenericDataMap M2 = GDMFactory.add(Old: M1, K: Key, D: Data);
555
556 if (M1 == M2)
557 return St;
558
559 ProgramState NewSt = *St;
560 NewSt.GDM = M2;
561 return getPersistentState(State&: NewSt);
562}
563
564ProgramStateRef ProgramStateManager::removeGDM(ProgramStateRef state, void *Key) {
565 ProgramState::GenericDataMap OldM = state->getGDM();
566 ProgramState::GenericDataMap NewM = GDMFactory.remove(Old: OldM, K: Key);
567
568 if (NewM == OldM)
569 return state;
570
571 ProgramState NewState = *state;
572 NewState.GDM = NewM;
573 return getPersistentState(State&: NewState);
574}
575
576bool ScanReachableSymbols::scan(nonloc::LazyCompoundVal val) {
577 bool wasVisited = !visited.insert(V: val.getCVData()).second;
578 if (wasVisited)
579 return true;
580
581 StoreManager &StoreMgr = state->getStateManager().getStoreManager();
582 // FIXME: We don't really want to use getBaseRegion() here because pointer
583 // arithmetic doesn't apply, but scanReachableSymbols only accepts base
584 // regions right now.
585 const MemRegion *R = val.getRegion()->getBaseRegion();
586 return StoreMgr.scanReachableSymbols(S: val.getStore(), R, Visitor&: *this);
587}
588
589bool ScanReachableSymbols::scan(nonloc::CompoundVal val) {
590 for (SVal V : val)
591 if (!scan(val: V))
592 return false;
593
594 return true;
595}
596
597bool ScanReachableSymbols::scan(const SymExpr *sym) {
598 for (SymbolRef SubSym : sym->symbols()) {
599 bool wasVisited = !visited.insert(V: SubSym).second;
600 if (wasVisited)
601 continue;
602
603 if (!visitor.VisitSymbol(sym: SubSym))
604 return false;
605 }
606
607 return true;
608}
609
610bool ScanReachableSymbols::scan(SVal val) {
611 if (std::optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>())
612 return scan(R: X->getRegion());
613
614 if (std::optional<nonloc::LazyCompoundVal> X =
615 val.getAs<nonloc::LazyCompoundVal>())
616 return scan(val: *X);
617
618 if (std::optional<nonloc::LocAsInteger> X = val.getAs<nonloc::LocAsInteger>())
619 return scan(val: X->getLoc());
620
621 if (SymbolRef Sym = val.getAsSymbol())
622 return scan(sym: Sym);
623
624 if (std::optional<nonloc::CompoundVal> X = val.getAs<nonloc::CompoundVal>())
625 return scan(val: *X);
626
627 return true;
628}
629
630bool ScanReachableSymbols::scan(const MemRegion *R) {
631 if (isa<MemSpaceRegion>(Val: R))
632 return true;
633
634 bool wasVisited = !visited.insert(V: R).second;
635 if (wasVisited)
636 return true;
637
638 if (!visitor.VisitMemRegion(R))
639 return false;
640
641 // If this is a symbolic region, visit the symbol for the region.
642 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(Val: R))
643 if (!visitor.VisitSymbol(sym: SR->getSymbol()))
644 return false;
645
646 // If this is a subregion, also visit the parent regions.
647 if (const SubRegion *SR = dyn_cast<SubRegion>(Val: R)) {
648 const MemRegion *Super = SR->getSuperRegion();
649 if (!scan(R: Super))
650 return false;
651
652 // When we reach the topmost region, scan all symbols in it.
653 if (isa<MemSpaceRegion>(Val: Super)) {
654 StoreManager &StoreMgr = state->getStateManager().getStoreManager();
655 if (!StoreMgr.scanReachableSymbols(S: state->getStore(), R: SR, Visitor&: *this))
656 return false;
657 }
658 }
659
660 // Regions captured by a block are also implicitly reachable.
661 if (const BlockDataRegion *BDR = dyn_cast<BlockDataRegion>(Val: R)) {
662 for (auto Var : BDR->referenced_vars()) {
663 if (!scan(R: Var.getCapturedRegion()))
664 return false;
665 }
666 }
667
668 return true;
669}
670
671bool ProgramState::scanReachableSymbols(SVal val, SymbolVisitor& visitor) const {
672 ScanReachableSymbols S(this, visitor);
673 return S.scan(val);
674}
675
676bool ProgramState::scanReachableSymbols(
677 llvm::iterator_range<region_iterator> Reachable,
678 SymbolVisitor &visitor) const {
679 ScanReachableSymbols S(this, visitor);
680 for (const MemRegion *R : Reachable) {
681 if (!S.scan(R))
682 return false;
683 }
684 return true;
685}
686