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