• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_GR_VALUESTATE_H
15 #define LLVM_CLANG_GR_VALUESTATE_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/Store.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/TaintTag.h"
25 #include "llvm/ADT/PointerIntPair.h"
26 #include "llvm/ADT/FoldingSet.h"
27 #include "llvm/ADT/ImmutableMap.h"
28 
29 namespace llvm {
30 class APSInt;
31 class BumpPtrAllocator;
32 }
33 
34 namespace clang {
35 class ASTContext;
36 
37 namespace ento {
38 
39 class CallEvent;
40 class CallEventManager;
41 
42 typedef ConstraintManager* (*ConstraintManagerCreator)(ProgramStateManager&,
43                                                        SubEngine&);
44 typedef StoreManager* (*StoreManagerCreator)(ProgramStateManager&);
45 
46 //===----------------------------------------------------------------------===//
47 // ProgramStateTrait - Traits used by the Generic Data Map of a ProgramState.
48 //===----------------------------------------------------------------------===//
49 
50 template <typename T> struct ProgramStatePartialTrait;
51 
52 template <typename T> struct ProgramStateTrait {
53   typedef typename T::data_type data_type;
MakeVoidPtrProgramStateTrait54   static inline void *MakeVoidPtr(data_type D) { return (void*) D; }
MakeDataProgramStateTrait55   static inline data_type MakeData(void *const* P) {
56     return P ? (data_type) *P : (data_type) 0;
57   }
58 };
59 
60 /// \class ProgramState
61 /// ProgramState - This class encapsulates:
62 ///
63 ///    1. A mapping from expressions to values (Environment)
64 ///    2. A mapping from locations to values (Store)
65 ///    3. Constraints on symbolic values (GenericDataMap)
66 ///
67 ///  Together these represent the "abstract state" of a program.
68 ///
69 ///  ProgramState is intended to be used as a functional object; that is,
70 ///  once it is created and made "persistent" in a FoldingSet, its
71 ///  values will never change.
72 class ProgramState : public llvm::FoldingSetNode {
73 public:
74   typedef llvm::ImmutableSet<llvm::APSInt*>                IntSetTy;
75   typedef llvm::ImmutableMap<void*, void*>                 GenericDataMap;
76 
77 private:
78   void operator=(const ProgramState& R) const; // Do not implement.
79 
80   friend class ProgramStateManager;
81   friend class ExplodedGraph;
82   friend class ExplodedNode;
83 
84   ProgramStateManager *stateMgr;
85   Environment Env;           // Maps a Stmt to its current SVal.
86   Store store;               // Maps a location to its current value.
87   GenericDataMap   GDM;      // Custom data stored by a client of this class.
88   unsigned refCount;
89 
90   /// makeWithStore - Return a ProgramState with the same values as the current
91   ///  state with the exception of using the specified Store.
92   ProgramStateRef makeWithStore(const StoreRef &store) const;
93 
94   void setStore(const StoreRef &storeRef);
95 
96 public:
97   /// This ctor is used when creating the first ProgramState object.
98   ProgramState(ProgramStateManager *mgr, const Environment& env,
99           StoreRef st, GenericDataMap gdm);
100 
101   /// Copy ctor - We must explicitly define this or else the "Next" ptr
102   ///  in FoldingSetNode will also get copied.
103   ProgramState(const ProgramState &RHS);
104 
105   ~ProgramState();
106 
107   /// Return the ProgramStateManager associated with this state.
getStateManager()108   ProgramStateManager &getStateManager() const {
109     return *stateMgr;
110   }
111 
112   /// Return the ConstraintManager.
113   ConstraintManager &getConstraintManager() const;
114 
115   /// getEnvironment - Return the environment associated with this state.
116   ///  The environment is the mapping from expressions to values.
getEnvironment()117   const Environment& getEnvironment() const { return Env; }
118 
119   /// Return the store associated with this state.  The store
120   ///  is a mapping from locations to values.
getStore()121   Store getStore() const { return store; }
122 
123 
124   /// getGDM - Return the generic data map associated with this state.
getGDM()125   GenericDataMap getGDM() const { return GDM; }
126 
setGDM(GenericDataMap gdm)127   void setGDM(GenericDataMap gdm) { GDM = gdm; }
128 
129   /// Profile - Profile the contents of a ProgramState object for use in a
130   ///  FoldingSet.  Two ProgramState objects are considered equal if they
131   ///  have the same Environment, Store, and GenericDataMap.
Profile(llvm::FoldingSetNodeID & ID,const ProgramState * V)132   static void Profile(llvm::FoldingSetNodeID& ID, const ProgramState *V) {
133     V->Env.Profile(ID);
134     ID.AddPointer(V->store);
135     V->GDM.Profile(ID);
136   }
137 
138   /// Profile - Used to profile the contents of this object for inclusion
139   ///  in a FoldingSet.
Profile(llvm::FoldingSetNodeID & ID)140   void Profile(llvm::FoldingSetNodeID& ID) const {
141     Profile(ID, this);
142   }
143 
144   BasicValueFactory &getBasicVals() const;
145   SymbolManager &getSymbolManager() const;
146 
147   //==---------------------------------------------------------------------==//
148   // Constraints on values.
149   //==---------------------------------------------------------------------==//
150   //
151   // Each ProgramState records constraints on symbolic values.  These constraints
152   // are managed using the ConstraintManager associated with a ProgramStateManager.
153   // As constraints gradually accrue on symbolic values, added constraints
154   // may conflict and indicate that a state is infeasible (as no real values
155   // could satisfy all the constraints).  This is the principal mechanism
156   // for modeling path-sensitivity in ExprEngine/ProgramState.
157   //
158   // Various "assume" methods form the interface for adding constraints to
159   // symbolic values.  A call to 'assume' indicates an assumption being placed
160   // on one or symbolic values.  'assume' methods take the following inputs:
161   //
162   //  (1) A ProgramState object representing the current state.
163   //
164   //  (2) The assumed constraint (which is specific to a given "assume" method).
165   //
166   //  (3) A binary value "Assumption" that indicates whether the constraint is
167   //      assumed to be true or false.
168   //
169   // The output of "assume*" is a new ProgramState object with the added constraints.
170   // If no new state is feasible, NULL is returned.
171   //
172 
173   ProgramStateRef assume(DefinedOrUnknownSVal cond, bool assumption) const;
174 
175   /// This method assumes both "true" and "false" for 'cond', and
176   ///  returns both corresponding states.  It's shorthand for doing
177   ///  'assume' twice.
178   std::pair<ProgramStateRef , ProgramStateRef >
179   assume(DefinedOrUnknownSVal cond) const;
180 
181   ProgramStateRef assumeInBound(DefinedOrUnknownSVal idx,
182                                DefinedOrUnknownSVal upperBound,
183                                bool assumption,
184                                QualType IndexType = QualType()) const;
185 
186   /// Utility method for getting regions.
187   const VarRegion* getRegion(const VarDecl *D, const LocationContext *LC) const;
188 
189   //==---------------------------------------------------------------------==//
190   // Binding and retrieving values to/from the environment and symbolic store.
191   //==---------------------------------------------------------------------==//
192 
193   /// \brief Create a new state with the specified CompoundLiteral binding.
194   /// \param CL the compound literal expression (the binding key)
195   /// \param LC the LocationContext of the binding
196   /// \param V the value to bind.
197   ProgramStateRef bindCompoundLiteral(const CompoundLiteralExpr *CL,
198                                       const LocationContext *LC,
199                                       SVal V) const;
200 
201   /// Create a new state by binding the value 'V' to the statement 'S' in the
202   /// state's environment.
203   ProgramStateRef BindExpr(const Stmt *S, const LocationContext *LCtx,
204                                SVal V, bool Invalidate = true) const;
205 
206   /// Create a new state by binding the value 'V' and location 'locaton' to the
207   /// statement 'S' in the state's environment.
208   ProgramStateRef bindExprAndLocation(const Stmt *S,
209                                           const LocationContext *LCtx,
210                                           SVal location, SVal V) const;
211 
212   ProgramStateRef bindLoc(Loc location,
213                           SVal V,
214                           bool notifyChanges = true) const;
215 
216   ProgramStateRef bindLoc(SVal location, SVal V) const;
217 
218   ProgramStateRef bindDefault(SVal loc, SVal V) const;
219 
220   ProgramStateRef killBinding(Loc LV) const;
221 
222   /// invalidateRegions - Returns the state with bindings for the given regions
223   ///  cleared from the store. The regions are provided as a continuous array
224   ///  from Begin to End. Optionally invalidates global regions as well.
225   ProgramStateRef invalidateRegions(ArrayRef<const MemRegion *> Regions,
226                                const Expr *E, unsigned BlockCount,
227                                const LocationContext *LCtx,
228                                StoreManager::InvalidatedSymbols *IS = 0,
229                                const CallEvent *Call = 0) const;
230 
231   /// enterStackFrame - Returns the state for entry to the given stack frame,
232   ///  preserving the current state.
233   ProgramStateRef enterStackFrame(const CallEvent &Call,
234                                   const StackFrameContext *CalleeCtx) const;
235 
236   /// Get the lvalue for a variable reference.
237   Loc getLValue(const VarDecl *D, const LocationContext *LC) const;
238 
239   Loc getLValue(const CompoundLiteralExpr *literal,
240                 const LocationContext *LC) const;
241 
242   /// Get the lvalue for an ivar reference.
243   SVal getLValue(const ObjCIvarDecl *decl, SVal base) const;
244 
245   /// Get the lvalue for a field reference.
246   SVal getLValue(const FieldDecl *decl, SVal Base) const;
247 
248   /// Get the lvalue for an indirect field reference.
249   SVal getLValue(const IndirectFieldDecl *decl, SVal Base) const;
250 
251   /// Get the lvalue for an array index.
252   SVal getLValue(QualType ElementType, SVal Idx, SVal Base) const;
253 
254   /// Returns the SVal bound to the statement 'S' in the state's environment.
255   SVal getSVal(const Stmt *S, const LocationContext *LCtx,
256                bool useOnlyDirectBindings = false) const;
257 
258   SVal getSValAsScalarOrLoc(const Stmt *Ex, const LocationContext *LCtx) const;
259 
260   /// \brief Return the value bound to the specified location.
261   /// Returns UnknownVal() if none found.
262   SVal getSVal(Loc LV, QualType T = QualType()) const;
263 
264   /// Returns the "raw" SVal bound to LV before any value simplfication.
265   SVal getRawSVal(Loc LV, QualType T= QualType()) const;
266 
267   /// \brief Return the value bound to the specified location.
268   /// Returns UnknownVal() if none found.
269   SVal getSVal(const MemRegion* R) const;
270 
271   SVal getSValAsScalarOrLoc(const MemRegion *R) const;
272 
273   /// \brief Visits the symbols reachable from the given SVal using the provided
274   /// SymbolVisitor.
275   ///
276   /// This is a convenience API. Consider using ScanReachableSymbols class
277   /// directly when making multiple scans on the same state with the same
278   /// visitor to avoid repeated initialization cost.
279   /// \sa ScanReachableSymbols
280   bool scanReachableSymbols(SVal val, SymbolVisitor& visitor) const;
281 
282   /// \brief Visits the symbols reachable from the SVals in the given range
283   /// using the provided SymbolVisitor.
284   bool scanReachableSymbols(const SVal *I, const SVal *E,
285                             SymbolVisitor &visitor) const;
286 
287   /// \brief Visits the symbols reachable from the regions in the given
288   /// MemRegions range using the provided SymbolVisitor.
289   bool scanReachableSymbols(const MemRegion * const *I,
290                             const MemRegion * const *E,
291                             SymbolVisitor &visitor) const;
292 
293   template <typename CB> CB scanReachableSymbols(SVal val) const;
294   template <typename CB> CB scanReachableSymbols(const SVal *beg,
295                                                  const SVal *end) const;
296 
297   template <typename CB> CB
298   scanReachableSymbols(const MemRegion * const *beg,
299                        const MemRegion * const *end) const;
300 
301   /// Create a new state in which the statement is marked as tainted.
302   ProgramStateRef addTaint(const Stmt *S, const LocationContext *LCtx,
303                                TaintTagType Kind = TaintTagGeneric) const;
304 
305   /// Create a new state in which the symbol is marked as tainted.
306   ProgramStateRef addTaint(SymbolRef S,
307                                TaintTagType Kind = TaintTagGeneric) const;
308 
309   /// Create a new state in which the region symbol is marked as tainted.
310   ProgramStateRef addTaint(const MemRegion *R,
311                                TaintTagType Kind = TaintTagGeneric) const;
312 
313   /// Check if the statement is tainted in the current state.
314   bool isTainted(const Stmt *S, const LocationContext *LCtx,
315                  TaintTagType Kind = TaintTagGeneric) const;
316   bool isTainted(SVal V, TaintTagType Kind = TaintTagGeneric) const;
317   bool isTainted(SymbolRef Sym, TaintTagType Kind = TaintTagGeneric) const;
318   bool isTainted(const MemRegion *Reg, TaintTagType Kind=TaintTagGeneric) const;
319 
320   /// \brief Get dynamic type information for a region.
321   DynamicTypeInfo getDynamicTypeInfo(const MemRegion *Reg) const;
322 
323   /// \brief Set dynamic type information of the region; return the new state.
324   ProgramStateRef setDynamicTypeInfo(const MemRegion *Reg,
325                                      DynamicTypeInfo NewTy) const;
326 
327   /// \brief Set dynamic type information of the region; return the new state.
328   ProgramStateRef setDynamicTypeInfo(const MemRegion *Reg,
329                                      QualType NewTy,
330                                      bool CanBeSubClassed = true) const {
331     return setDynamicTypeInfo(Reg, DynamicTypeInfo(NewTy, CanBeSubClassed));
332   }
333 
334   //==---------------------------------------------------------------------==//
335   // Accessing the Generic Data Map (GDM).
336   //==---------------------------------------------------------------------==//
337 
338   void *const* FindGDM(void *K) const;
339 
340   template<typename T>
341   ProgramStateRef add(typename ProgramStateTrait<T>::key_type K) const;
342 
343   template <typename T>
344   typename ProgramStateTrait<T>::data_type
get()345   get() const {
346     return ProgramStateTrait<T>::MakeData(FindGDM(ProgramStateTrait<T>::GDMIndex()));
347   }
348 
349   template<typename T>
350   typename ProgramStateTrait<T>::lookup_type
get(typename ProgramStateTrait<T>::key_type key)351   get(typename ProgramStateTrait<T>::key_type key) const {
352     void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
353     return ProgramStateTrait<T>::Lookup(ProgramStateTrait<T>::MakeData(d), key);
354   }
355 
356   template <typename T>
357   typename ProgramStateTrait<T>::context_type get_context() const;
358 
359 
360   template<typename T>
361   ProgramStateRef remove(typename ProgramStateTrait<T>::key_type K) const;
362 
363   template<typename T>
364   ProgramStateRef remove(typename ProgramStateTrait<T>::key_type K,
365                         typename ProgramStateTrait<T>::context_type C) const;
366   template <typename T>
367   ProgramStateRef remove() const;
368 
369   template<typename T>
370   ProgramStateRef set(typename ProgramStateTrait<T>::data_type D) const;
371 
372   template<typename T>
373   ProgramStateRef set(typename ProgramStateTrait<T>::key_type K,
374                      typename ProgramStateTrait<T>::value_type E) const;
375 
376   template<typename T>
377   ProgramStateRef set(typename ProgramStateTrait<T>::key_type K,
378                      typename ProgramStateTrait<T>::value_type E,
379                      typename ProgramStateTrait<T>::context_type C) const;
380 
381   template<typename T>
contains(typename ProgramStateTrait<T>::key_type key)382   bool contains(typename ProgramStateTrait<T>::key_type key) const {
383     void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex());
384     return ProgramStateTrait<T>::Contains(ProgramStateTrait<T>::MakeData(d), key);
385   }
386 
387   // Pretty-printing.
388   void print(raw_ostream &Out, const char *nl = "\n",
389              const char *sep = "") const;
390   void printDOT(raw_ostream &Out) const;
391   void printTaint(raw_ostream &Out, const char *nl = "\n",
392                   const char *sep = "") const;
393 
394   void dump() const;
395   void dumpTaint() const;
396 
397 private:
398   friend void ProgramStateRetain(const ProgramState *state);
399   friend void ProgramStateRelease(const ProgramState *state);
400 
401   ProgramStateRef
402   invalidateRegionsImpl(ArrayRef<const MemRegion *> Regions,
403                         const Expr *E, unsigned BlockCount,
404                         const LocationContext *LCtx,
405                         StoreManager::InvalidatedSymbols &IS,
406                         const CallEvent *Call) const;
407 };
408 
409 //===----------------------------------------------------------------------===//
410 // ProgramStateManager - Factory object for ProgramStates.
411 //===----------------------------------------------------------------------===//
412 
413 class ProgramStateManager {
414   friend class ProgramState;
415   friend void ProgramStateRelease(const ProgramState *state);
416 private:
417   /// Eng - The SubEngine that owns this state manager.
418   SubEngine *Eng; /* Can be null. */
419 
420   EnvironmentManager                   EnvMgr;
421   OwningPtr<StoreManager>              StoreMgr;
422   OwningPtr<ConstraintManager>         ConstraintMgr;
423 
424   ProgramState::GenericDataMap::Factory     GDMFactory;
425 
426   typedef llvm::DenseMap<void*,std::pair<void*,void (*)(void*)> > GDMContextsTy;
427   GDMContextsTy GDMContexts;
428 
429   /// StateSet - FoldingSet containing all the states created for analyzing
430   ///  a particular function.  This is used to unique states.
431   llvm::FoldingSet<ProgramState> StateSet;
432 
433   /// Object that manages the data for all created SVals.
434   OwningPtr<SValBuilder> svalBuilder;
435 
436   /// Manages memory for created CallEvents.
437   OwningPtr<CallEventManager> CallEventMgr;
438 
439   /// A BumpPtrAllocator to allocate states.
440   llvm::BumpPtrAllocator &Alloc;
441 
442   /// A vector of ProgramStates that we can reuse.
443   std::vector<ProgramState *> freeStates;
444 
445 public:
446   ProgramStateManager(ASTContext &Ctx,
447                  StoreManagerCreator CreateStoreManager,
448                  ConstraintManagerCreator CreateConstraintManager,
449                  llvm::BumpPtrAllocator& alloc,
450                  SubEngine &subeng);
451 
452   ~ProgramStateManager();
453 
454   ProgramStateRef getInitialState(const LocationContext *InitLoc);
455 
getContext()456   ASTContext &getContext() { return svalBuilder->getContext(); }
getContext()457   const ASTContext &getContext() const { return svalBuilder->getContext(); }
458 
getBasicVals()459   BasicValueFactory &getBasicVals() {
460     return svalBuilder->getBasicValueFactory();
461   }
getBasicVals()462   const BasicValueFactory& getBasicVals() const {
463     return svalBuilder->getBasicValueFactory();
464   }
465 
getSValBuilder()466   SValBuilder &getSValBuilder() {
467     return *svalBuilder;
468   }
469 
getSymbolManager()470   SymbolManager &getSymbolManager() {
471     return svalBuilder->getSymbolManager();
472   }
getSymbolManager()473   const SymbolManager &getSymbolManager() const {
474     return svalBuilder->getSymbolManager();
475   }
476 
getAllocator()477   llvm::BumpPtrAllocator& getAllocator() { return Alloc; }
478 
getRegionManager()479   MemRegionManager& getRegionManager() {
480     return svalBuilder->getRegionManager();
481   }
getRegionManager()482   const MemRegionManager& getRegionManager() const {
483     return svalBuilder->getRegionManager();
484   }
485 
getCallEventManager()486   CallEventManager &getCallEventManager() { return *CallEventMgr; }
487 
getStoreManager()488   StoreManager& getStoreManager() { return *StoreMgr; }
getConstraintManager()489   ConstraintManager& getConstraintManager() { return *ConstraintMgr; }
getOwningEngine()490   SubEngine* getOwningEngine() { return Eng; }
491 
492   ProgramStateRef removeDeadBindings(ProgramStateRef St,
493                                     const StackFrameContext *LCtx,
494                                     SymbolReaper& SymReaper);
495 
496 public:
497 
ArrayToPointer(Loc Array)498   SVal ArrayToPointer(Loc Array) {
499     return StoreMgr->ArrayToPointer(Array);
500   }
501 
502   // Methods that manipulate the GDM.
503   ProgramStateRef addGDM(ProgramStateRef St, void *Key, void *Data);
504   ProgramStateRef removeGDM(ProgramStateRef state, void *Key);
505 
506   // Methods that query & manipulate the Store.
507 
iterBindings(ProgramStateRef state,StoreManager::BindingsHandler & F)508   void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler& F) {
509     StoreMgr->iterBindings(state->getStore(), F);
510   }
511 
512   ProgramStateRef getPersistentState(ProgramState &Impl);
513   ProgramStateRef getPersistentStateWithGDM(ProgramStateRef FromState,
514                                            ProgramStateRef GDMState);
515 
haveEqualEnvironments(ProgramStateRef S1,ProgramStateRef S2)516   bool haveEqualEnvironments(ProgramStateRef S1, ProgramStateRef S2) {
517     return S1->Env == S2->Env;
518   }
519 
haveEqualStores(ProgramStateRef S1,ProgramStateRef S2)520   bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2) {
521     return S1->store == S2->store;
522   }
523 
524   //==---------------------------------------------------------------------==//
525   // Generic Data Map methods.
526   //==---------------------------------------------------------------------==//
527   //
528   // ProgramStateManager and ProgramState support a "generic data map" that allows
529   // different clients of ProgramState objects to embed arbitrary data within a
530   // ProgramState object.  The generic data map is essentially an immutable map
531   // from a "tag" (that acts as the "key" for a client) and opaque values.
532   // Tags/keys and values are simply void* values.  The typical way that clients
533   // generate unique tags are by taking the address of a static variable.
534   // Clients are responsible for ensuring that data values referred to by a
535   // the data pointer are immutable (and thus are essentially purely functional
536   // data).
537   //
538   // The templated methods below use the ProgramStateTrait<T> class
539   // to resolve keys into the GDM and to return data values to clients.
540   //
541 
542   // Trait based GDM dispatch.
543   template <typename T>
set(ProgramStateRef st,typename ProgramStateTrait<T>::data_type D)544   ProgramStateRef set(ProgramStateRef st, typename ProgramStateTrait<T>::data_type D) {
545     return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
546                   ProgramStateTrait<T>::MakeVoidPtr(D));
547   }
548 
549   template<typename T>
set(ProgramStateRef st,typename ProgramStateTrait<T>::key_type K,typename ProgramStateTrait<T>::value_type V,typename ProgramStateTrait<T>::context_type C)550   ProgramStateRef set(ProgramStateRef st,
551                      typename ProgramStateTrait<T>::key_type K,
552                      typename ProgramStateTrait<T>::value_type V,
553                      typename ProgramStateTrait<T>::context_type C) {
554 
555     return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
556      ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Set(st->get<T>(), K, V, C)));
557   }
558 
559   template <typename T>
add(ProgramStateRef st,typename ProgramStateTrait<T>::key_type K,typename ProgramStateTrait<T>::context_type C)560   ProgramStateRef add(ProgramStateRef st,
561                      typename ProgramStateTrait<T>::key_type K,
562                      typename ProgramStateTrait<T>::context_type C) {
563     return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
564         ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Add(st->get<T>(), K, C)));
565   }
566 
567   template <typename T>
remove(ProgramStateRef st,typename ProgramStateTrait<T>::key_type K,typename ProgramStateTrait<T>::context_type C)568   ProgramStateRef remove(ProgramStateRef st,
569                         typename ProgramStateTrait<T>::key_type K,
570                         typename ProgramStateTrait<T>::context_type C) {
571 
572     return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
573      ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Remove(st->get<T>(), K, C)));
574   }
575 
576   template <typename T>
remove(ProgramStateRef st)577   ProgramStateRef remove(ProgramStateRef st) {
578     return removeGDM(st, ProgramStateTrait<T>::GDMIndex());
579   }
580 
581   void *FindGDMContext(void *index,
582                        void *(*CreateContext)(llvm::BumpPtrAllocator&),
583                        void  (*DeleteContext)(void*));
584 
585   template <typename T>
get_context()586   typename ProgramStateTrait<T>::context_type get_context() {
587     void *p = FindGDMContext(ProgramStateTrait<T>::GDMIndex(),
588                              ProgramStateTrait<T>::CreateContext,
589                              ProgramStateTrait<T>::DeleteContext);
590 
591     return ProgramStateTrait<T>::MakeContext(p);
592   }
593 
EndPath(ProgramStateRef St)594   void EndPath(ProgramStateRef St) {
595     ConstraintMgr->EndPath(St);
596   }
597 };
598 
599 
600 //===----------------------------------------------------------------------===//
601 // Out-of-line method definitions for ProgramState.
602 //===----------------------------------------------------------------------===//
603 
getConstraintManager()604 inline ConstraintManager &ProgramState::getConstraintManager() const {
605   return stateMgr->getConstraintManager();
606 }
607 
getRegion(const VarDecl * D,const LocationContext * LC)608 inline const VarRegion* ProgramState::getRegion(const VarDecl *D,
609                                                 const LocationContext *LC) const
610 {
611   return getStateManager().getRegionManager().getVarRegion(D, LC);
612 }
613 
assume(DefinedOrUnknownSVal Cond,bool Assumption)614 inline ProgramStateRef ProgramState::assume(DefinedOrUnknownSVal Cond,
615                                       bool Assumption) const {
616   if (Cond.isUnknown())
617     return this;
618 
619   return getStateManager().ConstraintMgr->assume(this, cast<DefinedSVal>(Cond),
620                                                  Assumption);
621 }
622 
623 inline std::pair<ProgramStateRef , ProgramStateRef >
assume(DefinedOrUnknownSVal Cond)624 ProgramState::assume(DefinedOrUnknownSVal Cond) const {
625   if (Cond.isUnknown())
626     return std::make_pair(this, this);
627 
628   return getStateManager().ConstraintMgr->assumeDual(this,
629                                                      cast<DefinedSVal>(Cond));
630 }
631 
bindLoc(SVal LV,SVal V)632 inline ProgramStateRef ProgramState::bindLoc(SVal LV, SVal V) const {
633   return !isa<Loc>(LV) ? this : bindLoc(cast<Loc>(LV), V);
634 }
635 
getLValue(const VarDecl * VD,const LocationContext * LC)636 inline Loc ProgramState::getLValue(const VarDecl *VD,
637                                const LocationContext *LC) const {
638   return getStateManager().StoreMgr->getLValueVar(VD, LC);
639 }
640 
getLValue(const CompoundLiteralExpr * literal,const LocationContext * LC)641 inline Loc ProgramState::getLValue(const CompoundLiteralExpr *literal,
642                                const LocationContext *LC) const {
643   return getStateManager().StoreMgr->getLValueCompoundLiteral(literal, LC);
644 }
645 
getLValue(const ObjCIvarDecl * D,SVal Base)646 inline SVal ProgramState::getLValue(const ObjCIvarDecl *D, SVal Base) const {
647   return getStateManager().StoreMgr->getLValueIvar(D, Base);
648 }
649 
getLValue(const FieldDecl * D,SVal Base)650 inline SVal ProgramState::getLValue(const FieldDecl *D, SVal Base) const {
651   return getStateManager().StoreMgr->getLValueField(D, Base);
652 }
653 
getLValue(const IndirectFieldDecl * D,SVal Base)654 inline SVal ProgramState::getLValue(const IndirectFieldDecl *D,
655                                     SVal Base) const {
656   StoreManager &SM = *getStateManager().StoreMgr;
657   for (IndirectFieldDecl::chain_iterator I = D->chain_begin(),
658                                          E = D->chain_end();
659        I != E; ++I) {
660     Base = SM.getLValueField(cast<FieldDecl>(*I), Base);
661   }
662 
663   return Base;
664 }
665 
getLValue(QualType ElementType,SVal Idx,SVal Base)666 inline SVal ProgramState::getLValue(QualType ElementType, SVal Idx, SVal Base) const{
667   if (NonLoc *N = dyn_cast<NonLoc>(&Idx))
668     return getStateManager().StoreMgr->getLValueElement(ElementType, *N, Base);
669   return UnknownVal();
670 }
671 
getSVal(const Stmt * Ex,const LocationContext * LCtx,bool useOnlyDirectBindings)672 inline SVal ProgramState::getSVal(const Stmt *Ex, const LocationContext *LCtx,
673                                   bool useOnlyDirectBindings) const{
674   return Env.getSVal(EnvironmentEntry(Ex, LCtx),
675                      *getStateManager().svalBuilder,
676                      useOnlyDirectBindings);
677 }
678 
679 inline SVal
getSValAsScalarOrLoc(const Stmt * S,const LocationContext * LCtx)680 ProgramState::getSValAsScalarOrLoc(const Stmt *S,
681                                    const LocationContext *LCtx) const {
682   if (const Expr *Ex = dyn_cast<Expr>(S)) {
683     QualType T = Ex->getType();
684     if (Ex->isGLValue() || Loc::isLocType(T) || T->isIntegerType())
685       return getSVal(S, LCtx);
686   }
687 
688   return UnknownVal();
689 }
690 
getRawSVal(Loc LV,QualType T)691 inline SVal ProgramState::getRawSVal(Loc LV, QualType T) const {
692   return getStateManager().StoreMgr->getBinding(getStore(), LV, T);
693 }
694 
getSVal(const MemRegion * R)695 inline SVal ProgramState::getSVal(const MemRegion* R) const {
696   return getStateManager().StoreMgr->getBinding(getStore(),
697                                                 loc::MemRegionVal(R));
698 }
699 
getBasicVals()700 inline BasicValueFactory &ProgramState::getBasicVals() const {
701   return getStateManager().getBasicVals();
702 }
703 
getSymbolManager()704 inline SymbolManager &ProgramState::getSymbolManager() const {
705   return getStateManager().getSymbolManager();
706 }
707 
708 template<typename T>
add(typename ProgramStateTrait<T>::key_type K)709 ProgramStateRef ProgramState::add(typename ProgramStateTrait<T>::key_type K) const {
710   return getStateManager().add<T>(this, K, get_context<T>());
711 }
712 
713 template <typename T>
get_context()714 typename ProgramStateTrait<T>::context_type ProgramState::get_context() const {
715   return getStateManager().get_context<T>();
716 }
717 
718 template<typename T>
remove(typename ProgramStateTrait<T>::key_type K)719 ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K) const {
720   return getStateManager().remove<T>(this, K, get_context<T>());
721 }
722 
723 template<typename T>
remove(typename ProgramStateTrait<T>::key_type K,typename ProgramStateTrait<T>::context_type C)724 ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K,
725                                typename ProgramStateTrait<T>::context_type C) const {
726   return getStateManager().remove<T>(this, K, C);
727 }
728 
729 template <typename T>
remove()730 ProgramStateRef ProgramState::remove() const {
731   return getStateManager().remove<T>(this);
732 }
733 
734 template<typename T>
set(typename ProgramStateTrait<T>::data_type D)735 ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::data_type D) const {
736   return getStateManager().set<T>(this, D);
737 }
738 
739 template<typename T>
set(typename ProgramStateTrait<T>::key_type K,typename ProgramStateTrait<T>::value_type E)740 ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
741                             typename ProgramStateTrait<T>::value_type E) const {
742   return getStateManager().set<T>(this, K, E, get_context<T>());
743 }
744 
745 template<typename T>
set(typename ProgramStateTrait<T>::key_type K,typename ProgramStateTrait<T>::value_type E,typename ProgramStateTrait<T>::context_type C)746 ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K,
747                             typename ProgramStateTrait<T>::value_type E,
748                             typename ProgramStateTrait<T>::context_type C) const {
749   return getStateManager().set<T>(this, K, E, C);
750 }
751 
752 template <typename CB>
scanReachableSymbols(SVal val)753 CB ProgramState::scanReachableSymbols(SVal val) const {
754   CB cb(this);
755   scanReachableSymbols(val, cb);
756   return cb;
757 }
758 
759 template <typename CB>
scanReachableSymbols(const SVal * beg,const SVal * end)760 CB ProgramState::scanReachableSymbols(const SVal *beg, const SVal *end) const {
761   CB cb(this);
762   scanReachableSymbols(beg, end, cb);
763   return cb;
764 }
765 
766 template <typename CB>
scanReachableSymbols(const MemRegion * const * beg,const MemRegion * const * end)767 CB ProgramState::scanReachableSymbols(const MemRegion * const *beg,
768                                  const MemRegion * const *end) const {
769   CB cb(this);
770   scanReachableSymbols(beg, end, cb);
771   return cb;
772 }
773 
774 /// \class ScanReachableSymbols
775 /// A Utility class that allows to visit the reachable symbols using a custom
776 /// SymbolVisitor.
777 class ScanReachableSymbols {
778   typedef llvm::DenseMap<const void*, unsigned> VisitedItems;
779 
780   VisitedItems visited;
781   ProgramStateRef state;
782   SymbolVisitor &visitor;
783 public:
784 
ScanReachableSymbols(ProgramStateRef st,SymbolVisitor & v)785   ScanReachableSymbols(ProgramStateRef st, SymbolVisitor& v)
786     : state(st), visitor(v) {}
787 
788   bool scan(nonloc::CompoundVal val);
789   bool scan(SVal val);
790   bool scan(const MemRegion *R);
791   bool scan(const SymExpr *sym);
792 };
793 
794 } // end ento namespace
795 
796 } // end clang namespace
797 
798 #endif
799