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