1 //== RegionStore.cpp - Field-sensitive store model --------------*- 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 a basic region store model. In this model, we do have field
11 // sensitivity. But we assume nothing about the heap shape. So recursive data
12 // structures are largely ignored. Basically we do 1-limiting analysis.
13 // Parameter pointers are assumed with no aliasing. Pointee objects of
14 // parameters are created lazily.
15 //
16 //===----------------------------------------------------------------------===//
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/Analysis/Analyses/LiveVariables.h"
21 #include "clang/Analysis/AnalysisContext.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
26 #include "llvm/ADT/ImmutableList.h"
27 #include "llvm/ADT/ImmutableMap.h"
28 #include "llvm/ADT/Optional.h"
29 #include "llvm/Support/raw_ostream.h"
30 
31 using namespace clang;
32 using namespace ento;
33 using llvm::Optional;
34 
35 //===----------------------------------------------------------------------===//
36 // Representation of binding keys.
37 //===----------------------------------------------------------------------===//
38 
39 namespace {
40 class BindingKey {
41 public:
42   enum Kind { Direct = 0x0, Default = 0x1 };
43 private:
44   llvm ::PointerIntPair<const MemRegion*, 1> P;
45   uint64_t Offset;
46 
47   explicit BindingKey(const MemRegion *r, uint64_t offset, Kind k)
48     : P(r, (unsigned) k), Offset(offset) {}
49 public:
50 
51   bool isDirect() const { return P.getInt() == Direct; }
52 
53   const MemRegion *getRegion() const { return P.getPointer(); }
54   uint64_t getOffset() const { return Offset; }
55 
56   void Profile(llvm::FoldingSetNodeID& ID) const {
57     ID.AddPointer(P.getOpaqueValue());
58     ID.AddInteger(Offset);
59   }
60 
61   static BindingKey Make(const MemRegion *R, Kind k);
62 
63   bool operator<(const BindingKey &X) const {
64     if (P.getOpaqueValue() < X.P.getOpaqueValue())
65       return true;
66     if (P.getOpaqueValue() > X.P.getOpaqueValue())
67       return false;
68     return Offset < X.Offset;
69   }
70 
71   bool operator==(const BindingKey &X) const {
72     return P.getOpaqueValue() == X.P.getOpaqueValue() &&
73            Offset == X.Offset;
74   }
75 
76   bool isValid() const {
77     return getRegion() != NULL;
78   }
79 };
80 } // end anonymous namespace
81 
82 BindingKey BindingKey::Make(const MemRegion *R, Kind k) {
83   if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
84     const RegionRawOffset &O = ER->getAsArrayOffset();
85 
86     // FIXME: There are some ElementRegions for which we cannot compute
87     // raw offsets yet, including regions with symbolic offsets. These will be
88     // ignored by the store.
89     return BindingKey(O.getRegion(), O.getOffset().getQuantity(), k);
90   }
91 
92   return BindingKey(R, 0, k);
93 }
94 
95 namespace llvm {
96   static inline
97   raw_ostream &operator<<(raw_ostream &os, BindingKey K) {
98     os << '(' << K.getRegion() << ',' << K.getOffset()
99        << ',' << (K.isDirect() ? "direct" : "default")
100        << ')';
101     return os;
102   }
103 } // end llvm namespace
104 
105 //===----------------------------------------------------------------------===//
106 // Actual Store type.
107 //===----------------------------------------------------------------------===//
108 
109 typedef llvm::ImmutableMap<BindingKey, SVal> RegionBindings;
110 
111 //===----------------------------------------------------------------------===//
112 // Fine-grained control of RegionStoreManager.
113 //===----------------------------------------------------------------------===//
114 
115 namespace {
116 struct minimal_features_tag {};
117 struct maximal_features_tag {};
118 
119 class RegionStoreFeatures {
120   bool SupportsFields;
121 public:
122   RegionStoreFeatures(minimal_features_tag) :
123     SupportsFields(false) {}
124 
125   RegionStoreFeatures(maximal_features_tag) :
126     SupportsFields(true) {}
127 
128   void enableFields(bool t) { SupportsFields = t; }
129 
130   bool supportsFields() const { return SupportsFields; }
131 };
132 }
133 
134 //===----------------------------------------------------------------------===//
135 // Main RegionStore logic.
136 //===----------------------------------------------------------------------===//
137 
138 namespace {
139 
140 class RegionStoreSubRegionMap : public SubRegionMap {
141 public:
142   typedef llvm::ImmutableSet<const MemRegion*> Set;
143   typedef llvm::DenseMap<const MemRegion*, Set> Map;
144 private:
145   Set::Factory F;
146   Map M;
147 public:
148   bool add(const MemRegion* Parent, const MemRegion* SubRegion) {
149     Map::iterator I = M.find(Parent);
150 
151     if (I == M.end()) {
152       M.insert(std::make_pair(Parent, F.add(F.getEmptySet(), SubRegion)));
153       return true;
154     }
155 
156     I->second = F.add(I->second, SubRegion);
157     return false;
158   }
159 
160   void process(SmallVectorImpl<const SubRegion*> &WL, const SubRegion *R);
161 
162   ~RegionStoreSubRegionMap() {}
163 
164   const Set *getSubRegions(const MemRegion *Parent) const {
165     Map::const_iterator I = M.find(Parent);
166     return I == M.end() ? NULL : &I->second;
167   }
168 
169   bool iterSubRegions(const MemRegion* Parent, Visitor& V) const {
170     Map::const_iterator I = M.find(Parent);
171 
172     if (I == M.end())
173       return true;
174 
175     Set S = I->second;
176     for (Set::iterator SI=S.begin(),SE=S.end(); SI != SE; ++SI) {
177       if (!V.Visit(Parent, *SI))
178         return false;
179     }
180 
181     return true;
182   }
183 };
184 
185 void
186 RegionStoreSubRegionMap::process(SmallVectorImpl<const SubRegion*> &WL,
187                                  const SubRegion *R) {
188   const MemRegion *superR = R->getSuperRegion();
189   if (add(superR, R))
190     if (const SubRegion *sr = dyn_cast<SubRegion>(superR))
191       WL.push_back(sr);
192 }
193 
194 class RegionStoreManager : public StoreManager {
195   const RegionStoreFeatures Features;
196   RegionBindings::Factory RBFactory;
197 
198 public:
199   RegionStoreManager(ProgramStateManager& mgr, const RegionStoreFeatures &f)
200     : StoreManager(mgr),
201       Features(f),
202       RBFactory(mgr.getAllocator()) {}
203 
204   SubRegionMap *getSubRegionMap(Store store) {
205     return getRegionStoreSubRegionMap(store);
206   }
207 
208   RegionStoreSubRegionMap *getRegionStoreSubRegionMap(Store store);
209 
210   Optional<SVal> getDirectBinding(RegionBindings B, const MemRegion *R);
211   /// getDefaultBinding - Returns an SVal* representing an optional default
212   ///  binding associated with a region and its subregions.
213   Optional<SVal> getDefaultBinding(RegionBindings B, const MemRegion *R);
214 
215   /// setImplicitDefaultValue - Set the default binding for the provided
216   ///  MemRegion to the value implicitly defined for compound literals when
217   ///  the value is not specified.
218   StoreRef setImplicitDefaultValue(Store store, const MemRegion *R, QualType T);
219 
220   /// ArrayToPointer - Emulates the "decay" of an array to a pointer
221   ///  type.  'Array' represents the lvalue of the array being decayed
222   ///  to a pointer, and the returned SVal represents the decayed
223   ///  version of that lvalue (i.e., a pointer to the first element of
224   ///  the array).  This is called by ExprEngine when evaluating
225   ///  casts from arrays to pointers.
226   SVal ArrayToPointer(Loc Array);
227 
228   /// For DerivedToBase casts, create a CXXBaseObjectRegion and return it.
229   virtual SVal evalDerivedToBase(SVal derived, QualType basePtrType);
230 
231   StoreRef getInitialStore(const LocationContext *InitLoc) {
232     return StoreRef(RBFactory.getEmptyMap().getRootWithoutRetain(), *this);
233   }
234 
235   //===-------------------------------------------------------------------===//
236   // Binding values to regions.
237   //===-------------------------------------------------------------------===//
238 
239   StoreRef invalidateRegions(Store store, ArrayRef<const MemRegion *> Regions,
240                              const Expr *E, unsigned Count,
241                              InvalidatedSymbols &IS,
242                              bool invalidateGlobals,
243                              InvalidatedRegions *Invalidated);
244 
245 public:   // Made public for helper classes.
246 
247   void RemoveSubRegionBindings(RegionBindings &B, const MemRegion *R,
248                                RegionStoreSubRegionMap &M);
249 
250   RegionBindings addBinding(RegionBindings B, BindingKey K, SVal V);
251 
252   RegionBindings addBinding(RegionBindings B, const MemRegion *R,
253                      BindingKey::Kind k, SVal V);
254 
255   const SVal *lookup(RegionBindings B, BindingKey K);
256   const SVal *lookup(RegionBindings B, const MemRegion *R, BindingKey::Kind k);
257 
258   RegionBindings removeBinding(RegionBindings B, BindingKey K);
259   RegionBindings removeBinding(RegionBindings B, const MemRegion *R,
260                         BindingKey::Kind k);
261 
262   RegionBindings removeBinding(RegionBindings B, const MemRegion *R) {
263     return removeBinding(removeBinding(B, R, BindingKey::Direct), R,
264                         BindingKey::Default);
265   }
266 
267 public: // Part of public interface to class.
268 
269   StoreRef Bind(Store store, Loc LV, SVal V);
270 
271   // BindDefault is only used to initialize a region with a default value.
272   StoreRef BindDefault(Store store, const MemRegion *R, SVal V) {
273     RegionBindings B = GetRegionBindings(store);
274     assert(!lookup(B, R, BindingKey::Default));
275     assert(!lookup(B, R, BindingKey::Direct));
276     return StoreRef(addBinding(B, R, BindingKey::Default, V).getRootWithoutRetain(), *this);
277   }
278 
279   StoreRef BindCompoundLiteral(Store store, const CompoundLiteralExpr *CL,
280                                const LocationContext *LC, SVal V);
281 
282   StoreRef BindDecl(Store store, const VarRegion *VR, SVal InitVal);
283 
284   StoreRef BindDeclWithNoInit(Store store, const VarRegion *) {
285     return StoreRef(store, *this);
286   }
287 
288   /// BindStruct - Bind a compound value to a structure.
289   StoreRef BindStruct(Store store, const TypedValueRegion* R, SVal V);
290 
291   StoreRef BindArray(Store store, const TypedValueRegion* R, SVal V);
292 
293   /// KillStruct - Set the entire struct to unknown.
294   StoreRef KillStruct(Store store, const TypedRegion* R, SVal DefaultVal);
295 
296   StoreRef Remove(Store store, Loc LV);
297 
298   void incrementReferenceCount(Store store) {
299     GetRegionBindings(store).manualRetain();
300   }
301 
302   /// If the StoreManager supports it, decrement the reference count of
303   /// the specified Store object.  If the reference count hits 0, the memory
304   /// associated with the object is recycled.
305   void decrementReferenceCount(Store store) {
306     GetRegionBindings(store).manualRelease();
307   }
308 
309   bool includedInBindings(Store store, const MemRegion *region) const;
310 
311   //===------------------------------------------------------------------===//
312   // Loading values from regions.
313   //===------------------------------------------------------------------===//
314 
315   /// The high level logic for this method is this:
316   /// Retrieve (L)
317   ///   if L has binding
318   ///     return L's binding
319   ///   else if L is in killset
320   ///     return unknown
321   ///   else
322   ///     if L is on stack or heap
323   ///       return undefined
324   ///     else
325   ///       return symbolic
326   SVal Retrieve(Store store, Loc L, QualType T = QualType());
327 
328   SVal RetrieveElement(Store store, const ElementRegion *R);
329 
330   SVal RetrieveField(Store store, const FieldRegion *R);
331 
332   SVal RetrieveObjCIvar(Store store, const ObjCIvarRegion *R);
333 
334   SVal RetrieveVar(Store store, const VarRegion *R);
335 
336   SVal RetrieveLazySymbol(const TypedValueRegion *R);
337 
338   SVal RetrieveFieldOrElementCommon(Store store, const TypedValueRegion *R,
339                                     QualType Ty, const MemRegion *superR);
340 
341   SVal RetrieveLazyBinding(const MemRegion *lazyBindingRegion,
342                            Store lazyBindingStore);
343 
344   /// Retrieve the values in a struct and return a CompoundVal, used when doing
345   /// struct copy:
346   /// struct s x, y;
347   /// x = y;
348   /// y's value is retrieved by this method.
349   SVal RetrieveStruct(Store store, const TypedValueRegion* R);
350 
351   SVal RetrieveArray(Store store, const TypedValueRegion* R);
352 
353   /// Used to lazily generate derived symbols for bindings that are defined
354   ///  implicitly by default bindings in a super region.
355   Optional<SVal> RetrieveDerivedDefaultValue(RegionBindings B,
356                                              const MemRegion *superR,
357                                              const TypedValueRegion *R,
358                                              QualType Ty);
359 
360   /// Get the state and region whose binding this region R corresponds to.
361   std::pair<Store, const MemRegion*>
362   GetLazyBinding(RegionBindings B, const MemRegion *R,
363                  const MemRegion *originalRegion);
364 
365   StoreRef CopyLazyBindings(nonloc::LazyCompoundVal V, Store store,
366                             const TypedRegion *R);
367 
368   //===------------------------------------------------------------------===//
369   // State pruning.
370   //===------------------------------------------------------------------===//
371 
372   /// removeDeadBindings - Scans the RegionStore of 'state' for dead values.
373   ///  It returns a new Store with these values removed.
374   StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx,
375                               SymbolReaper& SymReaper);
376 
377   StoreRef enterStackFrame(const ProgramState *state,
378                            const StackFrameContext *frame);
379 
380   //===------------------------------------------------------------------===//
381   // Region "extents".
382   //===------------------------------------------------------------------===//
383 
384   // FIXME: This method will soon be eliminated; see the note in Store.h.
385   DefinedOrUnknownSVal getSizeInElements(const ProgramState *state,
386                                          const MemRegion* R, QualType EleTy);
387 
388   //===------------------------------------------------------------------===//
389   // Utility methods.
390   //===------------------------------------------------------------------===//
391 
392   static inline RegionBindings GetRegionBindings(Store store) {
393     return RegionBindings(static_cast<const RegionBindings::TreeTy*>(store));
394   }
395 
396   void print(Store store, raw_ostream &Out, const char* nl,
397              const char *sep);
398 
399   void iterBindings(Store store, BindingsHandler& f) {
400     RegionBindings B = GetRegionBindings(store);
401     for (RegionBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
402       const BindingKey &K = I.getKey();
403       if (!K.isDirect())
404         continue;
405       if (const SubRegion *R = dyn_cast<SubRegion>(I.getKey().getRegion())) {
406         // FIXME: Possibly incorporate the offset?
407         if (!f.HandleBinding(*this, store, R, I.getData()))
408           return;
409       }
410     }
411   }
412 };
413 
414 } // end anonymous namespace
415 
416 //===----------------------------------------------------------------------===//
417 // RegionStore creation.
418 //===----------------------------------------------------------------------===//
419 
420 StoreManager *ento::CreateRegionStoreManager(ProgramStateManager& StMgr) {
421   RegionStoreFeatures F = maximal_features_tag();
422   return new RegionStoreManager(StMgr, F);
423 }
424 
425 StoreManager *ento::CreateFieldsOnlyRegionStoreManager(ProgramStateManager &StMgr) {
426   RegionStoreFeatures F = minimal_features_tag();
427   F.enableFields(true);
428   return new RegionStoreManager(StMgr, F);
429 }
430 
431 
432 RegionStoreSubRegionMap*
433 RegionStoreManager::getRegionStoreSubRegionMap(Store store) {
434   RegionBindings B = GetRegionBindings(store);
435   RegionStoreSubRegionMap *M = new RegionStoreSubRegionMap();
436 
437   SmallVector<const SubRegion*, 10> WL;
438 
439   for (RegionBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I)
440     if (const SubRegion *R = dyn_cast<SubRegion>(I.getKey().getRegion()))
441       M->process(WL, R);
442 
443   // We also need to record in the subregion map "intermediate" regions that
444   // don't have direct bindings but are super regions of those that do.
445   while (!WL.empty()) {
446     const SubRegion *R = WL.back();
447     WL.pop_back();
448     M->process(WL, R);
449   }
450 
451   return M;
452 }
453 
454 //===----------------------------------------------------------------------===//
455 // Region Cluster analysis.
456 //===----------------------------------------------------------------------===//
457 
458 namespace {
459 template <typename DERIVED>
460 class ClusterAnalysis  {
461 protected:
462   typedef BumpVector<BindingKey> RegionCluster;
463   typedef llvm::DenseMap<const MemRegion *, RegionCluster *> ClusterMap;
464   llvm::DenseMap<const RegionCluster*, unsigned> Visited;
465   typedef SmallVector<std::pair<const MemRegion *, RegionCluster*>, 10>
466     WorkList;
467 
468   BumpVectorContext BVC;
469   ClusterMap ClusterM;
470   WorkList WL;
471 
472   RegionStoreManager &RM;
473   ASTContext &Ctx;
474   SValBuilder &svalBuilder;
475 
476   RegionBindings B;
477 
478   const bool includeGlobals;
479 
480 public:
481   ClusterAnalysis(RegionStoreManager &rm, ProgramStateManager &StateMgr,
482                   RegionBindings b, const bool includeGlobals)
483     : RM(rm), Ctx(StateMgr.getContext()),
484       svalBuilder(StateMgr.getSValBuilder()),
485       B(b), includeGlobals(includeGlobals) {}
486 
487   RegionBindings getRegionBindings() const { return B; }
488 
489   RegionCluster &AddToCluster(BindingKey K) {
490     const MemRegion *R = K.getRegion();
491     const MemRegion *baseR = R->getBaseRegion();
492     RegionCluster &C = getCluster(baseR);
493     C.push_back(K, BVC);
494     static_cast<DERIVED*>(this)->VisitAddedToCluster(baseR, C);
495     return C;
496   }
497 
498   bool isVisited(const MemRegion *R) {
499     return (bool) Visited[&getCluster(R->getBaseRegion())];
500   }
501 
502   RegionCluster& getCluster(const MemRegion *R) {
503     RegionCluster *&CRef = ClusterM[R];
504     if (!CRef) {
505       void *Mem = BVC.getAllocator().template Allocate<RegionCluster>();
506       CRef = new (Mem) RegionCluster(BVC, 10);
507     }
508     return *CRef;
509   }
510 
511   void GenerateClusters() {
512       // Scan the entire set of bindings and make the region clusters.
513     for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){
514       RegionCluster &C = AddToCluster(RI.getKey());
515       if (const MemRegion *R = RI.getData().getAsRegion()) {
516         // Generate a cluster, but don't add the region to the cluster
517         // if there aren't any bindings.
518         getCluster(R->getBaseRegion());
519       }
520       if (includeGlobals) {
521         const MemRegion *R = RI.getKey().getRegion();
522         if (isa<NonStaticGlobalSpaceRegion>(R->getMemorySpace()))
523           AddToWorkList(R, C);
524       }
525     }
526   }
527 
528   bool AddToWorkList(const MemRegion *R, RegionCluster &C) {
529     if (unsigned &visited = Visited[&C])
530       return false;
531     else
532       visited = 1;
533 
534     WL.push_back(std::make_pair(R, &C));
535     return true;
536   }
537 
538   bool AddToWorkList(BindingKey K) {
539     return AddToWorkList(K.getRegion());
540   }
541 
542   bool AddToWorkList(const MemRegion *R) {
543     const MemRegion *baseR = R->getBaseRegion();
544     return AddToWorkList(baseR, getCluster(baseR));
545   }
546 
547   void RunWorkList() {
548     while (!WL.empty()) {
549       const MemRegion *baseR;
550       RegionCluster *C;
551       llvm::tie(baseR, C) = WL.back();
552       WL.pop_back();
553 
554         // First visit the cluster.
555       static_cast<DERIVED*>(this)->VisitCluster(baseR, C->begin(), C->end());
556 
557         // Next, visit the base region.
558       static_cast<DERIVED*>(this)->VisitBaseRegion(baseR);
559     }
560   }
561 
562 public:
563   void VisitAddedToCluster(const MemRegion *baseR, RegionCluster &C) {}
564   void VisitCluster(const MemRegion *baseR, BindingKey *I, BindingKey *E) {}
565   void VisitBaseRegion(const MemRegion *baseR) {}
566 };
567 }
568 
569 //===----------------------------------------------------------------------===//
570 // Binding invalidation.
571 //===----------------------------------------------------------------------===//
572 
573 void RegionStoreManager::RemoveSubRegionBindings(RegionBindings &B,
574                                                  const MemRegion *R,
575                                                  RegionStoreSubRegionMap &M) {
576 
577   if (const RegionStoreSubRegionMap::Set *S = M.getSubRegions(R))
578     for (RegionStoreSubRegionMap::Set::iterator I = S->begin(), E = S->end();
579          I != E; ++I)
580       RemoveSubRegionBindings(B, *I, M);
581 
582   B = removeBinding(B, R);
583 }
584 
585 namespace {
586 class invalidateRegionsWorker : public ClusterAnalysis<invalidateRegionsWorker>
587 {
588   const Expr *Ex;
589   unsigned Count;
590   StoreManager::InvalidatedSymbols &IS;
591   StoreManager::InvalidatedRegions *Regions;
592 public:
593   invalidateRegionsWorker(RegionStoreManager &rm,
594                           ProgramStateManager &stateMgr,
595                           RegionBindings b,
596                           const Expr *ex, unsigned count,
597                           StoreManager::InvalidatedSymbols &is,
598                           StoreManager::InvalidatedRegions *r,
599                           bool includeGlobals)
600     : ClusterAnalysis<invalidateRegionsWorker>(rm, stateMgr, b, includeGlobals),
601       Ex(ex), Count(count), IS(is), Regions(r) {}
602 
603   void VisitCluster(const MemRegion *baseR, BindingKey *I, BindingKey *E);
604   void VisitBaseRegion(const MemRegion *baseR);
605 
606 private:
607   void VisitBinding(SVal V);
608 };
609 }
610 
611 void invalidateRegionsWorker::VisitBinding(SVal V) {
612   // A symbol?  Mark it touched by the invalidation.
613   if (SymbolRef Sym = V.getAsSymbol())
614     IS.insert(Sym);
615 
616   if (const MemRegion *R = V.getAsRegion()) {
617     AddToWorkList(R);
618     return;
619   }
620 
621   // Is it a LazyCompoundVal?  All references get invalidated as well.
622   if (const nonloc::LazyCompoundVal *LCS =
623         dyn_cast<nonloc::LazyCompoundVal>(&V)) {
624 
625     const MemRegion *LazyR = LCS->getRegion();
626     RegionBindings B = RegionStoreManager::GetRegionBindings(LCS->getStore());
627 
628     for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){
629       const SubRegion *baseR = dyn_cast<SubRegion>(RI.getKey().getRegion());
630       if (baseR && baseR->isSubRegionOf(LazyR))
631         VisitBinding(RI.getData());
632     }
633 
634     return;
635   }
636 }
637 
638 void invalidateRegionsWorker::VisitCluster(const MemRegion *baseR,
639                                            BindingKey *I, BindingKey *E) {
640   for ( ; I != E; ++I) {
641     // Get the old binding.  Is it a region?  If so, add it to the worklist.
642     const BindingKey &K = *I;
643     if (const SVal *V = RM.lookup(B, K))
644       VisitBinding(*V);
645 
646     B = RM.removeBinding(B, K);
647   }
648 }
649 
650 void invalidateRegionsWorker::VisitBaseRegion(const MemRegion *baseR) {
651   // Symbolic region?  Mark that symbol touched by the invalidation.
652   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR))
653     IS.insert(SR->getSymbol());
654 
655   // BlockDataRegion?  If so, invalidate captured variables that are passed
656   // by reference.
657   if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) {
658     for (BlockDataRegion::referenced_vars_iterator
659          BI = BR->referenced_vars_begin(), BE = BR->referenced_vars_end() ;
660          BI != BE; ++BI) {
661       const VarRegion *VR = *BI;
662       const VarDecl *VD = VR->getDecl();
663       if (VD->getAttr<BlocksAttr>() || !VD->hasLocalStorage())
664         AddToWorkList(VR);
665     }
666     return;
667   }
668 
669   // Otherwise, we have a normal data region. Record that we touched the region.
670   if (Regions)
671     Regions->push_back(baseR);
672 
673   if (isa<AllocaRegion>(baseR) || isa<SymbolicRegion>(baseR)) {
674     // Invalidate the region by setting its default value to
675     // conjured symbol. The type of the symbol is irrelavant.
676     DefinedOrUnknownSVal V =
677       svalBuilder.getConjuredSymbolVal(baseR, Ex, Ctx.IntTy, Count);
678     B = RM.addBinding(B, baseR, BindingKey::Default, V);
679     return;
680   }
681 
682   if (!baseR->isBoundable())
683     return;
684 
685   const TypedValueRegion *TR = cast<TypedValueRegion>(baseR);
686   QualType T = TR->getValueType();
687 
688     // Invalidate the binding.
689   if (T->isStructureOrClassType()) {
690     // Invalidate the region by setting its default value to
691     // conjured symbol. The type of the symbol is irrelavant.
692     DefinedOrUnknownSVal V =
693       svalBuilder.getConjuredSymbolVal(baseR, Ex, Ctx.IntTy, Count);
694     B = RM.addBinding(B, baseR, BindingKey::Default, V);
695     return;
696   }
697 
698   if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
699       // Set the default value of the array to conjured symbol.
700     DefinedOrUnknownSVal V =
701     svalBuilder.getConjuredSymbolVal(baseR, Ex, AT->getElementType(), Count);
702     B = RM.addBinding(B, baseR, BindingKey::Default, V);
703     return;
704   }
705 
706   if (includeGlobals &&
707       isa<NonStaticGlobalSpaceRegion>(baseR->getMemorySpace())) {
708     // If the region is a global and we are invalidating all globals,
709     // just erase the entry.  This causes all globals to be lazily
710     // symbolicated from the same base symbol.
711     B = RM.removeBinding(B, baseR);
712     return;
713   }
714 
715 
716   DefinedOrUnknownSVal V = svalBuilder.getConjuredSymbolVal(baseR, Ex, T, Count);
717   assert(SymbolManager::canSymbolicate(T) || V.isUnknown());
718   B = RM.addBinding(B, baseR, BindingKey::Direct, V);
719 }
720 
721 StoreRef RegionStoreManager::invalidateRegions(Store store,
722                                             ArrayRef<const MemRegion *> Regions,
723                                                const Expr *Ex, unsigned Count,
724                                                InvalidatedSymbols &IS,
725                                                bool invalidateGlobals,
726                                               InvalidatedRegions *Invalidated) {
727   invalidateRegionsWorker W(*this, StateMgr,
728                             RegionStoreManager::GetRegionBindings(store),
729                             Ex, Count, IS, Invalidated, invalidateGlobals);
730 
731   // Scan the bindings and generate the clusters.
732   W.GenerateClusters();
733 
734   // Add the regions to the worklist.
735   for (ArrayRef<const MemRegion *>::iterator
736        I = Regions.begin(), E = Regions.end(); I != E; ++I)
737     W.AddToWorkList(*I);
738 
739   W.RunWorkList();
740 
741   // Return the new bindings.
742   RegionBindings B = W.getRegionBindings();
743 
744   if (invalidateGlobals) {
745     // Bind the non-static globals memory space to a new symbol that we will
746     // use to derive the bindings for all non-static globals.
747     const GlobalsSpaceRegion *GS = MRMgr.getGlobalsRegion();
748     SVal V =
749       svalBuilder.getConjuredSymbolVal(/* SymbolTag = */ (void*) GS, Ex,
750                                   /* symbol type, doesn't matter */ Ctx.IntTy,
751                                   Count);
752     B = addBinding(B, BindingKey::Make(GS, BindingKey::Default), V);
753 
754     // Even if there are no bindings in the global scope, we still need to
755     // record that we touched it.
756     if (Invalidated)
757       Invalidated->push_back(GS);
758   }
759 
760   return StoreRef(B.getRootWithoutRetain(), *this);
761 }
762 
763 //===----------------------------------------------------------------------===//
764 // Extents for regions.
765 //===----------------------------------------------------------------------===//
766 
767 DefinedOrUnknownSVal RegionStoreManager::getSizeInElements(const ProgramState *state,
768                                                            const MemRegion *R,
769                                                            QualType EleTy) {
770   SVal Size = cast<SubRegion>(R)->getExtent(svalBuilder);
771   const llvm::APSInt *SizeInt = svalBuilder.getKnownValue(state, Size);
772   if (!SizeInt)
773     return UnknownVal();
774 
775   CharUnits RegionSize = CharUnits::fromQuantity(SizeInt->getSExtValue());
776 
777   if (Ctx.getAsVariableArrayType(EleTy)) {
778     // FIXME: We need to track extra state to properly record the size
779     // of VLAs.  Returning UnknownVal here, however, is a stop-gap so that
780     // we don't have a divide-by-zero below.
781     return UnknownVal();
782   }
783 
784   CharUnits EleSize = Ctx.getTypeSizeInChars(EleTy);
785 
786   // If a variable is reinterpreted as a type that doesn't fit into a larger
787   // type evenly, round it down.
788   // This is a signed value, since it's used in arithmetic with signed indices.
789   return svalBuilder.makeIntVal(RegionSize / EleSize, false);
790 }
791 
792 //===----------------------------------------------------------------------===//
793 // Location and region casting.
794 //===----------------------------------------------------------------------===//
795 
796 /// ArrayToPointer - Emulates the "decay" of an array to a pointer
797 ///  type.  'Array' represents the lvalue of the array being decayed
798 ///  to a pointer, and the returned SVal represents the decayed
799 ///  version of that lvalue (i.e., a pointer to the first element of
800 ///  the array).  This is called by ExprEngine when evaluating casts
801 ///  from arrays to pointers.
802 SVal RegionStoreManager::ArrayToPointer(Loc Array) {
803   if (!isa<loc::MemRegionVal>(Array))
804     return UnknownVal();
805 
806   const MemRegion* R = cast<loc::MemRegionVal>(&Array)->getRegion();
807   const TypedValueRegion* ArrayR = dyn_cast<TypedValueRegion>(R);
808 
809   if (!ArrayR)
810     return UnknownVal();
811 
812   // Strip off typedefs from the ArrayRegion's ValueType.
813   QualType T = ArrayR->getValueType().getDesugaredType(Ctx);
814   const ArrayType *AT = cast<ArrayType>(T);
815   T = AT->getElementType();
816 
817   NonLoc ZeroIdx = svalBuilder.makeZeroArrayIndex();
818   return loc::MemRegionVal(MRMgr.getElementRegion(T, ZeroIdx, ArrayR, Ctx));
819 }
820 
821 SVal RegionStoreManager::evalDerivedToBase(SVal derived, QualType baseType) {
822   const CXXRecordDecl *baseDecl;
823   if (baseType->isPointerType())
824     baseDecl = baseType->getCXXRecordDeclForPointerType();
825   else
826     baseDecl = baseType->getAsCXXRecordDecl();
827 
828   assert(baseDecl && "not a CXXRecordDecl?");
829 
830   loc::MemRegionVal *derivedRegVal = dyn_cast<loc::MemRegionVal>(&derived);
831   if (!derivedRegVal)
832     return derived;
833 
834   const MemRegion *baseReg =
835     MRMgr.getCXXBaseObjectRegion(baseDecl, derivedRegVal->getRegion());
836 
837   return loc::MemRegionVal(baseReg);
838 }
839 
840 //===----------------------------------------------------------------------===//
841 // Loading values from regions.
842 //===----------------------------------------------------------------------===//
843 
844 Optional<SVal> RegionStoreManager::getDirectBinding(RegionBindings B,
845                                                     const MemRegion *R) {
846 
847   if (const SVal *V = lookup(B, R, BindingKey::Direct))
848     return *V;
849 
850   return Optional<SVal>();
851 }
852 
853 Optional<SVal> RegionStoreManager::getDefaultBinding(RegionBindings B,
854                                                      const MemRegion *R) {
855   if (R->isBoundable())
856     if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R))
857       if (TR->getValueType()->isUnionType())
858         return UnknownVal();
859 
860   if (const SVal *V = lookup(B, R, BindingKey::Default))
861     return *V;
862 
863   return Optional<SVal>();
864 }
865 
866 SVal RegionStoreManager::Retrieve(Store store, Loc L, QualType T) {
867   assert(!isa<UnknownVal>(L) && "location unknown");
868   assert(!isa<UndefinedVal>(L) && "location undefined");
869 
870   // For access to concrete addresses, return UnknownVal.  Checks
871   // for null dereferences (and similar errors) are done by checkers, not
872   // the Store.
873   // FIXME: We can consider lazily symbolicating such memory, but we really
874   // should defer this when we can reason easily about symbolicating arrays
875   // of bytes.
876   if (isa<loc::ConcreteInt>(L)) {
877     return UnknownVal();
878   }
879   if (!isa<loc::MemRegionVal>(L)) {
880     return UnknownVal();
881   }
882 
883   const MemRegion *MR = cast<loc::MemRegionVal>(L).getRegion();
884 
885   if (isa<AllocaRegion>(MR) ||
886       isa<SymbolicRegion>(MR) ||
887       isa<CodeTextRegion>(MR)) {
888     if (T.isNull()) {
889       const SymbolicRegion *SR = cast<SymbolicRegion>(MR);
890       T = SR->getSymbol()->getType(Ctx);
891     }
892     MR = GetElementZeroRegion(MR, T);
893   }
894 
895   // FIXME: Perhaps this method should just take a 'const MemRegion*' argument
896   //  instead of 'Loc', and have the other Loc cases handled at a higher level.
897   const TypedValueRegion *R = cast<TypedValueRegion>(MR);
898   QualType RTy = R->getValueType();
899 
900   // FIXME: We should eventually handle funny addressing.  e.g.:
901   //
902   //   int x = ...;
903   //   int *p = &x;
904   //   char *q = (char*) p;
905   //   char c = *q;  // returns the first byte of 'x'.
906   //
907   // Such funny addressing will occur due to layering of regions.
908 
909   if (RTy->isStructureOrClassType())
910     return RetrieveStruct(store, R);
911 
912   // FIXME: Handle unions.
913   if (RTy->isUnionType())
914     return UnknownVal();
915 
916   if (RTy->isArrayType())
917     return RetrieveArray(store, R);
918 
919   // FIXME: handle Vector types.
920   if (RTy->isVectorType())
921     return UnknownVal();
922 
923   if (const FieldRegion* FR = dyn_cast<FieldRegion>(R))
924     return CastRetrievedVal(RetrieveField(store, FR), FR, T, false);
925 
926   if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) {
927     // FIXME: Here we actually perform an implicit conversion from the loaded
928     // value to the element type.  Eventually we want to compose these values
929     // more intelligently.  For example, an 'element' can encompass multiple
930     // bound regions (e.g., several bound bytes), or could be a subset of
931     // a larger value.
932     return CastRetrievedVal(RetrieveElement(store, ER), ER, T, false);
933   }
934 
935   if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) {
936     // FIXME: Here we actually perform an implicit conversion from the loaded
937     // value to the ivar type.  What we should model is stores to ivars
938     // that blow past the extent of the ivar.  If the address of the ivar is
939     // reinterpretted, it is possible we stored a different value that could
940     // fit within the ivar.  Either we need to cast these when storing them
941     // or reinterpret them lazily (as we do here).
942     return CastRetrievedVal(RetrieveObjCIvar(store, IVR), IVR, T, false);
943   }
944 
945   if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
946     // FIXME: Here we actually perform an implicit conversion from the loaded
947     // value to the variable type.  What we should model is stores to variables
948     // that blow past the extent of the variable.  If the address of the
949     // variable is reinterpretted, it is possible we stored a different value
950     // that could fit within the variable.  Either we need to cast these when
951     // storing them or reinterpret them lazily (as we do here).
952     return CastRetrievedVal(RetrieveVar(store, VR), VR, T, false);
953   }
954 
955   RegionBindings B = GetRegionBindings(store);
956   const SVal *V = lookup(B, R, BindingKey::Direct);
957 
958   // Check if the region has a binding.
959   if (V)
960     return *V;
961 
962   // The location does not have a bound value.  This means that it has
963   // the value it had upon its creation and/or entry to the analyzed
964   // function/method.  These are either symbolic values or 'undefined'.
965   if (R->hasStackNonParametersStorage()) {
966     // All stack variables are considered to have undefined values
967     // upon creation.  All heap allocated blocks are considered to
968     // have undefined values as well unless they are explicitly bound
969     // to specific values.
970     return UndefinedVal();
971   }
972 
973   // All other values are symbolic.
974   return svalBuilder.getRegionValueSymbolVal(R);
975 }
976 
977 std::pair<Store, const MemRegion *>
978 RegionStoreManager::GetLazyBinding(RegionBindings B, const MemRegion *R,
979                                    const MemRegion *originalRegion) {
980 
981   if (originalRegion != R) {
982     if (Optional<SVal> OV = getDefaultBinding(B, R)) {
983       if (const nonloc::LazyCompoundVal *V =
984           dyn_cast<nonloc::LazyCompoundVal>(OV.getPointer()))
985         return std::make_pair(V->getStore(), V->getRegion());
986     }
987   }
988 
989   if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
990     const std::pair<Store, const MemRegion *> &X =
991       GetLazyBinding(B, ER->getSuperRegion(), originalRegion);
992 
993     if (X.second)
994       return std::make_pair(X.first,
995                             MRMgr.getElementRegionWithSuper(ER, X.second));
996   }
997   else if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) {
998     const std::pair<Store, const MemRegion *> &X =
999       GetLazyBinding(B, FR->getSuperRegion(), originalRegion);
1000 
1001     if (X.second)
1002       return std::make_pair(X.first,
1003                             MRMgr.getFieldRegionWithSuper(FR, X.second));
1004   }
1005   // C++ base object region is another kind of region that we should blast
1006   // through to look for lazy compound value. It is like a field region.
1007   else if (const CXXBaseObjectRegion *baseReg =
1008                             dyn_cast<CXXBaseObjectRegion>(R)) {
1009     const std::pair<Store, const MemRegion *> &X =
1010       GetLazyBinding(B, baseReg->getSuperRegion(), originalRegion);
1011 
1012     if (X.second)
1013       return std::make_pair(X.first,
1014                      MRMgr.getCXXBaseObjectRegionWithSuper(baseReg, X.second));
1015   }
1016 
1017   // The NULL MemRegion indicates an non-existent lazy binding. A NULL Store is
1018   // possible for a valid lazy binding.
1019   return std::make_pair((Store) 0, (const MemRegion *) 0);
1020 }
1021 
1022 SVal RegionStoreManager::RetrieveElement(Store store,
1023                                          const ElementRegion* R) {
1024   // Check if the region has a binding.
1025   RegionBindings B = GetRegionBindings(store);
1026   if (const Optional<SVal> &V = getDirectBinding(B, R))
1027     return *V;
1028 
1029   const MemRegion* superR = R->getSuperRegion();
1030 
1031   // Check if the region is an element region of a string literal.
1032   if (const StringRegion *StrR=dyn_cast<StringRegion>(superR)) {
1033     // FIXME: Handle loads from strings where the literal is treated as
1034     // an integer, e.g., *((unsigned int*)"hello")
1035     QualType T = Ctx.getAsArrayType(StrR->getValueType())->getElementType();
1036     if (T != Ctx.getCanonicalType(R->getElementType()))
1037       return UnknownVal();
1038 
1039     const StringLiteral *Str = StrR->getStringLiteral();
1040     SVal Idx = R->getIndex();
1041     if (nonloc::ConcreteInt *CI = dyn_cast<nonloc::ConcreteInt>(&Idx)) {
1042       int64_t i = CI->getValue().getSExtValue();
1043       // Abort on string underrun.  This can be possible by arbitrary
1044       // clients of RetrieveElement().
1045       if (i < 0)
1046         return UndefinedVal();
1047       int64_t length = Str->getLength();
1048       // Technically, only i == length is guaranteed to be null.
1049       // However, such overflows should be caught before reaching this point;
1050       // the only time such an access would be made is if a string literal was
1051       // used to initialize a larger array.
1052       char c = (i >= length) ? '\0' : Str->getCodeUnit(i);
1053       return svalBuilder.makeIntVal(c, T);
1054     }
1055   }
1056 
1057   // Check for loads from a code text region.  For such loads, just give up.
1058   if (isa<CodeTextRegion>(superR))
1059     return UnknownVal();
1060 
1061   // Handle the case where we are indexing into a larger scalar object.
1062   // For example, this handles:
1063   //   int x = ...
1064   //   char *y = &x;
1065   //   return *y;
1066   // FIXME: This is a hack, and doesn't do anything really intelligent yet.
1067   const RegionRawOffset &O = R->getAsArrayOffset();
1068 
1069   // If we cannot reason about the offset, return an unknown value.
1070   if (!O.getRegion())
1071     return UnknownVal();
1072 
1073   if (const TypedValueRegion *baseR =
1074         dyn_cast_or_null<TypedValueRegion>(O.getRegion())) {
1075     QualType baseT = baseR->getValueType();
1076     if (baseT->isScalarType()) {
1077       QualType elemT = R->getElementType();
1078       if (elemT->isScalarType()) {
1079         if (Ctx.getTypeSizeInChars(baseT) >= Ctx.getTypeSizeInChars(elemT)) {
1080           if (const Optional<SVal> &V = getDirectBinding(B, superR)) {
1081             if (SymbolRef parentSym = V->getAsSymbol())
1082               return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1083 
1084             if (V->isUnknownOrUndef())
1085               return *V;
1086             // Other cases: give up.  We are indexing into a larger object
1087             // that has some value, but we don't know how to handle that yet.
1088             return UnknownVal();
1089           }
1090         }
1091       }
1092     }
1093   }
1094   return RetrieveFieldOrElementCommon(store, R, R->getElementType(), superR);
1095 }
1096 
1097 SVal RegionStoreManager::RetrieveField(Store store,
1098                                        const FieldRegion* R) {
1099 
1100   // Check if the region has a binding.
1101   RegionBindings B = GetRegionBindings(store);
1102   if (const Optional<SVal> &V = getDirectBinding(B, R))
1103     return *V;
1104 
1105   QualType Ty = R->getValueType();
1106   return RetrieveFieldOrElementCommon(store, R, Ty, R->getSuperRegion());
1107 }
1108 
1109 Optional<SVal>
1110 RegionStoreManager::RetrieveDerivedDefaultValue(RegionBindings B,
1111                                                 const MemRegion *superR,
1112                                                 const TypedValueRegion *R,
1113                                                 QualType Ty) {
1114 
1115   if (const Optional<SVal> &D = getDefaultBinding(B, superR)) {
1116     const SVal &val = D.getValue();
1117     if (SymbolRef parentSym = val.getAsSymbol())
1118       return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1119 
1120     if (val.isZeroConstant())
1121       return svalBuilder.makeZeroVal(Ty);
1122 
1123     if (val.isUnknownOrUndef())
1124       return val;
1125 
1126     // Lazy bindings are handled later.
1127     if (isa<nonloc::LazyCompoundVal>(val))
1128       return Optional<SVal>();
1129 
1130     llvm_unreachable("Unknown default value");
1131   }
1132 
1133   return Optional<SVal>();
1134 }
1135 
1136 SVal RegionStoreManager::RetrieveLazyBinding(const MemRegion *lazyBindingRegion,
1137                                              Store lazyBindingStore) {
1138   if (const ElementRegion *ER = dyn_cast<ElementRegion>(lazyBindingRegion))
1139     return RetrieveElement(lazyBindingStore, ER);
1140 
1141   return RetrieveField(lazyBindingStore,
1142                        cast<FieldRegion>(lazyBindingRegion));
1143 }
1144 
1145 SVal RegionStoreManager::RetrieveFieldOrElementCommon(Store store,
1146                                                       const TypedValueRegion *R,
1147                                                       QualType Ty,
1148                                                       const MemRegion *superR) {
1149 
1150   // At this point we have already checked in either RetrieveElement or
1151   // RetrieveField if 'R' has a direct binding.
1152 
1153   RegionBindings B = GetRegionBindings(store);
1154 
1155   while (superR) {
1156     if (const Optional<SVal> &D =
1157         RetrieveDerivedDefaultValue(B, superR, R, Ty))
1158       return *D;
1159 
1160     // If our super region is a field or element itself, walk up the region
1161     // hierarchy to see if there is a default value installed in an ancestor.
1162     if (const SubRegion *SR = dyn_cast<SubRegion>(superR)) {
1163       superR = SR->getSuperRegion();
1164       continue;
1165     }
1166     break;
1167   }
1168 
1169   // Lazy binding?
1170   Store lazyBindingStore = NULL;
1171   const MemRegion *lazyBindingRegion = NULL;
1172   llvm::tie(lazyBindingStore, lazyBindingRegion) = GetLazyBinding(B, R, R);
1173 
1174   if (lazyBindingRegion)
1175     return RetrieveLazyBinding(lazyBindingRegion, lazyBindingStore);
1176 
1177   if (R->hasStackNonParametersStorage()) {
1178     if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
1179       // Currently we don't reason specially about Clang-style vectors.  Check
1180       // if superR is a vector and if so return Unknown.
1181       if (const TypedValueRegion *typedSuperR =
1182             dyn_cast<TypedValueRegion>(superR)) {
1183         if (typedSuperR->getValueType()->isVectorType())
1184           return UnknownVal();
1185       }
1186 
1187       // FIXME: We also need to take ElementRegions with symbolic indexes into
1188       // account.
1189       if (!ER->getIndex().isConstant())
1190         return UnknownVal();
1191     }
1192 
1193     return UndefinedVal();
1194   }
1195 
1196   // All other values are symbolic.
1197   return svalBuilder.getRegionValueSymbolVal(R);
1198 }
1199 
1200 SVal RegionStoreManager::RetrieveObjCIvar(Store store, const ObjCIvarRegion* R){
1201 
1202     // Check if the region has a binding.
1203   RegionBindings B = GetRegionBindings(store);
1204 
1205   if (const Optional<SVal> &V = getDirectBinding(B, R))
1206     return *V;
1207 
1208   const MemRegion *superR = R->getSuperRegion();
1209 
1210   // Check if the super region has a default binding.
1211   if (const Optional<SVal> &V = getDefaultBinding(B, superR)) {
1212     if (SymbolRef parentSym = V->getAsSymbol())
1213       return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1214 
1215     // Other cases: give up.
1216     return UnknownVal();
1217   }
1218 
1219   return RetrieveLazySymbol(R);
1220 }
1221 
1222 SVal RegionStoreManager::RetrieveVar(Store store, const VarRegion *R) {
1223 
1224   // Check if the region has a binding.
1225   RegionBindings B = GetRegionBindings(store);
1226 
1227   if (const Optional<SVal> &V = getDirectBinding(B, R))
1228     return *V;
1229 
1230   // Lazily derive a value for the VarRegion.
1231   const VarDecl *VD = R->getDecl();
1232   QualType T = VD->getType();
1233   const MemSpaceRegion *MS = R->getMemorySpace();
1234 
1235   if (isa<UnknownSpaceRegion>(MS) ||
1236       isa<StackArgumentsSpaceRegion>(MS))
1237     return svalBuilder.getRegionValueSymbolVal(R);
1238 
1239   if (isa<GlobalsSpaceRegion>(MS)) {
1240     if (isa<NonStaticGlobalSpaceRegion>(MS)) {
1241       // Is 'VD' declared constant?  If so, retrieve the constant value.
1242       QualType CT = Ctx.getCanonicalType(T);
1243       if (CT.isConstQualified()) {
1244         const Expr *Init = VD->getInit();
1245         // Do the null check first, as we want to call 'IgnoreParenCasts'.
1246         if (Init)
1247           if (const IntegerLiteral *IL =
1248               dyn_cast<IntegerLiteral>(Init->IgnoreParenCasts())) {
1249             const nonloc::ConcreteInt &V = svalBuilder.makeIntVal(IL);
1250             return svalBuilder.evalCast(V, Init->getType(), IL->getType());
1251           }
1252       }
1253 
1254       if (const Optional<SVal> &V = RetrieveDerivedDefaultValue(B, MS, R, CT))
1255         return V.getValue();
1256 
1257       return svalBuilder.getRegionValueSymbolVal(R);
1258     }
1259 
1260     if (T->isIntegerType())
1261       return svalBuilder.makeIntVal(0, T);
1262     if (T->isPointerType())
1263       return svalBuilder.makeNull();
1264 
1265     return UnknownVal();
1266   }
1267 
1268   return UndefinedVal();
1269 }
1270 
1271 SVal RegionStoreManager::RetrieveLazySymbol(const TypedValueRegion *R) {
1272   // All other values are symbolic.
1273   return svalBuilder.getRegionValueSymbolVal(R);
1274 }
1275 
1276 SVal RegionStoreManager::RetrieveStruct(Store store,
1277                                         const TypedValueRegion* R) {
1278   QualType T = R->getValueType();
1279   assert(T->isStructureOrClassType());
1280   return svalBuilder.makeLazyCompoundVal(StoreRef(store, *this), R);
1281 }
1282 
1283 SVal RegionStoreManager::RetrieveArray(Store store,
1284                                        const TypedValueRegion * R) {
1285   assert(Ctx.getAsConstantArrayType(R->getValueType()));
1286   return svalBuilder.makeLazyCompoundVal(StoreRef(store, *this), R);
1287 }
1288 
1289 bool RegionStoreManager::includedInBindings(Store store,
1290                                             const MemRegion *region) const {
1291   RegionBindings B = GetRegionBindings(store);
1292   region = region->getBaseRegion();
1293 
1294   for (RegionBindings::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
1295     const BindingKey &K = it.getKey();
1296     if (region == K.getRegion())
1297       return true;
1298     const SVal &D = it.getData();
1299     if (const MemRegion *r = D.getAsRegion())
1300       if (r == region)
1301         return true;
1302   }
1303   return false;
1304 }
1305 
1306 //===----------------------------------------------------------------------===//
1307 // Binding values to regions.
1308 //===----------------------------------------------------------------------===//
1309 
1310 StoreRef RegionStoreManager::Remove(Store store, Loc L) {
1311   if (isa<loc::MemRegionVal>(L))
1312     if (const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion())
1313       return StoreRef(removeBinding(GetRegionBindings(store),
1314                                     R).getRootWithoutRetain(),
1315                       *this);
1316 
1317   return StoreRef(store, *this);
1318 }
1319 
1320 StoreRef RegionStoreManager::Bind(Store store, Loc L, SVal V) {
1321   if (isa<loc::ConcreteInt>(L))
1322     return StoreRef(store, *this);
1323 
1324   // If we get here, the location should be a region.
1325   const MemRegion *R = cast<loc::MemRegionVal>(L).getRegion();
1326 
1327   // Check if the region is a struct region.
1328   if (const TypedValueRegion* TR = dyn_cast<TypedValueRegion>(R))
1329     if (TR->getValueType()->isStructureOrClassType())
1330       return BindStruct(store, TR, V);
1331 
1332   if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
1333     if (ER->getIndex().isZeroConstant()) {
1334       if (const TypedValueRegion *superR =
1335             dyn_cast<TypedValueRegion>(ER->getSuperRegion())) {
1336         QualType superTy = superR->getValueType();
1337         // For now, just invalidate the fields of the struct/union/class.
1338         // This is for test rdar_test_7185607 in misc-ps-region-store.m.
1339         // FIXME: Precisely handle the fields of the record.
1340         if (superTy->isStructureOrClassType())
1341           return KillStruct(store, superR, UnknownVal());
1342       }
1343     }
1344   }
1345   else if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) {
1346     // Binding directly to a symbolic region should be treated as binding
1347     // to element 0.
1348     QualType T = SR->getSymbol()->getType(Ctx);
1349 
1350     // FIXME: Is this the right way to handle symbols that are references?
1351     if (const PointerType *PT = T->getAs<PointerType>())
1352       T = PT->getPointeeType();
1353     else
1354       T = T->getAs<ReferenceType>()->getPointeeType();
1355 
1356     R = GetElementZeroRegion(SR, T);
1357   }
1358 
1359   // Perform the binding.
1360   RegionBindings B = GetRegionBindings(store);
1361   return StoreRef(addBinding(B, R, BindingKey::Direct,
1362                              V).getRootWithoutRetain(), *this);
1363 }
1364 
1365 StoreRef RegionStoreManager::BindDecl(Store store, const VarRegion *VR,
1366                                       SVal InitVal) {
1367 
1368   QualType T = VR->getDecl()->getType();
1369 
1370   if (T->isArrayType())
1371     return BindArray(store, VR, InitVal);
1372   if (T->isStructureOrClassType())
1373     return BindStruct(store, VR, InitVal);
1374 
1375   return Bind(store, svalBuilder.makeLoc(VR), InitVal);
1376 }
1377 
1378 // FIXME: this method should be merged into Bind().
1379 StoreRef RegionStoreManager::BindCompoundLiteral(Store store,
1380                                                  const CompoundLiteralExpr *CL,
1381                                                  const LocationContext *LC,
1382                                                  SVal V) {
1383   return Bind(store, loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CL, LC)),
1384               V);
1385 }
1386 
1387 StoreRef RegionStoreManager::setImplicitDefaultValue(Store store,
1388                                                      const MemRegion *R,
1389                                                      QualType T) {
1390   RegionBindings B = GetRegionBindings(store);
1391   SVal V;
1392 
1393   if (Loc::isLocType(T))
1394     V = svalBuilder.makeNull();
1395   else if (T->isIntegerType())
1396     V = svalBuilder.makeZeroVal(T);
1397   else if (T->isStructureOrClassType() || T->isArrayType()) {
1398     // Set the default value to a zero constant when it is a structure
1399     // or array.  The type doesn't really matter.
1400     V = svalBuilder.makeZeroVal(Ctx.IntTy);
1401   }
1402   else {
1403     // We can't represent values of this type, but we still need to set a value
1404     // to record that the region has been initialized.
1405     // If this assertion ever fires, a new case should be added above -- we
1406     // should know how to default-initialize any value we can symbolicate.
1407     assert(!SymbolManager::canSymbolicate(T) && "This type is representable");
1408     V = UnknownVal();
1409   }
1410 
1411   return StoreRef(addBinding(B, R, BindingKey::Default,
1412                              V).getRootWithoutRetain(), *this);
1413 }
1414 
1415 StoreRef RegionStoreManager::BindArray(Store store, const TypedValueRegion* R,
1416                                        SVal Init) {
1417 
1418   const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType()));
1419   QualType ElementTy = AT->getElementType();
1420   Optional<uint64_t> Size;
1421 
1422   if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT))
1423     Size = CAT->getSize().getZExtValue();
1424 
1425   // Check if the init expr is a string literal.
1426   if (loc::MemRegionVal *MRV = dyn_cast<loc::MemRegionVal>(&Init)) {
1427     const StringRegion *S = cast<StringRegion>(MRV->getRegion());
1428 
1429     // Treat the string as a lazy compound value.
1430     nonloc::LazyCompoundVal LCV =
1431       cast<nonloc::LazyCompoundVal>(svalBuilder.
1432                                 makeLazyCompoundVal(StoreRef(store, *this), S));
1433     return CopyLazyBindings(LCV, store, R);
1434   }
1435 
1436   // Handle lazy compound values.
1437   if (nonloc::LazyCompoundVal *LCV = dyn_cast<nonloc::LazyCompoundVal>(&Init))
1438     return CopyLazyBindings(*LCV, store, R);
1439 
1440   // Remaining case: explicit compound values.
1441 
1442   if (Init.isUnknown())
1443     return setImplicitDefaultValue(store, R, ElementTy);
1444 
1445   nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(Init);
1446   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
1447   uint64_t i = 0;
1448 
1449   StoreRef newStore(store, *this);
1450   for (; Size.hasValue() ? i < Size.getValue() : true ; ++i, ++VI) {
1451     // The init list might be shorter than the array length.
1452     if (VI == VE)
1453       break;
1454 
1455     const NonLoc &Idx = svalBuilder.makeArrayIndex(i);
1456     const ElementRegion *ER = MRMgr.getElementRegion(ElementTy, Idx, R, Ctx);
1457 
1458     if (ElementTy->isStructureOrClassType())
1459       newStore = BindStruct(newStore.getStore(), ER, *VI);
1460     else if (ElementTy->isArrayType())
1461       newStore = BindArray(newStore.getStore(), ER, *VI);
1462     else
1463       newStore = Bind(newStore.getStore(), svalBuilder.makeLoc(ER), *VI);
1464   }
1465 
1466   // If the init list is shorter than the array length, set the
1467   // array default value.
1468   if (Size.hasValue() && i < Size.getValue())
1469     newStore = setImplicitDefaultValue(newStore.getStore(), R, ElementTy);
1470 
1471   return newStore;
1472 }
1473 
1474 StoreRef RegionStoreManager::BindStruct(Store store, const TypedValueRegion* R,
1475                                         SVal V) {
1476 
1477   if (!Features.supportsFields())
1478     return StoreRef(store, *this);
1479 
1480   QualType T = R->getValueType();
1481   assert(T->isStructureOrClassType());
1482 
1483   const RecordType* RT = T->getAs<RecordType>();
1484   RecordDecl *RD = RT->getDecl();
1485 
1486   if (!RD->isCompleteDefinition())
1487     return StoreRef(store, *this);
1488 
1489   // Handle lazy compound values.
1490   if (const nonloc::LazyCompoundVal *LCV=dyn_cast<nonloc::LazyCompoundVal>(&V))
1491     return CopyLazyBindings(*LCV, store, R);
1492 
1493   // We may get non-CompoundVal accidentally due to imprecise cast logic or
1494   // that we are binding symbolic struct value. Kill the field values, and if
1495   // the value is symbolic go and bind it as a "default" binding.
1496   if (V.isUnknown() || !isa<nonloc::CompoundVal>(V)) {
1497     SVal SV = isa<nonloc::SymbolVal>(V) ? V : UnknownVal();
1498     return KillStruct(store, R, SV);
1499   }
1500 
1501   nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(V);
1502   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
1503 
1504   RecordDecl::field_iterator FI, FE;
1505   StoreRef newStore(store, *this);
1506 
1507   for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; ++FI) {
1508 
1509     if (VI == VE)
1510       break;
1511 
1512     // Skip any unnamed bitfields to stay in sync with the initializers.
1513     if ((*FI)->isUnnamedBitfield())
1514       continue;
1515 
1516     QualType FTy = (*FI)->getType();
1517     const FieldRegion* FR = MRMgr.getFieldRegion(*FI, R);
1518 
1519     if (FTy->isArrayType())
1520       newStore = BindArray(newStore.getStore(), FR, *VI);
1521     else if (FTy->isStructureOrClassType())
1522       newStore = BindStruct(newStore.getStore(), FR, *VI);
1523     else
1524       newStore = Bind(newStore.getStore(), svalBuilder.makeLoc(FR), *VI);
1525     ++VI;
1526   }
1527 
1528   // There may be fewer values in the initialize list than the fields of struct.
1529   if (FI != FE) {
1530     RegionBindings B = GetRegionBindings(newStore.getStore());
1531     B = addBinding(B, R, BindingKey::Default, svalBuilder.makeIntVal(0, false));
1532     newStore = StoreRef(B.getRootWithoutRetain(), *this);
1533   }
1534 
1535   return newStore;
1536 }
1537 
1538 StoreRef RegionStoreManager::KillStruct(Store store, const TypedRegion* R,
1539                                      SVal DefaultVal) {
1540   BindingKey key = BindingKey::Make(R, BindingKey::Default);
1541 
1542   // The BindingKey may be "invalid" if we cannot handle the region binding
1543   // explicitly.  One example is something like array[index], where index
1544   // is a symbolic value.  In such cases, we want to invalidate the entire
1545   // array, as the index assignment could have been to any element.  In
1546   // the case of nested symbolic indices, we need to march up the region
1547   // hierarchy untile we reach a region whose binding we can reason about.
1548   const SubRegion *subReg = R;
1549 
1550   while (!key.isValid()) {
1551     if (const SubRegion *tmp = dyn_cast<SubRegion>(subReg->getSuperRegion())) {
1552       subReg = tmp;
1553       key = BindingKey::Make(tmp, BindingKey::Default);
1554     }
1555     else
1556       break;
1557   }
1558 
1559   // Remove the old bindings, using 'subReg' as the root of all regions
1560   // we will invalidate.
1561   RegionBindings B = GetRegionBindings(store);
1562   llvm::OwningPtr<RegionStoreSubRegionMap>
1563     SubRegions(getRegionStoreSubRegionMap(store));
1564   RemoveSubRegionBindings(B, subReg, *SubRegions);
1565 
1566   // Set the default value of the struct region to "unknown".
1567   if (!key.isValid())
1568     return StoreRef(B.getRootWithoutRetain(), *this);
1569 
1570   return StoreRef(addBinding(B, key, DefaultVal).getRootWithoutRetain(), *this);
1571 }
1572 
1573 StoreRef RegionStoreManager::CopyLazyBindings(nonloc::LazyCompoundVal V,
1574                                               Store store,
1575                                               const TypedRegion *R) {
1576 
1577   // Nuke the old bindings stemming from R.
1578   RegionBindings B = GetRegionBindings(store);
1579 
1580   llvm::OwningPtr<RegionStoreSubRegionMap>
1581     SubRegions(getRegionStoreSubRegionMap(store));
1582 
1583   // B and DVM are updated after the call to RemoveSubRegionBindings.
1584   RemoveSubRegionBindings(B, R, *SubRegions.get());
1585 
1586   // Now copy the bindings.  This amounts to just binding 'V' to 'R'.  This
1587   // results in a zero-copy algorithm.
1588   return StoreRef(addBinding(B, R, BindingKey::Default,
1589                              V).getRootWithoutRetain(), *this);
1590 }
1591 
1592 //===----------------------------------------------------------------------===//
1593 // "Raw" retrievals and bindings.
1594 //===----------------------------------------------------------------------===//
1595 
1596 
1597 RegionBindings RegionStoreManager::addBinding(RegionBindings B, BindingKey K,
1598                                               SVal V) {
1599   if (!K.isValid())
1600     return B;
1601   return RBFactory.add(B, K, V);
1602 }
1603 
1604 RegionBindings RegionStoreManager::addBinding(RegionBindings B,
1605                                               const MemRegion *R,
1606                                               BindingKey::Kind k, SVal V) {
1607   return addBinding(B, BindingKey::Make(R, k), V);
1608 }
1609 
1610 const SVal *RegionStoreManager::lookup(RegionBindings B, BindingKey K) {
1611   if (!K.isValid())
1612     return NULL;
1613   return B.lookup(K);
1614 }
1615 
1616 const SVal *RegionStoreManager::lookup(RegionBindings B,
1617                                        const MemRegion *R,
1618                                        BindingKey::Kind k) {
1619   return lookup(B, BindingKey::Make(R, k));
1620 }
1621 
1622 RegionBindings RegionStoreManager::removeBinding(RegionBindings B,
1623                                                  BindingKey K) {
1624   if (!K.isValid())
1625     return B;
1626   return RBFactory.remove(B, K);
1627 }
1628 
1629 RegionBindings RegionStoreManager::removeBinding(RegionBindings B,
1630                                                  const MemRegion *R,
1631                                                 BindingKey::Kind k){
1632   return removeBinding(B, BindingKey::Make(R, k));
1633 }
1634 
1635 //===----------------------------------------------------------------------===//
1636 // State pruning.
1637 //===----------------------------------------------------------------------===//
1638 
1639 namespace {
1640 class removeDeadBindingsWorker :
1641   public ClusterAnalysis<removeDeadBindingsWorker> {
1642   SmallVector<const SymbolicRegion*, 12> Postponed;
1643   SymbolReaper &SymReaper;
1644   const StackFrameContext *CurrentLCtx;
1645 
1646 public:
1647   removeDeadBindingsWorker(RegionStoreManager &rm, ProgramStateManager &stateMgr,
1648                            RegionBindings b, SymbolReaper &symReaper,
1649                            const StackFrameContext *LCtx)
1650     : ClusterAnalysis<removeDeadBindingsWorker>(rm, stateMgr, b,
1651                                                 /* includeGlobals = */ false),
1652       SymReaper(symReaper), CurrentLCtx(LCtx) {}
1653 
1654   // Called by ClusterAnalysis.
1655   void VisitAddedToCluster(const MemRegion *baseR, RegionCluster &C);
1656   void VisitCluster(const MemRegion *baseR, BindingKey *I, BindingKey *E);
1657 
1658   void VisitBindingKey(BindingKey K);
1659   bool UpdatePostponed();
1660   void VisitBinding(SVal V);
1661 };
1662 }
1663 
1664 void removeDeadBindingsWorker::VisitAddedToCluster(const MemRegion *baseR,
1665                                                    RegionCluster &C) {
1666 
1667   if (const VarRegion *VR = dyn_cast<VarRegion>(baseR)) {
1668     if (SymReaper.isLive(VR))
1669       AddToWorkList(baseR, C);
1670 
1671     return;
1672   }
1673 
1674   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) {
1675     if (SymReaper.isLive(SR->getSymbol()))
1676       AddToWorkList(SR, C);
1677     else
1678       Postponed.push_back(SR);
1679 
1680     return;
1681   }
1682 
1683   if (isa<NonStaticGlobalSpaceRegion>(baseR)) {
1684     AddToWorkList(baseR, C);
1685     return;
1686   }
1687 
1688   // CXXThisRegion in the current or parent location context is live.
1689   if (const CXXThisRegion *TR = dyn_cast<CXXThisRegion>(baseR)) {
1690     const StackArgumentsSpaceRegion *StackReg =
1691       cast<StackArgumentsSpaceRegion>(TR->getSuperRegion());
1692     const StackFrameContext *RegCtx = StackReg->getStackFrame();
1693     if (RegCtx == CurrentLCtx || RegCtx->isParentOf(CurrentLCtx))
1694       AddToWorkList(TR, C);
1695   }
1696 }
1697 
1698 void removeDeadBindingsWorker::VisitCluster(const MemRegion *baseR,
1699                                             BindingKey *I, BindingKey *E) {
1700   for ( ; I != E; ++I)
1701     VisitBindingKey(*I);
1702 }
1703 
1704 void removeDeadBindingsWorker::VisitBinding(SVal V) {
1705   // Is it a LazyCompoundVal?  All referenced regions are live as well.
1706   if (const nonloc::LazyCompoundVal *LCS =
1707       dyn_cast<nonloc::LazyCompoundVal>(&V)) {
1708 
1709     const MemRegion *LazyR = LCS->getRegion();
1710     RegionBindings B = RegionStoreManager::GetRegionBindings(LCS->getStore());
1711     for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){
1712       const SubRegion *baseR = dyn_cast<SubRegion>(RI.getKey().getRegion());
1713       if (baseR && baseR->isSubRegionOf(LazyR))
1714         VisitBinding(RI.getData());
1715     }
1716     return;
1717   }
1718 
1719   // If V is a region, then add it to the worklist.
1720   if (const MemRegion *R = V.getAsRegion())
1721     AddToWorkList(R);
1722 
1723   // Update the set of live symbols.
1724   for (SymExpr::symbol_iterator SI = V.symbol_begin(), SE = V.symbol_end();
1725        SI!=SE; ++SI)
1726     SymReaper.markLive(*SI);
1727 }
1728 
1729 void removeDeadBindingsWorker::VisitBindingKey(BindingKey K) {
1730   const MemRegion *R = K.getRegion();
1731 
1732   // Mark this region "live" by adding it to the worklist.  This will cause
1733   // use to visit all regions in the cluster (if we haven't visited them
1734   // already).
1735   if (AddToWorkList(R)) {
1736     // Mark the symbol for any live SymbolicRegion as "live".  This means we
1737     // should continue to track that symbol.
1738     if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(R))
1739       SymReaper.markLive(SymR->getSymbol());
1740 
1741     // For BlockDataRegions, enqueue the VarRegions for variables marked
1742     // with __block (passed-by-reference).
1743     // via BlockDeclRefExprs.
1744     if (const BlockDataRegion *BD = dyn_cast<BlockDataRegion>(R)) {
1745       for (BlockDataRegion::referenced_vars_iterator
1746            RI = BD->referenced_vars_begin(), RE = BD->referenced_vars_end();
1747            RI != RE; ++RI) {
1748         if ((*RI)->getDecl()->getAttr<BlocksAttr>())
1749           AddToWorkList(*RI);
1750       }
1751 
1752       // No possible data bindings on a BlockDataRegion.
1753       return;
1754     }
1755   }
1756 
1757   // Visit the data binding for K.
1758   if (const SVal *V = RM.lookup(B, K))
1759     VisitBinding(*V);
1760 }
1761 
1762 bool removeDeadBindingsWorker::UpdatePostponed() {
1763   // See if any postponed SymbolicRegions are actually live now, after
1764   // having done a scan.
1765   bool changed = false;
1766 
1767   for (SmallVectorImpl<const SymbolicRegion*>::iterator
1768         I = Postponed.begin(), E = Postponed.end() ; I != E ; ++I) {
1769     if (const SymbolicRegion *SR = cast_or_null<SymbolicRegion>(*I)) {
1770       if (SymReaper.isLive(SR->getSymbol())) {
1771         changed |= AddToWorkList(SR);
1772         *I = NULL;
1773       }
1774     }
1775   }
1776 
1777   return changed;
1778 }
1779 
1780 StoreRef RegionStoreManager::removeDeadBindings(Store store,
1781                                                 const StackFrameContext *LCtx,
1782                                                 SymbolReaper& SymReaper) {
1783   RegionBindings B = GetRegionBindings(store);
1784   removeDeadBindingsWorker W(*this, StateMgr, B, SymReaper, LCtx);
1785   W.GenerateClusters();
1786 
1787   // Enqueue the region roots onto the worklist.
1788   for (SymbolReaper::region_iterator I = SymReaper.region_begin(),
1789        E = SymReaper.region_end(); I != E; ++I) {
1790     W.AddToWorkList(*I);
1791   }
1792 
1793   do W.RunWorkList(); while (W.UpdatePostponed());
1794 
1795   // We have now scanned the store, marking reachable regions and symbols
1796   // as live.  We now remove all the regions that are dead from the store
1797   // as well as update DSymbols with the set symbols that are now dead.
1798   for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1799     const BindingKey &K = I.getKey();
1800 
1801     // If the cluster has been visited, we know the region has been marked.
1802     if (W.isVisited(K.getRegion()))
1803       continue;
1804 
1805     // Remove the dead entry.
1806     B = removeBinding(B, K);
1807 
1808     // Mark all non-live symbols that this binding references as dead.
1809     if (const SymbolicRegion* SymR = dyn_cast<SymbolicRegion>(K.getRegion()))
1810       SymReaper.maybeDead(SymR->getSymbol());
1811 
1812     SVal X = I.getData();
1813     SymExpr::symbol_iterator SI = X.symbol_begin(), SE = X.symbol_end();
1814     for (; SI != SE; ++SI)
1815       SymReaper.maybeDead(*SI);
1816   }
1817 
1818   return StoreRef(B.getRootWithoutRetain(), *this);
1819 }
1820 
1821 
1822 StoreRef RegionStoreManager::enterStackFrame(const ProgramState *state,
1823                                              const StackFrameContext *frame) {
1824   FunctionDecl const *FD = cast<FunctionDecl>(frame->getDecl());
1825   FunctionDecl::param_const_iterator PI = FD->param_begin(),
1826                                      PE = FD->param_end();
1827   StoreRef store = StoreRef(state->getStore(), *this);
1828 
1829   if (CallExpr const *CE = dyn_cast<CallExpr>(frame->getCallSite())) {
1830     CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end();
1831 
1832     // Copy the arg expression value to the arg variables.  We check that
1833     // PI != PE because the actual number of arguments may be different than
1834     // the function declaration.
1835     for (; AI != AE && PI != PE; ++AI, ++PI) {
1836       SVal ArgVal = state->getSVal(*AI);
1837       store = Bind(store.getStore(),
1838                    svalBuilder.makeLoc(MRMgr.getVarRegion(*PI, frame)), ArgVal);
1839     }
1840   } else if (const CXXConstructExpr *CE =
1841                dyn_cast<CXXConstructExpr>(frame->getCallSite())) {
1842     CXXConstructExpr::const_arg_iterator AI = CE->arg_begin(),
1843       AE = CE->arg_end();
1844 
1845     // Copy the arg expression value to the arg variables.
1846     for (; AI != AE; ++AI, ++PI) {
1847       SVal ArgVal = state->getSVal(*AI);
1848       store = Bind(store.getStore(),
1849                    svalBuilder.makeLoc(MRMgr.getVarRegion(*PI,frame)), ArgVal);
1850     }
1851   } else
1852     assert(isa<CXXDestructorDecl>(frame->getDecl()));
1853 
1854   return store;
1855 }
1856 
1857 //===----------------------------------------------------------------------===//
1858 // Utility methods.
1859 //===----------------------------------------------------------------------===//
1860 
1861 void RegionStoreManager::print(Store store, raw_ostream &OS,
1862                                const char* nl, const char *sep) {
1863   RegionBindings B = GetRegionBindings(store);
1864   OS << "Store (direct and default bindings):" << nl;
1865 
1866   for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
1867     OS << ' ' << I.getKey() << " : " << I.getData() << nl;
1868 }
1869