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"
39 class AnalysisManager;
41 class CallEventManager;
43 typedef std::unique_ptr<ConstraintManager>(*ConstraintManagerCreator)(
44 ProgramStateManager &, SubEngine *);
45 typedef std::unique_ptr<StoreManager>(*StoreManagerCreator)(
46 ProgramStateManager &);
47 typedef llvm::ImmutableMap<const SubRegion*, TaintTagType> TaintedSubRegions;
49 //===----------------------------------------------------------------------===//
50 // ProgramStateTrait - Traits used by the Generic Data Map of a ProgramState.
51 //===----------------------------------------------------------------------===//
53 template <typename T> struct ProgramStatePartialTrait;
55 template <typename T> struct ProgramStateTrait {
56 typedef typename T::data_type data_type;
57 static inline void *MakeVoidPtr(data_type D) { return (void*) D; }
58 static inline data_type MakeData(void *const* P) {
59 return P ? (data_type) *P : (data_type) 0;
63 /// \class ProgramState
64 /// ProgramState - This class encapsulates:
66 /// 1. A mapping from expressions to values (Environment)
67 /// 2. A mapping from locations to values (Store)
68 /// 3. Constraints on symbolic values (GenericDataMap)
70 /// Together these represent the "abstract state" of a program.
72 /// ProgramState is intended to be used as a functional object; that is,
73 /// once it is created and made "persistent" in a FoldingSet, its
74 /// values will never change.
75 class ProgramState : public llvm::FoldingSetNode {
77 typedef llvm::ImmutableSet<llvm::APSInt*> IntSetTy;
78 typedef llvm::ImmutableMap<void*, void*> GenericDataMap;
81 void operator=(const ProgramState& R) = delete;
83 friend class ProgramStateManager;
84 friend class ExplodedGraph;
85 friend class ExplodedNode;
87 ProgramStateManager *stateMgr;
88 Environment Env; // Maps a Stmt to its current SVal.
89 Store store; // Maps a location to its current value.
90 GenericDataMap GDM; // Custom data stored by a client of this class.
93 /// makeWithStore - Return a ProgramState with the same values as the current
94 /// state with the exception of using the specified Store.
95 ProgramStateRef makeWithStore(const StoreRef &store) const;
97 void setStore(const StoreRef &storeRef);
100 /// This ctor is used when creating the first ProgramState object.
101 ProgramState(ProgramStateManager *mgr, const Environment& env,
102 StoreRef st, GenericDataMap gdm);
104 /// Copy ctor - We must explicitly define this or else the "Next" ptr
105 /// in FoldingSetNode will also get copied.
106 ProgramState(const ProgramState &RHS);
110 /// Return the ProgramStateManager associated with this state.
111 ProgramStateManager &getStateManager() const {
115 AnalysisManager &getAnalysisManager() const;
117 /// Return the ConstraintManager.
118 ConstraintManager &getConstraintManager() const;
120 /// getEnvironment - Return the environment associated with this state.
121 /// The environment is the mapping from expressions to values.
122 const Environment& getEnvironment() const { return Env; }
124 /// Return the store associated with this state. The store
125 /// is a mapping from locations to values.
126 Store getStore() const { return store; }
129 /// getGDM - Return the generic data map associated with this state.
130 GenericDataMap getGDM() const { return GDM; }
132 void setGDM(GenericDataMap gdm) { GDM = gdm; }
134 /// Profile - Profile the contents of a ProgramState object for use in a
135 /// FoldingSet. Two ProgramState objects are considered equal if they
136 /// have the same Environment, Store, and GenericDataMap.
137 static void Profile(llvm::FoldingSetNodeID& ID, const ProgramState *V) {
139 ID.AddPointer(V->store);
143 /// Profile - Used to profile the contents of this object for inclusion
145 void Profile(llvm::FoldingSetNodeID& ID) const {
149 BasicValueFactory &getBasicVals() const;
150 SymbolManager &getSymbolManager() const;
152 //==---------------------------------------------------------------------==//
153 // Constraints on values.
154 //==---------------------------------------------------------------------==//
156 // Each ProgramState records constraints on symbolic values. These constraints
157 // are managed using the ConstraintManager associated with a ProgramStateManager.
158 // As constraints gradually accrue on symbolic values, added constraints
159 // may conflict and indicate that a state is infeasible (as no real values
160 // could satisfy all the constraints). This is the principal mechanism
161 // for modeling path-sensitivity in ExprEngine/ProgramState.
163 // Various "assume" methods form the interface for adding constraints to
164 // symbolic values. A call to 'assume' indicates an assumption being placed
165 // on one or symbolic values. 'assume' methods take the following inputs:
167 // (1) A ProgramState object representing the current state.
169 // (2) The assumed constraint (which is specific to a given "assume" method).
171 // (3) A binary value "Assumption" that indicates whether the constraint is
172 // assumed to be true or false.
174 // The output of "assume*" is a new ProgramState object with the added constraints.
175 // If no new state is feasible, NULL is returned.
178 /// Assumes that the value of \p cond is zero (if \p assumption is "false")
179 /// or non-zero (if \p assumption is "true").
181 /// This returns a new state with the added constraint on \p cond.
182 /// If no new state is feasible, NULL is returned.
183 LLVM_NODISCARD ProgramStateRef assume(DefinedOrUnknownSVal cond,
184 bool assumption) const;
186 /// Assumes both "true" and "false" for \p cond, and returns both
187 /// corresponding states (respectively).
189 /// This is more efficient than calling assume() twice. Note that one (but not
190 /// both) of the returned states may be NULL.
191 LLVM_NODISCARD std::pair<ProgramStateRef, ProgramStateRef>
192 assume(DefinedOrUnknownSVal cond) const;
194 LLVM_NODISCARD ProgramStateRef
195 assumeInBound(DefinedOrUnknownSVal idx, DefinedOrUnknownSVal upperBound,
196 bool assumption, QualType IndexType = QualType()) const;
198 /// Assumes that the value of \p Val is bounded with [\p From; \p To]
199 /// (if \p assumption is "true") or it is fully out of this range
200 /// (if \p assumption is "false").
202 /// This returns a new state with the added constraint on \p cond.
203 /// If no new state is feasible, NULL is returned.
204 LLVM_NODISCARD ProgramStateRef assumeInclusiveRange(DefinedOrUnknownSVal Val,
205 const llvm::APSInt &From,
206 const llvm::APSInt &To,
207 bool assumption) const;
209 /// Assumes given range both "true" and "false" for \p Val, and returns both
210 /// corresponding states (respectively).
212 /// This is more efficient than calling assume() twice. Note that one (but not
213 /// both) of the returned states may be NULL.
214 LLVM_NODISCARD std::pair<ProgramStateRef, ProgramStateRef>
215 assumeInclusiveRange(DefinedOrUnknownSVal Val, const llvm::APSInt &From,
216 const llvm::APSInt &To) const;
218 /// Check if the given SVal is not constrained to zero and is not
220 ConditionTruthVal isNonNull(SVal V) const;
222 /// Check if the given SVal is constrained to zero or is a zero
224 ConditionTruthVal isNull(SVal V) const;
226 /// \return Whether values \p Lhs and \p Rhs are equal.
227 ConditionTruthVal areEqual(SVal Lhs, SVal Rhs) const;
229 /// Utility method for getting regions.
230 const VarRegion* getRegion(const VarDecl *D, const LocationContext *LC) const;
232 //==---------------------------------------------------------------------==//
233 // Binding and retrieving values to/from the environment and symbolic store.
234 //==---------------------------------------------------------------------==//
236 /// Create a new state by binding the value 'V' to the statement 'S' in the
237 /// state's environment.
238 LLVM_NODISCARD ProgramStateRef BindExpr(const Stmt *S,
239 const LocationContext *LCtx, SVal V,
240 bool Invalidate = true) const;
242 LLVM_NODISCARD ProgramStateRef bindLoc(Loc location, SVal V,
243 const LocationContext *LCtx,
244 bool notifyChanges = true) const;
246 LLVM_NODISCARD ProgramStateRef bindLoc(SVal location, SVal V,
247 const LocationContext *LCtx) const;
249 /// Initializes the region of memory represented by \p loc with an initial
250 /// value. Once initialized, all values loaded from any sub-regions of that
251 /// region will be equal to \p V, unless overwritten later by the program.
252 /// This method should not be used on regions that are already initialized.
253 /// If you need to indicate that memory contents have suddenly become unknown
254 /// within a certain region of memory, consider invalidateRegions().
255 LLVM_NODISCARD ProgramStateRef
256 bindDefaultInitial(SVal loc, SVal V, const LocationContext *LCtx) const;
258 /// Performs C++ zero-initialization procedure on the region of memory
259 /// represented by \p loc.
260 LLVM_NODISCARD ProgramStateRef
261 bindDefaultZero(SVal loc, const LocationContext *LCtx) const;
263 LLVM_NODISCARD ProgramStateRef killBinding(Loc LV) const;
265 /// Returns the state with bindings for the given regions
266 /// cleared from the store.
268 /// Optionally invalidates global regions as well.
270 /// \param Regions the set of regions to be invalidated.
271 /// \param E the expression that caused the invalidation.
272 /// \param BlockCount The number of times the current basic block has been
274 /// \param CausesPointerEscape the flag is set to true when
275 /// the invalidation entails escape of a symbol (representing a
276 /// pointer). For example, due to it being passed as an argument in a
278 /// \param IS the set of invalidated symbols.
279 /// \param Call if non-null, the invalidated regions represent parameters to
280 /// the call and should be considered directly invalidated.
281 /// \param ITraits information about special handling for a particular
283 LLVM_NODISCARD ProgramStateRef
284 invalidateRegions(ArrayRef<const MemRegion *> Regions, const Expr *E,
285 unsigned BlockCount, const LocationContext *LCtx,
286 bool CausesPointerEscape, InvalidatedSymbols *IS = nullptr,
287 const CallEvent *Call = nullptr,
288 RegionAndSymbolInvalidationTraits *ITraits = nullptr) const;
290 LLVM_NODISCARD ProgramStateRef
291 invalidateRegions(ArrayRef<SVal> Regions, const Expr *E,
292 unsigned BlockCount, const LocationContext *LCtx,
293 bool CausesPointerEscape, InvalidatedSymbols *IS = nullptr,
294 const CallEvent *Call = nullptr,
295 RegionAndSymbolInvalidationTraits *ITraits = nullptr) const;
297 /// enterStackFrame - Returns the state for entry to the given stack frame,
298 /// preserving the current state.
299 LLVM_NODISCARD ProgramStateRef enterStackFrame(
300 const CallEvent &Call, const StackFrameContext *CalleeCtx) const;
302 /// Get the lvalue for a base class object reference.
303 Loc getLValue(const CXXBaseSpecifier &BaseSpec, const SubRegion *Super) const;
305 /// Get the lvalue for a base class object reference.
306 Loc getLValue(const CXXRecordDecl *BaseClass, const SubRegion *Super,
307 bool IsVirtual) const;
309 /// Get the lvalue for a variable reference.
310 Loc getLValue(const VarDecl *D, const LocationContext *LC) const;
312 Loc getLValue(const CompoundLiteralExpr *literal,
313 const LocationContext *LC) const;
315 /// Get the lvalue for an ivar reference.
316 SVal getLValue(const ObjCIvarDecl *decl, SVal base) const;
318 /// Get the lvalue for a field reference.
319 SVal getLValue(const FieldDecl *decl, SVal Base) const;
321 /// Get the lvalue for an indirect field reference.
322 SVal getLValue(const IndirectFieldDecl *decl, SVal Base) const;
324 /// Get the lvalue for an array index.
325 SVal getLValue(QualType ElementType, SVal Idx, SVal Base) const;
327 /// Returns the SVal bound to the statement 'S' in the state's environment.
328 SVal getSVal(const Stmt *S, const LocationContext *LCtx) const;
330 SVal getSValAsScalarOrLoc(const Stmt *Ex, const LocationContext *LCtx) const;
332 /// Return the value bound to the specified location.
333 /// Returns UnknownVal() if none found.
334 SVal getSVal(Loc LV, QualType T = QualType()) const;
336 /// Returns the "raw" SVal bound to LV before any value simplfication.
337 SVal getRawSVal(Loc LV, QualType T= QualType()) const;
339 /// Return the value bound to the specified location.
340 /// Returns UnknownVal() if none found.
341 SVal getSVal(const MemRegion* R, QualType T = QualType()) const;
343 /// Return the value bound to the specified location, assuming
344 /// that the value is a scalar integer or an enumeration or a pointer.
345 /// Returns UnknownVal() if none found or the region is not known to hold
346 /// a value of such type.
347 SVal getSValAsScalarOrLoc(const MemRegion *R) const;
349 /// Visits the symbols reachable from the given SVal using the provided
352 /// This is a convenience API. Consider using ScanReachableSymbols class
353 /// directly when making multiple scans on the same state with the same
354 /// visitor to avoid repeated initialization cost.
355 /// \sa ScanReachableSymbols
356 bool scanReachableSymbols(SVal val, SymbolVisitor& visitor) const;
358 /// Visits the symbols reachable from the SVals in the given range
359 /// using the provided SymbolVisitor.
360 bool scanReachableSymbols(const SVal *I, const SVal *E,
361 SymbolVisitor &visitor) const;
363 /// Visits the symbols reachable from the regions in the given
364 /// MemRegions range using the provided SymbolVisitor.
365 bool scanReachableSymbols(const MemRegion * const *I,
366 const MemRegion * const *E,
367 SymbolVisitor &visitor) const;
369 template <typename CB> CB scanReachableSymbols(SVal val) const;
370 template <typename CB> CB scanReachableSymbols(const SVal *beg,
371 const SVal *end) const;
373 template <typename CB> CB
374 scanReachableSymbols(const MemRegion * const *beg,
375 const MemRegion * const *end) const;
377 /// Create a new state in which the statement is marked as tainted.
378 LLVM_NODISCARD ProgramStateRef
379 addTaint(const Stmt *S, const LocationContext *LCtx,
380 TaintTagType Kind = TaintTagGeneric) const;
382 /// Create a new state in which the value is marked as tainted.
383 LLVM_NODISCARD ProgramStateRef
384 addTaint(SVal V, TaintTagType Kind = TaintTagGeneric) const;
386 /// Create a new state in which the symbol is marked as tainted.
387 LLVM_NODISCARD ProgramStateRef addTaint(SymbolRef S,
388 TaintTagType Kind = TaintTagGeneric) const;
390 /// Create a new state in which the region symbol is marked as tainted.
391 LLVM_NODISCARD ProgramStateRef
392 addTaint(const MemRegion *R, TaintTagType Kind = TaintTagGeneric) const;
394 /// Create a new state in a which a sub-region of a given symbol is tainted.
395 /// This might be necessary when referring to regions that can not have an
396 /// individual symbol, e.g. if they are represented by the default binding of
397 /// a LazyCompoundVal.
398 LLVM_NODISCARD ProgramStateRef
399 addPartialTaint(SymbolRef ParentSym, const SubRegion *SubRegion,
400 TaintTagType Kind = TaintTagGeneric) const;
402 /// Check if the statement is tainted in the current state.
403 bool isTainted(const Stmt *S, const LocationContext *LCtx,
404 TaintTagType Kind = TaintTagGeneric) const;
405 bool isTainted(SVal V, TaintTagType Kind = TaintTagGeneric) const;
406 bool isTainted(SymbolRef Sym, TaintTagType Kind = TaintTagGeneric) const;
407 bool isTainted(const MemRegion *Reg, TaintTagType Kind=TaintTagGeneric) const;
409 //==---------------------------------------------------------------------==//
410 // Accessing the Generic Data Map (GDM).
411 //==---------------------------------------------------------------------==//
413 void *const* FindGDM(void *K) const;
415 template <typename T>
416 LLVM_NODISCARD ProgramStateRef
417 add(typename ProgramStateTrait<T>::key_type K) const;
419 template <typename T>
420 typename ProgramStateTrait<T>::data_type
422 return ProgramStateTrait<T>::MakeData(FindGDM(ProgramStateTrait<T>::GDMIndex()));
426 typename ProgramStateTrait<T>::lookup_type
427 get(typename ProgramStateTrait<T>::key_type key) const {
428 void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
429 return ProgramStateTrait<T>::Lookup(ProgramStateTrait<T>::MakeData(d), key);
432 template <typename T>
433 typename ProgramStateTrait<T>::context_type get_context() const;
435 template <typename T>
436 LLVM_NODISCARD ProgramStateRef
437 remove(typename ProgramStateTrait<T>::key_type K) const;
439 template <typename T>
440 LLVM_NODISCARD ProgramStateRef
441 remove(typename ProgramStateTrait<T>::key_type K,
442 typename ProgramStateTrait<T>::context_type C) const;
444 template <typename T> LLVM_NODISCARD ProgramStateRef remove() const;
446 template <typename T>
447 LLVM_NODISCARD ProgramStateRef
448 set(typename ProgramStateTrait<T>::data_type D) const;
450 template <typename T>
451 LLVM_NODISCARD ProgramStateRef
452 set(typename ProgramStateTrait<T>::key_type K,
453 typename ProgramStateTrait<T>::value_type E) const;
455 template <typename T>
456 LLVM_NODISCARD ProgramStateRef
457 set(typename ProgramStateTrait<T>::key_type K,
458 typename ProgramStateTrait<T>::value_type E,
459 typename ProgramStateTrait<T>::context_type C) const;
462 bool contains(typename ProgramStateTrait<T>::key_type key) const {
463 void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
464 return ProgramStateTrait<T>::Contains(ProgramStateTrait<T>::MakeData(d), key);
468 void print(raw_ostream &Out, const char *nl = "\n", const char *sep = "",
469 const LocationContext *CurrentLC = nullptr) const;
470 void printDOT(raw_ostream &Out,
471 const LocationContext *CurrentLC = nullptr) const;
472 void printTaint(raw_ostream &Out, const char *nl = "\n",
473 const char *sep = "") const;
476 void dumpTaint() const;
479 friend void ProgramStateRetain(const ProgramState *state);
480 friend void ProgramStateRelease(const ProgramState *state);
482 /// \sa invalidateValues()
483 /// \sa invalidateRegions()
485 invalidateRegionsImpl(ArrayRef<SVal> Values,
486 const Expr *E, unsigned BlockCount,
487 const LocationContext *LCtx,
488 bool ResultsInSymbolEscape,
489 InvalidatedSymbols *IS,
490 RegionAndSymbolInvalidationTraits *HTraits,
491 const CallEvent *Call) const;
494 //===----------------------------------------------------------------------===//
495 // ProgramStateManager - Factory object for ProgramStates.
496 //===----------------------------------------------------------------------===//
498 class ProgramStateManager {
499 friend class ProgramState;
500 friend void ProgramStateRelease(const ProgramState *state);
502 /// Eng - The SubEngine that owns this state manager.
503 SubEngine *Eng; /* Can be null. */
505 EnvironmentManager EnvMgr;
506 std::unique_ptr<StoreManager> StoreMgr;
507 std::unique_ptr<ConstraintManager> ConstraintMgr;
509 ProgramState::GenericDataMap::Factory GDMFactory;
510 TaintedSubRegions::Factory TSRFactory;
512 typedef llvm::DenseMap<void*,std::pair<void*,void (*)(void*)> > GDMContextsTy;
513 GDMContextsTy GDMContexts;
515 /// StateSet - FoldingSet containing all the states created for analyzing
516 /// a particular function. This is used to unique states.
517 llvm::FoldingSet<ProgramState> StateSet;
519 /// Object that manages the data for all created SVals.
520 std::unique_ptr<SValBuilder> svalBuilder;
522 /// Manages memory for created CallEvents.
523 std::unique_ptr<CallEventManager> CallEventMgr;
525 /// A BumpPtrAllocator to allocate states.
526 llvm::BumpPtrAllocator &Alloc;
528 /// A vector of ProgramStates that we can reuse.
529 std::vector<ProgramState *> freeStates;
532 ProgramStateManager(ASTContext &Ctx,
533 StoreManagerCreator CreateStoreManager,
534 ConstraintManagerCreator CreateConstraintManager,
535 llvm::BumpPtrAllocator& alloc,
538 ~ProgramStateManager();
540 ProgramStateRef getInitialState(const LocationContext *InitLoc);
542 ASTContext &getContext() { return svalBuilder->getContext(); }
543 const ASTContext &getContext() const { return svalBuilder->getContext(); }
545 BasicValueFactory &getBasicVals() {
546 return svalBuilder->getBasicValueFactory();
549 SValBuilder &getSValBuilder() {
553 SymbolManager &getSymbolManager() {
554 return svalBuilder->getSymbolManager();
556 const SymbolManager &getSymbolManager() const {
557 return svalBuilder->getSymbolManager();
560 llvm::BumpPtrAllocator& getAllocator() { return Alloc; }
562 MemRegionManager& getRegionManager() {
563 return svalBuilder->getRegionManager();
565 const MemRegionManager& getRegionManager() const {
566 return svalBuilder->getRegionManager();
569 CallEventManager &getCallEventManager() { return *CallEventMgr; }
571 StoreManager& getStoreManager() { return *StoreMgr; }
572 ConstraintManager& getConstraintManager() { return *ConstraintMgr; }
573 SubEngine* getOwningEngine() { return Eng; }
575 ProgramStateRef removeDeadBindings(ProgramStateRef St,
576 const StackFrameContext *LCtx,
577 SymbolReaper& SymReaper);
581 SVal ArrayToPointer(Loc Array, QualType ElementTy) {
582 return StoreMgr->ArrayToPointer(Array, ElementTy);
585 // Methods that manipulate the GDM.
586 ProgramStateRef addGDM(ProgramStateRef St, void *Key, void *Data);
587 ProgramStateRef removeGDM(ProgramStateRef state, void *Key);
589 // Methods that query & manipulate the Store.
591 void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler& F) {
592 StoreMgr->iterBindings(state->getStore(), F);
595 ProgramStateRef getPersistentState(ProgramState &Impl);
596 ProgramStateRef getPersistentStateWithGDM(ProgramStateRef FromState,
597 ProgramStateRef GDMState);
599 bool haveEqualEnvironments(ProgramStateRef S1, ProgramStateRef S2) {
600 return S1->Env == S2->Env;
603 bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2) {
604 return S1->store == S2->store;
607 //==---------------------------------------------------------------------==//
608 // Generic Data Map methods.
609 //==---------------------------------------------------------------------==//
611 // ProgramStateManager and ProgramState support a "generic data map" that allows
612 // different clients of ProgramState objects to embed arbitrary data within a
613 // ProgramState object. The generic data map is essentially an immutable map
614 // from a "tag" (that acts as the "key" for a client) and opaque values.
615 // Tags/keys and values are simply void* values. The typical way that clients
616 // generate unique tags are by taking the address of a static variable.
617 // Clients are responsible for ensuring that data values referred to by a
618 // the data pointer are immutable (and thus are essentially purely functional
621 // The templated methods below use the ProgramStateTrait<T> class
622 // to resolve keys into the GDM and to return data values to clients.
625 // Trait based GDM dispatch.
626 template <typename T>
627 ProgramStateRef set(ProgramStateRef st, typename ProgramStateTrait<T>::data_type D) {
628 return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
629 ProgramStateTrait<T>::MakeVoidPtr(D));
633 ProgramStateRef set(ProgramStateRef st,
634 typename ProgramStateTrait<T>::key_type K,
635 typename ProgramStateTrait<T>::value_type V,
636 typename ProgramStateTrait<T>::context_type C) {
638 return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
639 ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Set(st->get<T>(), K, V, C)));
642 template <typename T>
643 ProgramStateRef add(ProgramStateRef st,
644 typename ProgramStateTrait<T>::key_type K,
645 typename ProgramStateTrait<T>::context_type C) {
646 return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
647 ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Add(st->get<T>(), K, C)));
650 template <typename T>
651 ProgramStateRef remove(ProgramStateRef st,
652 typename ProgramStateTrait<T>::key_type K,
653 typename ProgramStateTrait<T>::context_type C) {
655 return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
656 ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Remove(st->get<T>(), K, C)));
659 template <typename T>
660 ProgramStateRef remove(ProgramStateRef st) {
661 return removeGDM(st, ProgramStateTrait<T>::GDMIndex());
664 void *FindGDMContext(void *index,
665 void *(*CreateContext)(llvm::BumpPtrAllocator&),
666 void (*DeleteContext)(void*));
668 template <typename T>
669 typename ProgramStateTrait<T>::context_type get_context() {
670 void *p = FindGDMContext(ProgramStateTrait<T>::GDMIndex(),
671 ProgramStateTrait<T>::CreateContext,
672 ProgramStateTrait<T>::DeleteContext);
674 return ProgramStateTrait<T>::MakeContext(p);
677 void EndPath(ProgramStateRef St) {
678 ConstraintMgr->EndPath(St);
683 //===----------------------------------------------------------------------===//
684 // Out-of-line method definitions for ProgramState.
685 //===----------------------------------------------------------------------===//
687 inline ConstraintManager &ProgramState::getConstraintManager() const {
688 return stateMgr->getConstraintManager();
691 inline const VarRegion* ProgramState::getRegion(const VarDecl *D,
692 const LocationContext *LC) const
694 return getStateManager().getRegionManager().getVarRegion(D, LC);
697 inline ProgramStateRef ProgramState::assume(DefinedOrUnknownSVal Cond,
698 bool Assumption) const {
699 if (Cond.isUnknown())
702 return getStateManager().ConstraintMgr
703 ->assume(this, Cond.castAs<DefinedSVal>(), Assumption);
706 inline std::pair<ProgramStateRef , ProgramStateRef >
707 ProgramState::assume(DefinedOrUnknownSVal Cond) const {
708 if (Cond.isUnknown())
709 return std::make_pair(this, this);
711 return getStateManager().ConstraintMgr
712 ->assumeDual(this, Cond.castAs<DefinedSVal>());
715 inline ProgramStateRef ProgramState::assumeInclusiveRange(
716 DefinedOrUnknownSVal Val, const llvm::APSInt &From, const llvm::APSInt &To,
717 bool Assumption) const {
721 assert(Val.getAs<NonLoc>() && "Only NonLocs are supported!");
723 return getStateManager().ConstraintMgr->assumeInclusiveRange(
724 this, Val.castAs<NonLoc>(), From, To, Assumption);
727 inline std::pair<ProgramStateRef, ProgramStateRef>
728 ProgramState::assumeInclusiveRange(DefinedOrUnknownSVal Val,
729 const llvm::APSInt &From,
730 const llvm::APSInt &To) const {
732 return std::make_pair(this, this);
734 assert(Val.getAs<NonLoc>() && "Only NonLocs are supported!");
736 return getStateManager().ConstraintMgr->assumeInclusiveRangeDual(
737 this, Val.castAs<NonLoc>(), From, To);
740 inline ProgramStateRef ProgramState::bindLoc(SVal LV, SVal V, const LocationContext *LCtx) const {
741 if (Optional<Loc> L = LV.getAs<Loc>())
742 return bindLoc(*L, V, LCtx);
746 inline Loc ProgramState::getLValue(const CXXBaseSpecifier &BaseSpec,
747 const SubRegion *Super) const {
748 const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl();
749 return loc::MemRegionVal(
750 getStateManager().getRegionManager().getCXXBaseObjectRegion(
751 Base, Super, BaseSpec.isVirtual()));
754 inline Loc ProgramState::getLValue(const CXXRecordDecl *BaseClass,
755 const SubRegion *Super,
756 bool IsVirtual) const {
757 return loc::MemRegionVal(
758 getStateManager().getRegionManager().getCXXBaseObjectRegion(
759 BaseClass, Super, IsVirtual));
762 inline Loc ProgramState::getLValue(const VarDecl *VD,
763 const LocationContext *LC) const {
764 return getStateManager().StoreMgr->getLValueVar(VD, LC);
767 inline Loc ProgramState::getLValue(const CompoundLiteralExpr *literal,
768 const LocationContext *LC) const {
769 return getStateManager().StoreMgr->getLValueCompoundLiteral(literal, LC);
772 inline SVal ProgramState::getLValue(const ObjCIvarDecl *D, SVal Base) const {
773 return getStateManager().StoreMgr->getLValueIvar(D, Base);
776 inline SVal ProgramState::getLValue(const FieldDecl *D, SVal Base) const {
777 return getStateManager().StoreMgr->getLValueField(D, Base);
780 inline SVal ProgramState::getLValue(const IndirectFieldDecl *D,
782 StoreManager &SM = *getStateManager().StoreMgr;
783 for (const auto *I : D->chain()) {
784 Base = SM.getLValueField(cast<FieldDecl>(I), Base);
790 inline SVal ProgramState::getLValue(QualType ElementType, SVal Idx, SVal Base) const{
791 if (Optional<NonLoc> N = Idx.getAs<NonLoc>())
792 return getStateManager().StoreMgr->getLValueElement(ElementType, *N, Base);
796 inline SVal ProgramState::getSVal(const Stmt *Ex,
797 const LocationContext *LCtx) const{
798 return Env.getSVal(EnvironmentEntry(Ex, LCtx),
799 *getStateManager().svalBuilder);
803 ProgramState::getSValAsScalarOrLoc(const Stmt *S,
804 const LocationContext *LCtx) const {
805 if (const Expr *Ex = dyn_cast<Expr>(S)) {
806 QualType T = Ex->getType();
807 if (Ex->isGLValue() || Loc::isLocType(T) ||
808 T->isIntegralOrEnumerationType())
809 return getSVal(S, LCtx);
815 inline SVal ProgramState::getRawSVal(Loc LV, QualType T) const {
816 return getStateManager().StoreMgr->getBinding(getStore(), LV, T);
819 inline SVal ProgramState::getSVal(const MemRegion* R, QualType T) const {
820 return getStateManager().StoreMgr->getBinding(getStore(),
821 loc::MemRegionVal(R),
825 inline BasicValueFactory &ProgramState::getBasicVals() const {
826 return getStateManager().getBasicVals();
829 inline SymbolManager &ProgramState::getSymbolManager() const {
830 return getStateManager().getSymbolManager();
834 ProgramStateRef ProgramState::add(typename ProgramStateTrait<T>::key_type K) const {
835 return getStateManager().add<T>(this, K, get_context<T>());
838 template <typename T>
839 typename ProgramStateTrait<T>::context_type ProgramState::get_context() const {
840 return getStateManager().get_context<T>();
844 ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K) const {
845 return getStateManager().remove<T>(this, K, get_context<T>());
849 ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K,
850 typename ProgramStateTrait<T>::context_type C) const {
851 return getStateManager().remove<T>(this, K, C);
854 template <typename T>
855 ProgramStateRef ProgramState::remove() const {
856 return getStateManager().remove<T>(this);
860 ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::data_type D) const {
861 return getStateManager().set<T>(this, D);
865 ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
866 typename ProgramStateTrait<T>::value_type E) const {
867 return getStateManager().set<T>(this, K, E, get_context<T>());
871 ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
872 typename ProgramStateTrait<T>::value_type E,
873 typename ProgramStateTrait<T>::context_type C) const {
874 return getStateManager().set<T>(this, K, E, C);
877 template <typename CB>
878 CB ProgramState::scanReachableSymbols(SVal val) const {
880 scanReachableSymbols(val, cb);
884 template <typename CB>
885 CB ProgramState::scanReachableSymbols(const SVal *beg, const SVal *end) const {
887 scanReachableSymbols(beg, end, cb);
891 template <typename CB>
892 CB ProgramState::scanReachableSymbols(const MemRegion * const *beg,
893 const MemRegion * const *end) const {
895 scanReachableSymbols(beg, end, cb);
899 /// \class ScanReachableSymbols
900 /// A utility class that visits the reachable symbols using a custom
901 /// SymbolVisitor. Terminates recursive traversal when the visitor function
903 class ScanReachableSymbols {
904 typedef llvm::DenseSet<const void*> VisitedItems;
906 VisitedItems visited;
907 ProgramStateRef state;
908 SymbolVisitor &visitor;
910 ScanReachableSymbols(ProgramStateRef st, SymbolVisitor &v)
911 : state(std::move(st)), visitor(v) {}
913 bool scan(nonloc::LazyCompoundVal val);
914 bool scan(nonloc::CompoundVal val);
916 bool scan(const MemRegion *R);
917 bool scan(const SymExpr *sym);
920 } // end ento namespace
922 } // end clang namespace