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