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