]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
Merge clang trunk r338150, and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / include / clang / StaticAnalyzer / Core / PathSensitive / ProgramState.h
1 //== ProgramState.h - Path-sensitive "State" for tracking values -*- C++ -*--=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the state of the program along the analysisa path.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATE_H
15 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATE_H
16
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"
28 #include <utility>
29
30 namespace llvm {
31 class APSInt;
32 }
33
34 namespace clang {
35 class ASTContext;
36
37 namespace ento {
38
39 class CallEvent;
40 class CallEventManager;
41
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;
47
48 //===----------------------------------------------------------------------===//
49 // ProgramStateTrait - Traits used by the Generic Data Map of a ProgramState.
50 //===----------------------------------------------------------------------===//
51
52 template <typename T> struct ProgramStatePartialTrait;
53
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;
59   }
60 };
61
62 /// \class ProgramState
63 /// ProgramState - This class encapsulates:
64 ///
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)
68 ///
69 ///  Together these represent the "abstract state" of a program.
70 ///
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 {
75 public:
76   typedef llvm::ImmutableSet<llvm::APSInt*>                IntSetTy;
77   typedef llvm::ImmutableMap<void*, void*>                 GenericDataMap;
78
79 private:
80   void operator=(const ProgramState& R) = delete;
81
82   friend class ProgramStateManager;
83   friend class ExplodedGraph;
84   friend class ExplodedNode;
85
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.
90   unsigned refCount;
91
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;
95
96   void setStore(const StoreRef &storeRef);
97
98 public:
99   /// This ctor is used when creating the first ProgramState object.
100   ProgramState(ProgramStateManager *mgr, const Environment& env,
101           StoreRef st, GenericDataMap gdm);
102
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);
106
107   ~ProgramState();
108
109   /// Return the ProgramStateManager associated with this state.
110   ProgramStateManager &getStateManager() const {
111     return *stateMgr;
112   }
113
114   /// Return the ConstraintManager.
115   ConstraintManager &getConstraintManager() const;
116
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; }
120
121   /// Return the store associated with this state.  The store
122   ///  is a mapping from locations to values.
123   Store getStore() const { return store; }
124
125
126   /// getGDM - Return the generic data map associated with this state.
127   GenericDataMap getGDM() const { return GDM; }
128
129   void setGDM(GenericDataMap gdm) { GDM = gdm; }
130
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) {
135     V->Env.Profile(ID);
136     ID.AddPointer(V->store);
137     V->GDM.Profile(ID);
138   }
139
140   /// Profile - Used to profile the contents of this object for inclusion
141   ///  in a FoldingSet.
142   void Profile(llvm::FoldingSetNodeID& ID) const {
143     Profile(ID, this);
144   }
145
146   BasicValueFactory &getBasicVals() const;
147   SymbolManager &getSymbolManager() const;
148
149   //==---------------------------------------------------------------------==//
150   // Constraints on values.
151   //==---------------------------------------------------------------------==//
152   //
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.
159   //
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:
163   //
164   //  (1) A ProgramState object representing the current state.
165   //
166   //  (2) The assumed constraint (which is specific to a given "assume" method).
167   //
168   //  (3) A binary value "Assumption" that indicates whether the constraint is
169   //      assumed to be true or false.
170   //
171   // The output of "assume*" is a new ProgramState object with the added constraints.
172   // If no new state is feasible, NULL is returned.
173   //
174
175   /// Assumes that the value of \p cond is zero (if \p assumption is "false")
176   /// or non-zero (if \p assumption is "true").
177   ///
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;
182
183   /// Assumes both "true" and "false" for \p cond, and returns both
184   /// corresponding states (respectively).
185   ///
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;
190
191   LLVM_NODISCARD ProgramStateRef
192   assumeInBound(DefinedOrUnknownSVal idx, DefinedOrUnknownSVal upperBound,
193                 bool assumption, QualType IndexType = QualType()) const;
194
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").
198   ///
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;
205
206   /// Assumes given range both "true" and "false" for \p Val, and returns both
207   /// corresponding states (respectively).
208   ///
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;
214
215   /// Check if the given SVal is not constrained to zero and is not
216   ///        a zero constant.
217   ConditionTruthVal isNonNull(SVal V) const;
218
219   /// Check if the given SVal is constrained to zero or is a zero
220   ///        constant.
221   ConditionTruthVal isNull(SVal V) const;
222
223   /// \return Whether values \p Lhs and \p Rhs are equal.
224   ConditionTruthVal areEqual(SVal Lhs, SVal Rhs) const;
225
226   /// Utility method for getting regions.
227   const VarRegion* getRegion(const VarDecl *D, const LocationContext *LC) const;
228
229   //==---------------------------------------------------------------------==//
230   // Binding and retrieving values to/from the environment and symbolic store.
231   //==---------------------------------------------------------------------==//
232
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;
238
239   LLVM_NODISCARD ProgramStateRef bindLoc(Loc location, SVal V,
240                                          const LocationContext *LCtx,
241                                          bool notifyChanges = true) const;
242
243   LLVM_NODISCARD ProgramStateRef bindLoc(SVal location, SVal V,
244                                          const LocationContext *LCtx) const;
245
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;
254
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;
259
260   LLVM_NODISCARD ProgramStateRef killBinding(Loc LV) const;
261
262   /// Returns the state with bindings for the given regions
263   ///  cleared from the store.
264   ///
265   /// Optionally invalidates global regions as well.
266   ///
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
270   //         visited.
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
274   ///        call.
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
279   ///        region/symbol.
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;
286
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;
293
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;
298
299   /// Get the lvalue for a base class object reference.
300   Loc getLValue(const CXXBaseSpecifier &BaseSpec, const SubRegion *Super) const;
301
302   /// Get the lvalue for a base class object reference.
303   Loc getLValue(const CXXRecordDecl *BaseClass, const SubRegion *Super,
304                 bool IsVirtual) const;
305
306   /// Get the lvalue for a variable reference.
307   Loc getLValue(const VarDecl *D, const LocationContext *LC) const;
308
309   Loc getLValue(const CompoundLiteralExpr *literal,
310                 const LocationContext *LC) const;
311
312   /// Get the lvalue for an ivar reference.
313   SVal getLValue(const ObjCIvarDecl *decl, SVal base) const;
314
315   /// Get the lvalue for a field reference.
316   SVal getLValue(const FieldDecl *decl, SVal Base) const;
317
318   /// Get the lvalue for an indirect field reference.
319   SVal getLValue(const IndirectFieldDecl *decl, SVal Base) const;
320
321   /// Get the lvalue for an array index.
322   SVal getLValue(QualType ElementType, SVal Idx, SVal Base) const;
323
324   /// Returns the SVal bound to the statement 'S' in the state's environment.
325   SVal getSVal(const Stmt *S, const LocationContext *LCtx) const;
326
327   SVal getSValAsScalarOrLoc(const Stmt *Ex, const LocationContext *LCtx) const;
328
329   /// Return the value bound to the specified location.
330   /// Returns UnknownVal() if none found.
331   SVal getSVal(Loc LV, QualType T = QualType()) const;
332
333   /// Returns the "raw" SVal bound to LV before any value simplfication.
334   SVal getRawSVal(Loc LV, QualType T= QualType()) const;
335
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;
339
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;
345
346   /// Visits the symbols reachable from the given SVal using the provided
347   /// SymbolVisitor.
348   ///
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;
354
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;
359
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;
365
366   template <typename CB> CB scanReachableSymbols(SVal val) const;
367   template <typename CB> CB scanReachableSymbols(const SVal *beg,
368                                                  const SVal *end) const;
369
370   template <typename CB> CB
371   scanReachableSymbols(const MemRegion * const *beg,
372                        const MemRegion * const *end) const;
373
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;
378
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;
382
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;
386
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;
390
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;
398
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;
405
406   //==---------------------------------------------------------------------==//
407   // Accessing the Generic Data Map (GDM).
408   //==---------------------------------------------------------------------==//
409
410   void *const* FindGDM(void *K) const;
411
412   template <typename T>
413   LLVM_NODISCARD ProgramStateRef
414   add(typename ProgramStateTrait<T>::key_type K) const;
415
416   template <typename T>
417   typename ProgramStateTrait<T>::data_type
418   get() const {
419     return ProgramStateTrait<T>::MakeData(FindGDM(ProgramStateTrait<T>::GDMIndex()));
420   }
421
422   template<typename T>
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);
427   }
428
429   template <typename T>
430   typename ProgramStateTrait<T>::context_type get_context() const;
431
432   template <typename T>
433   LLVM_NODISCARD ProgramStateRef
434   remove(typename ProgramStateTrait<T>::key_type K) const;
435
436   template <typename T>
437   LLVM_NODISCARD ProgramStateRef
438   remove(typename ProgramStateTrait<T>::key_type K,
439          typename ProgramStateTrait<T>::context_type C) const;
440
441   template <typename T> LLVM_NODISCARD ProgramStateRef remove() const;
442
443   template <typename T>
444   LLVM_NODISCARD ProgramStateRef
445   set(typename ProgramStateTrait<T>::data_type D) const;
446
447   template <typename T>
448   LLVM_NODISCARD ProgramStateRef
449   set(typename ProgramStateTrait<T>::key_type K,
450       typename ProgramStateTrait<T>::value_type E) const;
451
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;
457
458   template<typename T>
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);
462   }
463
464   // Pretty-printing.
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;
471
472   void dump() const;
473   void dumpTaint() const;
474
475 private:
476   friend void ProgramStateRetain(const ProgramState *state);
477   friend void ProgramStateRelease(const ProgramState *state);
478
479   /// \sa invalidateValues()
480   /// \sa invalidateRegions()
481   ProgramStateRef
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;
489 };
490
491 //===----------------------------------------------------------------------===//
492 // ProgramStateManager - Factory object for ProgramStates.
493 //===----------------------------------------------------------------------===//
494
495 class ProgramStateManager {
496   friend class ProgramState;
497   friend void ProgramStateRelease(const ProgramState *state);
498 private:
499   /// Eng - The SubEngine that owns this state manager.
500   SubEngine *Eng; /* Can be null. */
501
502   EnvironmentManager                   EnvMgr;
503   std::unique_ptr<StoreManager>        StoreMgr;
504   std::unique_ptr<ConstraintManager>   ConstraintMgr;
505
506   ProgramState::GenericDataMap::Factory     GDMFactory;
507   TaintedSubRegions::Factory TSRFactory;
508
509   typedef llvm::DenseMap<void*,std::pair<void*,void (*)(void*)> > GDMContextsTy;
510   GDMContextsTy GDMContexts;
511
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;
515
516   /// Object that manages the data for all created SVals.
517   std::unique_ptr<SValBuilder> svalBuilder;
518
519   /// Manages memory for created CallEvents.
520   std::unique_ptr<CallEventManager> CallEventMgr;
521
522   /// A BumpPtrAllocator to allocate states.
523   llvm::BumpPtrAllocator &Alloc;
524
525   /// A vector of ProgramStates that we can reuse.
526   std::vector<ProgramState *> freeStates;
527
528 public:
529   ProgramStateManager(ASTContext &Ctx,
530                  StoreManagerCreator CreateStoreManager,
531                  ConstraintManagerCreator CreateConstraintManager,
532                  llvm::BumpPtrAllocator& alloc,
533                  SubEngine *subeng);
534
535   ~ProgramStateManager();
536
537   ProgramStateRef getInitialState(const LocationContext *InitLoc);
538
539   ASTContext &getContext() { return svalBuilder->getContext(); }
540   const ASTContext &getContext() const { return svalBuilder->getContext(); }
541
542   BasicValueFactory &getBasicVals() {
543     return svalBuilder->getBasicValueFactory();
544   }
545
546   SValBuilder &getSValBuilder() {
547     return *svalBuilder;
548   }
549
550   SymbolManager &getSymbolManager() {
551     return svalBuilder->getSymbolManager();
552   }
553   const SymbolManager &getSymbolManager() const {
554     return svalBuilder->getSymbolManager();
555   }
556
557   llvm::BumpPtrAllocator& getAllocator() { return Alloc; }
558
559   MemRegionManager& getRegionManager() {
560     return svalBuilder->getRegionManager();
561   }
562   const MemRegionManager& getRegionManager() const {
563     return svalBuilder->getRegionManager();
564   }
565
566   CallEventManager &getCallEventManager() { return *CallEventMgr; }
567
568   StoreManager& getStoreManager() { return *StoreMgr; }
569   ConstraintManager& getConstraintManager() { return *ConstraintMgr; }
570   SubEngine* getOwningEngine() { return Eng; }
571
572   ProgramStateRef removeDeadBindings(ProgramStateRef St,
573                                     const StackFrameContext *LCtx,
574                                     SymbolReaper& SymReaper);
575
576 public:
577
578   SVal ArrayToPointer(Loc Array, QualType ElementTy) {
579     return StoreMgr->ArrayToPointer(Array, ElementTy);
580   }
581
582   // Methods that manipulate the GDM.
583   ProgramStateRef addGDM(ProgramStateRef St, void *Key, void *Data);
584   ProgramStateRef removeGDM(ProgramStateRef state, void *Key);
585
586   // Methods that query & manipulate the Store.
587
588   void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler& F) {
589     StoreMgr->iterBindings(state->getStore(), F);
590   }
591
592   ProgramStateRef getPersistentState(ProgramState &Impl);
593   ProgramStateRef getPersistentStateWithGDM(ProgramStateRef FromState,
594                                            ProgramStateRef GDMState);
595
596   bool haveEqualEnvironments(ProgramStateRef S1, ProgramStateRef S2) {
597     return S1->Env == S2->Env;
598   }
599
600   bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2) {
601     return S1->store == S2->store;
602   }
603
604   //==---------------------------------------------------------------------==//
605   // Generic Data Map methods.
606   //==---------------------------------------------------------------------==//
607   //
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
616   // data).
617   //
618   // The templated methods below use the ProgramStateTrait<T> class
619   // to resolve keys into the GDM and to return data values to clients.
620   //
621
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));
627   }
628
629   template<typename T>
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) {
634
635     return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
636      ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Set(st->get<T>(), K, V, C)));
637   }
638
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)));
645   }
646
647   template <typename T>
648   ProgramStateRef remove(ProgramStateRef st,
649                         typename ProgramStateTrait<T>::key_type K,
650                         typename ProgramStateTrait<T>::context_type C) {
651
652     return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
653      ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Remove(st->get<T>(), K, C)));
654   }
655
656   template <typename T>
657   ProgramStateRef remove(ProgramStateRef st) {
658     return removeGDM(st, ProgramStateTrait<T>::GDMIndex());
659   }
660
661   void *FindGDMContext(void *index,
662                        void *(*CreateContext)(llvm::BumpPtrAllocator&),
663                        void  (*DeleteContext)(void*));
664
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);
670
671     return ProgramStateTrait<T>::MakeContext(p);
672   }
673
674   void EndPath(ProgramStateRef St) {
675     ConstraintMgr->EndPath(St);
676   }
677 };
678
679
680 //===----------------------------------------------------------------------===//
681 // Out-of-line method definitions for ProgramState.
682 //===----------------------------------------------------------------------===//
683
684 inline ConstraintManager &ProgramState::getConstraintManager() const {
685   return stateMgr->getConstraintManager();
686 }
687
688 inline const VarRegion* ProgramState::getRegion(const VarDecl *D,
689                                                 const LocationContext *LC) const
690 {
691   return getStateManager().getRegionManager().getVarRegion(D, LC);
692 }
693
694 inline ProgramStateRef ProgramState::assume(DefinedOrUnknownSVal Cond,
695                                       bool Assumption) const {
696   if (Cond.isUnknown())
697     return this;
698
699   return getStateManager().ConstraintMgr
700       ->assume(this, Cond.castAs<DefinedSVal>(), Assumption);
701 }
702
703 inline std::pair<ProgramStateRef , ProgramStateRef >
704 ProgramState::assume(DefinedOrUnknownSVal Cond) const {
705   if (Cond.isUnknown())
706     return std::make_pair(this, this);
707
708   return getStateManager().ConstraintMgr
709       ->assumeDual(this, Cond.castAs<DefinedSVal>());
710 }
711
712 inline ProgramStateRef ProgramState::assumeInclusiveRange(
713     DefinedOrUnknownSVal Val, const llvm::APSInt &From, const llvm::APSInt &To,
714     bool Assumption) const {
715   if (Val.isUnknown())
716     return this;
717
718   assert(Val.getAs<NonLoc>() && "Only NonLocs are supported!");
719
720   return getStateManager().ConstraintMgr->assumeInclusiveRange(
721       this, Val.castAs<NonLoc>(), From, To, Assumption);
722 }
723
724 inline std::pair<ProgramStateRef, ProgramStateRef>
725 ProgramState::assumeInclusiveRange(DefinedOrUnknownSVal Val,
726                                    const llvm::APSInt &From,
727                                    const llvm::APSInt &To) const {
728   if (Val.isUnknown())
729     return std::make_pair(this, this);
730
731   assert(Val.getAs<NonLoc>() && "Only NonLocs are supported!");
732
733   return getStateManager().ConstraintMgr->assumeInclusiveRangeDual(
734       this, Val.castAs<NonLoc>(), From, To);
735 }
736
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);
740   return this;
741 }
742
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()));
749 }
750
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));
757 }
758
759 inline Loc ProgramState::getLValue(const VarDecl *VD,
760                                const LocationContext *LC) const {
761   return getStateManager().StoreMgr->getLValueVar(VD, LC);
762 }
763
764 inline Loc ProgramState::getLValue(const CompoundLiteralExpr *literal,
765                                const LocationContext *LC) const {
766   return getStateManager().StoreMgr->getLValueCompoundLiteral(literal, LC);
767 }
768
769 inline SVal ProgramState::getLValue(const ObjCIvarDecl *D, SVal Base) const {
770   return getStateManager().StoreMgr->getLValueIvar(D, Base);
771 }
772
773 inline SVal ProgramState::getLValue(const FieldDecl *D, SVal Base) const {
774   return getStateManager().StoreMgr->getLValueField(D, Base);
775 }
776
777 inline SVal ProgramState::getLValue(const IndirectFieldDecl *D,
778                                     SVal Base) const {
779   StoreManager &SM = *getStateManager().StoreMgr;
780   for (const auto *I : D->chain()) {
781     Base = SM.getLValueField(cast<FieldDecl>(I), Base);
782   }
783
784   return Base;
785 }
786
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);
790   return UnknownVal();
791 }
792
793 inline SVal ProgramState::getSVal(const Stmt *Ex,
794                                   const LocationContext *LCtx) const{
795   return Env.getSVal(EnvironmentEntry(Ex, LCtx),
796                      *getStateManager().svalBuilder);
797 }
798
799 inline SVal
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);
807   }
808
809   return UnknownVal();
810 }
811
812 inline SVal ProgramState::getRawSVal(Loc LV, QualType T) const {
813   return getStateManager().StoreMgr->getBinding(getStore(), LV, T);
814 }
815
816 inline SVal ProgramState::getSVal(const MemRegion* R, QualType T) const {
817   return getStateManager().StoreMgr->getBinding(getStore(),
818                                                 loc::MemRegionVal(R),
819                                                 T);
820 }
821
822 inline BasicValueFactory &ProgramState::getBasicVals() const {
823   return getStateManager().getBasicVals();
824 }
825
826 inline SymbolManager &ProgramState::getSymbolManager() const {
827   return getStateManager().getSymbolManager();
828 }
829
830 template<typename T>
831 ProgramStateRef ProgramState::add(typename ProgramStateTrait<T>::key_type K) const {
832   return getStateManager().add<T>(this, K, get_context<T>());
833 }
834
835 template <typename T>
836 typename ProgramStateTrait<T>::context_type ProgramState::get_context() const {
837   return getStateManager().get_context<T>();
838 }
839
840 template<typename T>
841 ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K) const {
842   return getStateManager().remove<T>(this, K, get_context<T>());
843 }
844
845 template<typename 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);
849 }
850
851 template <typename T>
852 ProgramStateRef ProgramState::remove() const {
853   return getStateManager().remove<T>(this);
854 }
855
856 template<typename T>
857 ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::data_type D) const {
858   return getStateManager().set<T>(this, D);
859 }
860
861 template<typename T>
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>());
865 }
866
867 template<typename 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);
872 }
873
874 template <typename CB>
875 CB ProgramState::scanReachableSymbols(SVal val) const {
876   CB cb(this);
877   scanReachableSymbols(val, cb);
878   return cb;
879 }
880
881 template <typename CB>
882 CB ProgramState::scanReachableSymbols(const SVal *beg, const SVal *end) const {
883   CB cb(this);
884   scanReachableSymbols(beg, end, cb);
885   return cb;
886 }
887
888 template <typename CB>
889 CB ProgramState::scanReachableSymbols(const MemRegion * const *beg,
890                                  const MemRegion * const *end) const {
891   CB cb(this);
892   scanReachableSymbols(beg, end, cb);
893   return cb;
894 }
895
896 /// \class ScanReachableSymbols
897 /// A utility class that visits the reachable symbols using a custom
898 /// SymbolVisitor. Terminates recursive traversal when the visitor function
899 /// returns false.
900 class ScanReachableSymbols {
901   typedef llvm::DenseSet<const void*> VisitedItems;
902
903   VisitedItems visited;
904   ProgramStateRef state;
905   SymbolVisitor &visitor;
906 public:
907   ScanReachableSymbols(ProgramStateRef st, SymbolVisitor &v)
908       : state(std::move(st)), visitor(v) {}
909
910   bool scan(nonloc::LazyCompoundVal val);
911   bool scan(nonloc::CompoundVal val);
912   bool scan(SVal val);
913   bool scan(const MemRegion *R);
914   bool scan(const SymExpr *sym);
915 };
916
917 } // end ento namespace
918
919 } // end clang namespace
920
921 #endif