ProgramState.cpp 22 KB

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