1 //== ProgramState.h - 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 defines the state of the program along the analysisa path.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATE_H
15 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATE_H
17 #include "clang/Basic/LLVM.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/Environment.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/TaintTag.h"
25 #include "llvm/ADT/FoldingSet.h"
26 #include "llvm/ADT/ImmutableMap.h"
27 #include "llvm/Support/Allocator.h"
40 class CallEventManager;
42 typedef std::unique_ptr<ConstraintManager>(*ConstraintManagerCreator)(
43 ProgramStateManager &, SubEngine *);
44 typedef std::unique_ptr<StoreManager>(*StoreManagerCreator)(
45 ProgramStateManager &);
46 typedef llvm::ImmutableMap<const SubRegion*, TaintTagType> TaintedSubRegions;
48 //===----------------------------------------------------------------------===//
49 // ProgramStateTrait - Traits used by the Generic Data Map of a ProgramState.
50 //===----------------------------------------------------------------------===//
52 template <typename T> struct ProgramStatePartialTrait;
54 template <typename T> struct ProgramStateTrait {
55 typedef typename T::data_type data_type;
56 static inline void *MakeVoidPtr(data_type D) { return (void*) D; }
57 static inline data_type MakeData(void *const* P) {
58 return P ? (data_type) *P : (data_type) 0;
62 /// \class ProgramState
63 /// ProgramState - This class encapsulates:
65 /// 1. A mapping from expressions to values (Environment)
66 /// 2. A mapping from locations to values (Store)
67 /// 3. Constraints on symbolic values (GenericDataMap)
69 /// Together these represent the "abstract state" of a program.
71 /// ProgramState is intended to be used as a functional object; that is,
72 /// once it is created and made "persistent" in a FoldingSet, its
73 /// values will never change.
74 class ProgramState : public llvm::FoldingSetNode {
76 typedef llvm::ImmutableSet<llvm::APSInt*> IntSetTy;
77 typedef llvm::ImmutableMap<void*, void*> GenericDataMap;
80 void operator=(const ProgramState& R) = delete;
82 friend class ProgramStateManager;
83 friend class ExplodedGraph;
84 friend class ExplodedNode;
86 ProgramStateManager *stateMgr;
87 Environment Env; // Maps a Stmt to its current SVal.
88 Store store; // Maps a location to its current value.
89 GenericDataMap GDM; // Custom data stored by a client of this class.
92 /// makeWithStore - Return a ProgramState with the same values as the current
93 /// state with the exception of using the specified Store.
94 ProgramStateRef makeWithStore(const StoreRef &store) const;
96 void setStore(const StoreRef &storeRef);
99 /// This ctor is used when creating the first ProgramState object.
100 ProgramState(ProgramStateManager *mgr, const Environment& env,
101 StoreRef st, GenericDataMap gdm);
103 /// Copy ctor - We must explicitly define this or else the "Next" ptr
104 /// in FoldingSetNode will also get copied.
105 ProgramState(const ProgramState &RHS);
109 /// Return the ProgramStateManager associated with this state.
110 ProgramStateManager &getStateManager() const {
114 /// Return the ConstraintManager.
115 ConstraintManager &getConstraintManager() const;
117 /// getEnvironment - Return the environment associated with this state.
118 /// The environment is the mapping from expressions to values.
119 const Environment& getEnvironment() const { return Env; }
121 /// Return the store associated with this state. The store
122 /// is a mapping from locations to values.
123 Store getStore() const { return store; }
126 /// getGDM - Return the generic data map associated with this state.
127 GenericDataMap getGDM() const { return GDM; }
129 void setGDM(GenericDataMap gdm) { GDM = gdm; }
131 /// Profile - Profile the contents of a ProgramState object for use in a
132 /// FoldingSet. Two ProgramState objects are considered equal if they
133 /// have the same Environment, Store, and GenericDataMap.
134 static void Profile(llvm::FoldingSetNodeID& ID, const ProgramState *V) {
136 ID.AddPointer(V->store);
140 /// Profile - Used to profile the contents of this object for inclusion
142 void Profile(llvm::FoldingSetNodeID& ID) const {
146 BasicValueFactory &getBasicVals() const;
147 SymbolManager &getSymbolManager() const;
149 //==---------------------------------------------------------------------==//
150 // Constraints on values.
151 //==---------------------------------------------------------------------==//
153 // Each ProgramState records constraints on symbolic values. These constraints
154 // are managed using the ConstraintManager associated with a ProgramStateManager.
155 // As constraints gradually accrue on symbolic values, added constraints
156 // may conflict and indicate that a state is infeasible (as no real values
157 // could satisfy all the constraints). This is the principal mechanism
158 // for modeling path-sensitivity in ExprEngine/ProgramState.
160 // Various "assume" methods form the interface for adding constraints to
161 // symbolic values. A call to 'assume' indicates an assumption being placed
162 // on one or symbolic values. 'assume' methods take the following inputs:
164 // (1) A ProgramState object representing the current state.
166 // (2) The assumed constraint (which is specific to a given "assume" method).
168 // (3) A binary value "Assumption" that indicates whether the constraint is
169 // assumed to be true or false.
171 // The output of "assume*" is a new ProgramState object with the added constraints.
172 // If no new state is feasible, NULL is returned.
175 /// Assumes that the value of \p cond is zero (if \p assumption is "false")
176 /// or non-zero (if \p assumption is "true").
178 /// This returns a new state with the added constraint on \p cond.
179 /// If no new state is feasible, NULL is returned.
180 LLVM_NODISCARD ProgramStateRef assume(DefinedOrUnknownSVal cond,
181 bool assumption) const;
183 /// Assumes both "true" and "false" for \p cond, and returns both
184 /// corresponding states (respectively).
186 /// This is more efficient than calling assume() twice. Note that one (but not
187 /// both) of the returned states may be NULL.
188 LLVM_NODISCARD std::pair<ProgramStateRef, ProgramStateRef>
189 assume(DefinedOrUnknownSVal cond) const;
191 LLVM_NODISCARD ProgramStateRef
192 assumeInBound(DefinedOrUnknownSVal idx, DefinedOrUnknownSVal upperBound,
193 bool assumption, QualType IndexType = QualType()) const;
195 /// Assumes that the value of \p Val is bounded with [\p From; \p To]
196 /// (if \p assumption is "true") or it is fully out of this range
197 /// (if \p assumption is "false").
199 /// This returns a new state with the added constraint on \p cond.
200 /// If no new state is feasible, NULL is returned.
201 LLVM_NODISCARD ProgramStateRef assumeInclusiveRange(DefinedOrUnknownSVal Val,
202 const llvm::APSInt &From,
203 const llvm::APSInt &To,
204 bool assumption) const;
206 /// Assumes given range both "true" and "false" for \p Val, and returns both
207 /// corresponding states (respectively).
209 /// This is more efficient than calling assume() twice. Note that one (but not
210 /// both) of the returned states may be NULL.
211 LLVM_NODISCARD std::pair<ProgramStateRef, ProgramStateRef>
212 assumeInclusiveRange(DefinedOrUnknownSVal Val, const llvm::APSInt &From,
213 const llvm::APSInt &To) const;
215 /// Check if the given SVal is not constrained to zero and is not
217 ConditionTruthVal isNonNull(SVal V) const;
219 /// Check if the given SVal is constrained to zero or is a zero
221 ConditionTruthVal isNull(SVal V) const;
223 /// \return Whether values \p Lhs and \p Rhs are equal.
224 ConditionTruthVal areEqual(SVal Lhs, SVal Rhs) const;
226 /// Utility method for getting regions.
227 const VarRegion* getRegion(const VarDecl *D, const LocationContext *LC) const;
229 //==---------------------------------------------------------------------==//
230 // Binding and retrieving values to/from the environment and symbolic store.
231 //==---------------------------------------------------------------------==//
233 /// Create a new state by binding the value 'V' to the statement 'S' in the
234 /// state's environment.
235 LLVM_NODISCARD ProgramStateRef BindExpr(const Stmt *S,
236 const LocationContext *LCtx, SVal V,
237 bool Invalidate = true) const;
239 LLVM_NODISCARD ProgramStateRef bindLoc(Loc location, SVal V,
240 const LocationContext *LCtx,
241 bool notifyChanges = true) const;
243 LLVM_NODISCARD ProgramStateRef bindLoc(SVal location, SVal V,
244 const LocationContext *LCtx) const;
246 /// Initializes the region of memory represented by \p loc with an initial
247 /// value. Once initialized, all values loaded from any sub-regions of that
248 /// region will be equal to \p V, unless overwritten later by the program.
249 /// This method should not be used on regions that are already initialized.
250 /// If you need to indicate that memory contents have suddenly become unknown
251 /// within a certain region of memory, consider invalidateRegions().
252 LLVM_NODISCARD ProgramStateRef
253 bindDefaultInitial(SVal loc, SVal V, const LocationContext *LCtx) const;
255 /// Performs C++ zero-initialization procedure on the region of memory
256 /// represented by \p loc.
257 LLVM_NODISCARD ProgramStateRef
258 bindDefaultZero(SVal loc, const LocationContext *LCtx) const;
260 LLVM_NODISCARD ProgramStateRef killBinding(Loc LV) const;
262 /// Returns the state with bindings for the given regions
263 /// cleared from the store.
265 /// Optionally invalidates global regions as well.
267 /// \param Regions the set of regions to be invalidated.
268 /// \param E the expression that caused the invalidation.
269 /// \param BlockCount The number of times the current basic block has been
271 /// \param CausesPointerEscape the flag is set to true when
272 /// the invalidation entails escape of a symbol (representing a
273 /// pointer). For example, due to it being passed as an argument in a
275 /// \param IS the set of invalidated symbols.
276 /// \param Call if non-null, the invalidated regions represent parameters to
277 /// the call and should be considered directly invalidated.
278 /// \param ITraits information about special handling for a particular
280 LLVM_NODISCARD ProgramStateRef
281 invalidateRegions(ArrayRef<const MemRegion *> Regions, const Expr *E,
282 unsigned BlockCount, const LocationContext *LCtx,
283 bool CausesPointerEscape, InvalidatedSymbols *IS = nullptr,
284 const CallEvent *Call = nullptr,
285 RegionAndSymbolInvalidationTraits *ITraits = nullptr) const;
287 LLVM_NODISCARD ProgramStateRef
288 invalidateRegions(ArrayRef<SVal> Regions, const Expr *E,
289 unsigned BlockCount, const LocationContext *LCtx,
290 bool CausesPointerEscape, InvalidatedSymbols *IS = nullptr,
291 const CallEvent *Call = nullptr,
292 RegionAndSymbolInvalidationTraits *ITraits = nullptr) const;
294 /// enterStackFrame - Returns the state for entry to the given stack frame,
295 /// preserving the current state.
296 LLVM_NODISCARD ProgramStateRef enterStackFrame(
297 const CallEvent &Call, const StackFrameContext *CalleeCtx) const;
299 /// Get the lvalue for a base class object reference.
300 Loc getLValue(const CXXBaseSpecifier &BaseSpec, const SubRegion *Super) const;
302 /// Get the lvalue for a base class object reference.
303 Loc getLValue(const CXXRecordDecl *BaseClass, const SubRegion *Super,
304 bool IsVirtual) const;
306 /// Get the lvalue for a variable reference.
307 Loc getLValue(const VarDecl *D, const LocationContext *LC) const;
309 Loc getLValue(const CompoundLiteralExpr *literal,
310 const LocationContext *LC) const;
312 /// Get the lvalue for an ivar reference.
313 SVal getLValue(const ObjCIvarDecl *decl, SVal base) const;
315 /// Get the lvalue for a field reference.
316 SVal getLValue(const FieldDecl *decl, SVal Base) const;
318 /// Get the lvalue for an indirect field reference.
319 SVal getLValue(const IndirectFieldDecl *decl, SVal Base) const;
321 /// Get the lvalue for an array index.
322 SVal getLValue(QualType ElementType, SVal Idx, SVal Base) const;
324 /// Returns the SVal bound to the statement 'S' in the state's environment.
325 SVal getSVal(const Stmt *S, const LocationContext *LCtx) const;
327 SVal getSValAsScalarOrLoc(const Stmt *Ex, const LocationContext *LCtx) const;
329 /// Return the value bound to the specified location.
330 /// Returns UnknownVal() if none found.
331 SVal getSVal(Loc LV, QualType T = QualType()) const;
333 /// Returns the "raw" SVal bound to LV before any value simplfication.
334 SVal getRawSVal(Loc LV, QualType T= QualType()) const;
336 /// Return the value bound to the specified location.
337 /// Returns UnknownVal() if none found.
338 SVal getSVal(const MemRegion* R, QualType T = QualType()) const;
340 /// Return the value bound to the specified location, assuming
341 /// that the value is a scalar integer or an enumeration or a pointer.
342 /// Returns UnknownVal() if none found or the region is not known to hold
343 /// a value of such type.
344 SVal getSValAsScalarOrLoc(const MemRegion *R) const;
346 /// Visits the symbols reachable from the given SVal using the provided
349 /// This is a convenience API. Consider using ScanReachableSymbols class
350 /// directly when making multiple scans on the same state with the same
351 /// visitor to avoid repeated initialization cost.
352 /// \sa ScanReachableSymbols
353 bool scanReachableSymbols(SVal val, SymbolVisitor& visitor) const;
355 /// Visits the symbols reachable from the SVals in the given range
356 /// using the provided SymbolVisitor.
357 bool scanReachableSymbols(const SVal *I, const SVal *E,
358 SymbolVisitor &visitor) const;
360 /// Visits the symbols reachable from the regions in the given
361 /// MemRegions range using the provided SymbolVisitor.
362 bool scanReachableSymbols(const MemRegion * const *I,
363 const MemRegion * const *E,
364 SymbolVisitor &visitor) const;
366 template <typename CB> CB scanReachableSymbols(SVal val) const;
367 template <typename CB> CB scanReachableSymbols(const SVal *beg,
368 const SVal *end) const;
370 template <typename CB> CB
371 scanReachableSymbols(const MemRegion * const *beg,
372 const MemRegion * const *end) const;
374 /// Create a new state in which the statement is marked as tainted.
375 LLVM_NODISCARD ProgramStateRef
376 addTaint(const Stmt *S, const LocationContext *LCtx,
377 TaintTagType Kind = TaintTagGeneric) const;
379 /// Create a new state in which the value is marked as tainted.
380 LLVM_NODISCARD ProgramStateRef
381 addTaint(SVal V, TaintTagType Kind = TaintTagGeneric) const;
383 /// Create a new state in which the symbol is marked as tainted.
384 LLVM_NODISCARD ProgramStateRef addTaint(SymbolRef S,
385 TaintTagType Kind = TaintTagGeneric) const;
387 /// Create a new state in which the region symbol is marked as tainted.
388 LLVM_NODISCARD ProgramStateRef
389 addTaint(const MemRegion *R, TaintTagType Kind = TaintTagGeneric) const;
391 /// Create a new state in a which a sub-region of a given symbol is tainted.
392 /// This might be necessary when referring to regions that can not have an
393 /// individual symbol, e.g. if they are represented by the default binding of
394 /// a LazyCompoundVal.
395 LLVM_NODISCARD ProgramStateRef
396 addPartialTaint(SymbolRef ParentSym, const SubRegion *SubRegion,
397 TaintTagType Kind = TaintTagGeneric) const;
399 /// Check if the statement is tainted in the current state.
400 bool isTainted(const Stmt *S, const LocationContext *LCtx,
401 TaintTagType Kind = TaintTagGeneric) const;
402 bool isTainted(SVal V, TaintTagType Kind = TaintTagGeneric) const;
403 bool isTainted(SymbolRef Sym, TaintTagType Kind = TaintTagGeneric) const;
404 bool isTainted(const MemRegion *Reg, TaintTagType Kind=TaintTagGeneric) const;
406 //==---------------------------------------------------------------------==//
407 // Accessing the Generic Data Map (GDM).
408 //==---------------------------------------------------------------------==//
410 void *const* FindGDM(void *K) const;
412 template <typename T>
413 LLVM_NODISCARD ProgramStateRef
414 add(typename ProgramStateTrait<T>::key_type K) const;
416 template <typename T>
417 typename ProgramStateTrait<T>::data_type
419 return ProgramStateTrait<T>::MakeData(FindGDM(ProgramStateTrait<T>::GDMIndex()));
423 typename ProgramStateTrait<T>::lookup_type
424 get(typename ProgramStateTrait<T>::key_type key) const {
425 void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
426 return ProgramStateTrait<T>::Lookup(ProgramStateTrait<T>::MakeData(d), key);
429 template <typename T>
430 typename ProgramStateTrait<T>::context_type get_context() const;
432 template <typename T>
433 LLVM_NODISCARD ProgramStateRef
434 remove(typename ProgramStateTrait<T>::key_type K) const;
436 template <typename T>
437 LLVM_NODISCARD ProgramStateRef
438 remove(typename ProgramStateTrait<T>::key_type K,
439 typename ProgramStateTrait<T>::context_type C) const;
441 template <typename T> LLVM_NODISCARD ProgramStateRef remove() const;
443 template <typename T>
444 LLVM_NODISCARD ProgramStateRef
445 set(typename ProgramStateTrait<T>::data_type D) const;
447 template <typename T>
448 LLVM_NODISCARD ProgramStateRef
449 set(typename ProgramStateTrait<T>::key_type K,
450 typename ProgramStateTrait<T>::value_type E) const;
452 template <typename T>
453 LLVM_NODISCARD ProgramStateRef
454 set(typename ProgramStateTrait<T>::key_type K,
455 typename ProgramStateTrait<T>::value_type E,
456 typename ProgramStateTrait<T>::context_type C) const;
459 bool contains(typename ProgramStateTrait<T>::key_type key) const {
460 void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
461 return ProgramStateTrait<T>::Contains(ProgramStateTrait<T>::MakeData(d), key);
465 void print(raw_ostream &Out, const char *nl = "\n", const char *sep = "",
466 const LocationContext *CurrentLC = nullptr) const;
467 void printDOT(raw_ostream &Out,
468 const LocationContext *CurrentLC = nullptr) const;
469 void printTaint(raw_ostream &Out, const char *nl = "\n",
470 const char *sep = "") const;
473 void dumpTaint() const;
476 friend void ProgramStateRetain(const ProgramState *state);
477 friend void ProgramStateRelease(const ProgramState *state);
479 /// \sa invalidateValues()
480 /// \sa invalidateRegions()
482 invalidateRegionsImpl(ArrayRef<SVal> Values,
483 const Expr *E, unsigned BlockCount,
484 const LocationContext *LCtx,
485 bool ResultsInSymbolEscape,
486 InvalidatedSymbols *IS,
487 RegionAndSymbolInvalidationTraits *HTraits,
488 const CallEvent *Call) const;
491 //===----------------------------------------------------------------------===//
492 // ProgramStateManager - Factory object for ProgramStates.
493 //===----------------------------------------------------------------------===//
495 class ProgramStateManager {
496 friend class ProgramState;
497 friend void ProgramStateRelease(const ProgramState *state);
499 /// Eng - The SubEngine that owns this state manager.
500 SubEngine *Eng; /* Can be null. */
502 EnvironmentManager EnvMgr;
503 std::unique_ptr<StoreManager> StoreMgr;
504 std::unique_ptr<ConstraintManager> ConstraintMgr;
506 ProgramState::GenericDataMap::Factory GDMFactory;
507 TaintedSubRegions::Factory TSRFactory;
509 typedef llvm::DenseMap<void*,std::pair<void*,void (*)(void*)> > GDMContextsTy;
510 GDMContextsTy GDMContexts;
512 /// StateSet - FoldingSet containing all the states created for analyzing
513 /// a particular function. This is used to unique states.
514 llvm::FoldingSet<ProgramState> StateSet;
516 /// Object that manages the data for all created SVals.
517 std::unique_ptr<SValBuilder> svalBuilder;
519 /// Manages memory for created CallEvents.
520 std::unique_ptr<CallEventManager> CallEventMgr;
522 /// A BumpPtrAllocator to allocate states.
523 llvm::BumpPtrAllocator &Alloc;
525 /// A vector of ProgramStates that we can reuse.
526 std::vector<ProgramState *> freeStates;
529 ProgramStateManager(ASTContext &Ctx,
530 StoreManagerCreator CreateStoreManager,
531 ConstraintManagerCreator CreateConstraintManager,
532 llvm::BumpPtrAllocator& alloc,
535 ~ProgramStateManager();
537 ProgramStateRef getInitialState(const LocationContext *InitLoc);
539 ASTContext &getContext() { return svalBuilder->getContext(); }
540 const ASTContext &getContext() const { return svalBuilder->getContext(); }
542 BasicValueFactory &getBasicVals() {
543 return svalBuilder->getBasicValueFactory();
546 SValBuilder &getSValBuilder() {
550 SymbolManager &getSymbolManager() {
551 return svalBuilder->getSymbolManager();
553 const SymbolManager &getSymbolManager() const {
554 return svalBuilder->getSymbolManager();
557 llvm::BumpPtrAllocator& getAllocator() { return Alloc; }
559 MemRegionManager& getRegionManager() {
560 return svalBuilder->getRegionManager();
562 const MemRegionManager& getRegionManager() const {
563 return svalBuilder->getRegionManager();
566 CallEventManager &getCallEventManager() { return *CallEventMgr; }
568 StoreManager& getStoreManager() { return *StoreMgr; }
569 ConstraintManager& getConstraintManager() { return *ConstraintMgr; }
570 SubEngine* getOwningEngine() { return Eng; }
572 ProgramStateRef removeDeadBindings(ProgramStateRef St,
573 const StackFrameContext *LCtx,
574 SymbolReaper& SymReaper);
578 SVal ArrayToPointer(Loc Array, QualType ElementTy) {
579 return StoreMgr->ArrayToPointer(Array, ElementTy);
582 // Methods that manipulate the GDM.
583 ProgramStateRef addGDM(ProgramStateRef St, void *Key, void *Data);
584 ProgramStateRef removeGDM(ProgramStateRef state, void *Key);
586 // Methods that query & manipulate the Store.
588 void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler& F) {
589 StoreMgr->iterBindings(state->getStore(), F);
592 ProgramStateRef getPersistentState(ProgramState &Impl);
593 ProgramStateRef getPersistentStateWithGDM(ProgramStateRef FromState,
594 ProgramStateRef GDMState);
596 bool haveEqualEnvironments(ProgramStateRef S1, ProgramStateRef S2) {
597 return S1->Env == S2->Env;
600 bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2) {
601 return S1->store == S2->store;
604 //==---------------------------------------------------------------------==//
605 // Generic Data Map methods.
606 //==---------------------------------------------------------------------==//
608 // ProgramStateManager and ProgramState support a "generic data map" that allows
609 // different clients of ProgramState objects to embed arbitrary data within a
610 // ProgramState object. The generic data map is essentially an immutable map
611 // from a "tag" (that acts as the "key" for a client) and opaque values.
612 // Tags/keys and values are simply void* values. The typical way that clients
613 // generate unique tags are by taking the address of a static variable.
614 // Clients are responsible for ensuring that data values referred to by a
615 // the data pointer are immutable (and thus are essentially purely functional
618 // The templated methods below use the ProgramStateTrait<T> class
619 // to resolve keys into the GDM and to return data values to clients.
622 // Trait based GDM dispatch.
623 template <typename T>
624 ProgramStateRef set(ProgramStateRef st, typename ProgramStateTrait<T>::data_type D) {
625 return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
626 ProgramStateTrait<T>::MakeVoidPtr(D));
630 ProgramStateRef set(ProgramStateRef st,
631 typename ProgramStateTrait<T>::key_type K,
632 typename ProgramStateTrait<T>::value_type V,
633 typename ProgramStateTrait<T>::context_type C) {
635 return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
636 ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Set(st->get<T>(), K, V, C)));
639 template <typename T>
640 ProgramStateRef add(ProgramStateRef st,
641 typename ProgramStateTrait<T>::key_type K,
642 typename ProgramStateTrait<T>::context_type C) {
643 return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
644 ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Add(st->get<T>(), K, C)));
647 template <typename T>
648 ProgramStateRef remove(ProgramStateRef st,
649 typename ProgramStateTrait<T>::key_type K,
650 typename ProgramStateTrait<T>::context_type C) {
652 return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
653 ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Remove(st->get<T>(), K, C)));
656 template <typename T>
657 ProgramStateRef remove(ProgramStateRef st) {
658 return removeGDM(st, ProgramStateTrait<T>::GDMIndex());
661 void *FindGDMContext(void *index,
662 void *(*CreateContext)(llvm::BumpPtrAllocator&),
663 void (*DeleteContext)(void*));
665 template <typename T>
666 typename ProgramStateTrait<T>::context_type get_context() {
667 void *p = FindGDMContext(ProgramStateTrait<T>::GDMIndex(),
668 ProgramStateTrait<T>::CreateContext,
669 ProgramStateTrait<T>::DeleteContext);
671 return ProgramStateTrait<T>::MakeContext(p);
674 void EndPath(ProgramStateRef St) {
675 ConstraintMgr->EndPath(St);
680 //===----------------------------------------------------------------------===//
681 // Out-of-line method definitions for ProgramState.
682 //===----------------------------------------------------------------------===//
684 inline ConstraintManager &ProgramState::getConstraintManager() const {
685 return stateMgr->getConstraintManager();
688 inline const VarRegion* ProgramState::getRegion(const VarDecl *D,
689 const LocationContext *LC) const
691 return getStateManager().getRegionManager().getVarRegion(D, LC);
694 inline ProgramStateRef ProgramState::assume(DefinedOrUnknownSVal Cond,
695 bool Assumption) const {
696 if (Cond.isUnknown())
699 return getStateManager().ConstraintMgr
700 ->assume(this, Cond.castAs<DefinedSVal>(), Assumption);
703 inline std::pair<ProgramStateRef , ProgramStateRef >
704 ProgramState::assume(DefinedOrUnknownSVal Cond) const {
705 if (Cond.isUnknown())
706 return std::make_pair(this, this);
708 return getStateManager().ConstraintMgr
709 ->assumeDual(this, Cond.castAs<DefinedSVal>());
712 inline ProgramStateRef ProgramState::assumeInclusiveRange(
713 DefinedOrUnknownSVal Val, const llvm::APSInt &From, const llvm::APSInt &To,
714 bool Assumption) const {
718 assert(Val.getAs<NonLoc>() && "Only NonLocs are supported!");
720 return getStateManager().ConstraintMgr->assumeInclusiveRange(
721 this, Val.castAs<NonLoc>(), From, To, Assumption);
724 inline std::pair<ProgramStateRef, ProgramStateRef>
725 ProgramState::assumeInclusiveRange(DefinedOrUnknownSVal Val,
726 const llvm::APSInt &From,
727 const llvm::APSInt &To) const {
729 return std::make_pair(this, this);
731 assert(Val.getAs<NonLoc>() && "Only NonLocs are supported!");
733 return getStateManager().ConstraintMgr->assumeInclusiveRangeDual(
734 this, Val.castAs<NonLoc>(), From, To);
737 inline ProgramStateRef ProgramState::bindLoc(SVal LV, SVal V, const LocationContext *LCtx) const {
738 if (Optional<Loc> L = LV.getAs<Loc>())
739 return bindLoc(*L, V, LCtx);
743 inline Loc ProgramState::getLValue(const CXXBaseSpecifier &BaseSpec,
744 const SubRegion *Super) const {
745 const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl();
746 return loc::MemRegionVal(
747 getStateManager().getRegionManager().getCXXBaseObjectRegion(
748 Base, Super, BaseSpec.isVirtual()));
751 inline Loc ProgramState::getLValue(const CXXRecordDecl *BaseClass,
752 const SubRegion *Super,
753 bool IsVirtual) const {
754 return loc::MemRegionVal(
755 getStateManager().getRegionManager().getCXXBaseObjectRegion(
756 BaseClass, Super, IsVirtual));
759 inline Loc ProgramState::getLValue(const VarDecl *VD,
760 const LocationContext *LC) const {
761 return getStateManager().StoreMgr->getLValueVar(VD, LC);
764 inline Loc ProgramState::getLValue(const CompoundLiteralExpr *literal,
765 const LocationContext *LC) const {
766 return getStateManager().StoreMgr->getLValueCompoundLiteral(literal, LC);
769 inline SVal ProgramState::getLValue(const ObjCIvarDecl *D, SVal Base) const {
770 return getStateManager().StoreMgr->getLValueIvar(D, Base);
773 inline SVal ProgramState::getLValue(const FieldDecl *D, SVal Base) const {
774 return getStateManager().StoreMgr->getLValueField(D, Base);
777 inline SVal ProgramState::getLValue(const IndirectFieldDecl *D,
779 StoreManager &SM = *getStateManager().StoreMgr;
780 for (const auto *I : D->chain()) {
781 Base = SM.getLValueField(cast<FieldDecl>(I), Base);
787 inline SVal ProgramState::getLValue(QualType ElementType, SVal Idx, SVal Base) const{
788 if (Optional<NonLoc> N = Idx.getAs<NonLoc>())
789 return getStateManager().StoreMgr->getLValueElement(ElementType, *N, Base);
793 inline SVal ProgramState::getSVal(const Stmt *Ex,
794 const LocationContext *LCtx) const{
795 return Env.getSVal(EnvironmentEntry(Ex, LCtx),
796 *getStateManager().svalBuilder);
800 ProgramState::getSValAsScalarOrLoc(const Stmt *S,
801 const LocationContext *LCtx) const {
802 if (const Expr *Ex = dyn_cast<Expr>(S)) {
803 QualType T = Ex->getType();
804 if (Ex->isGLValue() || Loc::isLocType(T) ||
805 T->isIntegralOrEnumerationType())
806 return getSVal(S, LCtx);
812 inline SVal ProgramState::getRawSVal(Loc LV, QualType T) const {
813 return getStateManager().StoreMgr->getBinding(getStore(), LV, T);
816 inline SVal ProgramState::getSVal(const MemRegion* R, QualType T) const {
817 return getStateManager().StoreMgr->getBinding(getStore(),
818 loc::MemRegionVal(R),
822 inline BasicValueFactory &ProgramState::getBasicVals() const {
823 return getStateManager().getBasicVals();
826 inline SymbolManager &ProgramState::getSymbolManager() const {
827 return getStateManager().getSymbolManager();
831 ProgramStateRef ProgramState::add(typename ProgramStateTrait<T>::key_type K) const {
832 return getStateManager().add<T>(this, K, get_context<T>());
835 template <typename T>
836 typename ProgramStateTrait<T>::context_type ProgramState::get_context() const {
837 return getStateManager().get_context<T>();
841 ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K) const {
842 return getStateManager().remove<T>(this, K, get_context<T>());
846 ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K,
847 typename ProgramStateTrait<T>::context_type C) const {
848 return getStateManager().remove<T>(this, K, C);
851 template <typename T>
852 ProgramStateRef ProgramState::remove() const {
853 return getStateManager().remove<T>(this);
857 ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::data_type D) const {
858 return getStateManager().set<T>(this, D);
862 ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
863 typename ProgramStateTrait<T>::value_type E) const {
864 return getStateManager().set<T>(this, K, E, get_context<T>());
868 ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
869 typename ProgramStateTrait<T>::value_type E,
870 typename ProgramStateTrait<T>::context_type C) const {
871 return getStateManager().set<T>(this, K, E, C);
874 template <typename CB>
875 CB ProgramState::scanReachableSymbols(SVal val) const {
877 scanReachableSymbols(val, cb);
881 template <typename CB>
882 CB ProgramState::scanReachableSymbols(const SVal *beg, const SVal *end) const {
884 scanReachableSymbols(beg, end, cb);
888 template <typename CB>
889 CB ProgramState::scanReachableSymbols(const MemRegion * const *beg,
890 const MemRegion * const *end) const {
892 scanReachableSymbols(beg, end, cb);
896 /// \class ScanReachableSymbols
897 /// A utility class that visits the reachable symbols using a custom
898 /// SymbolVisitor. Terminates recursive traversal when the visitor function
900 class ScanReachableSymbols {
901 typedef llvm::DenseSet<const void*> VisitedItems;
903 VisitedItems visited;
904 ProgramStateRef state;
905 SymbolVisitor &visitor;
907 ScanReachableSymbols(ProgramStateRef st, SymbolVisitor &v)
908 : state(std::move(st)), visitor(v) {}
910 bool scan(nonloc::LazyCompoundVal val);
911 bool scan(nonloc::CompoundVal val);
913 bool scan(const MemRegion *R);
914 bool scan(const SymExpr *sym);
917 } // end ento namespace
919 } // end clang namespace