ProgramState.cpp revision 47cbd0f3892c7965cf16a58393f9f17a22d4d4d9
1//= ProgramState.cpp - 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 implements ProgramState and ProgramStateManager.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Analysis/CFG.h"
15#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
16#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
17#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/TaintManager.h"
20#include "llvm/Support/raw_ostream.h"
21
22using namespace clang;
23using namespace ento;
24
25namespace clang { namespace  ento {
26/// Increments the number of times this state is referenced.
27
28void ProgramStateRetain(const ProgramState *state) {
29  ++const_cast<ProgramState*>(state)->refCount;
30}
31
32/// Decrement the number of times this state is referenced.
33void ProgramStateRelease(const ProgramState *state) {
34  assert(state->refCount > 0);
35  ProgramState *s = const_cast<ProgramState*>(state);
36  if (--s->refCount == 0) {
37    ProgramStateManager &Mgr = s->getStateManager();
38    Mgr.StateSet.RemoveNode(s);
39    s->~ProgramState();
40    Mgr.freeStates.push_back(s);
41  }
42}
43}}
44
45ProgramState::ProgramState(ProgramStateManager *mgr, const Environment& env,
46                 StoreRef st, GenericDataMap gdm)
47  : stateMgr(mgr),
48    Env(env),
49    store(st.getStore()),
50    GDM(gdm),
51    refCount(0) {
52  stateMgr->getStoreManager().incrementReferenceCount(store);
53}
54
55ProgramState::ProgramState(const ProgramState &RHS)
56    : llvm::FoldingSetNode(),
57      stateMgr(RHS.stateMgr),
58      Env(RHS.Env),
59      store(RHS.store),
60      GDM(RHS.GDM),
61      refCount(0) {
62  stateMgr->getStoreManager().incrementReferenceCount(store);
63}
64
65ProgramState::~ProgramState() {
66  if (store)
67    stateMgr->getStoreManager().decrementReferenceCount(store);
68}
69
70ProgramStateManager::ProgramStateManager(ASTContext &Ctx,
71                                         StoreManagerCreator CreateSMgr,
72                                         ConstraintManagerCreator CreateCMgr,
73                                         llvm::BumpPtrAllocator &alloc,
74                                         SubEngine &SubEng)
75  : Eng(&SubEng), EnvMgr(alloc), GDMFactory(alloc),
76    svalBuilder(createSimpleSValBuilder(alloc, Ctx, *this)),
77    CallEventMgr(new CallEventManager(alloc)), Alloc(alloc) {
78  StoreMgr.reset((*CreateSMgr)(*this));
79  ConstraintMgr.reset((*CreateCMgr)(*this, SubEng));
80}
81
82
83ProgramStateManager::~ProgramStateManager() {
84  for (GDMContextsTy::iterator I=GDMContexts.begin(), E=GDMContexts.end();
85       I!=E; ++I)
86    I->second.second(I->second.first);
87}
88
89ProgramStateRef
90ProgramStateManager::removeDeadBindings(ProgramStateRef state,
91                                   const StackFrameContext *LCtx,
92                                   SymbolReaper& SymReaper) {
93
94  // This code essentially performs a "mark-and-sweep" of the VariableBindings.
95  // The roots are any Block-level exprs and Decls that our liveness algorithm
96  // tells us are live.  We then see what Decls they may reference, and keep
97  // those around.  This code more than likely can be made faster, and the
98  // frequency of which this method is called should be experimented with
99  // for optimum performance.
100  ProgramState NewState = *state;
101
102  NewState.Env = EnvMgr.removeDeadBindings(NewState.Env, SymReaper, state);
103
104  // Clean up the store.
105  StoreRef newStore = StoreMgr->removeDeadBindings(NewState.getStore(), LCtx,
106                                                   SymReaper);
107  NewState.setStore(newStore);
108  SymReaper.setReapedStore(newStore);
109
110  return getPersistentState(NewState);
111}
112
113ProgramStateRef ProgramStateManager::MarshalState(ProgramStateRef state,
114                                            const StackFrameContext *InitLoc) {
115  // make up an empty state for now.
116  ProgramState State(this,
117                EnvMgr.getInitialEnvironment(),
118                StoreMgr->getInitialStore(InitLoc),
119                GDMFactory.getEmptyMap());
120
121  return getPersistentState(State);
122}
123
124ProgramStateRef ProgramState::bindCompoundLiteral(const CompoundLiteralExpr *CL,
125                                            const LocationContext *LC,
126                                            SVal V) const {
127  const StoreRef &newStore =
128    getStateManager().StoreMgr->bindCompoundLiteral(getStore(), CL, LC, V);
129  return makeWithStore(newStore);
130}
131
132ProgramStateRef ProgramState::bindLoc(Loc LV, SVal V, bool notifyChanges) const {
133  ProgramStateManager &Mgr = getStateManager();
134  ProgramStateRef newState = makeWithStore(Mgr.StoreMgr->Bind(getStore(),
135                                                             LV, V));
136  const MemRegion *MR = LV.getAsRegion();
137  if (MR && Mgr.getOwningEngine() && notifyChanges)
138    return Mgr.getOwningEngine()->processRegionChange(newState, MR);
139
140  return newState;
141}
142
143ProgramStateRef ProgramState::bindDefault(SVal loc, SVal V) const {
144  ProgramStateManager &Mgr = getStateManager();
145  const MemRegion *R = cast<loc::MemRegionVal>(loc).getRegion();
146  const StoreRef &newStore = Mgr.StoreMgr->BindDefault(getStore(), R, V);
147  ProgramStateRef new_state = makeWithStore(newStore);
148  return Mgr.getOwningEngine() ?
149           Mgr.getOwningEngine()->processRegionChange(new_state, R) :
150           new_state;
151}
152
153ProgramStateRef
154ProgramState::invalidateRegions(ArrayRef<const MemRegion *> Regions,
155                                const Expr *E, unsigned Count,
156                                const LocationContext *LCtx,
157                                StoreManager::InvalidatedSymbols *IS,
158                                const CallEvent *Call) const {
159  if (!IS) {
160    StoreManager::InvalidatedSymbols invalidated;
161    return invalidateRegionsImpl(Regions, E, Count, LCtx,
162                                 invalidated, Call);
163  }
164  return invalidateRegionsImpl(Regions, E, Count, LCtx, *IS, Call);
165}
166
167ProgramStateRef
168ProgramState::invalidateRegionsImpl(ArrayRef<const MemRegion *> Regions,
169                                    const Expr *E, unsigned Count,
170                                    const LocationContext *LCtx,
171                                    StoreManager::InvalidatedSymbols &IS,
172                                    const CallEvent *Call) const {
173  ProgramStateManager &Mgr = getStateManager();
174  SubEngine* Eng = Mgr.getOwningEngine();
175
176  if (Eng && Eng->wantsRegionChangeUpdate(this)) {
177    StoreManager::InvalidatedRegions Invalidated;
178    const StoreRef &newStore
179      = Mgr.StoreMgr->invalidateRegions(getStore(), Regions, E, Count, LCtx, IS,
180                                        Call, &Invalidated);
181    ProgramStateRef newState = makeWithStore(newStore);
182    return Eng->processRegionChanges(newState, &IS, Regions, Invalidated, Call);
183  }
184
185  const StoreRef &newStore =
186    Mgr.StoreMgr->invalidateRegions(getStore(), Regions, E, Count, LCtx, IS,
187                                    Call, NULL);
188  return makeWithStore(newStore);
189}
190
191ProgramStateRef ProgramState::killBinding(Loc LV) const {
192  assert(!isa<loc::MemRegionVal>(LV) && "Use invalidateRegion instead.");
193
194  Store OldStore = getStore();
195  const StoreRef &newStore =
196    getStateManager().StoreMgr->killBinding(OldStore, LV);
197
198  if (newStore.getStore() == OldStore)
199    return this;
200
201  return makeWithStore(newStore);
202}
203
204ProgramStateRef
205ProgramState::enterStackFrame(const CallEvent &Call,
206                              const StackFrameContext *CalleeCtx) const {
207  const StoreRef &NewStore =
208    getStateManager().StoreMgr->enterStackFrame(getStore(), Call, CalleeCtx);
209  return makeWithStore(NewStore);
210}
211
212SVal ProgramState::getSValAsScalarOrLoc(const MemRegion *R) const {
213  // We only want to do fetches from regions that we can actually bind
214  // values.  For example, SymbolicRegions of type 'id<...>' cannot
215  // have direct bindings (but their can be bindings on their subregions).
216  if (!R->isBoundable())
217    return UnknownVal();
218
219  if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
220    QualType T = TR->getValueType();
221    if (Loc::isLocType(T) || T->isIntegerType())
222      return getSVal(R);
223  }
224
225  return UnknownVal();
226}
227
228SVal ProgramState::getSVal(Loc location, QualType T) const {
229  SVal V = getRawSVal(cast<Loc>(location), T);
230
231  // If 'V' is a symbolic value that is *perfectly* constrained to
232  // be a constant value, use that value instead to lessen the burden
233  // on later analysis stages (so we have less symbolic values to reason
234  // about).
235  if (!T.isNull()) {
236    if (SymbolRef sym = V.getAsSymbol()) {
237      if (const llvm::APSInt *Int = getStateManager()
238                                    .getConstraintManager()
239                                    .getSymVal(this, sym)) {
240        // FIXME: Because we don't correctly model (yet) sign-extension
241        // and truncation of symbolic values, we need to convert
242        // the integer value to the correct signedness and bitwidth.
243        //
244        // This shows up in the following:
245        //
246        //   char foo();
247        //   unsigned x = foo();
248        //   if (x == 54)
249        //     ...
250        //
251        //  The symbolic value stored to 'x' is actually the conjured
252        //  symbol for the call to foo(); the type of that symbol is 'char',
253        //  not unsigned.
254        const llvm::APSInt &NewV = getBasicVals().Convert(T, *Int);
255
256        if (isa<Loc>(V))
257          return loc::ConcreteInt(NewV);
258        else
259          return nonloc::ConcreteInt(NewV);
260      }
261    }
262  }
263
264  return V;
265}
266
267ProgramStateRef ProgramState::BindExpr(const Stmt *S,
268                                           const LocationContext *LCtx,
269                                           SVal V, bool Invalidate) const{
270  Environment NewEnv =
271    getStateManager().EnvMgr.bindExpr(Env, EnvironmentEntry(S, LCtx), V,
272                                      Invalidate);
273  if (NewEnv == Env)
274    return this;
275
276  ProgramState NewSt = *this;
277  NewSt.Env = NewEnv;
278  return getStateManager().getPersistentState(NewSt);
279}
280
281ProgramStateRef
282ProgramState::bindExprAndLocation(const Stmt *S, const LocationContext *LCtx,
283                                  SVal location,
284                                  SVal V) const {
285  Environment NewEnv =
286    getStateManager().EnvMgr.bindExprAndLocation(Env,
287                                                 EnvironmentEntry(S, LCtx),
288                                                 location, V);
289
290  if (NewEnv == Env)
291    return this;
292
293  ProgramState NewSt = *this;
294  NewSt.Env = NewEnv;
295  return getStateManager().getPersistentState(NewSt);
296}
297
298ProgramStateRef ProgramState::assumeInBound(DefinedOrUnknownSVal Idx,
299                                      DefinedOrUnknownSVal UpperBound,
300                                      bool Assumption,
301                                      QualType indexTy) const {
302  if (Idx.isUnknown() || UpperBound.isUnknown())
303    return this;
304
305  // Build an expression for 0 <= Idx < UpperBound.
306  // This is the same as Idx + MIN < UpperBound + MIN, if overflow is allowed.
307  // FIXME: This should probably be part of SValBuilder.
308  ProgramStateManager &SM = getStateManager();
309  SValBuilder &svalBuilder = SM.getSValBuilder();
310  ASTContext &Ctx = svalBuilder.getContext();
311
312  // Get the offset: the minimum value of the array index type.
313  BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
314  // FIXME: This should be using ValueManager::ArrayindexTy...somehow.
315  if (indexTy.isNull())
316    indexTy = Ctx.IntTy;
317  nonloc::ConcreteInt Min(BVF.getMinValue(indexTy));
318
319  // Adjust the index.
320  SVal newIdx = svalBuilder.evalBinOpNN(this, BO_Add,
321                                        cast<NonLoc>(Idx), Min, indexTy);
322  if (newIdx.isUnknownOrUndef())
323    return this;
324
325  // Adjust the upper bound.
326  SVal newBound =
327    svalBuilder.evalBinOpNN(this, BO_Add, cast<NonLoc>(UpperBound),
328                            Min, indexTy);
329
330  if (newBound.isUnknownOrUndef())
331    return this;
332
333  // Build the actual comparison.
334  SVal inBound = svalBuilder.evalBinOpNN(this, BO_LT,
335                                cast<NonLoc>(newIdx), cast<NonLoc>(newBound),
336                                Ctx.IntTy);
337  if (inBound.isUnknownOrUndef())
338    return this;
339
340  // Finally, let the constraint manager take care of it.
341  ConstraintManager &CM = SM.getConstraintManager();
342  return CM.assume(this, cast<DefinedSVal>(inBound), Assumption);
343}
344
345ProgramStateRef ProgramStateManager::getInitialState(const LocationContext *InitLoc) {
346  ProgramState State(this,
347                EnvMgr.getInitialEnvironment(),
348                StoreMgr->getInitialStore(InitLoc),
349                GDMFactory.getEmptyMap());
350
351  return getPersistentState(State);
352}
353
354ProgramStateRef ProgramStateManager::getPersistentStateWithGDM(
355                                                     ProgramStateRef FromState,
356                                                     ProgramStateRef GDMState) {
357  ProgramState NewState(*FromState);
358  NewState.GDM = GDMState->GDM;
359  return getPersistentState(NewState);
360}
361
362ProgramStateRef ProgramStateManager::getPersistentState(ProgramState &State) {
363
364  llvm::FoldingSetNodeID ID;
365  State.Profile(ID);
366  void *InsertPos;
367
368  if (ProgramState *I = StateSet.FindNodeOrInsertPos(ID, InsertPos))
369    return I;
370
371  ProgramState *newState = 0;
372  if (!freeStates.empty()) {
373    newState = freeStates.back();
374    freeStates.pop_back();
375  }
376  else {
377    newState = (ProgramState*) Alloc.Allocate<ProgramState>();
378  }
379  new (newState) ProgramState(State);
380  StateSet.InsertNode(newState, InsertPos);
381  return newState;
382}
383
384ProgramStateRef ProgramState::makeWithStore(const StoreRef &store) const {
385  ProgramState NewSt(*this);
386  NewSt.setStore(store);
387  return getStateManager().getPersistentState(NewSt);
388}
389
390void ProgramState::setStore(const StoreRef &newStore) {
391  Store newStoreStore = newStore.getStore();
392  if (newStoreStore)
393    stateMgr->getStoreManager().incrementReferenceCount(newStoreStore);
394  if (store)
395    stateMgr->getStoreManager().decrementReferenceCount(store);
396  store = newStoreStore;
397}
398
399//===----------------------------------------------------------------------===//
400//  State pretty-printing.
401//===----------------------------------------------------------------------===//
402
403void ProgramState::print(raw_ostream &Out,
404                         const char *NL, const char *Sep) const {
405  // Print the store.
406  ProgramStateManager &Mgr = getStateManager();
407  Mgr.getStoreManager().print(getStore(), Out, NL, Sep);
408
409  // Print out the environment.
410  Env.print(Out, NL, Sep);
411
412  // Print out the constraints.
413  Mgr.getConstraintManager().print(this, Out, NL, Sep);
414
415  // Print checker-specific data.
416  Mgr.getOwningEngine()->printState(Out, this, NL, Sep);
417}
418
419void ProgramState::printDOT(raw_ostream &Out) const {
420  print(Out, "\\l", "\\|");
421}
422
423void ProgramState::dump() const {
424  print(llvm::errs());
425}
426
427void ProgramState::printTaint(raw_ostream &Out,
428                              const char *NL, const char *Sep) const {
429  TaintMapImpl TM = get<TaintMap>();
430
431  if (!TM.isEmpty())
432    Out <<"Tainted Symbols:" << NL;
433
434  for (TaintMapImpl::iterator I = TM.begin(), E = TM.end(); I != E; ++I) {
435    Out << I->first << " : " << I->second << NL;
436  }
437}
438
439void ProgramState::dumpTaint() const {
440  printTaint(llvm::errs());
441}
442
443//===----------------------------------------------------------------------===//
444// Generic Data Map.
445//===----------------------------------------------------------------------===//
446
447void *const* ProgramState::FindGDM(void *K) const {
448  return GDM.lookup(K);
449}
450
451void*
452ProgramStateManager::FindGDMContext(void *K,
453                               void *(*CreateContext)(llvm::BumpPtrAllocator&),
454                               void (*DeleteContext)(void*)) {
455
456  std::pair<void*, void (*)(void*)>& p = GDMContexts[K];
457  if (!p.first) {
458    p.first = CreateContext(Alloc);
459    p.second = DeleteContext;
460  }
461
462  return p.first;
463}
464
465ProgramStateRef ProgramStateManager::addGDM(ProgramStateRef St, void *Key, void *Data){
466  ProgramState::GenericDataMap M1 = St->getGDM();
467  ProgramState::GenericDataMap M2 = GDMFactory.add(M1, Key, Data);
468
469  if (M1 == M2)
470    return St;
471
472  ProgramState NewSt = *St;
473  NewSt.GDM = M2;
474  return getPersistentState(NewSt);
475}
476
477ProgramStateRef ProgramStateManager::removeGDM(ProgramStateRef state, void *Key) {
478  ProgramState::GenericDataMap OldM = state->getGDM();
479  ProgramState::GenericDataMap NewM = GDMFactory.remove(OldM, Key);
480
481  if (NewM == OldM)
482    return state;
483
484  ProgramState NewState = *state;
485  NewState.GDM = NewM;
486  return getPersistentState(NewState);
487}
488
489bool ScanReachableSymbols::scan(nonloc::CompoundVal val) {
490  for (nonloc::CompoundVal::iterator I=val.begin(), E=val.end(); I!=E; ++I)
491    if (!scan(*I))
492      return false;
493
494  return true;
495}
496
497bool ScanReachableSymbols::scan(const SymExpr *sym) {
498  unsigned &isVisited = visited[sym];
499  if (isVisited)
500    return true;
501  isVisited = 1;
502
503  if (!visitor.VisitSymbol(sym))
504    return false;
505
506  // TODO: should be rewritten using SymExpr::symbol_iterator.
507  switch (sym->getKind()) {
508    case SymExpr::RegionValueKind:
509    case SymExpr::ConjuredKind:
510    case SymExpr::DerivedKind:
511    case SymExpr::ExtentKind:
512    case SymExpr::MetadataKind:
513      break;
514    case SymExpr::CastSymbolKind:
515      return scan(cast<SymbolCast>(sym)->getOperand());
516    case SymExpr::SymIntKind:
517      return scan(cast<SymIntExpr>(sym)->getLHS());
518    case SymExpr::IntSymKind:
519      return scan(cast<IntSymExpr>(sym)->getRHS());
520    case SymExpr::SymSymKind: {
521      const SymSymExpr *x = cast<SymSymExpr>(sym);
522      return scan(x->getLHS()) && scan(x->getRHS());
523    }
524  }
525  return true;
526}
527
528bool ScanReachableSymbols::scan(SVal val) {
529  if (loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&val))
530    return scan(X->getRegion());
531
532  if (nonloc::LazyCompoundVal *X = dyn_cast<nonloc::LazyCompoundVal>(&val))
533    return scan(X->getRegion());
534
535  if (nonloc::LocAsInteger *X = dyn_cast<nonloc::LocAsInteger>(&val))
536    return scan(X->getLoc());
537
538  if (SymbolRef Sym = val.getAsSymbol())
539    return scan(Sym);
540
541  if (const SymExpr *Sym = val.getAsSymbolicExpression())
542    return scan(Sym);
543
544  if (nonloc::CompoundVal *X = dyn_cast<nonloc::CompoundVal>(&val))
545    return scan(*X);
546
547  return true;
548}
549
550bool ScanReachableSymbols::scan(const MemRegion *R) {
551  if (isa<MemSpaceRegion>(R))
552    return true;
553
554  unsigned &isVisited = visited[R];
555  if (isVisited)
556    return true;
557  isVisited = 1;
558
559
560  if (!visitor.VisitMemRegion(R))
561    return false;
562
563  // If this is a symbolic region, visit the symbol for the region.
564  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
565    if (!visitor.VisitSymbol(SR->getSymbol()))
566      return false;
567
568  // If this is a subregion, also visit the parent regions.
569  if (const SubRegion *SR = dyn_cast<SubRegion>(R)) {
570    const MemRegion *Super = SR->getSuperRegion();
571    if (!scan(Super))
572      return false;
573
574    // When we reach the topmost region, scan all symbols in it.
575    if (isa<MemSpaceRegion>(Super)) {
576      StoreManager &StoreMgr = state->getStateManager().getStoreManager();
577      if (!StoreMgr.scanReachableSymbols(state->getStore(), SR, *this))
578        return false;
579    }
580  }
581
582  // Regions captured by a block are also implicitly reachable.
583  if (const BlockDataRegion *BDR = dyn_cast<BlockDataRegion>(R)) {
584    BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
585                                              E = BDR->referenced_vars_end();
586    for ( ; I != E; ++I) {
587      if (!scan(I.getCapturedRegion()))
588        return false;
589    }
590  }
591
592  return true;
593}
594
595bool ProgramState::scanReachableSymbols(SVal val, SymbolVisitor& visitor) const {
596  ScanReachableSymbols S(this, visitor);
597  return S.scan(val);
598}
599
600bool ProgramState::scanReachableSymbols(const SVal *I, const SVal *E,
601                                   SymbolVisitor &visitor) const {
602  ScanReachableSymbols S(this, visitor);
603  for ( ; I != E; ++I) {
604    if (!S.scan(*I))
605      return false;
606  }
607  return true;
608}
609
610bool ProgramState::scanReachableSymbols(const MemRegion * const *I,
611                                   const MemRegion * const *E,
612                                   SymbolVisitor &visitor) const {
613  ScanReachableSymbols S(this, visitor);
614  for ( ; I != E; ++I) {
615    if (!S.scan(*I))
616      return false;
617  }
618  return true;
619}
620
621ProgramStateRef ProgramState::addTaint(const Stmt *S,
622                                           const LocationContext *LCtx,
623                                           TaintTagType Kind) const {
624  if (const Expr *E = dyn_cast_or_null<Expr>(S))
625    S = E->IgnoreParens();
626
627  SymbolRef Sym = getSVal(S, LCtx).getAsSymbol();
628  if (Sym)
629    return addTaint(Sym, Kind);
630
631  const MemRegion *R = getSVal(S, LCtx).getAsRegion();
632  addTaint(R, Kind);
633
634  // Cannot add taint, so just return the state.
635  return this;
636}
637
638ProgramStateRef ProgramState::addTaint(const MemRegion *R,
639                                           TaintTagType Kind) const {
640  if (const SymbolicRegion *SR = dyn_cast_or_null<SymbolicRegion>(R))
641    return addTaint(SR->getSymbol(), Kind);
642  return this;
643}
644
645ProgramStateRef ProgramState::addTaint(SymbolRef Sym,
646                                           TaintTagType Kind) const {
647  // If this is a symbol cast, remove the cast before adding the taint. Taint
648  // is cast agnostic.
649  while (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym))
650    Sym = SC->getOperand();
651
652  ProgramStateRef NewState = set<TaintMap>(Sym, Kind);
653  assert(NewState);
654  return NewState;
655}
656
657bool ProgramState::isTainted(const Stmt *S, const LocationContext *LCtx,
658                             TaintTagType Kind) const {
659  if (const Expr *E = dyn_cast_or_null<Expr>(S))
660    S = E->IgnoreParens();
661
662  SVal val = getSVal(S, LCtx);
663  return isTainted(val, Kind);
664}
665
666bool ProgramState::isTainted(SVal V, TaintTagType Kind) const {
667  if (const SymExpr *Sym = V.getAsSymExpr())
668    return isTainted(Sym, Kind);
669  if (const MemRegion *Reg = V.getAsRegion())
670    return isTainted(Reg, Kind);
671  return false;
672}
673
674bool ProgramState::isTainted(const MemRegion *Reg, TaintTagType K) const {
675  if (!Reg)
676    return false;
677
678  // Element region (array element) is tainted if either the base or the offset
679  // are tainted.
680  if (const ElementRegion *ER = dyn_cast<ElementRegion>(Reg))
681    return isTainted(ER->getSuperRegion(), K) || isTainted(ER->getIndex(), K);
682
683  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(Reg))
684    return isTainted(SR->getSymbol(), K);
685
686  if (const SubRegion *ER = dyn_cast<SubRegion>(Reg))
687    return isTainted(ER->getSuperRegion(), K);
688
689  return false;
690}
691
692bool ProgramState::isTainted(SymbolRef Sym, TaintTagType Kind) const {
693  if (!Sym)
694    return false;
695
696  // Traverse all the symbols this symbol depends on to see if any are tainted.
697  bool Tainted = false;
698  for (SymExpr::symbol_iterator SI = Sym->symbol_begin(), SE =Sym->symbol_end();
699       SI != SE; ++SI) {
700    assert(isa<SymbolData>(*SI));
701    const TaintTagType *Tag = get<TaintMap>(*SI);
702    Tainted = (Tag && *Tag == Kind);
703
704    // If this is a SymbolDerived with a tainted parent, it's also tainted.
705    if (const SymbolDerived *SD = dyn_cast<SymbolDerived>(*SI))
706      Tainted = Tainted || isTainted(SD->getParentSymbol(), Kind);
707
708    // If memory region is tainted, data is also tainted.
709    if (const SymbolRegionValue *SRV = dyn_cast<SymbolRegionValue>(*SI))
710      Tainted = Tainted || isTainted(SRV->getRegion(), Kind);
711
712    // If If this is a SymbolCast from a tainted value, it's also tainted.
713    if (const SymbolCast *SC = dyn_cast<SymbolCast>(*SI))
714      Tainted = Tainted || isTainted(SC->getOperand(), Kind);
715
716    if (Tainted)
717      return true;
718  }
719
720  return Tainted;
721}
722
723/// The GDM component containing the dynamic type info. This is a map from a
724/// symbol to it's most likely type.
725namespace clang {
726namespace ento {
727typedef llvm::ImmutableMap<const MemRegion *, DynamicTypeInfo> DynamicTypeMap;
728template<> struct ProgramStateTrait<DynamicTypeMap>
729    : public ProgramStatePartialTrait<DynamicTypeMap> {
730  static void *GDMIndex() { static int index; return &index; }
731};
732}}
733
734DynamicTypeInfo ProgramState::getDynamicTypeInfo(const MemRegion *Reg) const {
735  Reg = Reg->StripCasts();
736
737  // Look up the dynamic type in the GDM.
738  const DynamicTypeInfo *GDMType = get<DynamicTypeMap>(Reg);
739  if (GDMType)
740    return *GDMType;
741
742  // Otherwise, fall back to what we know about the region.
743  if (const TypedRegion *TR = dyn_cast<TypedRegion>(Reg))
744    return DynamicTypeInfo(TR->getLocationType(), /*CanBeSubclass=*/false);
745
746  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(Reg)) {
747    SymbolRef Sym = SR->getSymbol();
748    return DynamicTypeInfo(Sym->getType(getStateManager().getContext()));
749  }
750
751  return DynamicTypeInfo();
752}
753
754ProgramStateRef ProgramState::setDynamicTypeInfo(const MemRegion *Reg,
755                                                 DynamicTypeInfo NewTy) const {
756  Reg = Reg->StripCasts();
757  ProgramStateRef NewState = set<DynamicTypeMap>(Reg, NewTy);
758  assert(NewState);
759  return NewState;
760}
761