clang 22.0.0git
Store.h
Go to the documentation of this file.
1//===- Store.h - Interface for maps from Locations to 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 defined the types Store and StoreManager.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_STORE_H
14#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_STORE_H
15
16#include "clang/AST/Type.h"
17#include "clang/Basic/LLVM.h"
24#include "llvm/ADT/ArrayRef.h"
25#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/SmallVector.h"
27#include <cassert>
28#include <cstdint>
29#include <memory>
30#include <optional>
31
32namespace clang {
33
34class ASTContext;
35class CastExpr;
36class CompoundLiteralExpr;
37class CXXBasePath;
38class Decl;
39class Expr;
40class LocationContext;
41class ObjCIvarDecl;
42class StackFrameContext;
43
44namespace ento {
45
46class CallEvent;
47class ProgramStateManager;
48class ScanReachableSymbols;
49class SymbolReaper;
50
51using InvalidatedSymbols = llvm::DenseSet<SymbolRef>;
52
53struct BindResult {
55
56 // If during the bind operation we exhaust the allowed binding budget, we set
57 // this to the beginning of the escaped part of the region.
59};
60
62protected:
65
66 /// MRMgr - Manages region objects associated with this StoreManager.
69
71
72public:
73 virtual ~StoreManager() = default;
74
75 /// Return the value bound to specified location in a given state.
76 /// \param[in] store The store in which to make the lookup.
77 /// \param[in] loc The symbolic memory location.
78 /// \param[in] T An optional type that provides a hint indicating the
79 /// expected type of the returned value. This is used if the value is
80 /// lazily computed.
81 /// \return The value bound to the location \c loc.
82 virtual SVal getBinding(Store store, Loc loc, QualType T = QualType()) = 0;
83
84 /// Return the default value bound to a region in a given store. The default
85 /// binding is the value of sub-regions that were not initialized separately
86 /// from their base region. For example, if the structure is zero-initialized
87 /// upon construction, this method retrieves the concrete zero value, even if
88 /// some or all fields were later overwritten manually. Default binding may be
89 /// an unknown, undefined, concrete, or symbolic value.
90 /// \param[in] store The store in which to make the lookup.
91 /// \param[in] R The region to find the default binding for.
92 /// \return The default value bound to the region in the store, if a default
93 /// binding exists.
94 virtual std::optional<SVal> getDefaultBinding(Store store,
95 const MemRegion *R) = 0;
96
97 /// Return the default value bound to a LazyCompoundVal. The default binding
98 /// is used to represent the value of any fields or elements within the
99 /// structure represented by the LazyCompoundVal which were not initialized
100 /// explicitly separately from the whole structure. Default binding may be an
101 /// unknown, undefined, concrete, or symbolic value.
102 /// \param[in] lcv The lazy compound value.
103 /// \return The default value bound to the LazyCompoundVal \c lcv, if a
104 /// default binding exists.
106 return getDefaultBinding(lcv.getStore(), lcv.getRegion());
107 }
108
109 /// Return a store with the specified value bound to the given location.
110 /// \param[in] store The store in which to make the binding.
111 /// \param[in] loc The symbolic memory location.
112 /// \param[in] val The value to bind to location \c loc.
113 /// \return A StoreRef object that contains the same
114 /// bindings as \c store with the addition of having the value specified
115 /// by \c val bound to the location given for \c loc.
116 virtual BindResult Bind(Store store, Loc loc, SVal val) = 0;
117
118 /// Return a store with the specified value bound to all sub-regions of the
119 /// region. The region must not have previous bindings. If you need to
120 /// invalidate existing bindings, consider invalidateRegions().
122 SVal V) = 0;
123
124 /// Return a store with in which all values within the given region are
125 /// reset to zero. This method is allowed to overwrite previous bindings.
126 virtual BindResult BindDefaultZero(Store store, const MemRegion *R) = 0;
127
128 /// Create a new store with the specified binding removed.
129 /// \param ST the original store, that is the basis for the new store.
130 /// \param L the location whose binding should be removed.
131 virtual StoreRef killBinding(Store ST, Loc L) = 0;
132
133 /// getInitialStore - Returns the initial "empty" store representing the
134 /// value bindings upon entry to an analyzed function.
135 virtual StoreRef getInitialStore(const LocationContext *InitLoc) = 0;
136
137 /// getRegionManager - Returns the internal RegionManager object that is
138 /// used to query and manipulate MemRegion objects.
140
142
143 virtual Loc getLValueVar(const VarDecl *VD, const LocationContext *LC) {
144 return svalBuilder.makeLoc(MRMgr.getVarRegion(VD, LC));
145 }
146
148 const LocationContext *LC) {
150 }
151
152 virtual SVal getLValueIvar(const ObjCIvarDecl *decl, SVal base);
153
155 return getLValueFieldOrIvar(D, Base);
156 }
157
158 virtual SVal getLValueElement(QualType elementType, NonLoc offset, SVal Base);
159
160 /// ArrayToPointer - Used by ExprEngine::VistCast to handle implicit
161 /// conversions between arrays and pointers.
162 virtual SVal ArrayToPointer(Loc Array, QualType ElementTy) = 0;
163
164 /// Evaluates a chain of derived-to-base casts through the path specified in
165 /// \p Cast.
166 SVal evalDerivedToBase(SVal Derived, const CastExpr *Cast);
167
168 /// Evaluates a chain of derived-to-base casts through the specified path.
169 SVal evalDerivedToBase(SVal Derived, const CXXBasePath &CastPath);
170
171 /// Evaluates a derived-to-base cast through a single level of derivation.
172 SVal evalDerivedToBase(SVal Derived, QualType DerivedPtrType,
173 bool IsVirtual);
174
175 /// Attempts to do a down cast. Used to model BaseToDerived and C++
176 /// dynamic_cast.
177 /// The callback may result in the following 3 scenarios:
178 /// - Successful cast (ex: derived is subclass of base).
179 /// - Failed cast (ex: derived is definitely not a subclass of base).
180 /// The distinction of this case from the next one is necessary to model
181 /// dynamic_cast.
182 /// - We don't know (base is a symbolic region and we don't have
183 /// enough info to determine if the cast will succeed at run time).
184 /// The function returns an optional with SVal representing the derived class
185 /// in case of a successful cast and `std::nullopt` otherwise.
186 std::optional<SVal> evalBaseToDerived(SVal Base, QualType DerivedPtrType);
187
189
190 /// castRegion - Used by ExprEngine::VisitCast to handle casts from
191 /// a MemRegion* to a specific location type. 'R' is the region being
192 /// casted and 'CastToTy' the result type of the cast.
193 std::optional<const MemRegion *> castRegion(const MemRegion *region,
194 QualType CastToTy);
195
197 SymbolReaper &SymReaper) = 0;
198
199 virtual bool includedInBindings(Store store,
200 const MemRegion *region) const = 0;
201
202 /// If the StoreManager supports it, increment the reference count of
203 /// the specified Store object.
204 virtual void incrementReferenceCount(Store store) {}
205
206 /// If the StoreManager supports it, decrement the reference count of
207 /// the specified Store object. If the reference count hits 0, the memory
208 /// associated with the object is recycled.
209 virtual void decrementReferenceCount(Store store) {}
210
212
213 /// invalidateRegions - Clears out the specified regions from the store,
214 /// marking their values as unknown. Depending on the store, this may also
215 /// invalidate additional regions that may have changed based on accessing
216 /// the given regions. If \p Call is non-null, then this also invalidates
217 /// non-static globals (but if \p Call is from a system header, then this is
218 /// limited to globals declared in system headers).
219 ///
220 /// Instead of calling this method directly, you should probably use
221 /// \c ProgramState::invalidateRegions, which calls this and then ensures that
222 /// the relevant checker callbacks are triggered.
223 ///
224 /// \param[in] store The initial store.
225 /// \param[in] Values The values to invalidate.
226 /// \param[in] Elem The current CFG Element being evaluated. Used to conjure
227 /// symbols to mark the values of invalidated regions.
228 /// \param[in] Count The current block count. Used to conjure
229 /// symbols to mark the values of invalidated regions.
230 /// \param[in] Call The call expression which will be used to determine which
231 /// globals should get invalidated.
232 /// \param[in,out] IS A set to fill with any symbols that are no longer
233 /// accessible. Pass \c NULL if this information will not be used.
234 /// \param[in] ITraits Information about invalidation for a particular
235 /// region/symbol.
236 /// \param[in,out] InvalidatedTopLevel A vector to fill with regions
237 //// explicitly being invalidated. Pass \c NULL if this
238 /// information will not be used.
239 /// \param[in,out] Invalidated A vector to fill with any regions being
240 /// invalidated. This should include any regions explicitly invalidated
241 /// even if they do not currently have bindings. Pass \c NULL if this
242 /// information will not be used.
244 Store store, ArrayRef<SVal> Values, ConstCFGElementRef Elem,
245 unsigned Count, const LocationContext *LCtx, const CallEvent *Call,
247 InvalidatedRegions *TopLevelRegions, InvalidatedRegions *Invalidated) = 0;
248
249 /// enterStackFrame - Let the StoreManager to do something when execution
250 /// engine is about to execute into a callee.
252 const StackFrameContext *CalleeCtx);
253
254 /// Finds the transitive closure of symbols within the given region.
255 ///
256 /// Returns false if the visitor aborted the scan.
257 virtual bool scanReachableSymbols(Store S, const MemRegion *R,
258 ScanReachableSymbols &Visitor) = 0;
259
260 virtual void printJson(raw_ostream &Out, Store S, const char *NL,
261 unsigned int Space, bool IsDot) const = 0;
262
264 public:
266
267 /// \return whether the iteration should continue.
268 virtual bool HandleBinding(StoreManager& SMgr, Store store,
269 const MemRegion *region, SVal val) = 0;
270 };
271
273 SymbolRef Sym;
274 const MemRegion* Binding = nullptr;
275 bool First = true;
276
277 public:
278 FindUniqueBinding(SymbolRef sym) : Sym(sym) {}
279
280 explicit operator bool() { return First && Binding; }
281
282 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
283 SVal val) override;
284 const MemRegion *getRegion() { return Binding; }
285 };
286
287 /// iterBindings - Iterate over the bindings in the Store.
288 virtual void iterBindings(Store store, BindingsHandler& f) = 0;
289
290protected:
291 const ElementRegion *MakeElementRegion(const SubRegion *baseRegion,
292 QualType pointeeTy,
293 uint64_t index = 0);
294
295private:
296 SVal getLValueFieldOrIvar(const Decl *decl, SVal base);
297};
298
300 : store(store), mgr(smgr) {
301 if (store)
302 mgr.incrementReferenceCount(store);
303}
304
306 : store(sr.store), mgr(sr.mgr)
307{
308 if (store)
309 mgr.incrementReferenceCount(store);
310}
311
313 if (store)
314 mgr.decrementReferenceCount(store);
315}
316
317inline StoreRef &StoreRef::operator=(StoreRef const &newStore) {
318 assert(&newStore.mgr == &mgr);
319 if (store != newStore.store) {
320 mgr.incrementReferenceCount(newStore.store);
321 mgr.decrementReferenceCount(store);
322 store = newStore.getStore();
323 }
324 return *this;
325}
326
327// FIXME: Do we need to pass ProgramStateManager anymore?
328std::unique_ptr<StoreManager>
330
331} // namespace ento
332
333} // namespace clang
334
335#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_STORE_H
#define V(N, I)
Definition: ASTContext.h:3597
const Decl * D
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3612
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3541
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Represents a member of a struct/union/class.
Definition: Decl.h:3157
It wraps the AnalysisDeclContext to represent both the call stack with the help of StackFrameContext ...
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1952
A (possibly-)qualified type.
Definition: TypeBase.h:937
It represents a stack frame of the call stack (based on CallEvent).
Represents a variable declaration or definition.
Definition: Decl.h:925
Represents an abstract call to a function or method along a particular path.
Definition: CallEvent.h:153
ElementRegion is used to represent both array elements and casts.
Definition: MemRegion.h:1227
const CompoundLiteralRegion * getCompoundLiteralRegion(const CompoundLiteralExpr *CL, const LocationContext *LC)
getCompoundLiteralRegion - Retrieve the region associated with a given CompoundLiteral.
Definition: MemRegion.cpp:1201
const VarRegion * getVarRegion(const VarDecl *VD, const LocationContext *LC)
getVarRegion - Retrieve or create the memory region associated with a specified VarDecl and LocationC...
Definition: MemRegion.cpp:1041
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:98
Information about invalidation for a particular region/symbol.
Definition: MemRegion.h:1657
loc::MemRegionVal makeLoc(SymbolRef sym)
Definition: SValBuilder.h:363
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition: SVals.h:56
A utility class that visits the reachable symbols using a custom SymbolVisitor.
Definition: ProgramState.h:890
virtual bool HandleBinding(StoreManager &SMgr, Store store, const MemRegion *region, SVal val)=0
bool HandleBinding(StoreManager &SMgr, Store store, const MemRegion *R, SVal val) override
Definition: Store.cpp:531
SVal evalDerivedToBase(SVal Derived, const CastExpr *Cast)
Evaluates a chain of derived-to-base casts through the path specified in Cast.
Definition: Store.cpp:254
ProgramStateManager & StateMgr
Definition: Store.h:64
SValBuilder & getSValBuilder()
Definition: Store.h:141
virtual StoreRef invalidateRegions(Store store, ArrayRef< SVal > Values, ConstCFGElementRef Elem, unsigned Count, const LocationContext *LCtx, const CallEvent *Call, InvalidatedSymbols &IS, RegionAndSymbolInvalidationTraits &ITraits, InvalidatedRegions *TopLevelRegions, InvalidatedRegions *Invalidated)=0
invalidateRegions - Clears out the specified regions from the store, marking their values as unknown.
virtual SVal getLValueField(const FieldDecl *D, SVal Base)
Definition: Store.h:154
virtual bool scanReachableSymbols(Store S, const MemRegion *R, ScanReachableSymbols &Visitor)=0
Finds the transitive closure of symbols within the given region.
MemRegionManager & getRegionManager()
getRegionManager - Returns the internal RegionManager object that is used to query and manipulate Mem...
Definition: Store.h:139
std::optional< SVal > evalBaseToDerived(SVal Base, QualType DerivedPtrType)
Attempts to do a down cast.
Definition: Store.cpp:318
BindResult enterStackFrame(Store store, const CallEvent &Call, const StackFrameContext *CalleeCtx)
enterStackFrame - Let the StoreManager to do something when execution engine is about to execute into...
Definition: Store.cpp:45
const ElementRegion * MakeElementRegion(const SubRegion *baseRegion, QualType pointeeTy, uint64_t index=0)
Definition: Store.cpp:62
virtual BindResult Bind(Store store, Loc loc, SVal val)=0
Return a store with the specified value bound to the given location.
virtual void iterBindings(Store store, BindingsHandler &f)=0
iterBindings - Iterate over the bindings in the Store.
MemRegionManager & MRMgr
MRMgr - Manages region objects associated with this StoreManager.
Definition: Store.h:67
SValBuilder & svalBuilder
Definition: Store.h:63
virtual BindResult BindDefaultZero(Store store, const MemRegion *R)=0
Return a store with in which all values within the given region are reset to zero.
virtual StoreRef getInitialStore(const LocationContext *InitLoc)=0
getInitialStore - Returns the initial "empty" store representing the value bindings upon entry to an ...
virtual SVal getLValueIvar(const ObjCIvarDecl *decl, SVal base)
Definition: Store.cpp:441
virtual std::optional< SVal > getDefaultBinding(Store store, const MemRegion *R)=0
Return the default value bound to a region in a given store.
virtual StoreRef killBinding(Store ST, Loc L)=0
Create a new store with the specified binding removed.
virtual void decrementReferenceCount(Store store)
If the StoreManager supports it, decrement the reference count of the specified Store object.
Definition: Store.h:209
virtual StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx, SymbolReaper &SymReaper)=0
virtual ~StoreManager()=default
virtual void incrementReferenceCount(Store store)
If the StoreManager supports it, increment the reference count of the specified Store object.
Definition: Store.h:204
virtual SVal ArrayToPointer(Loc Array, QualType ElementTy)=0
ArrayToPointer - Used by ExprEngine::VistCast to handle implicit conversions between arrays and point...
virtual bool includedInBindings(Store store, const MemRegion *region) const =0
virtual SVal getBinding(Store store, Loc loc, QualType T=QualType())=0
Return the value bound to specified location in a given state.
std::optional< SVal > getDefaultBinding(nonloc::LazyCompoundVal lcv)
Return the default value bound to a LazyCompoundVal.
Definition: Store.h:105
virtual Loc getLValueVar(const VarDecl *VD, const LocationContext *LC)
Definition: Store.h:143
const ElementRegion * GetElementZeroRegion(const SubRegion *R, QualType T)
Definition: Store.cpp:69
virtual BindResult BindDefaultInitial(Store store, const MemRegion *R, SVal V)=0
Return a store with the specified value bound to all sub-regions of the region.
virtual SVal getLValueElement(QualType elementType, NonLoc offset, SVal Base)
Definition: Store.cpp:445
virtual void printJson(raw_ostream &Out, Store S, const char *NL, unsigned int Space, bool IsDot) const =0
std::optional< const MemRegion * > castRegion(const MemRegion *region, QualType CastToTy)
castRegion - Used by ExprEngine::VisitCast to handle casts from a MemRegion* to a specific location t...
Definition: Store.cpp:76
ASTContext & Ctx
Definition: Store.h:68
Loc getLValueCompoundLiteral(const CompoundLiteralExpr *CL, const LocationContext *LC)
Definition: Store.h:147
Store getStore() const
Definition: StoreRef.h:46
StoreRef & operator=(StoreRef const &newStore)
Definition: Store.h:317
StoreRef(Store store, StoreManager &smgr)
Definition: Store.h:299
SubRegion - A region that subsets another larger region.
Definition: MemRegion.h:474
Symbolic value.
Definition: SymExpr.h:32
A class responsible for cleaning up unused symbols.
While nonloc::CompoundVal covers a few simple use cases, nonloc::LazyCompoundVal is a more performant...
Definition: SVals.h:389
LLVM_ATTRIBUTE_RETURNS_NONNULL const TypedValueRegion * getRegion() const
This function itself is immaterial.
Definition: SVals.cpp:193
const void * getStore() const
It might return null.
Definition: SVals.cpp:189
#define bool
Definition: gpuintrin.h:32
Definition: SPIR.cpp:35
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
llvm::DenseSet< SymbolRef > InvalidatedSymbols
Definition: Store.h:51
std::unique_ptr< StoreManager > CreateRegionStoreManager(ProgramStateManager &StMgr)
const void * Store
Store - This opaque type encapsulates an immutable mapping from locations to values.
Definition: StoreRef.h:27
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Definition: ModuleMapFile.h:36
The JSON file list parser is used to communicate input to InstallAPI.
CFGBlock::ConstCFGElementRef ConstCFGElementRef
Definition: CFG.h:1199
const FunctionProtoType * T
llvm::SmallVector< SVal, 0 > FailedToBindValues
Definition: Store.h:58
StoreRef ResultingStore
Definition: Store.h:54