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/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/Analysis/Analyses/LiveVariables.h"
20 #include "clang/Analysis/AnalysisContext.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
28 #include "llvm/ADT/ImmutableList.h"
29 #include "llvm/ADT/ImmutableMap.h"
30 #include "llvm/ADT/Optional.h"
31 #include "llvm/Support/raw_ostream.h"
32 
33 using namespace clang;
34 using namespace ento;
35 
36 //===----------------------------------------------------------------------===//
37 // Representation of binding keys.
38 //===----------------------------------------------------------------------===//
39 
40 namespace {
41 class BindingKey {
42 public:
43   enum Kind { Default = 0x0, Direct = 0x1 };
44 private:
45   enum { Symbolic = 0x2 };
46 
47   llvm::PointerIntPair<const MemRegion *, 2> P;
48   uint64_t Data;
49 
50   /// Create a key for a binding to region \p r, which has a symbolic offset
51   /// from region \p Base.
52   explicit BindingKey(const SubRegion *r, const SubRegion *Base, Kind k)
53     : P(r, k | Symbolic), Data(reinterpret_cast<uintptr_t>(Base)) {
54     assert(r && Base && "Must have known regions.");
55     assert(getConcreteOffsetRegion() == Base && "Failed to store base region");
56   }
57 
58   /// Create a key for a binding at \p offset from base region \p r.
59   explicit BindingKey(const MemRegion *r, uint64_t offset, Kind k)
60     : P(r, k), Data(offset) {
61     assert(r && "Must have known regions.");
62     assert(getOffset() == offset && "Failed to store offset");
63     assert((r == r->getBaseRegion() || isa<ObjCIvarRegion>(r)) && "Not a base");
64   }
65 public:
66 
67   bool isDirect() const { return P.getInt() & Direct; }
68   bool hasSymbolicOffset() const { return P.getInt() & Symbolic; }
69 
70   const MemRegion *getRegion() const { return P.getPointer(); }
71   uint64_t getOffset() const {
72     assert(!hasSymbolicOffset());
73     return Data;
74   }
75 
76   const SubRegion *getConcreteOffsetRegion() const {
77     assert(hasSymbolicOffset());
78     return reinterpret_cast<const SubRegion *>(static_cast<uintptr_t>(Data));
79   }
80 
81   const MemRegion *getBaseRegion() const {
82     if (hasSymbolicOffset())
83       return getConcreteOffsetRegion()->getBaseRegion();
84     return getRegion()->getBaseRegion();
85   }
86 
87   void Profile(llvm::FoldingSetNodeID& ID) const {
88     ID.AddPointer(P.getOpaqueValue());
89     ID.AddInteger(Data);
90   }
91 
92   static BindingKey Make(const MemRegion *R, Kind k);
93 
94   bool operator<(const BindingKey &X) const {
95     if (P.getOpaqueValue() < X.P.getOpaqueValue())
96       return true;
97     if (P.getOpaqueValue() > X.P.getOpaqueValue())
98       return false;
99     return Data < X.Data;
100   }
101 
102   bool operator==(const BindingKey &X) const {
103     return P.getOpaqueValue() == X.P.getOpaqueValue() &&
104            Data == X.Data;
105   }
106 
107   LLVM_ATTRIBUTE_USED void dump() const;
108 };
109 } // end anonymous namespace
110 
111 BindingKey BindingKey::Make(const MemRegion *R, Kind k) {
112   const RegionOffset &RO = R->getAsOffset();
113   if (RO.hasSymbolicOffset())
114     return BindingKey(cast<SubRegion>(R), cast<SubRegion>(RO.getRegion()), k);
115 
116   return BindingKey(RO.getRegion(), RO.getOffset(), k);
117 }
118 
119 namespace llvm {
120   static inline
121   raw_ostream &operator<<(raw_ostream &os, BindingKey K) {
122     os << '(' << K.getRegion();
123     if (!K.hasSymbolicOffset())
124       os << ',' << K.getOffset();
125     os << ',' << (K.isDirect() ? "direct" : "default")
126        << ')';
127     return os;
128   }
129 
130   template <typename T> struct isPodLike;
131   template <> struct isPodLike<BindingKey> {
132     static const bool value = true;
133   };
134 } // end llvm namespace
135 
136 void BindingKey::dump() const {
137   llvm::errs() << *this;
138 }
139 
140 //===----------------------------------------------------------------------===//
141 // Actual Store type.
142 //===----------------------------------------------------------------------===//
143 
144 typedef llvm::ImmutableMap<BindingKey, SVal>    ClusterBindings;
145 typedef llvm::ImmutableMapRef<BindingKey, SVal> ClusterBindingsRef;
146 typedef std::pair<BindingKey, SVal> BindingPair;
147 
148 typedef llvm::ImmutableMap<const MemRegion *, ClusterBindings>
149         RegionBindings;
150 
151 namespace {
152 class RegionBindingsRef : public llvm::ImmutableMapRef<const MemRegion *,
153                                  ClusterBindings> {
154  ClusterBindings::Factory &CBFactory;
155 public:
156   typedef llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>
157           ParentTy;
158 
159   RegionBindingsRef(ClusterBindings::Factory &CBFactory,
160                     const RegionBindings::TreeTy *T,
161                     RegionBindings::TreeTy::Factory *F)
162     : llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>(T, F),
163       CBFactory(CBFactory) {}
164 
165   RegionBindingsRef(const ParentTy &P, ClusterBindings::Factory &CBFactory)
166     : llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>(P),
167       CBFactory(CBFactory) {}
168 
169   RegionBindingsRef add(key_type_ref K, data_type_ref D) const {
170     return RegionBindingsRef(static_cast<const ParentTy*>(this)->add(K, D),
171                              CBFactory);
172   }
173 
174   RegionBindingsRef remove(key_type_ref K) const {
175     return RegionBindingsRef(static_cast<const ParentTy*>(this)->remove(K),
176                              CBFactory);
177   }
178 
179   RegionBindingsRef addBinding(BindingKey K, SVal V) const;
180 
181   RegionBindingsRef addBinding(const MemRegion *R,
182                                BindingKey::Kind k, SVal V) const;
183 
184   RegionBindingsRef &operator=(const RegionBindingsRef &X) {
185     *static_cast<ParentTy*>(this) = X;
186     return *this;
187   }
188 
189   const SVal *lookup(BindingKey K) const;
190   const SVal *lookup(const MemRegion *R, BindingKey::Kind k) const;
191   const ClusterBindings *lookup(const MemRegion *R) const {
192     return static_cast<const ParentTy*>(this)->lookup(R);
193   }
194 
195   RegionBindingsRef removeBinding(BindingKey K);
196 
197   RegionBindingsRef removeBinding(const MemRegion *R,
198                                   BindingKey::Kind k);
199 
200   RegionBindingsRef removeBinding(const MemRegion *R) {
201     return removeBinding(R, BindingKey::Direct).
202            removeBinding(R, BindingKey::Default);
203   }
204 
205   Optional<SVal> getDirectBinding(const MemRegion *R) const;
206 
207   /// getDefaultBinding - Returns an SVal* representing an optional default
208   ///  binding associated with a region and its subregions.
209   Optional<SVal> getDefaultBinding(const MemRegion *R) const;
210 
211   /// Return the internal tree as a Store.
212   Store asStore() const {
213     return asImmutableMap().getRootWithoutRetain();
214   }
215 
216   void dump(raw_ostream &OS, const char *nl) const {
217    for (iterator I = begin(), E = end(); I != E; ++I) {
218      const ClusterBindings &Cluster = I.getData();
219      for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
220           CI != CE; ++CI) {
221        OS << ' ' << CI.getKey() << " : " << CI.getData() << nl;
222      }
223      OS << nl;
224    }
225   }
226 
227   LLVM_ATTRIBUTE_USED void dump() const {
228     dump(llvm::errs(), "\n");
229   }
230 };
231 } // end anonymous namespace
232 
233 typedef const RegionBindingsRef& RegionBindingsConstRef;
234 
235 Optional<SVal> RegionBindingsRef::getDirectBinding(const MemRegion *R) const {
236   return Optional<SVal>::create(lookup(R, BindingKey::Direct));
237 }
238 
239 Optional<SVal> RegionBindingsRef::getDefaultBinding(const MemRegion *R) const {
240   if (R->isBoundable())
241     if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R))
242       if (TR->getValueType()->isUnionType())
243         return UnknownVal();
244 
245   return Optional<SVal>::create(lookup(R, BindingKey::Default));
246 }
247 
248 RegionBindingsRef RegionBindingsRef::addBinding(BindingKey K, SVal V) const {
249   const MemRegion *Base = K.getBaseRegion();
250 
251   const ClusterBindings *ExistingCluster = lookup(Base);
252   ClusterBindings Cluster = (ExistingCluster ? *ExistingCluster
253                              : CBFactory.getEmptyMap());
254 
255   ClusterBindings NewCluster = CBFactory.add(Cluster, K, V);
256   return add(Base, NewCluster);
257 }
258 
259 
260 RegionBindingsRef RegionBindingsRef::addBinding(const MemRegion *R,
261                                                 BindingKey::Kind k,
262                                                 SVal V) const {
263   return addBinding(BindingKey::Make(R, k), V);
264 }
265 
266 const SVal *RegionBindingsRef::lookup(BindingKey K) const {
267   const ClusterBindings *Cluster = lookup(K.getBaseRegion());
268   if (!Cluster)
269     return 0;
270   return Cluster->lookup(K);
271 }
272 
273 const SVal *RegionBindingsRef::lookup(const MemRegion *R,
274                                       BindingKey::Kind k) const {
275   return lookup(BindingKey::Make(R, k));
276 }
277 
278 RegionBindingsRef RegionBindingsRef::removeBinding(BindingKey K) {
279   const MemRegion *Base = K.getBaseRegion();
280   const ClusterBindings *Cluster = lookup(Base);
281   if (!Cluster)
282     return *this;
283 
284   ClusterBindings NewCluster = CBFactory.remove(*Cluster, K);
285   if (NewCluster.isEmpty())
286     return remove(Base);
287   return add(Base, NewCluster);
288 }
289 
290 RegionBindingsRef RegionBindingsRef::removeBinding(const MemRegion *R,
291                                                 BindingKey::Kind k){
292   return removeBinding(BindingKey::Make(R, k));
293 }
294 
295 //===----------------------------------------------------------------------===//
296 // Fine-grained control of RegionStoreManager.
297 //===----------------------------------------------------------------------===//
298 
299 namespace {
300 struct minimal_features_tag {};
301 struct maximal_features_tag {};
302 
303 class RegionStoreFeatures {
304   bool SupportsFields;
305 public:
306   RegionStoreFeatures(minimal_features_tag) :
307     SupportsFields(false) {}
308 
309   RegionStoreFeatures(maximal_features_tag) :
310     SupportsFields(true) {}
311 
312   void enableFields(bool t) { SupportsFields = t; }
313 
314   bool supportsFields() const { return SupportsFields; }
315 };
316 }
317 
318 //===----------------------------------------------------------------------===//
319 // Main RegionStore logic.
320 //===----------------------------------------------------------------------===//
321 
322 namespace {
323 class invalidateRegionsWorker;
324 
325 class RegionStoreManager : public StoreManager {
326 public:
327   const RegionStoreFeatures Features;
328 
329   RegionBindings::Factory RBFactory;
330   mutable ClusterBindings::Factory CBFactory;
331 
332   typedef std::vector<SVal> SValListTy;
333 private:
334   typedef llvm::DenseMap<const LazyCompoundValData *,
335                          SValListTy> LazyBindingsMapTy;
336   LazyBindingsMapTy LazyBindingsMap;
337 
338   /// The largest number of fields a struct can have and still be
339   /// considered "small".
340   ///
341   /// This is currently used to decide whether or not it is worth "forcing" a
342   /// LazyCompoundVal on bind.
343   ///
344   /// This is controlled by 'region-store-small-struct-limit' option.
345   /// To disable all small-struct-dependent behavior, set the option to "0".
346   unsigned SmallStructLimit;
347 
348   /// \brief A helper used to populate the work list with the given set of
349   /// regions.
350   void populateWorkList(invalidateRegionsWorker &W,
351                         ArrayRef<SVal> Values,
352                         bool IsArrayOfConstRegions,
353                         InvalidatedRegions *TopLevelRegions);
354 
355 public:
356   RegionStoreManager(ProgramStateManager& mgr, const RegionStoreFeatures &f)
357     : StoreManager(mgr), Features(f),
358       RBFactory(mgr.getAllocator()), CBFactory(mgr.getAllocator()),
359       SmallStructLimit(0) {
360     if (SubEngine *Eng = StateMgr.getOwningEngine()) {
361       AnalyzerOptions &Options = Eng->getAnalysisManager().options;
362       SmallStructLimit =
363         Options.getOptionAsInteger("region-store-small-struct-limit", 2);
364     }
365   }
366 
367 
368   /// setImplicitDefaultValue - Set the default binding for the provided
369   ///  MemRegion to the value implicitly defined for compound literals when
370   ///  the value is not specified.
371   RegionBindingsRef setImplicitDefaultValue(RegionBindingsConstRef B,
372                                             const MemRegion *R, QualType T);
373 
374   /// ArrayToPointer - Emulates the "decay" of an array to a pointer
375   ///  type.  'Array' represents the lvalue of the array being decayed
376   ///  to a pointer, and the returned SVal represents the decayed
377   ///  version of that lvalue (i.e., a pointer to the first element of
378   ///  the array).  This is called by ExprEngine when evaluating
379   ///  casts from arrays to pointers.
380   SVal ArrayToPointer(Loc Array);
381 
382   StoreRef getInitialStore(const LocationContext *InitLoc) {
383     return StoreRef(RBFactory.getEmptyMap().getRootWithoutRetain(), *this);
384   }
385 
386   //===-------------------------------------------------------------------===//
387   // Binding values to regions.
388   //===-------------------------------------------------------------------===//
389   RegionBindingsRef invalidateGlobalRegion(MemRegion::Kind K,
390                                            const Expr *Ex,
391                                            unsigned Count,
392                                            const LocationContext *LCtx,
393                                            RegionBindingsRef B,
394                                            InvalidatedRegions *Invalidated);
395 
396   StoreRef invalidateRegions(Store store,
397                              ArrayRef<SVal> Values,
398                              ArrayRef<SVal> ConstValues,
399                              const Expr *E, unsigned Count,
400                              const LocationContext *LCtx,
401                              const CallEvent *Call,
402                              InvalidatedSymbols &IS,
403                              InvalidatedSymbols &ConstIS,
404                              InvalidatedRegions *Invalidated,
405                              InvalidatedRegions *InvalidatedTopLevel,
406                              InvalidatedRegions *InvalidatedTopLevelConst);
407 
408   bool scanReachableSymbols(Store S, const MemRegion *R,
409                             ScanReachableSymbols &Callbacks);
410 
411   RegionBindingsRef removeSubRegionBindings(RegionBindingsConstRef B,
412                                             const SubRegion *R);
413 
414 public: // Part of public interface to class.
415 
416   virtual StoreRef Bind(Store store, Loc LV, SVal V) {
417     return StoreRef(bind(getRegionBindings(store), LV, V).asStore(), *this);
418   }
419 
420   RegionBindingsRef bind(RegionBindingsConstRef B, Loc LV, SVal V);
421 
422   // BindDefault is only used to initialize a region with a default value.
423   StoreRef BindDefault(Store store, const MemRegion *R, SVal V) {
424     RegionBindingsRef B = getRegionBindings(store);
425     assert(!B.lookup(R, BindingKey::Default));
426     assert(!B.lookup(R, BindingKey::Direct));
427     return StoreRef(B.addBinding(R, BindingKey::Default, V)
428                      .asImmutableMap()
429                      .getRootWithoutRetain(), *this);
430   }
431 
432   /// \brief Create a new store that binds a value to a compound literal.
433   ///
434   /// \param ST The original store whose bindings are the basis for the new
435   ///        store.
436   ///
437   /// \param CL The compound literal to bind (the binding key).
438   ///
439   /// \param LC The LocationContext for the binding.
440   ///
441   /// \param V The value to bind to the compound literal.
442   StoreRef bindCompoundLiteral(Store ST,
443                                const CompoundLiteralExpr *CL,
444                                const LocationContext *LC, SVal V);
445 
446   /// Attempt to extract the fields of \p LCV and bind them to the struct region
447   /// \p R.
448   ///
449   /// This path is used when it seems advantageous to "force" loading the values
450   /// within a LazyCompoundVal to bind memberwise to the struct region, rather
451   /// than using a Default binding at the base of the entire region. This is a
452   /// heuristic attempting to avoid building long chains of LazyCompoundVals.
453   ///
454   /// \returns The updated store bindings, or \c None if binding non-lazily
455   ///          would be too expensive.
456   Optional<RegionBindingsRef> tryBindSmallStruct(RegionBindingsConstRef B,
457                                                  const TypedValueRegion *R,
458                                                  const RecordDecl *RD,
459                                                  nonloc::LazyCompoundVal LCV);
460 
461   /// BindStruct - Bind a compound value to a structure.
462   RegionBindingsRef bindStruct(RegionBindingsConstRef B,
463                                const TypedValueRegion* R, SVal V);
464 
465   /// BindVector - Bind a compound value to a vector.
466   RegionBindingsRef bindVector(RegionBindingsConstRef B,
467                                const TypedValueRegion* R, SVal V);
468 
469   RegionBindingsRef bindArray(RegionBindingsConstRef B,
470                               const TypedValueRegion* R,
471                               SVal V);
472 
473   /// Clears out all bindings in the given region and assigns a new value
474   /// as a Default binding.
475   RegionBindingsRef bindAggregate(RegionBindingsConstRef B,
476                                   const TypedRegion *R,
477                                   SVal DefaultVal);
478 
479   /// \brief Create a new store with the specified binding removed.
480   /// \param ST the original store, that is the basis for the new store.
481   /// \param L the location whose binding should be removed.
482   virtual StoreRef killBinding(Store ST, Loc L);
483 
484   void incrementReferenceCount(Store store) {
485     getRegionBindings(store).manualRetain();
486   }
487 
488   /// If the StoreManager supports it, decrement the reference count of
489   /// the specified Store object.  If the reference count hits 0, the memory
490   /// associated with the object is recycled.
491   void decrementReferenceCount(Store store) {
492     getRegionBindings(store).manualRelease();
493   }
494 
495   bool includedInBindings(Store store, const MemRegion *region) const;
496 
497   /// \brief Return the value bound to specified location in a given state.
498   ///
499   /// The high level logic for this method is this:
500   /// getBinding (L)
501   ///   if L has binding
502   ///     return L's binding
503   ///   else if L is in killset
504   ///     return unknown
505   ///   else
506   ///     if L is on stack or heap
507   ///       return undefined
508   ///     else
509   ///       return symbolic
510   virtual SVal getBinding(Store S, Loc L, QualType T) {
511     return getBinding(getRegionBindings(S), L, T);
512   }
513 
514   SVal getBinding(RegionBindingsConstRef B, Loc L, QualType T = QualType());
515 
516   SVal getBindingForElement(RegionBindingsConstRef B, const ElementRegion *R);
517 
518   SVal getBindingForField(RegionBindingsConstRef B, const FieldRegion *R);
519 
520   SVal getBindingForObjCIvar(RegionBindingsConstRef B, const ObjCIvarRegion *R);
521 
522   SVal getBindingForVar(RegionBindingsConstRef B, const VarRegion *R);
523 
524   SVal getBindingForLazySymbol(const TypedValueRegion *R);
525 
526   SVal getBindingForFieldOrElementCommon(RegionBindingsConstRef B,
527                                          const TypedValueRegion *R,
528                                          QualType Ty);
529 
530   SVal getLazyBinding(const SubRegion *LazyBindingRegion,
531                       RegionBindingsRef LazyBinding);
532 
533   /// Get bindings for the values in a struct and return a CompoundVal, used
534   /// when doing struct copy:
535   /// struct s x, y;
536   /// x = y;
537   /// y's value is retrieved by this method.
538   SVal getBindingForStruct(RegionBindingsConstRef B, const TypedValueRegion *R);
539   SVal getBindingForArray(RegionBindingsConstRef B, const TypedValueRegion *R);
540   NonLoc createLazyBinding(RegionBindingsConstRef B, const TypedValueRegion *R);
541 
542   /// Used to lazily generate derived symbols for bindings that are defined
543   /// implicitly by default bindings in a super region.
544   ///
545   /// Note that callers may need to specially handle LazyCompoundVals, which
546   /// are returned as is in case the caller needs to treat them differently.
547   Optional<SVal> getBindingForDerivedDefaultValue(RegionBindingsConstRef B,
548                                                   const MemRegion *superR,
549                                                   const TypedValueRegion *R,
550                                                   QualType Ty);
551 
552   /// Get the state and region whose binding this region \p R corresponds to.
553   ///
554   /// If there is no lazy binding for \p R, the returned value will have a null
555   /// \c second. Note that a null pointer can represents a valid Store.
556   std::pair<Store, const SubRegion *>
557   findLazyBinding(RegionBindingsConstRef B, const SubRegion *R,
558                   const SubRegion *originalRegion);
559 
560   /// Returns the cached set of interesting SVals contained within a lazy
561   /// binding.
562   ///
563   /// The precise value of "interesting" is determined for the purposes of
564   /// RegionStore's internal analysis. It must always contain all regions and
565   /// symbols, but may omit constants and other kinds of SVal.
566   const SValListTy &getInterestingValues(nonloc::LazyCompoundVal LCV);
567 
568   //===------------------------------------------------------------------===//
569   // State pruning.
570   //===------------------------------------------------------------------===//
571 
572   /// removeDeadBindings - Scans the RegionStore of 'state' for dead values.
573   ///  It returns a new Store with these values removed.
574   StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx,
575                               SymbolReaper& SymReaper);
576 
577   //===------------------------------------------------------------------===//
578   // Region "extents".
579   //===------------------------------------------------------------------===//
580 
581   // FIXME: This method will soon be eliminated; see the note in Store.h.
582   DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state,
583                                          const MemRegion* R, QualType EleTy);
584 
585   //===------------------------------------------------------------------===//
586   // Utility methods.
587   //===------------------------------------------------------------------===//
588 
589   RegionBindingsRef getRegionBindings(Store store) const {
590     return RegionBindingsRef(CBFactory,
591                              static_cast<const RegionBindings::TreeTy*>(store),
592                              RBFactory.getTreeFactory());
593   }
594 
595   void print(Store store, raw_ostream &Out, const char* nl,
596              const char *sep);
597 
598   void iterBindings(Store store, BindingsHandler& f) {
599     RegionBindingsRef B = getRegionBindings(store);
600     for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; ++I) {
601       const ClusterBindings &Cluster = I.getData();
602       for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
603            CI != CE; ++CI) {
604         const BindingKey &K = CI.getKey();
605         if (!K.isDirect())
606           continue;
607         if (const SubRegion *R = dyn_cast<SubRegion>(K.getRegion())) {
608           // FIXME: Possibly incorporate the offset?
609           if (!f.HandleBinding(*this, store, R, CI.getData()))
610             return;
611         }
612       }
613     }
614   }
615 };
616 
617 } // end anonymous namespace
618 
619 //===----------------------------------------------------------------------===//
620 // RegionStore creation.
621 //===----------------------------------------------------------------------===//
622 
623 StoreManager *ento::CreateRegionStoreManager(ProgramStateManager& StMgr) {
624   RegionStoreFeatures F = maximal_features_tag();
625   return new RegionStoreManager(StMgr, F);
626 }
627 
628 StoreManager *
629 ento::CreateFieldsOnlyRegionStoreManager(ProgramStateManager &StMgr) {
630   RegionStoreFeatures F = minimal_features_tag();
631   F.enableFields(true);
632   return new RegionStoreManager(StMgr, F);
633 }
634 
635 
636 //===----------------------------------------------------------------------===//
637 // Region Cluster analysis.
638 //===----------------------------------------------------------------------===//
639 
640 namespace {
641 /// Used to determine which global regions are automatically included in the
642 /// initial worklist of a ClusterAnalysis.
643 enum GlobalsFilterKind {
644   /// Don't include any global regions.
645   GFK_None,
646   /// Only include system globals.
647   GFK_SystemOnly,
648   /// Include all global regions.
649   GFK_All
650 };
651 
652 template <typename DERIVED>
653 class ClusterAnalysis  {
654 protected:
655   typedef llvm::DenseMap<const MemRegion *, const ClusterBindings *> ClusterMap;
656   typedef llvm::PointerIntPair<const MemRegion *, 1, bool> WorkListElement;
657   typedef SmallVector<WorkListElement, 10> WorkList;
658 
659   llvm::SmallPtrSet<const ClusterBindings *, 16> Visited;
660 
661   WorkList WL;
662 
663   RegionStoreManager &RM;
664   ASTContext &Ctx;
665   SValBuilder &svalBuilder;
666 
667   RegionBindingsRef B;
668 
669 private:
670   GlobalsFilterKind GlobalsFilter;
671 
672 protected:
673   const ClusterBindings *getCluster(const MemRegion *R) {
674     return B.lookup(R);
675   }
676 
677   /// Returns true if the memory space of the given region is one of the global
678   /// regions specially included at the start of analysis.
679   bool isInitiallyIncludedGlobalRegion(const MemRegion *R) {
680     switch (GlobalsFilter) {
681     case GFK_None:
682       return false;
683     case GFK_SystemOnly:
684       return isa<GlobalSystemSpaceRegion>(R->getMemorySpace());
685     case GFK_All:
686       return isa<NonStaticGlobalSpaceRegion>(R->getMemorySpace());
687     }
688 
689     llvm_unreachable("unknown globals filter");
690   }
691 
692 public:
693   ClusterAnalysis(RegionStoreManager &rm, ProgramStateManager &StateMgr,
694                   RegionBindingsRef b, GlobalsFilterKind GFK)
695     : RM(rm), Ctx(StateMgr.getContext()),
696       svalBuilder(StateMgr.getSValBuilder()),
697       B(b), GlobalsFilter(GFK) {}
698 
699   RegionBindingsRef getRegionBindings() const { return B; }
700 
701   bool isVisited(const MemRegion *R) {
702     return Visited.count(getCluster(R));
703   }
704 
705   void GenerateClusters() {
706     // Scan the entire set of bindings and record the region clusters.
707     for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end();
708          RI != RE; ++RI){
709       const MemRegion *Base = RI.getKey();
710 
711       const ClusterBindings &Cluster = RI.getData();
712       assert(!Cluster.isEmpty() && "Empty clusters should be removed");
713       static_cast<DERIVED*>(this)->VisitAddedToCluster(Base, Cluster);
714 
715       // If this is an interesting global region, add it the work list up front.
716       if (isInitiallyIncludedGlobalRegion(Base))
717         AddToWorkList(WorkListElement(Base), &Cluster);
718     }
719   }
720 
721   bool AddToWorkList(WorkListElement E, const ClusterBindings *C) {
722     if (C && !Visited.insert(C))
723       return false;
724     WL.push_back(E);
725     return true;
726   }
727 
728   bool AddToWorkList(const MemRegion *R, bool Flag = false) {
729     const MemRegion *BaseR = R->getBaseRegion();
730     return AddToWorkList(WorkListElement(BaseR, Flag), getCluster(BaseR));
731   }
732 
733   void RunWorkList() {
734     while (!WL.empty()) {
735       WorkListElement E = WL.pop_back_val();
736       const MemRegion *BaseR = E.getPointer();
737 
738       static_cast<DERIVED*>(this)->VisitCluster(BaseR, getCluster(BaseR),
739                                                 E.getInt());
740     }
741   }
742 
743   void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C) {}
744   void VisitCluster(const MemRegion *baseR, const ClusterBindings *C) {}
745 
746   void VisitCluster(const MemRegion *BaseR, const ClusterBindings *C,
747                     bool Flag) {
748     static_cast<DERIVED*>(this)->VisitCluster(BaseR, C);
749   }
750 };
751 }
752 
753 //===----------------------------------------------------------------------===//
754 // Binding invalidation.
755 //===----------------------------------------------------------------------===//
756 
757 bool RegionStoreManager::scanReachableSymbols(Store S, const MemRegion *R,
758                                               ScanReachableSymbols &Callbacks) {
759   assert(R == R->getBaseRegion() && "Should only be called for base regions");
760   RegionBindingsRef B = getRegionBindings(S);
761   const ClusterBindings *Cluster = B.lookup(R);
762 
763   if (!Cluster)
764     return true;
765 
766   for (ClusterBindings::iterator RI = Cluster->begin(), RE = Cluster->end();
767        RI != RE; ++RI) {
768     if (!Callbacks.scan(RI.getData()))
769       return false;
770   }
771 
772   return true;
773 }
774 
775 static inline bool isUnionField(const FieldRegion *FR) {
776   return FR->getDecl()->getParent()->isUnion();
777 }
778 
779 typedef SmallVector<const FieldDecl *, 8> FieldVector;
780 
781 void getSymbolicOffsetFields(BindingKey K, FieldVector &Fields) {
782   assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys");
783 
784   const MemRegion *Base = K.getConcreteOffsetRegion();
785   const MemRegion *R = K.getRegion();
786 
787   while (R != Base) {
788     if (const FieldRegion *FR = dyn_cast<FieldRegion>(R))
789       if (!isUnionField(FR))
790         Fields.push_back(FR->getDecl());
791 
792     R = cast<SubRegion>(R)->getSuperRegion();
793   }
794 }
795 
796 static bool isCompatibleWithFields(BindingKey K, const FieldVector &Fields) {
797   assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys");
798 
799   if (Fields.empty())
800     return true;
801 
802   FieldVector FieldsInBindingKey;
803   getSymbolicOffsetFields(K, FieldsInBindingKey);
804 
805   ptrdiff_t Delta = FieldsInBindingKey.size() - Fields.size();
806   if (Delta >= 0)
807     return std::equal(FieldsInBindingKey.begin() + Delta,
808                       FieldsInBindingKey.end(),
809                       Fields.begin());
810   else
811     return std::equal(FieldsInBindingKey.begin(), FieldsInBindingKey.end(),
812                       Fields.begin() - Delta);
813 }
814 
815 /// Collects all bindings in \p Cluster that may refer to bindings within
816 /// \p Top.
817 ///
818 /// Each binding is a pair whose \c first is the key (a BindingKey) and whose
819 /// \c second is the value (an SVal).
820 ///
821 /// The \p IncludeAllDefaultBindings parameter specifies whether to include
822 /// default bindings that may extend beyond \p Top itself, e.g. if \p Top is
823 /// an aggregate within a larger aggregate with a default binding.
824 static void
825 collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings,
826                          SValBuilder &SVB, const ClusterBindings &Cluster,
827                          const SubRegion *Top, BindingKey TopKey,
828                          bool IncludeAllDefaultBindings) {
829   FieldVector FieldsInSymbolicSubregions;
830   if (TopKey.hasSymbolicOffset()) {
831     getSymbolicOffsetFields(TopKey, FieldsInSymbolicSubregions);
832     Top = cast<SubRegion>(TopKey.getConcreteOffsetRegion());
833     TopKey = BindingKey::Make(Top, BindingKey::Default);
834   }
835 
836   // Find the length (in bits) of the region being invalidated.
837   uint64_t Length = UINT64_MAX;
838   SVal Extent = Top->getExtent(SVB);
839   if (Optional<nonloc::ConcreteInt> ExtentCI =
840           Extent.getAs<nonloc::ConcreteInt>()) {
841     const llvm::APSInt &ExtentInt = ExtentCI->getValue();
842     assert(ExtentInt.isNonNegative() || ExtentInt.isUnsigned());
843     // Extents are in bytes but region offsets are in bits. Be careful!
844     Length = ExtentInt.getLimitedValue() * SVB.getContext().getCharWidth();
845   } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(Top)) {
846     if (FR->getDecl()->isBitField())
847       Length = FR->getDecl()->getBitWidthValue(SVB.getContext());
848   }
849 
850   for (ClusterBindings::iterator I = Cluster.begin(), E = Cluster.end();
851        I != E; ++I) {
852     BindingKey NextKey = I.getKey();
853     if (NextKey.getRegion() == TopKey.getRegion()) {
854       // FIXME: This doesn't catch the case where we're really invalidating a
855       // region with a symbolic offset. Example:
856       //      R: points[i].y
857       //   Next: points[0].x
858 
859       if (NextKey.getOffset() > TopKey.getOffset() &&
860           NextKey.getOffset() - TopKey.getOffset() < Length) {
861         // Case 1: The next binding is inside the region we're invalidating.
862         // Include it.
863         Bindings.push_back(*I);
864 
865       } else if (NextKey.getOffset() == TopKey.getOffset()) {
866         // Case 2: The next binding is at the same offset as the region we're
867         // invalidating. In this case, we need to leave default bindings alone,
868         // since they may be providing a default value for a regions beyond what
869         // we're invalidating.
870         // FIXME: This is probably incorrect; consider invalidating an outer
871         // struct whose first field is bound to a LazyCompoundVal.
872         if (IncludeAllDefaultBindings || NextKey.isDirect())
873           Bindings.push_back(*I);
874       }
875 
876     } else if (NextKey.hasSymbolicOffset()) {
877       const MemRegion *Base = NextKey.getConcreteOffsetRegion();
878       if (Top->isSubRegionOf(Base)) {
879         // Case 3: The next key is symbolic and we just changed something within
880         // its concrete region. We don't know if the binding is still valid, so
881         // we'll be conservative and include it.
882         if (IncludeAllDefaultBindings || NextKey.isDirect())
883           if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions))
884             Bindings.push_back(*I);
885       } else if (const SubRegion *BaseSR = dyn_cast<SubRegion>(Base)) {
886         // Case 4: The next key is symbolic, but we changed a known
887         // super-region. In this case the binding is certainly included.
888         if (Top == Base || BaseSR->isSubRegionOf(Top))
889           if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions))
890             Bindings.push_back(*I);
891       }
892     }
893   }
894 }
895 
896 static void
897 collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings,
898                          SValBuilder &SVB, const ClusterBindings &Cluster,
899                          const SubRegion *Top, bool IncludeAllDefaultBindings) {
900   collectSubRegionBindings(Bindings, SVB, Cluster, Top,
901                            BindingKey::Make(Top, BindingKey::Default),
902                            IncludeAllDefaultBindings);
903 }
904 
905 RegionBindingsRef
906 RegionStoreManager::removeSubRegionBindings(RegionBindingsConstRef B,
907                                             const SubRegion *Top) {
908   BindingKey TopKey = BindingKey::Make(Top, BindingKey::Default);
909   const MemRegion *ClusterHead = TopKey.getBaseRegion();
910 
911   if (Top == ClusterHead) {
912     // We can remove an entire cluster's bindings all in one go.
913     return B.remove(Top);
914   }
915 
916   const ClusterBindings *Cluster = B.lookup(ClusterHead);
917   if (!Cluster) {
918     // If we're invalidating a region with a symbolic offset, we need to make
919     // sure we don't treat the base region as uninitialized anymore.
920     if (TopKey.hasSymbolicOffset()) {
921       const SubRegion *Concrete = TopKey.getConcreteOffsetRegion();
922       return B.addBinding(Concrete, BindingKey::Default, UnknownVal());
923     }
924     return B;
925   }
926 
927   SmallVector<BindingPair, 32> Bindings;
928   collectSubRegionBindings(Bindings, svalBuilder, *Cluster, Top, TopKey,
929                            /*IncludeAllDefaultBindings=*/false);
930 
931   ClusterBindingsRef Result(*Cluster, CBFactory);
932   for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(),
933                                                     E = Bindings.end();
934        I != E; ++I)
935     Result = Result.remove(I->first);
936 
937   // If we're invalidating a region with a symbolic offset, we need to make sure
938   // we don't treat the base region as uninitialized anymore.
939   // FIXME: This isn't very precise; see the example in
940   // collectSubRegionBindings.
941   if (TopKey.hasSymbolicOffset()) {
942     const SubRegion *Concrete = TopKey.getConcreteOffsetRegion();
943     Result = Result.add(BindingKey::Make(Concrete, BindingKey::Default),
944                         UnknownVal());
945   }
946 
947   if (Result.isEmpty())
948     return B.remove(ClusterHead);
949   return B.add(ClusterHead, Result.asImmutableMap());
950 }
951 
952 namespace {
953 class invalidateRegionsWorker : public ClusterAnalysis<invalidateRegionsWorker>
954 {
955   const Expr *Ex;
956   unsigned Count;
957   const LocationContext *LCtx;
958   InvalidatedSymbols &IS;
959   InvalidatedSymbols &ConstIS;
960   StoreManager::InvalidatedRegions *Regions;
961 public:
962   invalidateRegionsWorker(RegionStoreManager &rm,
963                           ProgramStateManager &stateMgr,
964                           RegionBindingsRef b,
965                           const Expr *ex, unsigned count,
966                           const LocationContext *lctx,
967                           InvalidatedSymbols &is,
968                           InvalidatedSymbols &inConstIS,
969                           StoreManager::InvalidatedRegions *r,
970                           GlobalsFilterKind GFK)
971     : ClusterAnalysis<invalidateRegionsWorker>(rm, stateMgr, b, GFK),
972       Ex(ex), Count(count), LCtx(lctx), IS(is), ConstIS(inConstIS), Regions(r){}
973 
974   /// \param IsConst Specifies if the region we are invalidating is constant.
975   /// If it is, we invalidate all subregions, but not the base region itself.
976   void VisitCluster(const MemRegion *baseR, const ClusterBindings *C,
977                     bool IsConst);
978   void VisitBinding(SVal V);
979 };
980 }
981 
982 void invalidateRegionsWorker::VisitBinding(SVal V) {
983   // A symbol?  Mark it touched by the invalidation.
984   if (SymbolRef Sym = V.getAsSymbol())
985     IS.insert(Sym);
986 
987   if (const MemRegion *R = V.getAsRegion()) {
988     AddToWorkList(R);
989     return;
990   }
991 
992   // Is it a LazyCompoundVal?  All references get invalidated as well.
993   if (Optional<nonloc::LazyCompoundVal> LCS =
994           V.getAs<nonloc::LazyCompoundVal>()) {
995 
996     const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS);
997 
998     for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(),
999                                                         E = Vals.end();
1000          I != E; ++I)
1001       VisitBinding(*I);
1002 
1003     return;
1004   }
1005 }
1006 
1007 void invalidateRegionsWorker::VisitCluster(const MemRegion *baseR,
1008                                            const ClusterBindings *C,
1009                                            bool IsConst) {
1010   if (C) {
1011     for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I)
1012       VisitBinding(I.getData());
1013 
1014     // Invalidate the contents of a non-const base region.
1015     if (!IsConst)
1016       B = B.remove(baseR);
1017   }
1018 
1019   // BlockDataRegion?  If so, invalidate captured variables that are passed
1020   // by reference.
1021   if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) {
1022     for (BlockDataRegion::referenced_vars_iterator
1023          BI = BR->referenced_vars_begin(), BE = BR->referenced_vars_end() ;
1024          BI != BE; ++BI) {
1025       const VarRegion *VR = BI.getCapturedRegion();
1026       const VarDecl *VD = VR->getDecl();
1027       if (VD->getAttr<BlocksAttr>() || !VD->hasLocalStorage()) {
1028         AddToWorkList(VR);
1029       }
1030       else if (Loc::isLocType(VR->getValueType())) {
1031         // Map the current bindings to a Store to retrieve the value
1032         // of the binding.  If that binding itself is a region, we should
1033         // invalidate that region.  This is because a block may capture
1034         // a pointer value, but the thing pointed by that pointer may
1035         // get invalidated.
1036         SVal V = RM.getBinding(B, loc::MemRegionVal(VR));
1037         if (Optional<Loc> L = V.getAs<Loc>()) {
1038           if (const MemRegion *LR = L->getAsRegion())
1039             AddToWorkList(LR);
1040         }
1041       }
1042     }
1043     return;
1044   }
1045 
1046   // Symbolic region?
1047   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) {
1048     SymbolRef RegionSym = SR->getSymbol();
1049 
1050     // Mark that symbol touched by the invalidation.
1051     if (IsConst)
1052       ConstIS.insert(RegionSym);
1053     else
1054       IS.insert(RegionSym);
1055   }
1056 
1057   // Nothing else should be done for a const region.
1058   if (IsConst)
1059     return;
1060 
1061   // Otherwise, we have a normal data region. Record that we touched the region.
1062   if (Regions)
1063     Regions->push_back(baseR);
1064 
1065   if (isa<AllocaRegion>(baseR) || isa<SymbolicRegion>(baseR)) {
1066     // Invalidate the region by setting its default value to
1067     // conjured symbol. The type of the symbol is irrelavant.
1068     DefinedOrUnknownSVal V =
1069       svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count);
1070     B = B.addBinding(baseR, BindingKey::Default, V);
1071     return;
1072   }
1073 
1074   if (!baseR->isBoundable())
1075     return;
1076 
1077   const TypedValueRegion *TR = cast<TypedValueRegion>(baseR);
1078   QualType T = TR->getValueType();
1079 
1080   if (isInitiallyIncludedGlobalRegion(baseR)) {
1081     // If the region is a global and we are invalidating all globals,
1082     // erasing the entry is good enough.  This causes all globals to be lazily
1083     // symbolicated from the same base symbol.
1084     return;
1085   }
1086 
1087   if (T->isStructureOrClassType()) {
1088     // Invalidate the region by setting its default value to
1089     // conjured symbol. The type of the symbol is irrelavant.
1090     DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
1091                                                           Ctx.IntTy, Count);
1092     B = B.addBinding(baseR, BindingKey::Default, V);
1093     return;
1094   }
1095 
1096   if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
1097       // Set the default value of the array to conjured symbol.
1098     DefinedOrUnknownSVal V =
1099     svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
1100                                      AT->getElementType(), Count);
1101     B = B.addBinding(baseR, BindingKey::Default, V);
1102     return;
1103   }
1104 
1105   DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
1106                                                         T,Count);
1107   assert(SymbolManager::canSymbolicate(T) || V.isUnknown());
1108   B = B.addBinding(baseR, BindingKey::Direct, V);
1109 }
1110 
1111 RegionBindingsRef
1112 RegionStoreManager::invalidateGlobalRegion(MemRegion::Kind K,
1113                                            const Expr *Ex,
1114                                            unsigned Count,
1115                                            const LocationContext *LCtx,
1116                                            RegionBindingsRef B,
1117                                            InvalidatedRegions *Invalidated) {
1118   // Bind the globals memory space to a new symbol that we will use to derive
1119   // the bindings for all globals.
1120   const GlobalsSpaceRegion *GS = MRMgr.getGlobalsRegion(K);
1121   SVal V = svalBuilder.conjureSymbolVal(/* SymbolTag = */ (const void*) GS, Ex, LCtx,
1122                                         /* type does not matter */ Ctx.IntTy,
1123                                         Count);
1124 
1125   B = B.removeBinding(GS)
1126        .addBinding(BindingKey::Make(GS, BindingKey::Default), V);
1127 
1128   // Even if there are no bindings in the global scope, we still need to
1129   // record that we touched it.
1130   if (Invalidated)
1131     Invalidated->push_back(GS);
1132 
1133   return B;
1134 }
1135 
1136 void RegionStoreManager::populateWorkList(invalidateRegionsWorker &W,
1137                                           ArrayRef<SVal> Values,
1138                                           bool IsArrayOfConstRegions,
1139                                           InvalidatedRegions *TopLevelRegions) {
1140   for (ArrayRef<SVal>::iterator I = Values.begin(),
1141                                 E = Values.end(); I != E; ++I) {
1142     SVal V = *I;
1143     if (Optional<nonloc::LazyCompoundVal> LCS =
1144         V.getAs<nonloc::LazyCompoundVal>()) {
1145 
1146       const SValListTy &Vals = getInterestingValues(*LCS);
1147 
1148       for (SValListTy::const_iterator I = Vals.begin(),
1149                                       E = Vals.end(); I != E; ++I) {
1150         // Note: the last argument is false here because these are
1151         // non-top-level regions.
1152         if (const MemRegion *R = (*I).getAsRegion())
1153           W.AddToWorkList(R, /*IsConst=*/ false);
1154       }
1155       continue;
1156     }
1157 
1158     if (const MemRegion *R = V.getAsRegion()) {
1159       if (TopLevelRegions)
1160         TopLevelRegions->push_back(R);
1161       W.AddToWorkList(R, /*IsConst=*/ IsArrayOfConstRegions);
1162       continue;
1163     }
1164   }
1165 }
1166 
1167 StoreRef
1168 RegionStoreManager::invalidateRegions(Store store,
1169                                       ArrayRef<SVal> Values,
1170                                       ArrayRef<SVal> ConstValues,
1171                                       const Expr *Ex, unsigned Count,
1172                                       const LocationContext *LCtx,
1173                                       const CallEvent *Call,
1174                                       InvalidatedSymbols &IS,
1175                                       InvalidatedSymbols &ConstIS,
1176                                       InvalidatedRegions *TopLevelRegions,
1177                                       InvalidatedRegions *TopLevelConstRegions,
1178                                       InvalidatedRegions *Invalidated) {
1179   GlobalsFilterKind GlobalsFilter;
1180   if (Call) {
1181     if (Call->isInSystemHeader())
1182       GlobalsFilter = GFK_SystemOnly;
1183     else
1184       GlobalsFilter = GFK_All;
1185   } else {
1186     GlobalsFilter = GFK_None;
1187   }
1188 
1189   RegionBindingsRef B = getRegionBindings(store);
1190   invalidateRegionsWorker W(*this, StateMgr, B, Ex, Count, LCtx, IS, ConstIS,
1191                             Invalidated, GlobalsFilter);
1192 
1193   // Scan the bindings and generate the clusters.
1194   W.GenerateClusters();
1195 
1196   // Add the regions to the worklist.
1197   populateWorkList(W, Values, /*IsArrayOfConstRegions*/ false,
1198                    TopLevelRegions);
1199   populateWorkList(W, ConstValues, /*IsArrayOfConstRegions*/ true,
1200                    TopLevelConstRegions);
1201 
1202   W.RunWorkList();
1203 
1204   // Return the new bindings.
1205   B = W.getRegionBindings();
1206 
1207   // For calls, determine which global regions should be invalidated and
1208   // invalidate them. (Note that function-static and immutable globals are never
1209   // invalidated by this.)
1210   // TODO: This could possibly be more precise with modules.
1211   switch (GlobalsFilter) {
1212   case GFK_All:
1213     B = invalidateGlobalRegion(MemRegion::GlobalInternalSpaceRegionKind,
1214                                Ex, Count, LCtx, B, Invalidated);
1215     // FALLTHROUGH
1216   case GFK_SystemOnly:
1217     B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind,
1218                                Ex, Count, LCtx, B, Invalidated);
1219     // FALLTHROUGH
1220   case GFK_None:
1221     break;
1222   }
1223 
1224   return StoreRef(B.asStore(), *this);
1225 }
1226 
1227 //===----------------------------------------------------------------------===//
1228 // Extents for regions.
1229 //===----------------------------------------------------------------------===//
1230 
1231 DefinedOrUnknownSVal
1232 RegionStoreManager::getSizeInElements(ProgramStateRef state,
1233                                       const MemRegion *R,
1234                                       QualType EleTy) {
1235   SVal Size = cast<SubRegion>(R)->getExtent(svalBuilder);
1236   const llvm::APSInt *SizeInt = svalBuilder.getKnownValue(state, Size);
1237   if (!SizeInt)
1238     return UnknownVal();
1239 
1240   CharUnits RegionSize = CharUnits::fromQuantity(SizeInt->getSExtValue());
1241 
1242   if (Ctx.getAsVariableArrayType(EleTy)) {
1243     // FIXME: We need to track extra state to properly record the size
1244     // of VLAs.  Returning UnknownVal here, however, is a stop-gap so that
1245     // we don't have a divide-by-zero below.
1246     return UnknownVal();
1247   }
1248 
1249   CharUnits EleSize = Ctx.getTypeSizeInChars(EleTy);
1250 
1251   // If a variable is reinterpreted as a type that doesn't fit into a larger
1252   // type evenly, round it down.
1253   // This is a signed value, since it's used in arithmetic with signed indices.
1254   return svalBuilder.makeIntVal(RegionSize / EleSize, false);
1255 }
1256 
1257 //===----------------------------------------------------------------------===//
1258 // Location and region casting.
1259 //===----------------------------------------------------------------------===//
1260 
1261 /// ArrayToPointer - Emulates the "decay" of an array to a pointer
1262 ///  type.  'Array' represents the lvalue of the array being decayed
1263 ///  to a pointer, and the returned SVal represents the decayed
1264 ///  version of that lvalue (i.e., a pointer to the first element of
1265 ///  the array).  This is called by ExprEngine when evaluating casts
1266 ///  from arrays to pointers.
1267 SVal RegionStoreManager::ArrayToPointer(Loc Array) {
1268   if (!Array.getAs<loc::MemRegionVal>())
1269     return UnknownVal();
1270 
1271   const MemRegion* R = Array.castAs<loc::MemRegionVal>().getRegion();
1272   const TypedValueRegion* ArrayR = dyn_cast<TypedValueRegion>(R);
1273 
1274   if (!ArrayR)
1275     return UnknownVal();
1276 
1277   // Strip off typedefs from the ArrayRegion's ValueType.
1278   QualType T = ArrayR->getValueType().getDesugaredType(Ctx);
1279   const ArrayType *AT = cast<ArrayType>(T);
1280   T = AT->getElementType();
1281 
1282   NonLoc ZeroIdx = svalBuilder.makeZeroArrayIndex();
1283   return loc::MemRegionVal(MRMgr.getElementRegion(T, ZeroIdx, ArrayR, Ctx));
1284 }
1285 
1286 //===----------------------------------------------------------------------===//
1287 // Loading values from regions.
1288 //===----------------------------------------------------------------------===//
1289 
1290 SVal RegionStoreManager::getBinding(RegionBindingsConstRef B, Loc L, QualType T) {
1291   assert(!L.getAs<UnknownVal>() && "location unknown");
1292   assert(!L.getAs<UndefinedVal>() && "location undefined");
1293 
1294   // For access to concrete addresses, return UnknownVal.  Checks
1295   // for null dereferences (and similar errors) are done by checkers, not
1296   // the Store.
1297   // FIXME: We can consider lazily symbolicating such memory, but we really
1298   // should defer this when we can reason easily about symbolicating arrays
1299   // of bytes.
1300   if (L.getAs<loc::ConcreteInt>()) {
1301     return UnknownVal();
1302   }
1303   if (!L.getAs<loc::MemRegionVal>()) {
1304     return UnknownVal();
1305   }
1306 
1307   const MemRegion *MR = L.castAs<loc::MemRegionVal>().getRegion();
1308 
1309   if (isa<AllocaRegion>(MR) ||
1310       isa<SymbolicRegion>(MR) ||
1311       isa<CodeTextRegion>(MR)) {
1312     if (T.isNull()) {
1313       if (const TypedRegion *TR = dyn_cast<TypedRegion>(MR))
1314         T = TR->getLocationType();
1315       else {
1316         const SymbolicRegion *SR = cast<SymbolicRegion>(MR);
1317         T = SR->getSymbol()->getType();
1318       }
1319     }
1320     MR = GetElementZeroRegion(MR, T);
1321   }
1322 
1323   // FIXME: Perhaps this method should just take a 'const MemRegion*' argument
1324   //  instead of 'Loc', and have the other Loc cases handled at a higher level.
1325   const TypedValueRegion *R = cast<TypedValueRegion>(MR);
1326   QualType RTy = R->getValueType();
1327 
1328   // FIXME: we do not yet model the parts of a complex type, so treat the
1329   // whole thing as "unknown".
1330   if (RTy->isAnyComplexType())
1331     return UnknownVal();
1332 
1333   // FIXME: We should eventually handle funny addressing.  e.g.:
1334   //
1335   //   int x = ...;
1336   //   int *p = &x;
1337   //   char *q = (char*) p;
1338   //   char c = *q;  // returns the first byte of 'x'.
1339   //
1340   // Such funny addressing will occur due to layering of regions.
1341   if (RTy->isStructureOrClassType())
1342     return getBindingForStruct(B, R);
1343 
1344   // FIXME: Handle unions.
1345   if (RTy->isUnionType())
1346     return UnknownVal();
1347 
1348   if (RTy->isArrayType()) {
1349     if (RTy->isConstantArrayType())
1350       return getBindingForArray(B, R);
1351     else
1352       return UnknownVal();
1353   }
1354 
1355   // FIXME: handle Vector types.
1356   if (RTy->isVectorType())
1357     return UnknownVal();
1358 
1359   if (const FieldRegion* FR = dyn_cast<FieldRegion>(R))
1360     return CastRetrievedVal(getBindingForField(B, FR), FR, T, false);
1361 
1362   if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) {
1363     // FIXME: Here we actually perform an implicit conversion from the loaded
1364     // value to the element type.  Eventually we want to compose these values
1365     // more intelligently.  For example, an 'element' can encompass multiple
1366     // bound regions (e.g., several bound bytes), or could be a subset of
1367     // a larger value.
1368     return CastRetrievedVal(getBindingForElement(B, ER), ER, T, false);
1369   }
1370 
1371   if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) {
1372     // FIXME: Here we actually perform an implicit conversion from the loaded
1373     // value to the ivar type.  What we should model is stores to ivars
1374     // that blow past the extent of the ivar.  If the address of the ivar is
1375     // reinterpretted, it is possible we stored a different value that could
1376     // fit within the ivar.  Either we need to cast these when storing them
1377     // or reinterpret them lazily (as we do here).
1378     return CastRetrievedVal(getBindingForObjCIvar(B, IVR), IVR, T, false);
1379   }
1380 
1381   if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
1382     // FIXME: Here we actually perform an implicit conversion from the loaded
1383     // value to the variable type.  What we should model is stores to variables
1384     // that blow past the extent of the variable.  If the address of the
1385     // variable is reinterpretted, it is possible we stored a different value
1386     // that could fit within the variable.  Either we need to cast these when
1387     // storing them or reinterpret them lazily (as we do here).
1388     return CastRetrievedVal(getBindingForVar(B, VR), VR, T, false);
1389   }
1390 
1391   const SVal *V = B.lookup(R, BindingKey::Direct);
1392 
1393   // Check if the region has a binding.
1394   if (V)
1395     return *V;
1396 
1397   // The location does not have a bound value.  This means that it has
1398   // the value it had upon its creation and/or entry to the analyzed
1399   // function/method.  These are either symbolic values or 'undefined'.
1400   if (R->hasStackNonParametersStorage()) {
1401     // All stack variables are considered to have undefined values
1402     // upon creation.  All heap allocated blocks are considered to
1403     // have undefined values as well unless they are explicitly bound
1404     // to specific values.
1405     return UndefinedVal();
1406   }
1407 
1408   // All other values are symbolic.
1409   return svalBuilder.getRegionValueSymbolVal(R);
1410 }
1411 
1412 static QualType getUnderlyingType(const SubRegion *R) {
1413   QualType RegionTy;
1414   if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(R))
1415     RegionTy = TVR->getValueType();
1416 
1417   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
1418     RegionTy = SR->getSymbol()->getType();
1419 
1420   return RegionTy;
1421 }
1422 
1423 /// Checks to see if store \p B has a lazy binding for region \p R.
1424 ///
1425 /// If \p AllowSubregionBindings is \c false, a lazy binding will be rejected
1426 /// if there are additional bindings within \p R.
1427 ///
1428 /// Note that unlike RegionStoreManager::findLazyBinding, this will not search
1429 /// for lazy bindings for super-regions of \p R.
1430 static Optional<nonloc::LazyCompoundVal>
1431 getExistingLazyBinding(SValBuilder &SVB, RegionBindingsConstRef B,
1432                        const SubRegion *R, bool AllowSubregionBindings) {
1433   Optional<SVal> V = B.getDefaultBinding(R);
1434   if (!V)
1435     return None;
1436 
1437   Optional<nonloc::LazyCompoundVal> LCV = V->getAs<nonloc::LazyCompoundVal>();
1438   if (!LCV)
1439     return None;
1440 
1441   // If the LCV is for a subregion, the types might not match, and we shouldn't
1442   // reuse the binding.
1443   QualType RegionTy = getUnderlyingType(R);
1444   if (!RegionTy.isNull() &&
1445       !RegionTy->isVoidPointerType()) {
1446     QualType SourceRegionTy = LCV->getRegion()->getValueType();
1447     if (!SVB.getContext().hasSameUnqualifiedType(RegionTy, SourceRegionTy))
1448       return None;
1449   }
1450 
1451   if (!AllowSubregionBindings) {
1452     // If there are any other bindings within this region, we shouldn't reuse
1453     // the top-level binding.
1454     SmallVector<BindingPair, 16> Bindings;
1455     collectSubRegionBindings(Bindings, SVB, *B.lookup(R->getBaseRegion()), R,
1456                              /*IncludeAllDefaultBindings=*/true);
1457     if (Bindings.size() > 1)
1458       return None;
1459   }
1460 
1461   return *LCV;
1462 }
1463 
1464 
1465 std::pair<Store, const SubRegion *>
1466 RegionStoreManager::findLazyBinding(RegionBindingsConstRef B,
1467                                    const SubRegion *R,
1468                                    const SubRegion *originalRegion) {
1469   if (originalRegion != R) {
1470     if (Optional<nonloc::LazyCompoundVal> V =
1471           getExistingLazyBinding(svalBuilder, B, R, true))
1472       return std::make_pair(V->getStore(), V->getRegion());
1473   }
1474 
1475   typedef std::pair<Store, const SubRegion *> StoreRegionPair;
1476   StoreRegionPair Result = StoreRegionPair();
1477 
1478   if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
1479     Result = findLazyBinding(B, cast<SubRegion>(ER->getSuperRegion()),
1480                              originalRegion);
1481 
1482     if (Result.second)
1483       Result.second = MRMgr.getElementRegionWithSuper(ER, Result.second);
1484 
1485   } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) {
1486     Result = findLazyBinding(B, cast<SubRegion>(FR->getSuperRegion()),
1487                                        originalRegion);
1488 
1489     if (Result.second)
1490       Result.second = MRMgr.getFieldRegionWithSuper(FR, Result.second);
1491 
1492   } else if (const CXXBaseObjectRegion *BaseReg =
1493                dyn_cast<CXXBaseObjectRegion>(R)) {
1494     // C++ base object region is another kind of region that we should blast
1495     // through to look for lazy compound value. It is like a field region.
1496     Result = findLazyBinding(B, cast<SubRegion>(BaseReg->getSuperRegion()),
1497                              originalRegion);
1498 
1499     if (Result.second)
1500       Result.second = MRMgr.getCXXBaseObjectRegionWithSuper(BaseReg,
1501                                                             Result.second);
1502   }
1503 
1504   return Result;
1505 }
1506 
1507 SVal RegionStoreManager::getBindingForElement(RegionBindingsConstRef B,
1508                                               const ElementRegion* R) {
1509   // We do not currently model bindings of the CompoundLiteralregion.
1510   if (isa<CompoundLiteralRegion>(R->getBaseRegion()))
1511     return UnknownVal();
1512 
1513   // Check if the region has a binding.
1514   if (const Optional<SVal> &V = B.getDirectBinding(R))
1515     return *V;
1516 
1517   const MemRegion* superR = R->getSuperRegion();
1518 
1519   // Check if the region is an element region of a string literal.
1520   if (const StringRegion *StrR=dyn_cast<StringRegion>(superR)) {
1521     // FIXME: Handle loads from strings where the literal is treated as
1522     // an integer, e.g., *((unsigned int*)"hello")
1523     QualType T = Ctx.getAsArrayType(StrR->getValueType())->getElementType();
1524     if (T != Ctx.getCanonicalType(R->getElementType()))
1525       return UnknownVal();
1526 
1527     const StringLiteral *Str = StrR->getStringLiteral();
1528     SVal Idx = R->getIndex();
1529     if (Optional<nonloc::ConcreteInt> CI = Idx.getAs<nonloc::ConcreteInt>()) {
1530       int64_t i = CI->getValue().getSExtValue();
1531       // Abort on string underrun.  This can be possible by arbitrary
1532       // clients of getBindingForElement().
1533       if (i < 0)
1534         return UndefinedVal();
1535       int64_t length = Str->getLength();
1536       // Technically, only i == length is guaranteed to be null.
1537       // However, such overflows should be caught before reaching this point;
1538       // the only time such an access would be made is if a string literal was
1539       // used to initialize a larger array.
1540       char c = (i >= length) ? '\0' : Str->getCodeUnit(i);
1541       return svalBuilder.makeIntVal(c, T);
1542     }
1543   }
1544 
1545   // Check for loads from a code text region.  For such loads, just give up.
1546   if (isa<CodeTextRegion>(superR))
1547     return UnknownVal();
1548 
1549   // Handle the case where we are indexing into a larger scalar object.
1550   // For example, this handles:
1551   //   int x = ...
1552   //   char *y = &x;
1553   //   return *y;
1554   // FIXME: This is a hack, and doesn't do anything really intelligent yet.
1555   const RegionRawOffset &O = R->getAsArrayOffset();
1556 
1557   // If we cannot reason about the offset, return an unknown value.
1558   if (!O.getRegion())
1559     return UnknownVal();
1560 
1561   if (const TypedValueRegion *baseR =
1562         dyn_cast_or_null<TypedValueRegion>(O.getRegion())) {
1563     QualType baseT = baseR->getValueType();
1564     if (baseT->isScalarType()) {
1565       QualType elemT = R->getElementType();
1566       if (elemT->isScalarType()) {
1567         if (Ctx.getTypeSizeInChars(baseT) >= Ctx.getTypeSizeInChars(elemT)) {
1568           if (const Optional<SVal> &V = B.getDirectBinding(superR)) {
1569             if (SymbolRef parentSym = V->getAsSymbol())
1570               return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1571 
1572             if (V->isUnknownOrUndef())
1573               return *V;
1574             // Other cases: give up.  We are indexing into a larger object
1575             // that has some value, but we don't know how to handle that yet.
1576             return UnknownVal();
1577           }
1578         }
1579       }
1580     }
1581   }
1582   return getBindingForFieldOrElementCommon(B, R, R->getElementType());
1583 }
1584 
1585 SVal RegionStoreManager::getBindingForField(RegionBindingsConstRef B,
1586                                             const FieldRegion* R) {
1587 
1588   // Check if the region has a binding.
1589   if (const Optional<SVal> &V = B.getDirectBinding(R))
1590     return *V;
1591 
1592   QualType Ty = R->getValueType();
1593   return getBindingForFieldOrElementCommon(B, R, Ty);
1594 }
1595 
1596 Optional<SVal>
1597 RegionStoreManager::getBindingForDerivedDefaultValue(RegionBindingsConstRef B,
1598                                                      const MemRegion *superR,
1599                                                      const TypedValueRegion *R,
1600                                                      QualType Ty) {
1601 
1602   if (const Optional<SVal> &D = B.getDefaultBinding(superR)) {
1603     const SVal &val = D.getValue();
1604     if (SymbolRef parentSym = val.getAsSymbol())
1605       return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1606 
1607     if (val.isZeroConstant())
1608       return svalBuilder.makeZeroVal(Ty);
1609 
1610     if (val.isUnknownOrUndef())
1611       return val;
1612 
1613     // Lazy bindings are usually handled through getExistingLazyBinding().
1614     // We should unify these two code paths at some point.
1615     if (val.getAs<nonloc::LazyCompoundVal>())
1616       return val;
1617 
1618     llvm_unreachable("Unknown default value");
1619   }
1620 
1621   return None;
1622 }
1623 
1624 SVal RegionStoreManager::getLazyBinding(const SubRegion *LazyBindingRegion,
1625                                         RegionBindingsRef LazyBinding) {
1626   SVal Result;
1627   if (const ElementRegion *ER = dyn_cast<ElementRegion>(LazyBindingRegion))
1628     Result = getBindingForElement(LazyBinding, ER);
1629   else
1630     Result = getBindingForField(LazyBinding,
1631                                 cast<FieldRegion>(LazyBindingRegion));
1632 
1633   // FIXME: This is a hack to deal with RegionStore's inability to distinguish a
1634   // default value for /part/ of an aggregate from a default value for the
1635   // /entire/ aggregate. The most common case of this is when struct Outer
1636   // has as its first member a struct Inner, which is copied in from a stack
1637   // variable. In this case, even if the Outer's default value is symbolic, 0,
1638   // or unknown, it gets overridden by the Inner's default value of undefined.
1639   //
1640   // This is a general problem -- if the Inner is zero-initialized, the Outer
1641   // will now look zero-initialized. The proper way to solve this is with a
1642   // new version of RegionStore that tracks the extent of a binding as well
1643   // as the offset.
1644   //
1645   // This hack only takes care of the undefined case because that can very
1646   // quickly result in a warning.
1647   if (Result.isUndef())
1648     Result = UnknownVal();
1649 
1650   return Result;
1651 }
1652 
1653 SVal
1654 RegionStoreManager::getBindingForFieldOrElementCommon(RegionBindingsConstRef B,
1655                                                       const TypedValueRegion *R,
1656                                                       QualType Ty) {
1657 
1658   // At this point we have already checked in either getBindingForElement or
1659   // getBindingForField if 'R' has a direct binding.
1660 
1661   // Lazy binding?
1662   Store lazyBindingStore = NULL;
1663   const SubRegion *lazyBindingRegion = NULL;
1664   llvm::tie(lazyBindingStore, lazyBindingRegion) = findLazyBinding(B, R, R);
1665   if (lazyBindingRegion)
1666     return getLazyBinding(lazyBindingRegion,
1667                           getRegionBindings(lazyBindingStore));
1668 
1669   // Record whether or not we see a symbolic index.  That can completely
1670   // be out of scope of our lookup.
1671   bool hasSymbolicIndex = false;
1672 
1673   // FIXME: This is a hack to deal with RegionStore's inability to distinguish a
1674   // default value for /part/ of an aggregate from a default value for the
1675   // /entire/ aggregate. The most common case of this is when struct Outer
1676   // has as its first member a struct Inner, which is copied in from a stack
1677   // variable. In this case, even if the Outer's default value is symbolic, 0,
1678   // or unknown, it gets overridden by the Inner's default value of undefined.
1679   //
1680   // This is a general problem -- if the Inner is zero-initialized, the Outer
1681   // will now look zero-initialized. The proper way to solve this is with a
1682   // new version of RegionStore that tracks the extent of a binding as well
1683   // as the offset.
1684   //
1685   // This hack only takes care of the undefined case because that can very
1686   // quickly result in a warning.
1687   bool hasPartialLazyBinding = false;
1688 
1689   const SubRegion *SR = dyn_cast<SubRegion>(R);
1690   while (SR) {
1691     const MemRegion *Base = SR->getSuperRegion();
1692     if (Optional<SVal> D = getBindingForDerivedDefaultValue(B, Base, R, Ty)) {
1693       if (D->getAs<nonloc::LazyCompoundVal>()) {
1694         hasPartialLazyBinding = true;
1695         break;
1696       }
1697 
1698       return *D;
1699     }
1700 
1701     if (const ElementRegion *ER = dyn_cast<ElementRegion>(Base)) {
1702       NonLoc index = ER->getIndex();
1703       if (!index.isConstant())
1704         hasSymbolicIndex = true;
1705     }
1706 
1707     // If our super region is a field or element itself, walk up the region
1708     // hierarchy to see if there is a default value installed in an ancestor.
1709     SR = dyn_cast<SubRegion>(Base);
1710   }
1711 
1712   if (R->hasStackNonParametersStorage()) {
1713     if (isa<ElementRegion>(R)) {
1714       // Currently we don't reason specially about Clang-style vectors.  Check
1715       // if superR is a vector and if so return Unknown.
1716       if (const TypedValueRegion *typedSuperR =
1717             dyn_cast<TypedValueRegion>(R->getSuperRegion())) {
1718         if (typedSuperR->getValueType()->isVectorType())
1719           return UnknownVal();
1720       }
1721     }
1722 
1723     // FIXME: We also need to take ElementRegions with symbolic indexes into
1724     // account.  This case handles both directly accessing an ElementRegion
1725     // with a symbolic offset, but also fields within an element with
1726     // a symbolic offset.
1727     if (hasSymbolicIndex)
1728       return UnknownVal();
1729 
1730     if (!hasPartialLazyBinding)
1731       return UndefinedVal();
1732   }
1733 
1734   // All other values are symbolic.
1735   return svalBuilder.getRegionValueSymbolVal(R);
1736 }
1737 
1738 SVal RegionStoreManager::getBindingForObjCIvar(RegionBindingsConstRef B,
1739                                                const ObjCIvarRegion* R) {
1740   // Check if the region has a binding.
1741   if (const Optional<SVal> &V = B.getDirectBinding(R))
1742     return *V;
1743 
1744   const MemRegion *superR = R->getSuperRegion();
1745 
1746   // Check if the super region has a default binding.
1747   if (const Optional<SVal> &V = B.getDefaultBinding(superR)) {
1748     if (SymbolRef parentSym = V->getAsSymbol())
1749       return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1750 
1751     // Other cases: give up.
1752     return UnknownVal();
1753   }
1754 
1755   return getBindingForLazySymbol(R);
1756 }
1757 
1758 SVal RegionStoreManager::getBindingForVar(RegionBindingsConstRef B,
1759                                           const VarRegion *R) {
1760 
1761   // Check if the region has a binding.
1762   if (const Optional<SVal> &V = B.getDirectBinding(R))
1763     return *V;
1764 
1765   // Lazily derive a value for the VarRegion.
1766   const VarDecl *VD = R->getDecl();
1767   const MemSpaceRegion *MS = R->getMemorySpace();
1768 
1769   // Arguments are always symbolic.
1770   if (isa<StackArgumentsSpaceRegion>(MS))
1771     return svalBuilder.getRegionValueSymbolVal(R);
1772 
1773   // Is 'VD' declared constant?  If so, retrieve the constant value.
1774   if (VD->getType().isConstQualified())
1775     if (const Expr *Init = VD->getInit())
1776       if (Optional<SVal> V = svalBuilder.getConstantVal(Init))
1777         return *V;
1778 
1779   // This must come after the check for constants because closure-captured
1780   // constant variables may appear in UnknownSpaceRegion.
1781   if (isa<UnknownSpaceRegion>(MS))
1782     return svalBuilder.getRegionValueSymbolVal(R);
1783 
1784   if (isa<GlobalsSpaceRegion>(MS)) {
1785     QualType T = VD->getType();
1786 
1787     // Function-scoped static variables are default-initialized to 0; if they
1788     // have an initializer, it would have been processed by now.
1789     if (isa<StaticGlobalSpaceRegion>(MS))
1790       return svalBuilder.makeZeroVal(T);
1791 
1792     if (Optional<SVal> V = getBindingForDerivedDefaultValue(B, MS, R, T)) {
1793       assert(!V->getAs<nonloc::LazyCompoundVal>());
1794       return V.getValue();
1795     }
1796 
1797     return svalBuilder.getRegionValueSymbolVal(R);
1798   }
1799 
1800   return UndefinedVal();
1801 }
1802 
1803 SVal RegionStoreManager::getBindingForLazySymbol(const TypedValueRegion *R) {
1804   // All other values are symbolic.
1805   return svalBuilder.getRegionValueSymbolVal(R);
1806 }
1807 
1808 const RegionStoreManager::SValListTy &
1809 RegionStoreManager::getInterestingValues(nonloc::LazyCompoundVal LCV) {
1810   // First, check the cache.
1811   LazyBindingsMapTy::iterator I = LazyBindingsMap.find(LCV.getCVData());
1812   if (I != LazyBindingsMap.end())
1813     return I->second;
1814 
1815   // If we don't have a list of values cached, start constructing it.
1816   SValListTy List;
1817 
1818   const SubRegion *LazyR = LCV.getRegion();
1819   RegionBindingsRef B = getRegionBindings(LCV.getStore());
1820 
1821   // If this region had /no/ bindings at the time, there are no interesting
1822   // values to return.
1823   const ClusterBindings *Cluster = B.lookup(LazyR->getBaseRegion());
1824   if (!Cluster)
1825     return (LazyBindingsMap[LCV.getCVData()] = llvm_move(List));
1826 
1827   SmallVector<BindingPair, 32> Bindings;
1828   collectSubRegionBindings(Bindings, svalBuilder, *Cluster, LazyR,
1829                            /*IncludeAllDefaultBindings=*/true);
1830   for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(),
1831                                                     E = Bindings.end();
1832        I != E; ++I) {
1833     SVal V = I->second;
1834     if (V.isUnknownOrUndef() || V.isConstant())
1835       continue;
1836 
1837     if (Optional<nonloc::LazyCompoundVal> InnerLCV =
1838             V.getAs<nonloc::LazyCompoundVal>()) {
1839       const SValListTy &InnerList = getInterestingValues(*InnerLCV);
1840       List.insert(List.end(), InnerList.begin(), InnerList.end());
1841       continue;
1842     }
1843 
1844     List.push_back(V);
1845   }
1846 
1847   return (LazyBindingsMap[LCV.getCVData()] = llvm_move(List));
1848 }
1849 
1850 NonLoc RegionStoreManager::createLazyBinding(RegionBindingsConstRef B,
1851                                              const TypedValueRegion *R) {
1852   if (Optional<nonloc::LazyCompoundVal> V =
1853         getExistingLazyBinding(svalBuilder, B, R, false))
1854     return *V;
1855 
1856   return svalBuilder.makeLazyCompoundVal(StoreRef(B.asStore(), *this), R);
1857 }
1858 
1859 SVal RegionStoreManager::getBindingForStruct(RegionBindingsConstRef B,
1860                                              const TypedValueRegion *R) {
1861   const RecordDecl *RD = R->getValueType()->castAs<RecordType>()->getDecl();
1862   if (RD->field_empty())
1863     return UnknownVal();
1864 
1865   return createLazyBinding(B, R);
1866 }
1867 
1868 SVal RegionStoreManager::getBindingForArray(RegionBindingsConstRef B,
1869                                             const TypedValueRegion *R) {
1870   assert(Ctx.getAsConstantArrayType(R->getValueType()) &&
1871          "Only constant array types can have compound bindings.");
1872 
1873   return createLazyBinding(B, R);
1874 }
1875 
1876 bool RegionStoreManager::includedInBindings(Store store,
1877                                             const MemRegion *region) const {
1878   RegionBindingsRef B = getRegionBindings(store);
1879   region = region->getBaseRegion();
1880 
1881   // Quick path: if the base is the head of a cluster, the region is live.
1882   if (B.lookup(region))
1883     return true;
1884 
1885   // Slow path: if the region is the VALUE of any binding, it is live.
1886   for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI) {
1887     const ClusterBindings &Cluster = RI.getData();
1888     for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
1889          CI != CE; ++CI) {
1890       const SVal &D = CI.getData();
1891       if (const MemRegion *R = D.getAsRegion())
1892         if (R->getBaseRegion() == region)
1893           return true;
1894     }
1895   }
1896 
1897   return false;
1898 }
1899 
1900 //===----------------------------------------------------------------------===//
1901 // Binding values to regions.
1902 //===----------------------------------------------------------------------===//
1903 
1904 StoreRef RegionStoreManager::killBinding(Store ST, Loc L) {
1905   if (Optional<loc::MemRegionVal> LV = L.getAs<loc::MemRegionVal>())
1906     if (const MemRegion* R = LV->getRegion())
1907       return StoreRef(getRegionBindings(ST).removeBinding(R)
1908                                            .asImmutableMap()
1909                                            .getRootWithoutRetain(),
1910                       *this);
1911 
1912   return StoreRef(ST, *this);
1913 }
1914 
1915 RegionBindingsRef
1916 RegionStoreManager::bind(RegionBindingsConstRef B, Loc L, SVal V) {
1917   if (L.getAs<loc::ConcreteInt>())
1918     return B;
1919 
1920   // If we get here, the location should be a region.
1921   const MemRegion *R = L.castAs<loc::MemRegionVal>().getRegion();
1922 
1923   // Check if the region is a struct region.
1924   if (const TypedValueRegion* TR = dyn_cast<TypedValueRegion>(R)) {
1925     QualType Ty = TR->getValueType();
1926     if (Ty->isArrayType())
1927       return bindArray(B, TR, V);
1928     if (Ty->isStructureOrClassType())
1929       return bindStruct(B, TR, V);
1930     if (Ty->isVectorType())
1931       return bindVector(B, TR, V);
1932   }
1933 
1934   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) {
1935     // Binding directly to a symbolic region should be treated as binding
1936     // to element 0.
1937     QualType T = SR->getSymbol()->getType();
1938     if (T->isAnyPointerType() || T->isReferenceType())
1939       T = T->getPointeeType();
1940 
1941     R = GetElementZeroRegion(SR, T);
1942   }
1943 
1944   // Clear out bindings that may overlap with this binding.
1945   RegionBindingsRef NewB = removeSubRegionBindings(B, cast<SubRegion>(R));
1946   return NewB.addBinding(BindingKey::Make(R, BindingKey::Direct), V);
1947 }
1948 
1949 // FIXME: this method should be merged into Bind().
1950 StoreRef RegionStoreManager::bindCompoundLiteral(Store ST,
1951                                                  const CompoundLiteralExpr *CL,
1952                                                  const LocationContext *LC,
1953                                                  SVal V) {
1954   return Bind(ST, loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CL, LC)), V);
1955 }
1956 
1957 RegionBindingsRef
1958 RegionStoreManager::setImplicitDefaultValue(RegionBindingsConstRef B,
1959                                             const MemRegion *R,
1960                                             QualType T) {
1961   SVal V;
1962 
1963   if (Loc::isLocType(T))
1964     V = svalBuilder.makeNull();
1965   else if (T->isIntegralOrEnumerationType())
1966     V = svalBuilder.makeZeroVal(T);
1967   else if (T->isStructureOrClassType() || T->isArrayType()) {
1968     // Set the default value to a zero constant when it is a structure
1969     // or array.  The type doesn't really matter.
1970     V = svalBuilder.makeZeroVal(Ctx.IntTy);
1971   }
1972   else {
1973     // We can't represent values of this type, but we still need to set a value
1974     // to record that the region has been initialized.
1975     // If this assertion ever fires, a new case should be added above -- we
1976     // should know how to default-initialize any value we can symbolicate.
1977     assert(!SymbolManager::canSymbolicate(T) && "This type is representable");
1978     V = UnknownVal();
1979   }
1980 
1981   return B.addBinding(R, BindingKey::Default, V);
1982 }
1983 
1984 RegionBindingsRef
1985 RegionStoreManager::bindArray(RegionBindingsConstRef B,
1986                               const TypedValueRegion* R,
1987                               SVal Init) {
1988 
1989   const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType()));
1990   QualType ElementTy = AT->getElementType();
1991   Optional<uint64_t> Size;
1992 
1993   if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT))
1994     Size = CAT->getSize().getZExtValue();
1995 
1996   // Check if the init expr is a string literal.
1997   if (Optional<loc::MemRegionVal> MRV = Init.getAs<loc::MemRegionVal>()) {
1998     const StringRegion *S = cast<StringRegion>(MRV->getRegion());
1999 
2000     // Treat the string as a lazy compound value.
2001     StoreRef store(B.asStore(), *this);
2002     nonloc::LazyCompoundVal LCV = svalBuilder.makeLazyCompoundVal(store, S)
2003         .castAs<nonloc::LazyCompoundVal>();
2004     return bindAggregate(B, R, LCV);
2005   }
2006 
2007   // Handle lazy compound values.
2008   if (Init.getAs<nonloc::LazyCompoundVal>())
2009     return bindAggregate(B, R, Init);
2010 
2011   // Remaining case: explicit compound values.
2012 
2013   if (Init.isUnknown())
2014     return setImplicitDefaultValue(B, R, ElementTy);
2015 
2016   const nonloc::CompoundVal& CV = Init.castAs<nonloc::CompoundVal>();
2017   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
2018   uint64_t i = 0;
2019 
2020   RegionBindingsRef NewB(B);
2021 
2022   for (; Size.hasValue() ? i < Size.getValue() : true ; ++i, ++VI) {
2023     // The init list might be shorter than the array length.
2024     if (VI == VE)
2025       break;
2026 
2027     const NonLoc &Idx = svalBuilder.makeArrayIndex(i);
2028     const ElementRegion *ER = MRMgr.getElementRegion(ElementTy, Idx, R, Ctx);
2029 
2030     if (ElementTy->isStructureOrClassType())
2031       NewB = bindStruct(NewB, ER, *VI);
2032     else if (ElementTy->isArrayType())
2033       NewB = bindArray(NewB, ER, *VI);
2034     else
2035       NewB = bind(NewB, loc::MemRegionVal(ER), *VI);
2036   }
2037 
2038   // If the init list is shorter than the array length, set the
2039   // array default value.
2040   if (Size.hasValue() && i < Size.getValue())
2041     NewB = setImplicitDefaultValue(NewB, R, ElementTy);
2042 
2043   return NewB;
2044 }
2045 
2046 RegionBindingsRef RegionStoreManager::bindVector(RegionBindingsConstRef B,
2047                                                  const TypedValueRegion* R,
2048                                                  SVal V) {
2049   QualType T = R->getValueType();
2050   assert(T->isVectorType());
2051   const VectorType *VT = T->getAs<VectorType>(); // Use getAs for typedefs.
2052 
2053   // Handle lazy compound values and symbolic values.
2054   if (V.getAs<nonloc::LazyCompoundVal>() || V.getAs<nonloc::SymbolVal>())
2055     return bindAggregate(B, R, V);
2056 
2057   // We may get non-CompoundVal accidentally due to imprecise cast logic or
2058   // that we are binding symbolic struct value. Kill the field values, and if
2059   // the value is symbolic go and bind it as a "default" binding.
2060   if (!V.getAs<nonloc::CompoundVal>()) {
2061     return bindAggregate(B, R, UnknownVal());
2062   }
2063 
2064   QualType ElemType = VT->getElementType();
2065   nonloc::CompoundVal CV = V.castAs<nonloc::CompoundVal>();
2066   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
2067   unsigned index = 0, numElements = VT->getNumElements();
2068   RegionBindingsRef NewB(B);
2069 
2070   for ( ; index != numElements ; ++index) {
2071     if (VI == VE)
2072       break;
2073 
2074     NonLoc Idx = svalBuilder.makeArrayIndex(index);
2075     const ElementRegion *ER = MRMgr.getElementRegion(ElemType, Idx, R, Ctx);
2076 
2077     if (ElemType->isArrayType())
2078       NewB = bindArray(NewB, ER, *VI);
2079     else if (ElemType->isStructureOrClassType())
2080       NewB = bindStruct(NewB, ER, *VI);
2081     else
2082       NewB = bind(NewB, loc::MemRegionVal(ER), *VI);
2083   }
2084   return NewB;
2085 }
2086 
2087 Optional<RegionBindingsRef>
2088 RegionStoreManager::tryBindSmallStruct(RegionBindingsConstRef B,
2089                                        const TypedValueRegion *R,
2090                                        const RecordDecl *RD,
2091                                        nonloc::LazyCompoundVal LCV) {
2092   FieldVector Fields;
2093 
2094   if (const CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(RD))
2095     if (Class->getNumBases() != 0 || Class->getNumVBases() != 0)
2096       return None;
2097 
2098   for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2099        I != E; ++I) {
2100     const FieldDecl *FD = *I;
2101     if (FD->isUnnamedBitfield())
2102       continue;
2103 
2104     // If there are too many fields, or if any of the fields are aggregates,
2105     // just use the LCV as a default binding.
2106     if (Fields.size() == SmallStructLimit)
2107       return None;
2108 
2109     QualType Ty = FD->getType();
2110     if (!(Ty->isScalarType() || Ty->isReferenceType()))
2111       return None;
2112 
2113     Fields.push_back(*I);
2114   }
2115 
2116   RegionBindingsRef NewB = B;
2117 
2118   for (FieldVector::iterator I = Fields.begin(), E = Fields.end(); I != E; ++I){
2119     const FieldRegion *SourceFR = MRMgr.getFieldRegion(*I, LCV.getRegion());
2120     SVal V = getBindingForField(getRegionBindings(LCV.getStore()), SourceFR);
2121 
2122     const FieldRegion *DestFR = MRMgr.getFieldRegion(*I, R);
2123     NewB = bind(NewB, loc::MemRegionVal(DestFR), V);
2124   }
2125 
2126   return NewB;
2127 }
2128 
2129 RegionBindingsRef RegionStoreManager::bindStruct(RegionBindingsConstRef B,
2130                                                  const TypedValueRegion* R,
2131                                                  SVal V) {
2132   if (!Features.supportsFields())
2133     return B;
2134 
2135   QualType T = R->getValueType();
2136   assert(T->isStructureOrClassType());
2137 
2138   const RecordType* RT = T->getAs<RecordType>();
2139   const RecordDecl *RD = RT->getDecl();
2140 
2141   if (!RD->isCompleteDefinition())
2142     return B;
2143 
2144   // Handle lazy compound values and symbolic values.
2145   if (Optional<nonloc::LazyCompoundVal> LCV =
2146         V.getAs<nonloc::LazyCompoundVal>()) {
2147     if (Optional<RegionBindingsRef> NewB = tryBindSmallStruct(B, R, RD, *LCV))
2148       return *NewB;
2149     return bindAggregate(B, R, V);
2150   }
2151   if (V.getAs<nonloc::SymbolVal>())
2152     return bindAggregate(B, R, V);
2153 
2154   // We may get non-CompoundVal accidentally due to imprecise cast logic or
2155   // that we are binding symbolic struct value. Kill the field values, and if
2156   // the value is symbolic go and bind it as a "default" binding.
2157   if (V.isUnknown() || !V.getAs<nonloc::CompoundVal>())
2158     return bindAggregate(B, R, UnknownVal());
2159 
2160   const nonloc::CompoundVal& CV = V.castAs<nonloc::CompoundVal>();
2161   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
2162 
2163   RecordDecl::field_iterator FI, FE;
2164   RegionBindingsRef NewB(B);
2165 
2166   for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; ++FI) {
2167 
2168     if (VI == VE)
2169       break;
2170 
2171     // Skip any unnamed bitfields to stay in sync with the initializers.
2172     if (FI->isUnnamedBitfield())
2173       continue;
2174 
2175     QualType FTy = FI->getType();
2176     const FieldRegion* FR = MRMgr.getFieldRegion(*FI, R);
2177 
2178     if (FTy->isArrayType())
2179       NewB = bindArray(NewB, FR, *VI);
2180     else if (FTy->isStructureOrClassType())
2181       NewB = bindStruct(NewB, FR, *VI);
2182     else
2183       NewB = bind(NewB, loc::MemRegionVal(FR), *VI);
2184     ++VI;
2185   }
2186 
2187   // There may be fewer values in the initialize list than the fields of struct.
2188   if (FI != FE) {
2189     NewB = NewB.addBinding(R, BindingKey::Default,
2190                            svalBuilder.makeIntVal(0, false));
2191   }
2192 
2193   return NewB;
2194 }
2195 
2196 RegionBindingsRef
2197 RegionStoreManager::bindAggregate(RegionBindingsConstRef B,
2198                                   const TypedRegion *R,
2199                                   SVal Val) {
2200   // Remove the old bindings, using 'R' as the root of all regions
2201   // we will invalidate. Then add the new binding.
2202   return removeSubRegionBindings(B, R).addBinding(R, BindingKey::Default, Val);
2203 }
2204 
2205 //===----------------------------------------------------------------------===//
2206 // State pruning.
2207 //===----------------------------------------------------------------------===//
2208 
2209 namespace {
2210 class removeDeadBindingsWorker :
2211   public ClusterAnalysis<removeDeadBindingsWorker> {
2212   SmallVector<const SymbolicRegion*, 12> Postponed;
2213   SymbolReaper &SymReaper;
2214   const StackFrameContext *CurrentLCtx;
2215 
2216 public:
2217   removeDeadBindingsWorker(RegionStoreManager &rm,
2218                            ProgramStateManager &stateMgr,
2219                            RegionBindingsRef b, SymbolReaper &symReaper,
2220                            const StackFrameContext *LCtx)
2221     : ClusterAnalysis<removeDeadBindingsWorker>(rm, stateMgr, b, GFK_None),
2222       SymReaper(symReaper), CurrentLCtx(LCtx) {}
2223 
2224   // Called by ClusterAnalysis.
2225   void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C);
2226   void VisitCluster(const MemRegion *baseR, const ClusterBindings *C);
2227   using ClusterAnalysis<removeDeadBindingsWorker>::VisitCluster;
2228 
2229   bool UpdatePostponed();
2230   void VisitBinding(SVal V);
2231 };
2232 }
2233 
2234 void removeDeadBindingsWorker::VisitAddedToCluster(const MemRegion *baseR,
2235                                                    const ClusterBindings &C) {
2236 
2237   if (const VarRegion *VR = dyn_cast<VarRegion>(baseR)) {
2238     if (SymReaper.isLive(VR))
2239       AddToWorkList(baseR, &C);
2240 
2241     return;
2242   }
2243 
2244   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) {
2245     if (SymReaper.isLive(SR->getSymbol()))
2246       AddToWorkList(SR, &C);
2247     else
2248       Postponed.push_back(SR);
2249 
2250     return;
2251   }
2252 
2253   if (isa<NonStaticGlobalSpaceRegion>(baseR)) {
2254     AddToWorkList(baseR, &C);
2255     return;
2256   }
2257 
2258   // CXXThisRegion in the current or parent location context is live.
2259   if (const CXXThisRegion *TR = dyn_cast<CXXThisRegion>(baseR)) {
2260     const StackArgumentsSpaceRegion *StackReg =
2261       cast<StackArgumentsSpaceRegion>(TR->getSuperRegion());
2262     const StackFrameContext *RegCtx = StackReg->getStackFrame();
2263     if (CurrentLCtx &&
2264         (RegCtx == CurrentLCtx || RegCtx->isParentOf(CurrentLCtx)))
2265       AddToWorkList(TR, &C);
2266   }
2267 }
2268 
2269 void removeDeadBindingsWorker::VisitCluster(const MemRegion *baseR,
2270                                             const ClusterBindings *C) {
2271   if (!C)
2272     return;
2273 
2274   // Mark the symbol for any SymbolicRegion with live bindings as live itself.
2275   // This means we should continue to track that symbol.
2276   if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(baseR))
2277     SymReaper.markLive(SymR->getSymbol());
2278 
2279   for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I)
2280     VisitBinding(I.getData());
2281 }
2282 
2283 void removeDeadBindingsWorker::VisitBinding(SVal V) {
2284   // Is it a LazyCompoundVal?  All referenced regions are live as well.
2285   if (Optional<nonloc::LazyCompoundVal> LCS =
2286           V.getAs<nonloc::LazyCompoundVal>()) {
2287 
2288     const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS);
2289 
2290     for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(),
2291                                                         E = Vals.end();
2292          I != E; ++I)
2293       VisitBinding(*I);
2294 
2295     return;
2296   }
2297 
2298   // If V is a region, then add it to the worklist.
2299   if (const MemRegion *R = V.getAsRegion()) {
2300     AddToWorkList(R);
2301 
2302     // All regions captured by a block are also live.
2303     if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(R)) {
2304       BlockDataRegion::referenced_vars_iterator I = BR->referenced_vars_begin(),
2305                                                 E = BR->referenced_vars_end();
2306       for ( ; I != E; ++I)
2307         AddToWorkList(I.getCapturedRegion());
2308     }
2309   }
2310 
2311 
2312   // Update the set of live symbols.
2313   for (SymExpr::symbol_iterator SI = V.symbol_begin(), SE = V.symbol_end();
2314        SI!=SE; ++SI)
2315     SymReaper.markLive(*SI);
2316 }
2317 
2318 bool removeDeadBindingsWorker::UpdatePostponed() {
2319   // See if any postponed SymbolicRegions are actually live now, after
2320   // having done a scan.
2321   bool changed = false;
2322 
2323   for (SmallVectorImpl<const SymbolicRegion*>::iterator
2324         I = Postponed.begin(), E = Postponed.end() ; I != E ; ++I) {
2325     if (const SymbolicRegion *SR = *I) {
2326       if (SymReaper.isLive(SR->getSymbol())) {
2327         changed |= AddToWorkList(SR);
2328         *I = NULL;
2329       }
2330     }
2331   }
2332 
2333   return changed;
2334 }
2335 
2336 StoreRef RegionStoreManager::removeDeadBindings(Store store,
2337                                                 const StackFrameContext *LCtx,
2338                                                 SymbolReaper& SymReaper) {
2339   RegionBindingsRef B = getRegionBindings(store);
2340   removeDeadBindingsWorker W(*this, StateMgr, B, SymReaper, LCtx);
2341   W.GenerateClusters();
2342 
2343   // Enqueue the region roots onto the worklist.
2344   for (SymbolReaper::region_iterator I = SymReaper.region_begin(),
2345        E = SymReaper.region_end(); I != E; ++I) {
2346     W.AddToWorkList(*I);
2347   }
2348 
2349   do W.RunWorkList(); while (W.UpdatePostponed());
2350 
2351   // We have now scanned the store, marking reachable regions and symbols
2352   // as live.  We now remove all the regions that are dead from the store
2353   // as well as update DSymbols with the set symbols that are now dead.
2354   for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; ++I) {
2355     const MemRegion *Base = I.getKey();
2356 
2357     // If the cluster has been visited, we know the region has been marked.
2358     if (W.isVisited(Base))
2359       continue;
2360 
2361     // Remove the dead entry.
2362     B = B.remove(Base);
2363 
2364     if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(Base))
2365       SymReaper.maybeDead(SymR->getSymbol());
2366 
2367     // Mark all non-live symbols that this binding references as dead.
2368     const ClusterBindings &Cluster = I.getData();
2369     for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
2370          CI != CE; ++CI) {
2371       SVal X = CI.getData();
2372       SymExpr::symbol_iterator SI = X.symbol_begin(), SE = X.symbol_end();
2373       for (; SI != SE; ++SI)
2374         SymReaper.maybeDead(*SI);
2375     }
2376   }
2377 
2378   return StoreRef(B.asStore(), *this);
2379 }
2380 
2381 //===----------------------------------------------------------------------===//
2382 // Utility methods.
2383 //===----------------------------------------------------------------------===//
2384 
2385 void RegionStoreManager::print(Store store, raw_ostream &OS,
2386                                const char* nl, const char *sep) {
2387   RegionBindingsRef B = getRegionBindings(store);
2388   OS << "Store (direct and default bindings), "
2389      << B.asStore()
2390      << " :" << nl;
2391   B.dump(OS, nl);
2392 }
2393