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