1 //= GRState.cpp - Path-Sensitive "State" for tracking values -----*- C++ -*--=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements GRState and GRStateManager.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Analysis/CFG.h"
15 #include "clang/StaticAnalyzer/Core/PathSensitive/GRStateTrait.h"
16 #include "clang/StaticAnalyzer/Core/PathSensitive/GRState.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/TransferFuncs.h"
19 #include "llvm/Support/raw_ostream.h"
21 using namespace clang;
24 // Give the vtable for ConstraintManager somewhere to live.
25 // FIXME: Move this elsewhere.
26 ConstraintManager::~ConstraintManager() {}
28 GRState::GRState(GRStateManager *mgr, const Environment& env,
29 StoreRef st, GenericDataMap gdm)
35 stateMgr->getStoreManager().incrementReferenceCount(store);
38 GRState::GRState(const GRState& RHS)
39 : llvm::FoldingSetNode(),
40 stateMgr(RHS.stateMgr),
45 stateMgr->getStoreManager().incrementReferenceCount(store);
50 stateMgr->getStoreManager().decrementReferenceCount(store);
53 GRStateManager::~GRStateManager() {
54 for (std::vector<GRState::Printer*>::iterator I=Printers.begin(),
55 E=Printers.end(); I!=E; ++I)
58 for (GDMContextsTy::iterator I=GDMContexts.begin(), E=GDMContexts.end();
60 I->second.second(I->second.first);
64 GRStateManager::removeDeadBindings(const GRState* state,
65 const StackFrameContext *LCtx,
66 SymbolReaper& SymReaper) {
68 // This code essentially performs a "mark-and-sweep" of the VariableBindings.
69 // The roots are any Block-level exprs and Decls that our liveness algorithm
70 // tells us are live. We then see what Decls they may reference, and keep
71 // those around. This code more than likely can be made faster, and the
72 // frequency of which this method is called should be experimented with
73 // for optimum performance.
74 llvm::SmallVector<const MemRegion*, 10> RegionRoots;
75 GRState NewState = *state;
77 NewState.Env = EnvMgr.removeDeadBindings(NewState.Env, SymReaper,
80 // Clean up the store.
81 NewState.setStore(StoreMgr->removeDeadBindings(NewState.getStore(), LCtx,
82 SymReaper, RegionRoots));
83 state = getPersistentState(NewState);
84 return ConstraintMgr->removeDeadBindings(state, SymReaper);
87 const GRState *GRStateManager::MarshalState(const GRState *state,
88 const StackFrameContext *InitLoc) {
89 // make up an empty state for now.
91 EnvMgr.getInitialEnvironment(),
92 StoreMgr->getInitialStore(InitLoc),
93 GDMFactory.getEmptyMap());
95 return getPersistentState(State);
98 const GRState *GRState::bindCompoundLiteral(const CompoundLiteralExpr* CL,
99 const LocationContext *LC,
101 const StoreRef &newStore =
102 getStateManager().StoreMgr->BindCompoundLiteral(getStore(), CL, LC, V);
103 return makeWithStore(newStore);
106 const GRState *GRState::bindDecl(const VarRegion* VR, SVal IVal) const {
107 const StoreRef &newStore =
108 getStateManager().StoreMgr->BindDecl(getStore(), VR, IVal);
109 return makeWithStore(newStore);
112 const GRState *GRState::bindDeclWithNoInit(const VarRegion* VR) const {
113 const StoreRef &newStore =
114 getStateManager().StoreMgr->BindDeclWithNoInit(getStore(), VR);
115 return makeWithStore(newStore);
118 const GRState *GRState::bindLoc(Loc LV, SVal V) const {
119 GRStateManager &Mgr = getStateManager();
120 const GRState *newState = makeWithStore(Mgr.StoreMgr->Bind(getStore(),
122 const MemRegion *MR = LV.getAsRegion();
123 if (MR && Mgr.getOwningEngine())
124 return Mgr.getOwningEngine()->processRegionChange(newState, MR);
129 const GRState *GRState::bindDefault(SVal loc, SVal V) const {
130 GRStateManager &Mgr = getStateManager();
131 const MemRegion *R = cast<loc::MemRegionVal>(loc).getRegion();
132 const StoreRef &newStore = Mgr.StoreMgr->BindDefault(getStore(), R, V);
133 const GRState *new_state = makeWithStore(newStore);
134 return Mgr.getOwningEngine() ?
135 Mgr.getOwningEngine()->processRegionChange(new_state, R) :
139 const GRState *GRState::invalidateRegions(const MemRegion * const *Begin,
140 const MemRegion * const *End,
141 const Expr *E, unsigned Count,
142 StoreManager::InvalidatedSymbols *IS,
143 bool invalidateGlobals) const {
145 StoreManager::InvalidatedSymbols invalidated;
146 return invalidateRegionsImpl(Begin, End, E, Count,
147 invalidated, invalidateGlobals);
149 return invalidateRegionsImpl(Begin, End, E, Count, *IS, invalidateGlobals);
153 GRState::invalidateRegionsImpl(const MemRegion * const *Begin,
154 const MemRegion * const *End,
155 const Expr *E, unsigned Count,
156 StoreManager::InvalidatedSymbols &IS,
157 bool invalidateGlobals) const {
158 GRStateManager &Mgr = getStateManager();
159 SubEngine* Eng = Mgr.getOwningEngine();
161 if (Eng && Eng->wantsRegionChangeUpdate(this)) {
162 StoreManager::InvalidatedRegions Regions;
163 const StoreRef &newStore
164 = Mgr.StoreMgr->invalidateRegions(getStore(), Begin, End, E, Count, IS,
165 invalidateGlobals, &Regions);
166 const GRState *newState = makeWithStore(newStore);
167 return Eng->processRegionChanges(newState, &IS,
172 const StoreRef &newStore =
173 Mgr.StoreMgr->invalidateRegions(getStore(), Begin, End, E, Count, IS,
174 invalidateGlobals, NULL);
175 return makeWithStore(newStore);
178 const GRState *GRState::unbindLoc(Loc LV) const {
179 assert(!isa<loc::MemRegionVal>(LV) && "Use invalidateRegion instead.");
181 Store OldStore = getStore();
182 const StoreRef &newStore = getStateManager().StoreMgr->Remove(OldStore, LV);
184 if (newStore.getStore() == OldStore)
187 return makeWithStore(newStore);
190 const GRState *GRState::enterStackFrame(const StackFrameContext *frame) const {
191 const StoreRef &new_store =
192 getStateManager().StoreMgr->enterStackFrame(this, frame);
193 return makeWithStore(new_store);
196 SVal GRState::getSValAsScalarOrLoc(const MemRegion *R) const {
197 // We only want to do fetches from regions that we can actually bind
198 // values. For example, SymbolicRegions of type 'id<...>' cannot
199 // have direct bindings (but their can be bindings on their subregions).
200 if (!R->isBoundable())
203 if (const TypedRegion *TR = dyn_cast<TypedRegion>(R)) {
204 QualType T = TR->getValueType();
205 if (Loc::isLocType(T) || T->isIntegerType())
212 SVal GRState::getSVal(Loc location, QualType T) const {
213 SVal V = getRawSVal(cast<Loc>(location), T);
215 // If 'V' is a symbolic value that is *perfectly* constrained to
216 // be a constant value, use that value instead to lessen the burden
217 // on later analysis stages (so we have less symbolic values to reason
220 if (SymbolRef sym = V.getAsSymbol()) {
221 if (const llvm::APSInt *Int = getSymVal(sym)) {
222 // FIXME: Because we don't correctly model (yet) sign-extension
223 // and truncation of symbolic values, we need to convert
224 // the integer value to the correct signedness and bitwidth.
226 // This shows up in the following:
229 // unsigned x = foo();
233 // The symbolic value stored to 'x' is actually the conjured
234 // symbol for the call to foo(); the type of that symbol is 'char',
236 const llvm::APSInt &NewV = getBasicVals().Convert(T, *Int);
239 return loc::ConcreteInt(NewV);
241 return nonloc::ConcreteInt(NewV);
249 const GRState *GRState::BindExpr(const Stmt* S, SVal V, bool Invalidate) const{
250 Environment NewEnv = getStateManager().EnvMgr.bindExpr(Env, S, V,
255 GRState NewSt = *this;
257 return getStateManager().getPersistentState(NewSt);
260 const GRState *GRState::bindExprAndLocation(const Stmt *S, SVal location,
263 getStateManager().EnvMgr.bindExprAndLocation(Env, S, location, V);
268 GRState NewSt = *this;
270 return getStateManager().getPersistentState(NewSt);
273 const GRState *GRState::assumeInBound(DefinedOrUnknownSVal Idx,
274 DefinedOrUnknownSVal UpperBound,
275 bool Assumption) const {
276 if (Idx.isUnknown() || UpperBound.isUnknown())
279 // Build an expression for 0 <= Idx < UpperBound.
280 // This is the same as Idx + MIN < UpperBound + MIN, if overflow is allowed.
281 // FIXME: This should probably be part of SValBuilder.
282 GRStateManager &SM = getStateManager();
283 SValBuilder &svalBuilder = SM.getSValBuilder();
284 ASTContext &Ctx = svalBuilder.getContext();
286 // Get the offset: the minimum value of the array index type.
287 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
288 // FIXME: This should be using ValueManager::ArrayindexTy...somehow.
289 QualType indexTy = Ctx.IntTy;
290 nonloc::ConcreteInt Min(BVF.getMinValue(indexTy));
293 SVal newIdx = svalBuilder.evalBinOpNN(this, BO_Add,
294 cast<NonLoc>(Idx), Min, indexTy);
295 if (newIdx.isUnknownOrUndef())
298 // Adjust the upper bound.
300 svalBuilder.evalBinOpNN(this, BO_Add, cast<NonLoc>(UpperBound),
303 if (newBound.isUnknownOrUndef())
306 // Build the actual comparison.
307 SVal inBound = svalBuilder.evalBinOpNN(this, BO_LT,
308 cast<NonLoc>(newIdx), cast<NonLoc>(newBound),
310 if (inBound.isUnknownOrUndef())
313 // Finally, let the constraint manager take care of it.
314 ConstraintManager &CM = SM.getConstraintManager();
315 return CM.assume(this, cast<DefinedSVal>(inBound), Assumption);
318 const GRState* GRStateManager::getInitialState(const LocationContext *InitLoc) {
320 EnvMgr.getInitialEnvironment(),
321 StoreMgr->getInitialStore(InitLoc),
322 GDMFactory.getEmptyMap());
324 return getPersistentState(State);
327 void GRStateManager::recycleUnusedStates() {
328 for (std::vector<GRState*>::iterator i = recentlyAllocatedStates.begin(),
329 e = recentlyAllocatedStates.end(); i != e; ++i) {
331 if (state->referencedByExplodedNode())
333 StateSet.RemoveNode(state);
334 freeStates.push_back(state);
337 recentlyAllocatedStates.clear();
340 const GRState* GRStateManager::getPersistentState(GRState& State) {
342 llvm::FoldingSetNodeID ID;
346 if (GRState* I = StateSet.FindNodeOrInsertPos(ID, InsertPos))
349 GRState *newState = 0;
350 if (!freeStates.empty()) {
351 newState = freeStates.back();
352 freeStates.pop_back();
355 newState = (GRState*) Alloc.Allocate<GRState>();
357 new (newState) GRState(State);
358 StateSet.InsertNode(newState, InsertPos);
359 recentlyAllocatedStates.push_back(newState);
363 const GRState* GRState::makeWithStore(const StoreRef &store) const {
364 GRState NewSt = *this;
365 NewSt.setStore(store);
366 return getStateManager().getPersistentState(NewSt);
369 void GRState::setStore(const StoreRef &newStore) {
370 Store newStoreStore = newStore.getStore();
372 stateMgr->getStoreManager().incrementReferenceCount(newStoreStore);
374 stateMgr->getStoreManager().decrementReferenceCount(store);
375 store = newStoreStore;
378 //===----------------------------------------------------------------------===//
379 // State pretty-printing.
380 //===----------------------------------------------------------------------===//
382 static bool IsEnvLoc(const Stmt *S) {
383 // FIXME: This is a layering violation. Should be in environment.
384 return (bool) (((uintptr_t) S) & 0x1);
387 void GRState::print(llvm::raw_ostream& Out, CFG &C, const char* nl,
388 const char* sep) const {
390 GRStateManager &Mgr = getStateManager();
391 Mgr.getStoreManager().print(getStore(), Out, nl, sep);
393 // Print Subexpression bindings.
396 // FIXME: All environment printing should be moved inside Environment.
397 for (Environment::iterator I = Env.begin(), E = Env.end(); I != E; ++I) {
398 if (C.isBlkExpr(I.getKey()) || IsEnvLoc(I.getKey()))
402 Out << nl << nl << "Sub-Expressions:" << nl;
407 Out << " (" << (void*) I.getKey() << ") ";
408 LangOptions LO; // FIXME.
409 I.getKey()->printPretty(Out, 0, PrintingPolicy(LO));
410 Out << " : " << I.getData();
413 // Print block-expression bindings.
416 for (Environment::iterator I = Env.begin(), E = Env.end(); I != E; ++I) {
417 if (!C.isBlkExpr(I.getKey()))
421 Out << nl << nl << "Block-level Expressions:" << nl;
426 Out << " (" << (void*) I.getKey() << ") ";
427 LangOptions LO; // FIXME.
428 I.getKey()->printPretty(Out, 0, PrintingPolicy(LO));
429 Out << " : " << I.getData();
435 for (Environment::iterator I = Env.begin(), E = Env.end(); I != E; ++I) {
436 if (!IsEnvLoc(I.getKey()))
440 Out << nl << nl << "Load/store locations:" << nl;
445 const Stmt *S = (Stmt*) (((uintptr_t) I.getKey()) & ((uintptr_t) ~0x1));
447 Out << " (" << (void*) S << ") ";
448 LangOptions LO; // FIXME.
449 S->printPretty(Out, 0, PrintingPolicy(LO));
450 Out << " : " << I.getData();
453 Mgr.getConstraintManager().print(this, Out, nl, sep);
455 // Print checker-specific data.
456 for (std::vector<Printer*>::iterator I = Mgr.Printers.begin(),
457 E = Mgr.Printers.end(); I != E; ++I) {
458 (*I)->Print(Out, this, nl, sep);
462 void GRState::printDOT(llvm::raw_ostream& Out, CFG &C) const {
463 print(Out, C, "\\l", "\\|");
466 void GRState::printStdErr(CFG &C) const {
467 print(llvm::errs(), C);
470 //===----------------------------------------------------------------------===//
472 //===----------------------------------------------------------------------===//
474 void* const* GRState::FindGDM(void* K) const {
475 return GDM.lookup(K);
479 GRStateManager::FindGDMContext(void* K,
480 void* (*CreateContext)(llvm::BumpPtrAllocator&),
481 void (*DeleteContext)(void*)) {
483 std::pair<void*, void (*)(void*)>& p = GDMContexts[K];
485 p.first = CreateContext(Alloc);
486 p.second = DeleteContext;
492 const GRState* GRStateManager::addGDM(const GRState* St, void* Key, void* Data){
493 GRState::GenericDataMap M1 = St->getGDM();
494 GRState::GenericDataMap M2 = GDMFactory.add(M1, Key, Data);
501 return getPersistentState(NewSt);
504 const GRState *GRStateManager::removeGDM(const GRState *state, void *Key) {
505 GRState::GenericDataMap OldM = state->getGDM();
506 GRState::GenericDataMap NewM = GDMFactory.remove(OldM, Key);
511 GRState NewState = *state;
513 return getPersistentState(NewState);
516 //===----------------------------------------------------------------------===//
518 //===----------------------------------------------------------------------===//
521 class ScanReachableSymbols : public SubRegionMap::Visitor {
522 typedef llvm::DenseSet<const MemRegion*> VisitedRegionsTy;
524 VisitedRegionsTy visited;
525 const GRState *state;
526 SymbolVisitor &visitor;
527 llvm::OwningPtr<SubRegionMap> SRM;
530 ScanReachableSymbols(const GRState *st, SymbolVisitor& v)
531 : state(st), visitor(v) {}
533 bool scan(nonloc::CompoundVal val);
535 bool scan(const MemRegion *R);
537 // From SubRegionMap::Visitor.
538 bool Visit(const MemRegion* Parent, const MemRegion* SubRegion) {
539 return scan(SubRegion);
544 bool ScanReachableSymbols::scan(nonloc::CompoundVal val) {
545 for (nonloc::CompoundVal::iterator I=val.begin(), E=val.end(); I!=E; ++I)
552 bool ScanReachableSymbols::scan(SVal val) {
553 if (loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&val))
554 return scan(X->getRegion());
556 if (nonloc::LocAsInteger *X = dyn_cast<nonloc::LocAsInteger>(&val))
557 return scan(X->getLoc());
559 if (SymbolRef Sym = val.getAsSymbol())
560 return visitor.VisitSymbol(Sym);
562 if (nonloc::CompoundVal *X = dyn_cast<nonloc::CompoundVal>(&val))
568 bool ScanReachableSymbols::scan(const MemRegion *R) {
569 if (isa<MemSpaceRegion>(R) || visited.count(R))
574 // If this is a symbolic region, visit the symbol for the region.
575 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
576 if (!visitor.VisitSymbol(SR->getSymbol()))
579 // If this is a subregion, also visit the parent regions.
580 if (const SubRegion *SR = dyn_cast<SubRegion>(R))
581 if (!scan(SR->getSuperRegion()))
584 // Now look at the binding to this region (if any).
585 if (!scan(state->getSValAsScalarOrLoc(R)))
588 // Now look at the subregions.
590 SRM.reset(state->getStateManager().getStoreManager().
591 getSubRegionMap(state->getStore()));
593 return SRM->iterSubRegions(R, *this);
596 bool GRState::scanReachableSymbols(SVal val, SymbolVisitor& visitor) const {
597 ScanReachableSymbols S(this, visitor);
601 bool GRState::scanReachableSymbols(const SVal *I, const SVal *E,
602 SymbolVisitor &visitor) const {
603 ScanReachableSymbols S(this, visitor);
604 for ( ; I != E; ++I) {
611 bool GRState::scanReachableSymbols(const MemRegion * const *I,
612 const MemRegion * const *E,
613 SymbolVisitor &visitor) const {
614 ScanReachableSymbols S(this, visitor);
615 for ( ; I != E; ++I) {