]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
Upgrade Unbound to 1.6.8. More to follow.
[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   ProgramStateRef assume(DefinedOrUnknownSVal cond, bool assumption) const;
181
182   /// Assumes both "true" and "false" for \p cond, and returns both
183   /// corresponding states (respectively).
184   ///
185   /// This is more efficient than calling assume() twice. Note that one (but not
186   /// both) of the returned states may be NULL.
187   std::pair<ProgramStateRef, ProgramStateRef>
188   assume(DefinedOrUnknownSVal cond) const;
189
190   ProgramStateRef assumeInBound(DefinedOrUnknownSVal idx,
191                                DefinedOrUnknownSVal upperBound,
192                                bool assumption,
193                                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   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   std::pair<ProgramStateRef, ProgramStateRef>
212   assumeInclusiveRange(DefinedOrUnknownSVal Val, const llvm::APSInt &From,
213                        const llvm::APSInt &To) const;
214
215   /// \brief Check if the given SVal is constrained to zero or is a zero
216   ///        constant.
217   ConditionTruthVal isNull(SVal V) const;
218
219   /// Utility method for getting regions.
220   const VarRegion* getRegion(const VarDecl *D, const LocationContext *LC) const;
221
222   //==---------------------------------------------------------------------==//
223   // Binding and retrieving values to/from the environment and symbolic store.
224   //==---------------------------------------------------------------------==//
225
226   /// Create a new state by binding the value 'V' to the statement 'S' in the
227   /// state's environment.
228   ProgramStateRef BindExpr(const Stmt *S, const LocationContext *LCtx,
229                                SVal V, bool Invalidate = true) const;
230
231   ProgramStateRef bindLoc(Loc location,
232                           SVal V,
233                           const LocationContext *LCtx,
234                           bool notifyChanges = true) const;
235
236   ProgramStateRef bindLoc(SVal location, SVal V, const LocationContext *LCtx) const;
237
238   ProgramStateRef bindDefault(SVal loc, SVal V, const LocationContext *LCtx) const;
239
240   ProgramStateRef killBinding(Loc LV) const;
241
242   /// \brief Returns the state with bindings for the given regions
243   ///  cleared from the store.
244   ///
245   /// Optionally invalidates global regions as well.
246   ///
247   /// \param Regions the set of regions to be invalidated.
248   /// \param E the expression that caused the invalidation.
249   /// \param BlockCount The number of times the current basic block has been
250   //         visited.
251   /// \param CausesPointerEscape the flag is set to true when
252   ///        the invalidation entails escape of a symbol (representing a
253   ///        pointer). For example, due to it being passed as an argument in a
254   ///        call.
255   /// \param IS the set of invalidated symbols.
256   /// \param Call if non-null, the invalidated regions represent parameters to
257   ///        the call and should be considered directly invalidated.
258   /// \param ITraits information about special handling for a particular
259   ///        region/symbol.
260   ProgramStateRef
261   invalidateRegions(ArrayRef<const MemRegion *> Regions, const Expr *E,
262                     unsigned BlockCount, const LocationContext *LCtx,
263                     bool CausesPointerEscape, InvalidatedSymbols *IS = nullptr,
264                     const CallEvent *Call = nullptr,
265                     RegionAndSymbolInvalidationTraits *ITraits = nullptr) const;
266
267   ProgramStateRef
268   invalidateRegions(ArrayRef<SVal> Regions, const Expr *E,
269                     unsigned BlockCount, const LocationContext *LCtx,
270                     bool CausesPointerEscape, InvalidatedSymbols *IS = nullptr,
271                     const CallEvent *Call = nullptr,
272                     RegionAndSymbolInvalidationTraits *ITraits = nullptr) const;
273
274   /// enterStackFrame - Returns the state for entry to the given stack frame,
275   ///  preserving the current state.
276   ProgramStateRef enterStackFrame(const CallEvent &Call,
277                                   const StackFrameContext *CalleeCtx) const;
278
279   /// Get the lvalue for a variable reference.
280   Loc getLValue(const VarDecl *D, const LocationContext *LC) const;
281
282   Loc getLValue(const CompoundLiteralExpr *literal,
283                 const LocationContext *LC) const;
284
285   /// Get the lvalue for an ivar reference.
286   SVal getLValue(const ObjCIvarDecl *decl, SVal base) const;
287
288   /// Get the lvalue for a field reference.
289   SVal getLValue(const FieldDecl *decl, SVal Base) const;
290
291   /// Get the lvalue for an indirect field reference.
292   SVal getLValue(const IndirectFieldDecl *decl, SVal Base) const;
293
294   /// Get the lvalue for an array index.
295   SVal getLValue(QualType ElementType, SVal Idx, SVal Base) const;
296
297   /// Returns the SVal bound to the statement 'S' in the state's environment.
298   SVal getSVal(const Stmt *S, const LocationContext *LCtx) const;
299
300   SVal getSValAsScalarOrLoc(const Stmt *Ex, const LocationContext *LCtx) const;
301
302   /// \brief Return the value bound to the specified location.
303   /// Returns UnknownVal() if none found.
304   SVal getSVal(Loc LV, QualType T = QualType()) const;
305
306   /// Returns the "raw" SVal bound to LV before any value simplfication.
307   SVal getRawSVal(Loc LV, QualType T= QualType()) const;
308
309   /// \brief Return the value bound to the specified location.
310   /// Returns UnknownVal() if none found.
311   SVal getSVal(const MemRegion* R, QualType T = QualType()) const;
312
313   /// \brief Return the value bound to the specified location, assuming
314   /// that the value is a scalar integer or an enumeration or a pointer.
315   /// Returns UnknownVal() if none found or the region is not known to hold
316   /// a value of such type.
317   SVal getSValAsScalarOrLoc(const MemRegion *R) const;
318
319   /// \brief Visits the symbols reachable from the given SVal using the provided
320   /// SymbolVisitor.
321   ///
322   /// This is a convenience API. Consider using ScanReachableSymbols class
323   /// directly when making multiple scans on the same state with the same
324   /// visitor to avoid repeated initialization cost.
325   /// \sa ScanReachableSymbols
326   bool scanReachableSymbols(SVal val, SymbolVisitor& visitor) const;
327
328   /// \brief Visits the symbols reachable from the SVals in the given range
329   /// using the provided SymbolVisitor.
330   bool scanReachableSymbols(const SVal *I, const SVal *E,
331                             SymbolVisitor &visitor) const;
332
333   /// \brief Visits the symbols reachable from the regions in the given
334   /// MemRegions range using the provided SymbolVisitor.
335   bool scanReachableSymbols(const MemRegion * const *I,
336                             const MemRegion * const *E,
337                             SymbolVisitor &visitor) const;
338
339   template <typename CB> CB scanReachableSymbols(SVal val) const;
340   template <typename CB> CB scanReachableSymbols(const SVal *beg,
341                                                  const SVal *end) const;
342
343   template <typename CB> CB
344   scanReachableSymbols(const MemRegion * const *beg,
345                        const MemRegion * const *end) const;
346
347   /// Create a new state in which the statement is marked as tainted.
348   ProgramStateRef addTaint(const Stmt *S, const LocationContext *LCtx,
349                                TaintTagType Kind = TaintTagGeneric) const;
350
351   /// Create a new state in which the value is marked as tainted.
352   ProgramStateRef addTaint(SVal V, TaintTagType Kind = TaintTagGeneric) const;
353
354   /// Create a new state in which the symbol is marked as tainted.
355   ProgramStateRef addTaint(SymbolRef S,
356                                TaintTagType Kind = TaintTagGeneric) const;
357
358   /// Create a new state in which the region symbol is marked as tainted.
359   ProgramStateRef addTaint(const MemRegion *R,
360                                TaintTagType Kind = TaintTagGeneric) const;
361
362   /// Create a new state in a which a sub-region of a given symbol is tainted.
363   /// This might be necessary when referring to regions that can not have an
364   /// individual symbol, e.g. if they are represented by the default binding of
365   /// a LazyCompoundVal.
366   ProgramStateRef addPartialTaint(SymbolRef ParentSym,
367                                   const SubRegion *SubRegion,
368                                   TaintTagType Kind = TaintTagGeneric) const;
369
370   /// Check if the statement is tainted in the current state.
371   bool isTainted(const Stmt *S, const LocationContext *LCtx,
372                  TaintTagType Kind = TaintTagGeneric) const;
373   bool isTainted(SVal V, TaintTagType Kind = TaintTagGeneric) const;
374   bool isTainted(SymbolRef Sym, TaintTagType Kind = TaintTagGeneric) const;
375   bool isTainted(const MemRegion *Reg, TaintTagType Kind=TaintTagGeneric) const;
376
377   //==---------------------------------------------------------------------==//
378   // Accessing the Generic Data Map (GDM).
379   //==---------------------------------------------------------------------==//
380
381   void *const* FindGDM(void *K) const;
382
383   template<typename T>
384   ProgramStateRef add(typename ProgramStateTrait<T>::key_type K) const;
385
386   template <typename T>
387   typename ProgramStateTrait<T>::data_type
388   get() const {
389     return ProgramStateTrait<T>::MakeData(FindGDM(ProgramStateTrait<T>::GDMIndex()));
390   }
391
392   template<typename T>
393   typename ProgramStateTrait<T>::lookup_type
394   get(typename ProgramStateTrait<T>::key_type key) const {
395     void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
396     return ProgramStateTrait<T>::Lookup(ProgramStateTrait<T>::MakeData(d), key);
397   }
398
399   template <typename T>
400   typename ProgramStateTrait<T>::context_type get_context() const;
401
402
403   template<typename T>
404   ProgramStateRef remove(typename ProgramStateTrait<T>::key_type K) const;
405
406   template<typename T>
407   ProgramStateRef remove(typename ProgramStateTrait<T>::key_type K,
408                         typename ProgramStateTrait<T>::context_type C) const;
409   template <typename T>
410   ProgramStateRef remove() const;
411
412   template<typename T>
413   ProgramStateRef set(typename ProgramStateTrait<T>::data_type D) const;
414
415   template<typename T>
416   ProgramStateRef set(typename ProgramStateTrait<T>::key_type K,
417                      typename ProgramStateTrait<T>::value_type E) const;
418
419   template<typename T>
420   ProgramStateRef set(typename ProgramStateTrait<T>::key_type K,
421                      typename ProgramStateTrait<T>::value_type E,
422                      typename ProgramStateTrait<T>::context_type C) const;
423
424   template<typename T>
425   bool contains(typename ProgramStateTrait<T>::key_type key) const {
426     void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
427     return ProgramStateTrait<T>::Contains(ProgramStateTrait<T>::MakeData(d), key);
428   }
429
430   // Pretty-printing.
431   void print(raw_ostream &Out, const char *nl = "\n",
432              const char *sep = "") const;
433   void printDOT(raw_ostream &Out) const;
434   void printTaint(raw_ostream &Out, const char *nl = "\n",
435                   const char *sep = "") const;
436
437   void dump() const;
438   void dumpTaint() const;
439
440 private:
441   friend void ProgramStateRetain(const ProgramState *state);
442   friend void ProgramStateRelease(const ProgramState *state);
443
444   /// \sa invalidateValues()
445   /// \sa invalidateRegions()
446   ProgramStateRef
447   invalidateRegionsImpl(ArrayRef<SVal> Values,
448                         const Expr *E, unsigned BlockCount,
449                         const LocationContext *LCtx,
450                         bool ResultsInSymbolEscape,
451                         InvalidatedSymbols *IS,
452                         RegionAndSymbolInvalidationTraits *HTraits,
453                         const CallEvent *Call) const;
454 };
455
456 //===----------------------------------------------------------------------===//
457 // ProgramStateManager - Factory object for ProgramStates.
458 //===----------------------------------------------------------------------===//
459
460 class ProgramStateManager {
461   friend class ProgramState;
462   friend void ProgramStateRelease(const ProgramState *state);
463 private:
464   /// Eng - The SubEngine that owns this state manager.
465   SubEngine *Eng; /* Can be null. */
466
467   EnvironmentManager                   EnvMgr;
468   std::unique_ptr<StoreManager>        StoreMgr;
469   std::unique_ptr<ConstraintManager>   ConstraintMgr;
470
471   ProgramState::GenericDataMap::Factory     GDMFactory;
472   TaintedSubRegions::Factory TSRFactory;
473
474   typedef llvm::DenseMap<void*,std::pair<void*,void (*)(void*)> > GDMContextsTy;
475   GDMContextsTy GDMContexts;
476
477   /// StateSet - FoldingSet containing all the states created for analyzing
478   ///  a particular function.  This is used to unique states.
479   llvm::FoldingSet<ProgramState> StateSet;
480
481   /// Object that manages the data for all created SVals.
482   std::unique_ptr<SValBuilder> svalBuilder;
483
484   /// Manages memory for created CallEvents.
485   std::unique_ptr<CallEventManager> CallEventMgr;
486
487   /// A BumpPtrAllocator to allocate states.
488   llvm::BumpPtrAllocator &Alloc;
489
490   /// A vector of ProgramStates that we can reuse.
491   std::vector<ProgramState *> freeStates;
492
493 public:
494   ProgramStateManager(ASTContext &Ctx,
495                  StoreManagerCreator CreateStoreManager,
496                  ConstraintManagerCreator CreateConstraintManager,
497                  llvm::BumpPtrAllocator& alloc,
498                  SubEngine *subeng);
499
500   ~ProgramStateManager();
501
502   ProgramStateRef getInitialState(const LocationContext *InitLoc);
503
504   ASTContext &getContext() { return svalBuilder->getContext(); }
505   const ASTContext &getContext() const { return svalBuilder->getContext(); }
506
507   BasicValueFactory &getBasicVals() {
508     return svalBuilder->getBasicValueFactory();
509   }
510
511   SValBuilder &getSValBuilder() {
512     return *svalBuilder;
513   }
514
515   SymbolManager &getSymbolManager() {
516     return svalBuilder->getSymbolManager();
517   }
518   const SymbolManager &getSymbolManager() const {
519     return svalBuilder->getSymbolManager();
520   }
521
522   llvm::BumpPtrAllocator& getAllocator() { return Alloc; }
523
524   MemRegionManager& getRegionManager() {
525     return svalBuilder->getRegionManager();
526   }
527   const MemRegionManager& getRegionManager() const {
528     return svalBuilder->getRegionManager();
529   }
530
531   CallEventManager &getCallEventManager() { return *CallEventMgr; }
532
533   StoreManager& getStoreManager() { return *StoreMgr; }
534   ConstraintManager& getConstraintManager() { return *ConstraintMgr; }
535   SubEngine* getOwningEngine() { return Eng; }
536
537   ProgramStateRef removeDeadBindings(ProgramStateRef St,
538                                     const StackFrameContext *LCtx,
539                                     SymbolReaper& SymReaper);
540
541 public:
542
543   SVal ArrayToPointer(Loc Array, QualType ElementTy) {
544     return StoreMgr->ArrayToPointer(Array, ElementTy);
545   }
546
547   // Methods that manipulate the GDM.
548   ProgramStateRef addGDM(ProgramStateRef St, void *Key, void *Data);
549   ProgramStateRef removeGDM(ProgramStateRef state, void *Key);
550
551   // Methods that query & manipulate the Store.
552
553   void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler& F) {
554     StoreMgr->iterBindings(state->getStore(), F);
555   }
556
557   ProgramStateRef getPersistentState(ProgramState &Impl);
558   ProgramStateRef getPersistentStateWithGDM(ProgramStateRef FromState,
559                                            ProgramStateRef GDMState);
560
561   bool haveEqualEnvironments(ProgramStateRef S1, ProgramStateRef S2) {
562     return S1->Env == S2->Env;
563   }
564
565   bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2) {
566     return S1->store == S2->store;
567   }
568
569   //==---------------------------------------------------------------------==//
570   // Generic Data Map methods.
571   //==---------------------------------------------------------------------==//
572   //
573   // ProgramStateManager and ProgramState support a "generic data map" that allows
574   // different clients of ProgramState objects to embed arbitrary data within a
575   // ProgramState object.  The generic data map is essentially an immutable map
576   // from a "tag" (that acts as the "key" for a client) and opaque values.
577   // Tags/keys and values are simply void* values.  The typical way that clients
578   // generate unique tags are by taking the address of a static variable.
579   // Clients are responsible for ensuring that data values referred to by a
580   // the data pointer are immutable (and thus are essentially purely functional
581   // data).
582   //
583   // The templated methods below use the ProgramStateTrait<T> class
584   // to resolve keys into the GDM and to return data values to clients.
585   //
586
587   // Trait based GDM dispatch.
588   template <typename T>
589   ProgramStateRef set(ProgramStateRef st, typename ProgramStateTrait<T>::data_type D) {
590     return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
591                   ProgramStateTrait<T>::MakeVoidPtr(D));
592   }
593
594   template<typename T>
595   ProgramStateRef set(ProgramStateRef st,
596                      typename ProgramStateTrait<T>::key_type K,
597                      typename ProgramStateTrait<T>::value_type V,
598                      typename ProgramStateTrait<T>::context_type C) {
599
600     return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
601      ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Set(st->get<T>(), K, V, C)));
602   }
603
604   template <typename T>
605   ProgramStateRef add(ProgramStateRef st,
606                      typename ProgramStateTrait<T>::key_type K,
607                      typename ProgramStateTrait<T>::context_type C) {
608     return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
609         ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Add(st->get<T>(), K, C)));
610   }
611
612   template <typename T>
613   ProgramStateRef remove(ProgramStateRef st,
614                         typename ProgramStateTrait<T>::key_type K,
615                         typename ProgramStateTrait<T>::context_type C) {
616
617     return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
618      ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Remove(st->get<T>(), K, C)));
619   }
620
621   template <typename T>
622   ProgramStateRef remove(ProgramStateRef st) {
623     return removeGDM(st, ProgramStateTrait<T>::GDMIndex());
624   }
625
626   void *FindGDMContext(void *index,
627                        void *(*CreateContext)(llvm::BumpPtrAllocator&),
628                        void  (*DeleteContext)(void*));
629
630   template <typename T>
631   typename ProgramStateTrait<T>::context_type get_context() {
632     void *p = FindGDMContext(ProgramStateTrait<T>::GDMIndex(),
633                              ProgramStateTrait<T>::CreateContext,
634                              ProgramStateTrait<T>::DeleteContext);
635
636     return ProgramStateTrait<T>::MakeContext(p);
637   }
638
639   void EndPath(ProgramStateRef St) {
640     ConstraintMgr->EndPath(St);
641   }
642 };
643
644
645 //===----------------------------------------------------------------------===//
646 // Out-of-line method definitions for ProgramState.
647 //===----------------------------------------------------------------------===//
648
649 inline ConstraintManager &ProgramState::getConstraintManager() const {
650   return stateMgr->getConstraintManager();
651 }
652
653 inline const VarRegion* ProgramState::getRegion(const VarDecl *D,
654                                                 const LocationContext *LC) const
655 {
656   return getStateManager().getRegionManager().getVarRegion(D, LC);
657 }
658
659 inline ProgramStateRef ProgramState::assume(DefinedOrUnknownSVal Cond,
660                                       bool Assumption) const {
661   if (Cond.isUnknown())
662     return this;
663
664   return getStateManager().ConstraintMgr
665       ->assume(this, Cond.castAs<DefinedSVal>(), Assumption);
666 }
667
668 inline std::pair<ProgramStateRef , ProgramStateRef >
669 ProgramState::assume(DefinedOrUnknownSVal Cond) const {
670   if (Cond.isUnknown())
671     return std::make_pair(this, this);
672
673   return getStateManager().ConstraintMgr
674       ->assumeDual(this, Cond.castAs<DefinedSVal>());
675 }
676
677 inline ProgramStateRef ProgramState::assumeInclusiveRange(
678     DefinedOrUnknownSVal Val, const llvm::APSInt &From, const llvm::APSInt &To,
679     bool Assumption) const {
680   if (Val.isUnknown())
681     return this;
682
683   assert(Val.getAs<NonLoc>() && "Only NonLocs are supported!");
684
685   return getStateManager().ConstraintMgr->assumeInclusiveRange(
686       this, Val.castAs<NonLoc>(), From, To, Assumption);
687 }
688
689 inline std::pair<ProgramStateRef, ProgramStateRef>
690 ProgramState::assumeInclusiveRange(DefinedOrUnknownSVal Val,
691                                    const llvm::APSInt &From,
692                                    const llvm::APSInt &To) const {
693   if (Val.isUnknown())
694     return std::make_pair(this, this);
695
696   assert(Val.getAs<NonLoc>() && "Only NonLocs are supported!");
697
698   return getStateManager().ConstraintMgr->assumeInclusiveRangeDual(
699       this, Val.castAs<NonLoc>(), From, To);
700 }
701
702 inline ProgramStateRef ProgramState::bindLoc(SVal LV, SVal V, const LocationContext *LCtx) const {
703   if (Optional<Loc> L = LV.getAs<Loc>())
704     return bindLoc(*L, V, LCtx);
705   return this;
706 }
707
708 inline Loc ProgramState::getLValue(const VarDecl *VD,
709                                const LocationContext *LC) const {
710   return getStateManager().StoreMgr->getLValueVar(VD, LC);
711 }
712
713 inline Loc ProgramState::getLValue(const CompoundLiteralExpr *literal,
714                                const LocationContext *LC) const {
715   return getStateManager().StoreMgr->getLValueCompoundLiteral(literal, LC);
716 }
717
718 inline SVal ProgramState::getLValue(const ObjCIvarDecl *D, SVal Base) const {
719   return getStateManager().StoreMgr->getLValueIvar(D, Base);
720 }
721
722 inline SVal ProgramState::getLValue(const FieldDecl *D, SVal Base) const {
723   return getStateManager().StoreMgr->getLValueField(D, Base);
724 }
725
726 inline SVal ProgramState::getLValue(const IndirectFieldDecl *D,
727                                     SVal Base) const {
728   StoreManager &SM = *getStateManager().StoreMgr;
729   for (const auto *I : D->chain()) {
730     Base = SM.getLValueField(cast<FieldDecl>(I), Base);
731   }
732
733   return Base;
734 }
735
736 inline SVal ProgramState::getLValue(QualType ElementType, SVal Idx, SVal Base) const{
737   if (Optional<NonLoc> N = Idx.getAs<NonLoc>())
738     return getStateManager().StoreMgr->getLValueElement(ElementType, *N, Base);
739   return UnknownVal();
740 }
741
742 inline SVal ProgramState::getSVal(const Stmt *Ex,
743                                   const LocationContext *LCtx) const{
744   return Env.getSVal(EnvironmentEntry(Ex, LCtx),
745                      *getStateManager().svalBuilder);
746 }
747
748 inline SVal
749 ProgramState::getSValAsScalarOrLoc(const Stmt *S,
750                                    const LocationContext *LCtx) const {
751   if (const Expr *Ex = dyn_cast<Expr>(S)) {
752     QualType T = Ex->getType();
753     if (Ex->isGLValue() || Loc::isLocType(T) ||
754         T->isIntegralOrEnumerationType())
755       return getSVal(S, LCtx);
756   }
757
758   return UnknownVal();
759 }
760
761 inline SVal ProgramState::getRawSVal(Loc LV, QualType T) const {
762   return getStateManager().StoreMgr->getBinding(getStore(), LV, T);
763 }
764
765 inline SVal ProgramState::getSVal(const MemRegion* R, QualType T) const {
766   return getStateManager().StoreMgr->getBinding(getStore(),
767                                                 loc::MemRegionVal(R),
768                                                 T);
769 }
770
771 inline BasicValueFactory &ProgramState::getBasicVals() const {
772   return getStateManager().getBasicVals();
773 }
774
775 inline SymbolManager &ProgramState::getSymbolManager() const {
776   return getStateManager().getSymbolManager();
777 }
778
779 template<typename T>
780 ProgramStateRef ProgramState::add(typename ProgramStateTrait<T>::key_type K) const {
781   return getStateManager().add<T>(this, K, get_context<T>());
782 }
783
784 template <typename T>
785 typename ProgramStateTrait<T>::context_type ProgramState::get_context() const {
786   return getStateManager().get_context<T>();
787 }
788
789 template<typename T>
790 ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K) const {
791   return getStateManager().remove<T>(this, K, get_context<T>());
792 }
793
794 template<typename T>
795 ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K,
796                                typename ProgramStateTrait<T>::context_type C) const {
797   return getStateManager().remove<T>(this, K, C);
798 }
799
800 template <typename T>
801 ProgramStateRef ProgramState::remove() const {
802   return getStateManager().remove<T>(this);
803 }
804
805 template<typename T>
806 ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::data_type D) const {
807   return getStateManager().set<T>(this, D);
808 }
809
810 template<typename T>
811 ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
812                             typename ProgramStateTrait<T>::value_type E) const {
813   return getStateManager().set<T>(this, K, E, get_context<T>());
814 }
815
816 template<typename T>
817 ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
818                             typename ProgramStateTrait<T>::value_type E,
819                             typename ProgramStateTrait<T>::context_type C) const {
820   return getStateManager().set<T>(this, K, E, C);
821 }
822
823 template <typename CB>
824 CB ProgramState::scanReachableSymbols(SVal val) const {
825   CB cb(this);
826   scanReachableSymbols(val, cb);
827   return cb;
828 }
829
830 template <typename CB>
831 CB ProgramState::scanReachableSymbols(const SVal *beg, const SVal *end) const {
832   CB cb(this);
833   scanReachableSymbols(beg, end, cb);
834   return cb;
835 }
836
837 template <typename CB>
838 CB ProgramState::scanReachableSymbols(const MemRegion * const *beg,
839                                  const MemRegion * const *end) const {
840   CB cb(this);
841   scanReachableSymbols(beg, end, cb);
842   return cb;
843 }
844
845 /// \class ScanReachableSymbols
846 /// A utility class that visits the reachable symbols using a custom
847 /// SymbolVisitor. Terminates recursive traversal when the visitor function
848 /// returns false.
849 class ScanReachableSymbols {
850   typedef llvm::DenseSet<const void*> VisitedItems;
851
852   VisitedItems visited;
853   ProgramStateRef state;
854   SymbolVisitor &visitor;
855 public:
856   ScanReachableSymbols(ProgramStateRef st, SymbolVisitor &v)
857       : state(std::move(st)), visitor(v) {}
858
859   bool scan(nonloc::LazyCompoundVal val);
860   bool scan(nonloc::CompoundVal val);
861   bool scan(SVal val);
862   bool scan(const MemRegion *R);
863   bool scan(const SymExpr *sym);
864 };
865
866 } // end ento namespace
867
868 } // end clang namespace
869
870 #endif