ProgramState.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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. using namespace clang;
  22. using namespace ento;
  23. namespace clang { namespace ento {
  24. /// Increments the number of times this state is referenced.
  25. void ProgramStateRetain(const ProgramState *state) {
  26. ++const_cast<ProgramState*>(state)->refCount;
  27. }
  28. /// Decrement the number of times this state is referenced.
  29. void ProgramStateRelease(const ProgramState *state) {
  30. assert(state->refCount > 0);
  31. ProgramState *s = const_cast<ProgramState*>(state);
  32. if (--s->refCount == 0) {
  33. ProgramStateManager &Mgr = s->getStateManager();
  34. Mgr.StateSet.RemoveNode(s);
  35. s->~ProgramState();
  36. Mgr.freeStates.push_back(s);
  37. }
  38. }
  39. }}
  40. ProgramState::ProgramState(ProgramStateManager *mgr, const Environment& env,
  41. StoreRef st, GenericDataMap gdm)
  42. : stateMgr(mgr),
  43. Env(env),
  44. store(st.getStore()),
  45. GDM(gdm),
  46. refCount(0) {
  47. stateMgr->getStoreManager().incrementReferenceCount(store);
  48. }
  49. ProgramState::ProgramState(const ProgramState &RHS)
  50. : stateMgr(RHS.stateMgr), Env(RHS.Env), store(RHS.store), GDM(RHS.GDM),
  51. refCount(0) {
  52. stateMgr->getStoreManager().incrementReferenceCount(store);
  53. }
  54. ProgramState::~ProgramState() {
  55. if (store)
  56. stateMgr->getStoreManager().decrementReferenceCount(store);
  57. }
  58. int64_t ProgramState::getID() const {
  59. return getStateManager().Alloc.identifyKnownAlignedObject<ProgramState>(this);
  60. }
  61. ProgramStateManager::ProgramStateManager(ASTContext &Ctx,
  62. StoreManagerCreator CreateSMgr,
  63. ConstraintManagerCreator CreateCMgr,
  64. llvm::BumpPtrAllocator &alloc,
  65. ExprEngine *ExprEng)
  66. : Eng(ExprEng), EnvMgr(alloc), GDMFactory(alloc),
  67. svalBuilder(createSimpleSValBuilder(alloc, Ctx, *this)),
  68. CallEventMgr(new CallEventManager(alloc)), Alloc(alloc) {
  69. StoreMgr = (*CreateSMgr)(*this);
  70. ConstraintMgr = (*CreateCMgr)(*this, ExprEng);
  71. }
  72. ProgramStateManager::~ProgramStateManager() {
  73. for (GDMContextsTy::iterator I=GDMContexts.begin(), E=GDMContexts.end();
  74. I!=E; ++I)
  75. I->second.second(I->second.first);
  76. }
  77. ProgramStateRef ProgramStateManager::removeDeadBindingsFromEnvironmentAndStore(
  78. ProgramStateRef state, const StackFrameContext *LCtx,
  79. SymbolReaper &SymReaper) {
  80. // This code essentially performs a "mark-and-sweep" of the VariableBindings.
  81. // The roots are any Block-level exprs and Decls that our liveness algorithm
  82. // tells us are live. We then see what Decls they may reference, and keep
  83. // those around. This code more than likely can be made faster, and the
  84. // frequency of which this method is called should be experimented with
  85. // for optimum performance.
  86. ProgramState NewState = *state;
  87. NewState.Env = EnvMgr.removeDeadBindings(NewState.Env, SymReaper, state);
  88. // Clean up the store.
  89. StoreRef newStore = StoreMgr->removeDeadBindings(NewState.getStore(), LCtx,
  90. SymReaper);
  91. NewState.setStore(newStore);
  92. SymReaper.setReapedStore(newStore);
  93. return getPersistentState(NewState);
  94. }
  95. ProgramStateRef ProgramState::bindLoc(Loc LV,
  96. SVal V,
  97. const LocationContext *LCtx,
  98. bool notifyChanges) const {
  99. ProgramStateManager &Mgr = getStateManager();
  100. ProgramStateRef newState = makeWithStore(Mgr.StoreMgr->Bind(getStore(),
  101. LV, V));
  102. const MemRegion *MR = LV.getAsRegion();
  103. if (MR && notifyChanges)
  104. return Mgr.getOwningEngine().processRegionChange(newState, MR, LCtx);
  105. return newState;
  106. }
  107. ProgramStateRef
  108. ProgramState::bindDefaultInitial(SVal loc, SVal V,
  109. const LocationContext *LCtx) const {
  110. ProgramStateManager &Mgr = getStateManager();
  111. const MemRegion *R = loc.castAs<loc::MemRegionVal>().getRegion();
  112. const StoreRef &newStore = Mgr.StoreMgr->BindDefaultInitial(getStore(), R, V);
  113. ProgramStateRef new_state = makeWithStore(newStore);
  114. return Mgr.getOwningEngine().processRegionChange(new_state, R, LCtx);
  115. }
  116. ProgramStateRef
  117. ProgramState::bindDefaultZero(SVal loc, const LocationContext *LCtx) const {
  118. ProgramStateManager &Mgr = getStateManager();
  119. const MemRegion *R = loc.castAs<loc::MemRegionVal>().getRegion();
  120. const StoreRef &newStore = Mgr.StoreMgr->BindDefaultZero(getStore(), R);
  121. ProgramStateRef new_state = makeWithStore(newStore);
  122. return Mgr.getOwningEngine().processRegionChange(new_state, R, LCtx);
  123. }
  124. typedef ArrayRef<const MemRegion *> RegionList;
  125. typedef ArrayRef<SVal> ValueList;
  126. ProgramStateRef
  127. ProgramState::invalidateRegions(RegionList Regions,
  128. const Expr *E, unsigned Count,
  129. const LocationContext *LCtx,
  130. bool CausedByPointerEscape,
  131. InvalidatedSymbols *IS,
  132. const CallEvent *Call,
  133. RegionAndSymbolInvalidationTraits *ITraits) const {
  134. SmallVector<SVal, 8> Values;
  135. for (RegionList::const_iterator I = Regions.begin(),
  136. End = Regions.end(); I != End; ++I)
  137. Values.push_back(loc::MemRegionVal(*I));
  138. return invalidateRegionsImpl(Values, E, Count, LCtx, CausedByPointerEscape,
  139. IS, ITraits, Call);
  140. }
  141. ProgramStateRef
  142. ProgramState::invalidateRegions(ValueList Values,
  143. const Expr *E, unsigned Count,
  144. const LocationContext *LCtx,
  145. bool CausedByPointerEscape,
  146. InvalidatedSymbols *IS,
  147. const CallEvent *Call,
  148. RegionAndSymbolInvalidationTraits *ITraits) const {
  149. return invalidateRegionsImpl(Values, E, Count, LCtx, CausedByPointerEscape,
  150. IS, ITraits, Call);
  151. }
  152. ProgramStateRef
  153. ProgramState::invalidateRegionsImpl(ValueList Values,
  154. const Expr *E, unsigned Count,
  155. const LocationContext *LCtx,
  156. bool CausedByPointerEscape,
  157. InvalidatedSymbols *IS,
  158. RegionAndSymbolInvalidationTraits *ITraits,
  159. const CallEvent *Call) const {
  160. ProgramStateManager &Mgr = getStateManager();
  161. ExprEngine &Eng = Mgr.getOwningEngine();
  162. InvalidatedSymbols InvalidatedSyms;
  163. if (!IS)
  164. IS = &InvalidatedSyms;
  165. RegionAndSymbolInvalidationTraits ITraitsLocal;
  166. if (!ITraits)
  167. ITraits = &ITraitsLocal;
  168. StoreManager::InvalidatedRegions TopLevelInvalidated;
  169. StoreManager::InvalidatedRegions Invalidated;
  170. const StoreRef &newStore
  171. = Mgr.StoreMgr->invalidateRegions(getStore(), Values, E, Count, LCtx, Call,
  172. *IS, *ITraits, &TopLevelInvalidated,
  173. &Invalidated);
  174. ProgramStateRef newState = makeWithStore(newStore);
  175. if (CausedByPointerEscape) {
  176. newState = Eng.notifyCheckersOfPointerEscape(newState, IS,
  177. TopLevelInvalidated,
  178. Call,
  179. *ITraits);
  180. }
  181. return Eng.processRegionChanges(newState, IS, TopLevelInvalidated,
  182. Invalidated, LCtx, Call);
  183. }
  184. ProgramStateRef ProgramState::killBinding(Loc LV) const {
  185. assert(!LV.getAs<loc::MemRegionVal>() && "Use invalidateRegion instead.");
  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. ProgramStateRef ProgramState::assumeInBound(DefinedOrUnknownSVal Idx,
  269. DefinedOrUnknownSVal UpperBound,
  270. bool Assumption,
  271. QualType indexTy) const {
  272. if (Idx.isUnknown() || UpperBound.isUnknown())
  273. return 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;
  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;
  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;
  301. // Finally, let the constraint manager take care of it.
  302. ConstraintManager &CM = SM.getConstraintManager();
  303. return CM.assume(this, inBound.castAs<DefinedSVal>(), Assumption);
  304. }
  305. ConditionTruthVal ProgramState::isNonNull(SVal V) const {
  306. ConditionTruthVal IsNull = isNull(V);
  307. if (IsNull.isUnderconstrained())
  308. return IsNull;
  309. return ConditionTruthVal(!IsNull.getValue());
  310. }
  311. ConditionTruthVal ProgramState::areEqual(SVal Lhs, SVal Rhs) const {
  312. return stateMgr->getSValBuilder().areEqual(this, Lhs, Rhs);
  313. }
  314. ConditionTruthVal ProgramState::isNull(SVal V) const {
  315. if (V.isZeroConstant())
  316. return true;
  317. if (V.isConstant())
  318. return false;
  319. SymbolRef Sym = V.getAsSymbol(/* IncludeBaseRegion */ true);
  320. if (!Sym)
  321. return ConditionTruthVal();
  322. return getStateManager().ConstraintMgr->isNull(this, Sym);
  323. }
  324. ProgramStateRef ProgramStateManager::getInitialState(const LocationContext *InitLoc) {
  325. ProgramState State(this,
  326. EnvMgr.getInitialEnvironment(),
  327. StoreMgr->getInitialStore(InitLoc),
  328. GDMFactory.getEmptyMap());
  329. return getPersistentState(State);
  330. }
  331. ProgramStateRef ProgramStateManager::getPersistentStateWithGDM(
  332. ProgramStateRef FromState,
  333. ProgramStateRef GDMState) {
  334. ProgramState NewState(*FromState);
  335. NewState.GDM = GDMState->GDM;
  336. return getPersistentState(NewState);
  337. }
  338. ProgramStateRef ProgramStateManager::getPersistentState(ProgramState &State) {
  339. llvm::FoldingSetNodeID ID;
  340. State.Profile(ID);
  341. void *InsertPos;
  342. if (ProgramState *I = StateSet.FindNodeOrInsertPos(ID, InsertPos))
  343. return I;
  344. ProgramState *newState = nullptr;
  345. if (!freeStates.empty()) {
  346. newState = freeStates.back();
  347. freeStates.pop_back();
  348. }
  349. else {
  350. newState = (ProgramState*) Alloc.Allocate<ProgramState>();
  351. }
  352. new (newState) ProgramState(State);
  353. StateSet.InsertNode(newState, InsertPos);
  354. return newState;
  355. }
  356. ProgramStateRef ProgramState::makeWithStore(const StoreRef &store) const {
  357. ProgramState NewSt(*this);
  358. NewSt.setStore(store);
  359. return getStateManager().getPersistentState(NewSt);
  360. }
  361. void ProgramState::setStore(const StoreRef &newStore) {
  362. Store newStoreStore = newStore.getStore();
  363. if (newStoreStore)
  364. stateMgr->getStoreManager().incrementReferenceCount(newStoreStore);
  365. if (store)
  366. stateMgr->getStoreManager().decrementReferenceCount(store);
  367. store = newStoreStore;
  368. }
  369. //===----------------------------------------------------------------------===//
  370. // State pretty-printing.
  371. //===----------------------------------------------------------------------===//
  372. void ProgramState::printJson(raw_ostream &Out, const LocationContext *LCtx,
  373. const char *NL, unsigned int Space,
  374. bool IsDot) const {
  375. Indent(Out, Space, IsDot) << "\"program_state\": {" << NL;
  376. ++Space;
  377. ProgramStateManager &Mgr = getStateManager();
  378. // Print the store.
  379. Mgr.getStoreManager().printJson(Out, getStore(), NL, Space, IsDot);
  380. // Print out the environment.
  381. Env.printJson(Out, Mgr.getContext(), LCtx, NL, Space, IsDot);
  382. // Print out the constraints.
  383. Mgr.getConstraintManager().printJson(Out, this, NL, Space, IsDot);
  384. // Print out the tracked dynamic types.
  385. printDynamicTypeInfoJson(Out, this, NL, Space, IsDot);
  386. // Print checker-specific data.
  387. Mgr.getOwningEngine().printJson(Out, this, LCtx, NL, Space, IsDot);
  388. --Space;
  389. Indent(Out, Space, IsDot) << '}';
  390. }
  391. void ProgramState::printDOT(raw_ostream &Out, const LocationContext *LCtx,
  392. unsigned int Space) const {
  393. printJson(Out, LCtx, /*NL=*/"\\l", Space, /*IsDot=*/true);
  394. }
  395. LLVM_DUMP_METHOD void ProgramState::dump() const {
  396. printJson(llvm::errs());
  397. }
  398. AnalysisManager& ProgramState::getAnalysisManager() const {
  399. return stateMgr->getOwningEngine().getAnalysisManager();
  400. }
  401. //===----------------------------------------------------------------------===//
  402. // Generic Data Map.
  403. //===----------------------------------------------------------------------===//
  404. void *const* ProgramState::FindGDM(void *K) const {
  405. return GDM.lookup(K);
  406. }
  407. void*
  408. ProgramStateManager::FindGDMContext(void *K,
  409. void *(*CreateContext)(llvm::BumpPtrAllocator&),
  410. void (*DeleteContext)(void*)) {
  411. std::pair<void*, void (*)(void*)>& p = GDMContexts[K];
  412. if (!p.first) {
  413. p.first = CreateContext(Alloc);
  414. p.second = DeleteContext;
  415. }
  416. return p.first;
  417. }
  418. ProgramStateRef ProgramStateManager::addGDM(ProgramStateRef St, void *Key, void *Data){
  419. ProgramState::GenericDataMap M1 = St->getGDM();
  420. ProgramState::GenericDataMap M2 = GDMFactory.add(M1, Key, Data);
  421. if (M1 == M2)
  422. return St;
  423. ProgramState NewSt = *St;
  424. NewSt.GDM = M2;
  425. return getPersistentState(NewSt);
  426. }
  427. ProgramStateRef ProgramStateManager::removeGDM(ProgramStateRef state, void *Key) {
  428. ProgramState::GenericDataMap OldM = state->getGDM();
  429. ProgramState::GenericDataMap NewM = GDMFactory.remove(OldM, Key);
  430. if (NewM == OldM)
  431. return state;
  432. ProgramState NewState = *state;
  433. NewState.GDM = NewM;
  434. return getPersistentState(NewState);
  435. }
  436. bool ScanReachableSymbols::scan(nonloc::LazyCompoundVal val) {
  437. bool wasVisited = !visited.insert(val.getCVData()).second;
  438. if (wasVisited)
  439. return true;
  440. StoreManager &StoreMgr = state->getStateManager().getStoreManager();
  441. // FIXME: We don't really want to use getBaseRegion() here because pointer
  442. // arithmetic doesn't apply, but scanReachableSymbols only accepts base
  443. // regions right now.
  444. const MemRegion *R = val.getRegion()->getBaseRegion();
  445. return StoreMgr.scanReachableSymbols(val.getStore(), R, *this);
  446. }
  447. bool ScanReachableSymbols::scan(nonloc::CompoundVal val) {
  448. for (nonloc::CompoundVal::iterator I=val.begin(), E=val.end(); I!=E; ++I)
  449. if (!scan(*I))
  450. return false;
  451. return true;
  452. }
  453. bool ScanReachableSymbols::scan(const SymExpr *sym) {
  454. for (SymExpr::symbol_iterator SI = sym->symbol_begin(),
  455. SE = sym->symbol_end();
  456. SI != SE; ++SI) {
  457. bool wasVisited = !visited.insert(*SI).second;
  458. if (wasVisited)
  459. continue;
  460. if (!visitor.VisitSymbol(*SI))
  461. return false;
  462. }
  463. return true;
  464. }
  465. bool ScanReachableSymbols::scan(SVal val) {
  466. if (Optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>())
  467. return scan(X->getRegion());
  468. if (Optional<nonloc::LazyCompoundVal> X =
  469. val.getAs<nonloc::LazyCompoundVal>())
  470. return scan(*X);
  471. if (Optional<nonloc::LocAsInteger> X = val.getAs<nonloc::LocAsInteger>())
  472. return scan(X->getLoc());
  473. if (SymbolRef Sym = val.getAsSymbol())
  474. return scan(Sym);
  475. if (Optional<nonloc::CompoundVal> X = val.getAs<nonloc::CompoundVal>())
  476. return scan(*X);
  477. return true;
  478. }
  479. bool ScanReachableSymbols::scan(const MemRegion *R) {
  480. if (isa<MemSpaceRegion>(R))
  481. return true;
  482. bool wasVisited = !visited.insert(R).second;
  483. if (wasVisited)
  484. return true;
  485. if (!visitor.VisitMemRegion(R))
  486. return false;
  487. // If this is a symbolic region, visit the symbol for the region.
  488. if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
  489. if (!visitor.VisitSymbol(SR->getSymbol()))
  490. return false;
  491. // If this is a subregion, also visit the parent regions.
  492. if (const SubRegion *SR = dyn_cast<SubRegion>(R)) {
  493. const MemRegion *Super = SR->getSuperRegion();
  494. if (!scan(Super))
  495. return false;
  496. // When we reach the topmost region, scan all symbols in it.
  497. if (isa<MemSpaceRegion>(Super)) {
  498. StoreManager &StoreMgr = state->getStateManager().getStoreManager();
  499. if (!StoreMgr.scanReachableSymbols(state->getStore(), SR, *this))
  500. return false;
  501. }
  502. }
  503. // Regions captured by a block are also implicitly reachable.
  504. if (const BlockDataRegion *BDR = dyn_cast<BlockDataRegion>(R)) {
  505. BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
  506. E = BDR->referenced_vars_end();
  507. for ( ; I != E; ++I) {
  508. if (!scan(I.getCapturedRegion()))
  509. return false;
  510. }
  511. }
  512. return true;
  513. }
  514. bool ProgramState::scanReachableSymbols(SVal val, SymbolVisitor& visitor) const {
  515. ScanReachableSymbols S(this, visitor);
  516. return S.scan(val);
  517. }
  518. bool ProgramState::scanReachableSymbols(
  519. llvm::iterator_range<region_iterator> Reachable,
  520. SymbolVisitor &visitor) const {
  521. ScanReachableSymbols S(this, visitor);
  522. for (const MemRegion *R : Reachable) {
  523. if (!S.scan(R))
  524. return false;
  525. }
  526. return true;
  527. }