clang API Documentation

RegionStore.cpp
Go to the documentation of this file.
00001 //== RegionStore.cpp - Field-sensitive store model --------------*- C++ -*--==//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines a basic region store model. In this model, we do have field
00011 // sensitivity. But we assume nothing about the heap shape. So recursive data
00012 // structures are largely ignored. Basically we do 1-limiting analysis.
00013 // Parameter pointers are assumed with no aliasing. Pointee objects of
00014 // parameters are created lazily.
00015 //
00016 //===----------------------------------------------------------------------===//
00017 #include "clang/AST/Attr.h"
00018 #include "clang/AST/CharUnits.h"
00019 #include "clang/Analysis/Analyses/LiveVariables.h"
00020 #include "clang/Analysis/AnalysisContext.h"
00021 #include "clang/Basic/TargetInfo.h"
00022 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
00023 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
00024 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
00025 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
00026 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
00027 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
00028 #include "llvm/ADT/ImmutableList.h"
00029 #include "llvm/ADT/ImmutableMap.h"
00030 #include "llvm/ADT/Optional.h"
00031 #include "llvm/Support/raw_ostream.h"
00032 
00033 using namespace clang;
00034 using namespace ento;
00035 
00036 //===----------------------------------------------------------------------===//
00037 // Representation of binding keys.
00038 //===----------------------------------------------------------------------===//
00039 
00040 namespace {
00041 class BindingKey {
00042 public:
00043   enum Kind { Default = 0x0, Direct = 0x1 };
00044 private:
00045   enum { Symbolic = 0x2 };
00046 
00047   llvm::PointerIntPair<const MemRegion *, 2> P;
00048   uint64_t Data;
00049 
00050   /// Create a key for a binding to region \p r, which has a symbolic offset
00051   /// from region \p Base.
00052   explicit BindingKey(const SubRegion *r, const SubRegion *Base, Kind k)
00053     : P(r, k | Symbolic), Data(reinterpret_cast<uintptr_t>(Base)) {
00054     assert(r && Base && "Must have known regions.");
00055     assert(getConcreteOffsetRegion() == Base && "Failed to store base region");
00056   }
00057 
00058   /// Create a key for a binding at \p offset from base region \p r.
00059   explicit BindingKey(const MemRegion *r, uint64_t offset, Kind k)
00060     : P(r, k), Data(offset) {
00061     assert(r && "Must have known regions.");
00062     assert(getOffset() == offset && "Failed to store offset");
00063     assert((r == r->getBaseRegion() || isa<ObjCIvarRegion>(r)) && "Not a base");
00064   }
00065 public:
00066 
00067   bool isDirect() const { return P.getInt() & Direct; }
00068   bool hasSymbolicOffset() const { return P.getInt() & Symbolic; }
00069 
00070   const MemRegion *getRegion() const { return P.getPointer(); }
00071   uint64_t getOffset() const {
00072     assert(!hasSymbolicOffset());
00073     return Data;
00074   }
00075 
00076   const SubRegion *getConcreteOffsetRegion() const {
00077     assert(hasSymbolicOffset());
00078     return reinterpret_cast<const SubRegion *>(static_cast<uintptr_t>(Data));
00079   }
00080 
00081   const MemRegion *getBaseRegion() const {
00082     if (hasSymbolicOffset())
00083       return getConcreteOffsetRegion()->getBaseRegion();
00084     return getRegion()->getBaseRegion();
00085   }
00086 
00087   void Profile(llvm::FoldingSetNodeID& ID) const {
00088     ID.AddPointer(P.getOpaqueValue());
00089     ID.AddInteger(Data);
00090   }
00091 
00092   static BindingKey Make(const MemRegion *R, Kind k);
00093 
00094   bool operator<(const BindingKey &X) const {
00095     if (P.getOpaqueValue() < X.P.getOpaqueValue())
00096       return true;
00097     if (P.getOpaqueValue() > X.P.getOpaqueValue())
00098       return false;
00099     return Data < X.Data;
00100   }
00101 
00102   bool operator==(const BindingKey &X) const {
00103     return P.getOpaqueValue() == X.P.getOpaqueValue() &&
00104            Data == X.Data;
00105   }
00106 
00107   void dump() const;
00108 };
00109 } // end anonymous namespace
00110 
00111 BindingKey BindingKey::Make(const MemRegion *R, Kind k) {
00112   const RegionOffset &RO = R->getAsOffset();
00113   if (RO.hasSymbolicOffset())
00114     return BindingKey(cast<SubRegion>(R), cast<SubRegion>(RO.getRegion()), k);
00115 
00116   return BindingKey(RO.getRegion(), RO.getOffset(), k);
00117 }
00118 
00119 namespace llvm {
00120   static inline
00121   raw_ostream &operator<<(raw_ostream &os, BindingKey K) {
00122     os << '(' << K.getRegion();
00123     if (!K.hasSymbolicOffset())
00124       os << ',' << K.getOffset();
00125     os << ',' << (K.isDirect() ? "direct" : "default")
00126        << ')';
00127     return os;
00128   }
00129 
00130   template <typename T> struct isPodLike;
00131   template <> struct isPodLike<BindingKey> {
00132     static const bool value = true;
00133   };
00134 } // end llvm namespace
00135 
00136 LLVM_DUMP_METHOD void BindingKey::dump() const { llvm::errs() << *this; }
00137 
00138 //===----------------------------------------------------------------------===//
00139 // Actual Store type.
00140 //===----------------------------------------------------------------------===//
00141 
00142 typedef llvm::ImmutableMap<BindingKey, SVal>    ClusterBindings;
00143 typedef llvm::ImmutableMapRef<BindingKey, SVal> ClusterBindingsRef;
00144 typedef std::pair<BindingKey, SVal> BindingPair;
00145 
00146 typedef llvm::ImmutableMap<const MemRegion *, ClusterBindings>
00147         RegionBindings;
00148 
00149 namespace {
00150 class RegionBindingsRef : public llvm::ImmutableMapRef<const MemRegion *,
00151                                  ClusterBindings> {
00152  ClusterBindings::Factory &CBFactory;
00153 public:
00154   typedef llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>
00155           ParentTy;
00156 
00157   RegionBindingsRef(ClusterBindings::Factory &CBFactory,
00158                     const RegionBindings::TreeTy *T,
00159                     RegionBindings::TreeTy::Factory *F)
00160     : llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>(T, F),
00161       CBFactory(CBFactory) {}
00162 
00163   RegionBindingsRef(const ParentTy &P, ClusterBindings::Factory &CBFactory)
00164     : llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>(P),
00165       CBFactory(CBFactory) {}
00166 
00167   RegionBindingsRef add(key_type_ref K, data_type_ref D) const {
00168     return RegionBindingsRef(static_cast<const ParentTy*>(this)->add(K, D),
00169                              CBFactory);
00170   }
00171 
00172   RegionBindingsRef remove(key_type_ref K) const {
00173     return RegionBindingsRef(static_cast<const ParentTy*>(this)->remove(K),
00174                              CBFactory);
00175   }
00176 
00177   RegionBindingsRef addBinding(BindingKey K, SVal V) const;
00178 
00179   RegionBindingsRef addBinding(const MemRegion *R,
00180                                BindingKey::Kind k, SVal V) const;
00181 
00182   RegionBindingsRef &operator=(const RegionBindingsRef &X) {
00183     *static_cast<ParentTy*>(this) = X;
00184     return *this;
00185   }
00186 
00187   const SVal *lookup(BindingKey K) const;
00188   const SVal *lookup(const MemRegion *R, BindingKey::Kind k) const;
00189   const ClusterBindings *lookup(const MemRegion *R) const {
00190     return static_cast<const ParentTy*>(this)->lookup(R);
00191   }
00192 
00193   RegionBindingsRef removeBinding(BindingKey K);
00194 
00195   RegionBindingsRef removeBinding(const MemRegion *R,
00196                                   BindingKey::Kind k);
00197 
00198   RegionBindingsRef removeBinding(const MemRegion *R) {
00199     return removeBinding(R, BindingKey::Direct).
00200            removeBinding(R, BindingKey::Default);
00201   }
00202 
00203   Optional<SVal> getDirectBinding(const MemRegion *R) const;
00204 
00205   /// getDefaultBinding - Returns an SVal* representing an optional default
00206   ///  binding associated with a region and its subregions.
00207   Optional<SVal> getDefaultBinding(const MemRegion *R) const;
00208 
00209   /// Return the internal tree as a Store.
00210   Store asStore() const {
00211     return asImmutableMap().getRootWithoutRetain();
00212   }
00213 
00214   void dump(raw_ostream &OS, const char *nl) const {
00215    for (iterator I = begin(), E = end(); I != E; ++I) {
00216      const ClusterBindings &Cluster = I.getData();
00217      for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
00218           CI != CE; ++CI) {
00219        OS << ' ' << CI.getKey() << " : " << CI.getData() << nl;
00220      }
00221      OS << nl;
00222    }
00223   }
00224 
00225   LLVM_DUMP_METHOD void dump() const { dump(llvm::errs(), "\n"); }
00226 };
00227 } // end anonymous namespace
00228 
00229 typedef const RegionBindingsRef& RegionBindingsConstRef;
00230 
00231 Optional<SVal> RegionBindingsRef::getDirectBinding(const MemRegion *R) const {
00232   return Optional<SVal>::create(lookup(R, BindingKey::Direct));
00233 }
00234 
00235 Optional<SVal> RegionBindingsRef::getDefaultBinding(const MemRegion *R) const {
00236   if (R->isBoundable())
00237     if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R))
00238       if (TR->getValueType()->isUnionType())
00239         return UnknownVal();
00240 
00241   return Optional<SVal>::create(lookup(R, BindingKey::Default));
00242 }
00243 
00244 RegionBindingsRef RegionBindingsRef::addBinding(BindingKey K, SVal V) const {
00245   const MemRegion *Base = K.getBaseRegion();
00246 
00247   const ClusterBindings *ExistingCluster = lookup(Base);
00248   ClusterBindings Cluster = (ExistingCluster ? *ExistingCluster
00249                              : CBFactory.getEmptyMap());
00250 
00251   ClusterBindings NewCluster = CBFactory.add(Cluster, K, V);
00252   return add(Base, NewCluster);
00253 }
00254 
00255 
00256 RegionBindingsRef RegionBindingsRef::addBinding(const MemRegion *R,
00257                                                 BindingKey::Kind k,
00258                                                 SVal V) const {
00259   return addBinding(BindingKey::Make(R, k), V);
00260 }
00261 
00262 const SVal *RegionBindingsRef::lookup(BindingKey K) const {
00263   const ClusterBindings *Cluster = lookup(K.getBaseRegion());
00264   if (!Cluster)
00265     return nullptr;
00266   return Cluster->lookup(K);
00267 }
00268 
00269 const SVal *RegionBindingsRef::lookup(const MemRegion *R,
00270                                       BindingKey::Kind k) const {
00271   return lookup(BindingKey::Make(R, k));
00272 }
00273 
00274 RegionBindingsRef RegionBindingsRef::removeBinding(BindingKey K) {
00275   const MemRegion *Base = K.getBaseRegion();
00276   const ClusterBindings *Cluster = lookup(Base);
00277   if (!Cluster)
00278     return *this;
00279 
00280   ClusterBindings NewCluster = CBFactory.remove(*Cluster, K);
00281   if (NewCluster.isEmpty())
00282     return remove(Base);
00283   return add(Base, NewCluster);
00284 }
00285 
00286 RegionBindingsRef RegionBindingsRef::removeBinding(const MemRegion *R,
00287                                                 BindingKey::Kind k){
00288   return removeBinding(BindingKey::Make(R, k));
00289 }
00290 
00291 //===----------------------------------------------------------------------===//
00292 // Fine-grained control of RegionStoreManager.
00293 //===----------------------------------------------------------------------===//
00294 
00295 namespace {
00296 struct minimal_features_tag {};
00297 struct maximal_features_tag {};
00298 
00299 class RegionStoreFeatures {
00300   bool SupportsFields;
00301 public:
00302   RegionStoreFeatures(minimal_features_tag) :
00303     SupportsFields(false) {}
00304 
00305   RegionStoreFeatures(maximal_features_tag) :
00306     SupportsFields(true) {}
00307 
00308   void enableFields(bool t) { SupportsFields = t; }
00309 
00310   bool supportsFields() const { return SupportsFields; }
00311 };
00312 }
00313 
00314 //===----------------------------------------------------------------------===//
00315 // Main RegionStore logic.
00316 //===----------------------------------------------------------------------===//
00317 
00318 namespace {
00319 class invalidateRegionsWorker;
00320 
00321 class RegionStoreManager : public StoreManager {
00322 public:
00323   const RegionStoreFeatures Features;
00324 
00325   RegionBindings::Factory RBFactory;
00326   mutable ClusterBindings::Factory CBFactory;
00327 
00328   typedef std::vector<SVal> SValListTy;
00329 private:
00330   typedef llvm::DenseMap<const LazyCompoundValData *,
00331                          SValListTy> LazyBindingsMapTy;
00332   LazyBindingsMapTy LazyBindingsMap;
00333 
00334   /// The largest number of fields a struct can have and still be
00335   /// considered "small".
00336   ///
00337   /// This is currently used to decide whether or not it is worth "forcing" a
00338   /// LazyCompoundVal on bind.
00339   ///
00340   /// This is controlled by 'region-store-small-struct-limit' option.
00341   /// To disable all small-struct-dependent behavior, set the option to "0".
00342   unsigned SmallStructLimit;
00343 
00344   /// \brief A helper used to populate the work list with the given set of
00345   /// regions.
00346   void populateWorkList(invalidateRegionsWorker &W,
00347                         ArrayRef<SVal> Values,
00348                         InvalidatedRegions *TopLevelRegions);
00349 
00350 public:
00351   RegionStoreManager(ProgramStateManager& mgr, const RegionStoreFeatures &f)
00352     : StoreManager(mgr), Features(f),
00353       RBFactory(mgr.getAllocator()), CBFactory(mgr.getAllocator()),
00354       SmallStructLimit(0) {
00355     if (SubEngine *Eng = StateMgr.getOwningEngine()) {
00356       AnalyzerOptions &Options = Eng->getAnalysisManager().options;
00357       SmallStructLimit =
00358         Options.getOptionAsInteger("region-store-small-struct-limit", 2);
00359     }
00360   }
00361 
00362 
00363   /// setImplicitDefaultValue - Set the default binding for the provided
00364   ///  MemRegion to the value implicitly defined for compound literals when
00365   ///  the value is not specified.
00366   RegionBindingsRef setImplicitDefaultValue(RegionBindingsConstRef B,
00367                                             const MemRegion *R, QualType T);
00368 
00369   /// ArrayToPointer - Emulates the "decay" of an array to a pointer
00370   ///  type.  'Array' represents the lvalue of the array being decayed
00371   ///  to a pointer, and the returned SVal represents the decayed
00372   ///  version of that lvalue (i.e., a pointer to the first element of
00373   ///  the array).  This is called by ExprEngine when evaluating
00374   ///  casts from arrays to pointers.
00375   SVal ArrayToPointer(Loc Array, QualType ElementTy) override;
00376 
00377   StoreRef getInitialStore(const LocationContext *InitLoc) override {
00378     return StoreRef(RBFactory.getEmptyMap().getRootWithoutRetain(), *this);
00379   }
00380 
00381   //===-------------------------------------------------------------------===//
00382   // Binding values to regions.
00383   //===-------------------------------------------------------------------===//
00384   RegionBindingsRef invalidateGlobalRegion(MemRegion::Kind K,
00385                                            const Expr *Ex,
00386                                            unsigned Count,
00387                                            const LocationContext *LCtx,
00388                                            RegionBindingsRef B,
00389                                            InvalidatedRegions *Invalidated);
00390 
00391   StoreRef invalidateRegions(Store store,
00392                              ArrayRef<SVal> Values,
00393                              const Expr *E, unsigned Count,
00394                              const LocationContext *LCtx,
00395                              const CallEvent *Call,
00396                              InvalidatedSymbols &IS,
00397                              RegionAndSymbolInvalidationTraits &ITraits,
00398                              InvalidatedRegions *Invalidated,
00399                              InvalidatedRegions *InvalidatedTopLevel) override;
00400 
00401   bool scanReachableSymbols(Store S, const MemRegion *R,
00402                             ScanReachableSymbols &Callbacks) override;
00403 
00404   RegionBindingsRef removeSubRegionBindings(RegionBindingsConstRef B,
00405                                             const SubRegion *R);
00406 
00407 public: // Part of public interface to class.
00408 
00409   StoreRef Bind(Store store, Loc LV, SVal V) override {
00410     return StoreRef(bind(getRegionBindings(store), LV, V).asStore(), *this);
00411   }
00412 
00413   RegionBindingsRef bind(RegionBindingsConstRef B, Loc LV, SVal V);
00414 
00415   // BindDefault is only used to initialize a region with a default value.
00416   StoreRef BindDefault(Store store, const MemRegion *R, SVal V) override {
00417     RegionBindingsRef B = getRegionBindings(store);
00418     assert(!B.lookup(R, BindingKey::Direct));
00419 
00420     BindingKey Key = BindingKey::Make(R, BindingKey::Default);
00421     if (B.lookup(Key)) {
00422       const SubRegion *SR = cast<SubRegion>(R);
00423       assert(SR->getAsOffset().getOffset() ==
00424              SR->getSuperRegion()->getAsOffset().getOffset() &&
00425              "A default value must come from a super-region");
00426       B = removeSubRegionBindings(B, SR);
00427     } else {
00428       B = B.addBinding(Key, V);
00429     }
00430 
00431     return StoreRef(B.asImmutableMap().getRootWithoutRetain(), *this);
00432   }
00433 
00434   /// Attempt to extract the fields of \p LCV and bind them to the struct region
00435   /// \p R.
00436   ///
00437   /// This path is used when it seems advantageous to "force" loading the values
00438   /// within a LazyCompoundVal to bind memberwise to the struct region, rather
00439   /// than using a Default binding at the base of the entire region. This is a
00440   /// heuristic attempting to avoid building long chains of LazyCompoundVals.
00441   ///
00442   /// \returns The updated store bindings, or \c None if binding non-lazily
00443   ///          would be too expensive.
00444   Optional<RegionBindingsRef> tryBindSmallStruct(RegionBindingsConstRef B,
00445                                                  const TypedValueRegion *R,
00446                                                  const RecordDecl *RD,
00447                                                  nonloc::LazyCompoundVal LCV);
00448 
00449   /// BindStruct - Bind a compound value to a structure.
00450   RegionBindingsRef bindStruct(RegionBindingsConstRef B,
00451                                const TypedValueRegion* R, SVal V);
00452 
00453   /// BindVector - Bind a compound value to a vector.
00454   RegionBindingsRef bindVector(RegionBindingsConstRef B,
00455                                const TypedValueRegion* R, SVal V);
00456 
00457   RegionBindingsRef bindArray(RegionBindingsConstRef B,
00458                               const TypedValueRegion* R,
00459                               SVal V);
00460 
00461   /// Clears out all bindings in the given region and assigns a new value
00462   /// as a Default binding.
00463   RegionBindingsRef bindAggregate(RegionBindingsConstRef B,
00464                                   const TypedRegion *R,
00465                                   SVal DefaultVal);
00466 
00467   /// \brief Create a new store with the specified binding removed.
00468   /// \param ST the original store, that is the basis for the new store.
00469   /// \param L the location whose binding should be removed.
00470   StoreRef killBinding(Store ST, Loc L) override;
00471 
00472   void incrementReferenceCount(Store store) override {
00473     getRegionBindings(store).manualRetain();    
00474   }
00475   
00476   /// If the StoreManager supports it, decrement the reference count of
00477   /// the specified Store object.  If the reference count hits 0, the memory
00478   /// associated with the object is recycled.
00479   void decrementReferenceCount(Store store) override {
00480     getRegionBindings(store).manualRelease();
00481   }
00482 
00483   bool includedInBindings(Store store, const MemRegion *region) const override;
00484 
00485   /// \brief Return the value bound to specified location in a given state.
00486   ///
00487   /// The high level logic for this method is this:
00488   /// getBinding (L)
00489   ///   if L has binding
00490   ///     return L's binding
00491   ///   else if L is in killset
00492   ///     return unknown
00493   ///   else
00494   ///     if L is on stack or heap
00495   ///       return undefined
00496   ///     else
00497   ///       return symbolic
00498   SVal getBinding(Store S, Loc L, QualType T) override {
00499     return getBinding(getRegionBindings(S), L, T);
00500   }
00501 
00502   SVal getBinding(RegionBindingsConstRef B, Loc L, QualType T = QualType());
00503 
00504   SVal getBindingForElement(RegionBindingsConstRef B, const ElementRegion *R);
00505 
00506   SVal getBindingForField(RegionBindingsConstRef B, const FieldRegion *R);
00507 
00508   SVal getBindingForObjCIvar(RegionBindingsConstRef B, const ObjCIvarRegion *R);
00509 
00510   SVal getBindingForVar(RegionBindingsConstRef B, const VarRegion *R);
00511 
00512   SVal getBindingForLazySymbol(const TypedValueRegion *R);
00513 
00514   SVal getBindingForFieldOrElementCommon(RegionBindingsConstRef B,
00515                                          const TypedValueRegion *R,
00516                                          QualType Ty);
00517   
00518   SVal getLazyBinding(const SubRegion *LazyBindingRegion,
00519                       RegionBindingsRef LazyBinding);
00520 
00521   /// Get bindings for the values in a struct and return a CompoundVal, used
00522   /// when doing struct copy:
00523   /// struct s x, y;
00524   /// x = y;
00525   /// y's value is retrieved by this method.
00526   SVal getBindingForStruct(RegionBindingsConstRef B, const TypedValueRegion *R);
00527   SVal getBindingForArray(RegionBindingsConstRef B, const TypedValueRegion *R);
00528   NonLoc createLazyBinding(RegionBindingsConstRef B, const TypedValueRegion *R);
00529 
00530   /// Used to lazily generate derived symbols for bindings that are defined
00531   /// implicitly by default bindings in a super region.
00532   ///
00533   /// Note that callers may need to specially handle LazyCompoundVals, which
00534   /// are returned as is in case the caller needs to treat them differently.
00535   Optional<SVal> getBindingForDerivedDefaultValue(RegionBindingsConstRef B,
00536                                                   const MemRegion *superR,
00537                                                   const TypedValueRegion *R,
00538                                                   QualType Ty);
00539 
00540   /// Get the state and region whose binding this region \p R corresponds to.
00541   ///
00542   /// If there is no lazy binding for \p R, the returned value will have a null
00543   /// \c second. Note that a null pointer can represents a valid Store.
00544   std::pair<Store, const SubRegion *>
00545   findLazyBinding(RegionBindingsConstRef B, const SubRegion *R,
00546                   const SubRegion *originalRegion);
00547 
00548   /// Returns the cached set of interesting SVals contained within a lazy
00549   /// binding.
00550   ///
00551   /// The precise value of "interesting" is determined for the purposes of
00552   /// RegionStore's internal analysis. It must always contain all regions and
00553   /// symbols, but may omit constants and other kinds of SVal.
00554   const SValListTy &getInterestingValues(nonloc::LazyCompoundVal LCV);
00555 
00556   //===------------------------------------------------------------------===//
00557   // State pruning.
00558   //===------------------------------------------------------------------===//
00559 
00560   /// removeDeadBindings - Scans the RegionStore of 'state' for dead values.
00561   ///  It returns a new Store with these values removed.
00562   StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx,
00563                               SymbolReaper& SymReaper) override;
00564 
00565   //===------------------------------------------------------------------===//
00566   // Region "extents".
00567   //===------------------------------------------------------------------===//
00568 
00569   // FIXME: This method will soon be eliminated; see the note in Store.h.
00570   DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state,
00571                                          const MemRegion* R,
00572                                          QualType EleTy) override;
00573 
00574   //===------------------------------------------------------------------===//
00575   // Utility methods.
00576   //===------------------------------------------------------------------===//
00577 
00578   RegionBindingsRef getRegionBindings(Store store) const {
00579     return RegionBindingsRef(CBFactory,
00580                              static_cast<const RegionBindings::TreeTy*>(store),
00581                              RBFactory.getTreeFactory());
00582   }
00583 
00584   void print(Store store, raw_ostream &Out, const char* nl,
00585              const char *sep) override;
00586 
00587   void iterBindings(Store store, BindingsHandler& f) override {
00588     RegionBindingsRef B = getRegionBindings(store);
00589     for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; ++I) {
00590       const ClusterBindings &Cluster = I.getData();
00591       for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
00592            CI != CE; ++CI) {
00593         const BindingKey &K = CI.getKey();
00594         if (!K.isDirect())
00595           continue;
00596         if (const SubRegion *R = dyn_cast<SubRegion>(K.getRegion())) {
00597           // FIXME: Possibly incorporate the offset?
00598           if (!f.HandleBinding(*this, store, R, CI.getData()))
00599             return;
00600         }
00601       }
00602     }
00603   }
00604 };
00605 
00606 } // end anonymous namespace
00607 
00608 //===----------------------------------------------------------------------===//
00609 // RegionStore creation.
00610 //===----------------------------------------------------------------------===//
00611 
00612 std::unique_ptr<StoreManager>
00613 ento::CreateRegionStoreManager(ProgramStateManager &StMgr) {
00614   RegionStoreFeatures F = maximal_features_tag();
00615   return llvm::make_unique<RegionStoreManager>(StMgr, F);
00616 }
00617 
00618 std::unique_ptr<StoreManager>
00619 ento::CreateFieldsOnlyRegionStoreManager(ProgramStateManager &StMgr) {
00620   RegionStoreFeatures F = minimal_features_tag();
00621   F.enableFields(true);
00622   return llvm::make_unique<RegionStoreManager>(StMgr, F);
00623 }
00624 
00625 
00626 //===----------------------------------------------------------------------===//
00627 // Region Cluster analysis.
00628 //===----------------------------------------------------------------------===//
00629 
00630 namespace {
00631 /// Used to determine which global regions are automatically included in the
00632 /// initial worklist of a ClusterAnalysis.
00633 enum GlobalsFilterKind {
00634   /// Don't include any global regions.
00635   GFK_None,
00636   /// Only include system globals.
00637   GFK_SystemOnly,
00638   /// Include all global regions.
00639   GFK_All
00640 };
00641 
00642 template <typename DERIVED>
00643 class ClusterAnalysis  {
00644 protected:
00645   typedef llvm::DenseMap<const MemRegion *, const ClusterBindings *> ClusterMap;
00646   typedef const MemRegion * WorkListElement;
00647   typedef SmallVector<WorkListElement, 10> WorkList;
00648 
00649   llvm::SmallPtrSet<const ClusterBindings *, 16> Visited;
00650 
00651   WorkList WL;
00652 
00653   RegionStoreManager &RM;
00654   ASTContext &Ctx;
00655   SValBuilder &svalBuilder;
00656 
00657   RegionBindingsRef B;
00658 
00659 private:
00660   GlobalsFilterKind GlobalsFilter;
00661 
00662 protected:
00663   const ClusterBindings *getCluster(const MemRegion *R) {
00664     return B.lookup(R);
00665   }
00666 
00667   /// Returns true if the memory space of the given region is one of the global
00668   /// regions specially included at the start of analysis.
00669   bool isInitiallyIncludedGlobalRegion(const MemRegion *R) {
00670     switch (GlobalsFilter) {
00671     case GFK_None:
00672       return false;
00673     case GFK_SystemOnly:
00674       return isa<GlobalSystemSpaceRegion>(R->getMemorySpace());
00675     case GFK_All:
00676       return isa<NonStaticGlobalSpaceRegion>(R->getMemorySpace());
00677     }
00678 
00679     llvm_unreachable("unknown globals filter");
00680   }
00681 
00682 public:
00683   ClusterAnalysis(RegionStoreManager &rm, ProgramStateManager &StateMgr,
00684                   RegionBindingsRef b, GlobalsFilterKind GFK)
00685     : RM(rm), Ctx(StateMgr.getContext()),
00686       svalBuilder(StateMgr.getSValBuilder()),
00687       B(b), GlobalsFilter(GFK) {}
00688 
00689   RegionBindingsRef getRegionBindings() const { return B; }
00690 
00691   bool isVisited(const MemRegion *R) {
00692     return Visited.count(getCluster(R));
00693   }
00694 
00695   void GenerateClusters() {
00696     // Scan the entire set of bindings and record the region clusters.
00697     for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end();
00698          RI != RE; ++RI){
00699       const MemRegion *Base = RI.getKey();
00700 
00701       const ClusterBindings &Cluster = RI.getData();
00702       assert(!Cluster.isEmpty() && "Empty clusters should be removed");
00703       static_cast<DERIVED*>(this)->VisitAddedToCluster(Base, Cluster);
00704 
00705       // If this is an interesting global region, add it the work list up front.
00706       if (isInitiallyIncludedGlobalRegion(Base))
00707         AddToWorkList(WorkListElement(Base), &Cluster);
00708     }
00709   }
00710 
00711   bool AddToWorkList(WorkListElement E, const ClusterBindings *C) {
00712     if (C && !Visited.insert(C))
00713       return false;
00714     WL.push_back(E);
00715     return true;
00716   }
00717 
00718   bool AddToWorkList(const MemRegion *R) {
00719     const MemRegion *BaseR = R->getBaseRegion();
00720     return AddToWorkList(WorkListElement(BaseR), getCluster(BaseR));
00721   }
00722 
00723   void RunWorkList() {
00724     while (!WL.empty()) {
00725       WorkListElement E = WL.pop_back_val();
00726       const MemRegion *BaseR = E;
00727 
00728       static_cast<DERIVED*>(this)->VisitCluster(BaseR, getCluster(BaseR));
00729     }
00730   }
00731 
00732   void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C) {}
00733   void VisitCluster(const MemRegion *baseR, const ClusterBindings *C) {}
00734 
00735   void VisitCluster(const MemRegion *BaseR, const ClusterBindings *C,
00736                     bool Flag) {
00737     static_cast<DERIVED*>(this)->VisitCluster(BaseR, C);
00738   }
00739 };
00740 }
00741 
00742 //===----------------------------------------------------------------------===//
00743 // Binding invalidation.
00744 //===----------------------------------------------------------------------===//
00745 
00746 bool RegionStoreManager::scanReachableSymbols(Store S, const MemRegion *R,
00747                                               ScanReachableSymbols &Callbacks) {
00748   assert(R == R->getBaseRegion() && "Should only be called for base regions");
00749   RegionBindingsRef B = getRegionBindings(S);
00750   const ClusterBindings *Cluster = B.lookup(R);
00751 
00752   if (!Cluster)
00753     return true;
00754 
00755   for (ClusterBindings::iterator RI = Cluster->begin(), RE = Cluster->end();
00756        RI != RE; ++RI) {
00757     if (!Callbacks.scan(RI.getData()))
00758       return false;
00759   }
00760 
00761   return true;
00762 }
00763 
00764 static inline bool isUnionField(const FieldRegion *FR) {
00765   return FR->getDecl()->getParent()->isUnion();
00766 }
00767 
00768 typedef SmallVector<const FieldDecl *, 8> FieldVector;
00769 
00770 void getSymbolicOffsetFields(BindingKey K, FieldVector &Fields) {
00771   assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys");
00772 
00773   const MemRegion *Base = K.getConcreteOffsetRegion();
00774   const MemRegion *R = K.getRegion();
00775 
00776   while (R != Base) {
00777     if (const FieldRegion *FR = dyn_cast<FieldRegion>(R))
00778       if (!isUnionField(FR))
00779         Fields.push_back(FR->getDecl());
00780 
00781     R = cast<SubRegion>(R)->getSuperRegion();
00782   }
00783 }
00784 
00785 static bool isCompatibleWithFields(BindingKey K, const FieldVector &Fields) {
00786   assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys");
00787 
00788   if (Fields.empty())
00789     return true;
00790 
00791   FieldVector FieldsInBindingKey;
00792   getSymbolicOffsetFields(K, FieldsInBindingKey);
00793 
00794   ptrdiff_t Delta = FieldsInBindingKey.size() - Fields.size();
00795   if (Delta >= 0)
00796     return std::equal(FieldsInBindingKey.begin() + Delta,
00797                       FieldsInBindingKey.end(),
00798                       Fields.begin());
00799   else
00800     return std::equal(FieldsInBindingKey.begin(), FieldsInBindingKey.end(),
00801                       Fields.begin() - Delta);
00802 }
00803 
00804 /// Collects all bindings in \p Cluster that may refer to bindings within
00805 /// \p Top.
00806 ///
00807 /// Each binding is a pair whose \c first is the key (a BindingKey) and whose
00808 /// \c second is the value (an SVal).
00809 ///
00810 /// The \p IncludeAllDefaultBindings parameter specifies whether to include
00811 /// default bindings that may extend beyond \p Top itself, e.g. if \p Top is
00812 /// an aggregate within a larger aggregate with a default binding.
00813 static void
00814 collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings,
00815                          SValBuilder &SVB, const ClusterBindings &Cluster,
00816                          const SubRegion *Top, BindingKey TopKey,
00817                          bool IncludeAllDefaultBindings) {
00818   FieldVector FieldsInSymbolicSubregions;
00819   if (TopKey.hasSymbolicOffset()) {
00820     getSymbolicOffsetFields(TopKey, FieldsInSymbolicSubregions);
00821     Top = cast<SubRegion>(TopKey.getConcreteOffsetRegion());
00822     TopKey = BindingKey::Make(Top, BindingKey::Default);
00823   }
00824 
00825   // Find the length (in bits) of the region being invalidated.
00826   uint64_t Length = UINT64_MAX;
00827   SVal Extent = Top->getExtent(SVB);
00828   if (Optional<nonloc::ConcreteInt> ExtentCI =
00829           Extent.getAs<nonloc::ConcreteInt>()) {
00830     const llvm::APSInt &ExtentInt = ExtentCI->getValue();
00831     assert(ExtentInt.isNonNegative() || ExtentInt.isUnsigned());
00832     // Extents are in bytes but region offsets are in bits. Be careful!
00833     Length = ExtentInt.getLimitedValue() * SVB.getContext().getCharWidth();
00834   } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(Top)) {
00835     if (FR->getDecl()->isBitField())
00836       Length = FR->getDecl()->getBitWidthValue(SVB.getContext());
00837   }
00838 
00839   for (ClusterBindings::iterator I = Cluster.begin(), E = Cluster.end();
00840        I != E; ++I) {
00841     BindingKey NextKey = I.getKey();
00842     if (NextKey.getRegion() == TopKey.getRegion()) {
00843       // FIXME: This doesn't catch the case where we're really invalidating a
00844       // region with a symbolic offset. Example:
00845       //      R: points[i].y
00846       //   Next: points[0].x
00847 
00848       if (NextKey.getOffset() > TopKey.getOffset() &&
00849           NextKey.getOffset() - TopKey.getOffset() < Length) {
00850         // Case 1: The next binding is inside the region we're invalidating.
00851         // Include it.
00852         Bindings.push_back(*I);
00853 
00854       } else if (NextKey.getOffset() == TopKey.getOffset()) {
00855         // Case 2: The next binding is at the same offset as the region we're
00856         // invalidating. In this case, we need to leave default bindings alone,
00857         // since they may be providing a default value for a regions beyond what
00858         // we're invalidating.
00859         // FIXME: This is probably incorrect; consider invalidating an outer
00860         // struct whose first field is bound to a LazyCompoundVal.
00861         if (IncludeAllDefaultBindings || NextKey.isDirect())
00862           Bindings.push_back(*I);
00863       }
00864 
00865     } else if (NextKey.hasSymbolicOffset()) {
00866       const MemRegion *Base = NextKey.getConcreteOffsetRegion();
00867       if (Top->isSubRegionOf(Base)) {
00868         // Case 3: The next key is symbolic and we just changed something within
00869         // its concrete region. We don't know if the binding is still valid, so
00870         // we'll be conservative and include it.
00871         if (IncludeAllDefaultBindings || NextKey.isDirect())
00872           if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions))
00873             Bindings.push_back(*I);
00874       } else if (const SubRegion *BaseSR = dyn_cast<SubRegion>(Base)) {
00875         // Case 4: The next key is symbolic, but we changed a known
00876         // super-region. In this case the binding is certainly included.
00877         if (Top == Base || BaseSR->isSubRegionOf(Top))
00878           if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions))
00879             Bindings.push_back(*I);
00880       }
00881     }
00882   }
00883 }
00884 
00885 static void
00886 collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings,
00887                          SValBuilder &SVB, const ClusterBindings &Cluster,
00888                          const SubRegion *Top, bool IncludeAllDefaultBindings) {
00889   collectSubRegionBindings(Bindings, SVB, Cluster, Top,
00890                            BindingKey::Make(Top, BindingKey::Default),
00891                            IncludeAllDefaultBindings);
00892 }
00893 
00894 RegionBindingsRef
00895 RegionStoreManager::removeSubRegionBindings(RegionBindingsConstRef B,
00896                                             const SubRegion *Top) {
00897   BindingKey TopKey = BindingKey::Make(Top, BindingKey::Default);
00898   const MemRegion *ClusterHead = TopKey.getBaseRegion();
00899 
00900   if (Top == ClusterHead) {
00901     // We can remove an entire cluster's bindings all in one go.
00902     return B.remove(Top);
00903   }
00904 
00905   const ClusterBindings *Cluster = B.lookup(ClusterHead);
00906   if (!Cluster) {
00907     // If we're invalidating a region with a symbolic offset, we need to make
00908     // sure we don't treat the base region as uninitialized anymore.
00909     if (TopKey.hasSymbolicOffset()) {
00910       const SubRegion *Concrete = TopKey.getConcreteOffsetRegion();
00911       return B.addBinding(Concrete, BindingKey::Default, UnknownVal());
00912     }
00913     return B;
00914   }
00915 
00916   SmallVector<BindingPair, 32> Bindings;
00917   collectSubRegionBindings(Bindings, svalBuilder, *Cluster, Top, TopKey,
00918                            /*IncludeAllDefaultBindings=*/false);
00919 
00920   ClusterBindingsRef Result(*Cluster, CBFactory);
00921   for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(),
00922                                                     E = Bindings.end();
00923        I != E; ++I)
00924     Result = Result.remove(I->first);
00925 
00926   // If we're invalidating a region with a symbolic offset, we need to make sure
00927   // we don't treat the base region as uninitialized anymore.
00928   // FIXME: This isn't very precise; see the example in
00929   // collectSubRegionBindings.
00930   if (TopKey.hasSymbolicOffset()) {
00931     const SubRegion *Concrete = TopKey.getConcreteOffsetRegion();
00932     Result = Result.add(BindingKey::Make(Concrete, BindingKey::Default),
00933                         UnknownVal());
00934   }
00935 
00936   if (Result.isEmpty())
00937     return B.remove(ClusterHead);
00938   return B.add(ClusterHead, Result.asImmutableMap());
00939 }
00940 
00941 namespace {
00942 class invalidateRegionsWorker : public ClusterAnalysis<invalidateRegionsWorker>
00943 {
00944   const Expr *Ex;
00945   unsigned Count;
00946   const LocationContext *LCtx;
00947   InvalidatedSymbols &IS;
00948   RegionAndSymbolInvalidationTraits &ITraits;
00949   StoreManager::InvalidatedRegions *Regions;
00950 public:
00951   invalidateRegionsWorker(RegionStoreManager &rm,
00952                           ProgramStateManager &stateMgr,
00953                           RegionBindingsRef b,
00954                           const Expr *ex, unsigned count,
00955                           const LocationContext *lctx,
00956                           InvalidatedSymbols &is,
00957                           RegionAndSymbolInvalidationTraits &ITraitsIn,
00958                           StoreManager::InvalidatedRegions *r,
00959                           GlobalsFilterKind GFK)
00960     : ClusterAnalysis<invalidateRegionsWorker>(rm, stateMgr, b, GFK),
00961       Ex(ex), Count(count), LCtx(lctx), IS(is), ITraits(ITraitsIn), Regions(r){}
00962 
00963   void VisitCluster(const MemRegion *baseR, const ClusterBindings *C);
00964   void VisitBinding(SVal V);
00965 };
00966 }
00967 
00968 void invalidateRegionsWorker::VisitBinding(SVal V) {
00969   // A symbol?  Mark it touched by the invalidation.
00970   if (SymbolRef Sym = V.getAsSymbol())
00971     IS.insert(Sym);
00972 
00973   if (const MemRegion *R = V.getAsRegion()) {
00974     AddToWorkList(R);
00975     return;
00976   }
00977 
00978   // Is it a LazyCompoundVal?  All references get invalidated as well.
00979   if (Optional<nonloc::LazyCompoundVal> LCS =
00980           V.getAs<nonloc::LazyCompoundVal>()) {
00981 
00982     const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS);
00983 
00984     for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(),
00985                                                         E = Vals.end();
00986          I != E; ++I)
00987       VisitBinding(*I);
00988 
00989     return;
00990   }
00991 }
00992 
00993 void invalidateRegionsWorker::VisitCluster(const MemRegion *baseR,
00994                                            const ClusterBindings *C) {
00995 
00996   bool PreserveRegionsContents = 
00997       ITraits.hasTrait(baseR, 
00998                        RegionAndSymbolInvalidationTraits::TK_PreserveContents);
00999 
01000   if (C) {
01001     for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I)
01002       VisitBinding(I.getData());
01003 
01004     // Invalidate regions contents.
01005     if (!PreserveRegionsContents)
01006       B = B.remove(baseR);
01007   }
01008 
01009   // BlockDataRegion?  If so, invalidate captured variables that are passed
01010   // by reference.
01011   if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) {
01012     for (BlockDataRegion::referenced_vars_iterator
01013          BI = BR->referenced_vars_begin(), BE = BR->referenced_vars_end() ;
01014          BI != BE; ++BI) {
01015       const VarRegion *VR = BI.getCapturedRegion();
01016       const VarDecl *VD = VR->getDecl();
01017       if (VD->hasAttr<BlocksAttr>() || !VD->hasLocalStorage()) {
01018         AddToWorkList(VR);
01019       }
01020       else if (Loc::isLocType(VR->getValueType())) {
01021         // Map the current bindings to a Store to retrieve the value
01022         // of the binding.  If that binding itself is a region, we should
01023         // invalidate that region.  This is because a block may capture
01024         // a pointer value, but the thing pointed by that pointer may
01025         // get invalidated.
01026         SVal V = RM.getBinding(B, loc::MemRegionVal(VR));
01027         if (Optional<Loc> L = V.getAs<Loc>()) {
01028           if (const MemRegion *LR = L->getAsRegion())
01029             AddToWorkList(LR);
01030         }
01031       }
01032     }
01033     return;
01034   }
01035 
01036   // Symbolic region?
01037   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR))
01038     IS.insert(SR->getSymbol());
01039 
01040   // Nothing else should be done in the case when we preserve regions context.
01041   if (PreserveRegionsContents)
01042     return;
01043 
01044   // Otherwise, we have a normal data region. Record that we touched the region.
01045   if (Regions)
01046     Regions->push_back(baseR);
01047 
01048   if (isa<AllocaRegion>(baseR) || isa<SymbolicRegion>(baseR)) {
01049     // Invalidate the region by setting its default value to
01050     // conjured symbol. The type of the symbol is irrelevant.
01051     DefinedOrUnknownSVal V =
01052       svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count);
01053     B = B.addBinding(baseR, BindingKey::Default, V);
01054     return;
01055   }
01056 
01057   if (!baseR->isBoundable())
01058     return;
01059 
01060   const TypedValueRegion *TR = cast<TypedValueRegion>(baseR);
01061   QualType T = TR->getValueType();
01062 
01063   if (isInitiallyIncludedGlobalRegion(baseR)) {
01064     // If the region is a global and we are invalidating all globals,
01065     // erasing the entry is good enough.  This causes all globals to be lazily
01066     // symbolicated from the same base symbol.
01067     return;
01068   }
01069 
01070   if (T->isStructureOrClassType()) {
01071     // Invalidate the region by setting its default value to
01072     // conjured symbol. The type of the symbol is irrelevant.
01073     DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
01074                                                           Ctx.IntTy, Count);
01075     B = B.addBinding(baseR, BindingKey::Default, V);
01076     return;
01077   }
01078 
01079   if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
01080       // Set the default value of the array to conjured symbol.
01081     DefinedOrUnknownSVal V =
01082     svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
01083                                      AT->getElementType(), Count);
01084     B = B.addBinding(baseR, BindingKey::Default, V);
01085     return;
01086   }
01087 
01088   DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
01089                                                         T,Count);
01090   assert(SymbolManager::canSymbolicate(T) || V.isUnknown());
01091   B = B.addBinding(baseR, BindingKey::Direct, V);
01092 }
01093 
01094 RegionBindingsRef
01095 RegionStoreManager::invalidateGlobalRegion(MemRegion::Kind K,
01096                                            const Expr *Ex,
01097                                            unsigned Count,
01098                                            const LocationContext *LCtx,
01099                                            RegionBindingsRef B,
01100                                            InvalidatedRegions *Invalidated) {
01101   // Bind the globals memory space to a new symbol that we will use to derive
01102   // the bindings for all globals.
01103   const GlobalsSpaceRegion *GS = MRMgr.getGlobalsRegion(K);
01104   SVal V = svalBuilder.conjureSymbolVal(/* SymbolTag = */ (const void*) GS, Ex, LCtx,
01105                                         /* type does not matter */ Ctx.IntTy,
01106                                         Count);
01107 
01108   B = B.removeBinding(GS)
01109        .addBinding(BindingKey::Make(GS, BindingKey::Default), V);
01110 
01111   // Even if there are no bindings in the global scope, we still need to
01112   // record that we touched it.
01113   if (Invalidated)
01114     Invalidated->push_back(GS);
01115 
01116   return B;
01117 }
01118 
01119 void RegionStoreManager::populateWorkList(invalidateRegionsWorker &W,
01120                                           ArrayRef<SVal> Values,
01121                                           InvalidatedRegions *TopLevelRegions) {
01122   for (ArrayRef<SVal>::iterator I = Values.begin(),
01123                                 E = Values.end(); I != E; ++I) {
01124     SVal V = *I;
01125     if (Optional<nonloc::LazyCompoundVal> LCS =
01126         V.getAs<nonloc::LazyCompoundVal>()) {
01127 
01128       const SValListTy &Vals = getInterestingValues(*LCS);
01129 
01130       for (SValListTy::const_iterator I = Vals.begin(),
01131                                       E = Vals.end(); I != E; ++I) {
01132         // Note: the last argument is false here because these are
01133         // non-top-level regions.
01134         if (const MemRegion *R = (*I).getAsRegion())
01135           W.AddToWorkList(R);
01136       }
01137       continue;
01138     }
01139 
01140     if (const MemRegion *R = V.getAsRegion()) {
01141       if (TopLevelRegions)
01142         TopLevelRegions->push_back(R);
01143       W.AddToWorkList(R);
01144       continue;
01145     }
01146   }
01147 }
01148 
01149 StoreRef
01150 RegionStoreManager::invalidateRegions(Store store,
01151                                      ArrayRef<SVal> Values,
01152                                      const Expr *Ex, unsigned Count,
01153                                      const LocationContext *LCtx,
01154                                      const CallEvent *Call,
01155                                      InvalidatedSymbols &IS,
01156                                      RegionAndSymbolInvalidationTraits &ITraits,
01157                                      InvalidatedRegions *TopLevelRegions,
01158                                      InvalidatedRegions *Invalidated) {
01159   GlobalsFilterKind GlobalsFilter;
01160   if (Call) {
01161     if (Call->isInSystemHeader())
01162       GlobalsFilter = GFK_SystemOnly;
01163     else
01164       GlobalsFilter = GFK_All;
01165   } else {
01166     GlobalsFilter = GFK_None;
01167   }
01168 
01169   RegionBindingsRef B = getRegionBindings(store);
01170   invalidateRegionsWorker W(*this, StateMgr, B, Ex, Count, LCtx, IS, ITraits,
01171                             Invalidated, GlobalsFilter);
01172 
01173   // Scan the bindings and generate the clusters.
01174   W.GenerateClusters();
01175 
01176   // Add the regions to the worklist.
01177   populateWorkList(W, Values, TopLevelRegions);
01178 
01179   W.RunWorkList();
01180 
01181   // Return the new bindings.
01182   B = W.getRegionBindings();
01183 
01184   // For calls, determine which global regions should be invalidated and
01185   // invalidate them. (Note that function-static and immutable globals are never
01186   // invalidated by this.)
01187   // TODO: This could possibly be more precise with modules.
01188   switch (GlobalsFilter) {
01189   case GFK_All:
01190     B = invalidateGlobalRegion(MemRegion::GlobalInternalSpaceRegionKind,
01191                                Ex, Count, LCtx, B, Invalidated);
01192     // FALLTHROUGH
01193   case GFK_SystemOnly:
01194     B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind,
01195                                Ex, Count, LCtx, B, Invalidated);
01196     // FALLTHROUGH
01197   case GFK_None:
01198     break;
01199   }
01200 
01201   return StoreRef(B.asStore(), *this);
01202 }
01203 
01204 //===----------------------------------------------------------------------===//
01205 // Extents for regions.
01206 //===----------------------------------------------------------------------===//
01207 
01208 DefinedOrUnknownSVal
01209 RegionStoreManager::getSizeInElements(ProgramStateRef state,
01210                                       const MemRegion *R,
01211                                       QualType EleTy) {
01212   SVal Size = cast<SubRegion>(R)->getExtent(svalBuilder);
01213   const llvm::APSInt *SizeInt = svalBuilder.getKnownValue(state, Size);
01214   if (!SizeInt)
01215     return UnknownVal();
01216 
01217   CharUnits RegionSize = CharUnits::fromQuantity(SizeInt->getSExtValue());
01218 
01219   if (Ctx.getAsVariableArrayType(EleTy)) {
01220     // FIXME: We need to track extra state to properly record the size
01221     // of VLAs.  Returning UnknownVal here, however, is a stop-gap so that
01222     // we don't have a divide-by-zero below.
01223     return UnknownVal();
01224   }
01225 
01226   CharUnits EleSize = Ctx.getTypeSizeInChars(EleTy);
01227 
01228   // If a variable is reinterpreted as a type that doesn't fit into a larger
01229   // type evenly, round it down.
01230   // This is a signed value, since it's used in arithmetic with signed indices.
01231   return svalBuilder.makeIntVal(RegionSize / EleSize, false);
01232 }
01233 
01234 //===----------------------------------------------------------------------===//
01235 // Location and region casting.
01236 //===----------------------------------------------------------------------===//
01237 
01238 /// ArrayToPointer - Emulates the "decay" of an array to a pointer
01239 ///  type.  'Array' represents the lvalue of the array being decayed
01240 ///  to a pointer, and the returned SVal represents the decayed
01241 ///  version of that lvalue (i.e., a pointer to the first element of
01242 ///  the array).  This is called by ExprEngine when evaluating casts
01243 ///  from arrays to pointers.
01244 SVal RegionStoreManager::ArrayToPointer(Loc Array, QualType T) {
01245   if (!Array.getAs<loc::MemRegionVal>())
01246     return UnknownVal();
01247 
01248   const MemRegion* R = Array.castAs<loc::MemRegionVal>().getRegion();
01249   NonLoc ZeroIdx = svalBuilder.makeZeroArrayIndex();
01250   return loc::MemRegionVal(MRMgr.getElementRegion(T, ZeroIdx, R, Ctx));
01251 }
01252 
01253 //===----------------------------------------------------------------------===//
01254 // Loading values from regions.
01255 //===----------------------------------------------------------------------===//
01256 
01257 SVal RegionStoreManager::getBinding(RegionBindingsConstRef B, Loc L, QualType T) {
01258   assert(!L.getAs<UnknownVal>() && "location unknown");
01259   assert(!L.getAs<UndefinedVal>() && "location undefined");
01260 
01261   // For access to concrete addresses, return UnknownVal.  Checks
01262   // for null dereferences (and similar errors) are done by checkers, not
01263   // the Store.
01264   // FIXME: We can consider lazily symbolicating such memory, but we really
01265   // should defer this when we can reason easily about symbolicating arrays
01266   // of bytes.
01267   if (L.getAs<loc::ConcreteInt>()) {
01268     return UnknownVal();
01269   }
01270   if (!L.getAs<loc::MemRegionVal>()) {
01271     return UnknownVal();
01272   }
01273 
01274   const MemRegion *MR = L.castAs<loc::MemRegionVal>().getRegion();
01275 
01276   if (isa<AllocaRegion>(MR) ||
01277       isa<SymbolicRegion>(MR) ||
01278       isa<CodeTextRegion>(MR)) {
01279     if (T.isNull()) {
01280       if (const TypedRegion *TR = dyn_cast<TypedRegion>(MR))
01281         T = TR->getLocationType();
01282       else {
01283         const SymbolicRegion *SR = cast<SymbolicRegion>(MR);
01284         T = SR->getSymbol()->getType();
01285       }
01286     }
01287     MR = GetElementZeroRegion(MR, T);
01288   }
01289 
01290   // FIXME: Perhaps this method should just take a 'const MemRegion*' argument
01291   //  instead of 'Loc', and have the other Loc cases handled at a higher level.
01292   const TypedValueRegion *R = cast<TypedValueRegion>(MR);
01293   QualType RTy = R->getValueType();
01294 
01295   // FIXME: we do not yet model the parts of a complex type, so treat the
01296   // whole thing as "unknown".
01297   if (RTy->isAnyComplexType())
01298     return UnknownVal();
01299 
01300   // FIXME: We should eventually handle funny addressing.  e.g.:
01301   //
01302   //   int x = ...;
01303   //   int *p = &x;
01304   //   char *q = (char*) p;
01305   //   char c = *q;  // returns the first byte of 'x'.
01306   //
01307   // Such funny addressing will occur due to layering of regions.
01308   if (RTy->isStructureOrClassType())
01309     return getBindingForStruct(B, R);
01310 
01311   // FIXME: Handle unions.
01312   if (RTy->isUnionType())
01313     return createLazyBinding(B, R);
01314 
01315   if (RTy->isArrayType()) {
01316     if (RTy->isConstantArrayType())
01317       return getBindingForArray(B, R);
01318     else
01319       return UnknownVal();
01320   }
01321 
01322   // FIXME: handle Vector types.
01323   if (RTy->isVectorType())
01324     return UnknownVal();
01325 
01326   if (const FieldRegion* FR = dyn_cast<FieldRegion>(R))
01327     return CastRetrievedVal(getBindingForField(B, FR), FR, T, false);
01328 
01329   if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) {
01330     // FIXME: Here we actually perform an implicit conversion from the loaded
01331     // value to the element type.  Eventually we want to compose these values
01332     // more intelligently.  For example, an 'element' can encompass multiple
01333     // bound regions (e.g., several bound bytes), or could be a subset of
01334     // a larger value.
01335     return CastRetrievedVal(getBindingForElement(B, ER), ER, T, false);
01336   }
01337 
01338   if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) {
01339     // FIXME: Here we actually perform an implicit conversion from the loaded
01340     // value to the ivar type.  What we should model is stores to ivars
01341     // that blow past the extent of the ivar.  If the address of the ivar is
01342     // reinterpretted, it is possible we stored a different value that could
01343     // fit within the ivar.  Either we need to cast these when storing them
01344     // or reinterpret them lazily (as we do here).
01345     return CastRetrievedVal(getBindingForObjCIvar(B, IVR), IVR, T, false);
01346   }
01347 
01348   if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
01349     // FIXME: Here we actually perform an implicit conversion from the loaded
01350     // value to the variable type.  What we should model is stores to variables
01351     // that blow past the extent of the variable.  If the address of the
01352     // variable is reinterpretted, it is possible we stored a different value
01353     // that could fit within the variable.  Either we need to cast these when
01354     // storing them or reinterpret them lazily (as we do here).
01355     return CastRetrievedVal(getBindingForVar(B, VR), VR, T, false);
01356   }
01357 
01358   const SVal *V = B.lookup(R, BindingKey::Direct);
01359 
01360   // Check if the region has a binding.
01361   if (V)
01362     return *V;
01363 
01364   // The location does not have a bound value.  This means that it has
01365   // the value it had upon its creation and/or entry to the analyzed
01366   // function/method.  These are either symbolic values or 'undefined'.
01367   if (R->hasStackNonParametersStorage()) {
01368     // All stack variables are considered to have undefined values
01369     // upon creation.  All heap allocated blocks are considered to
01370     // have undefined values as well unless they are explicitly bound
01371     // to specific values.
01372     return UndefinedVal();
01373   }
01374 
01375   // All other values are symbolic.
01376   return svalBuilder.getRegionValueSymbolVal(R);
01377 }
01378 
01379 static QualType getUnderlyingType(const SubRegion *R) {
01380   QualType RegionTy;
01381   if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(R))
01382     RegionTy = TVR->getValueType();
01383 
01384   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
01385     RegionTy = SR->getSymbol()->getType();
01386 
01387   return RegionTy;
01388 }
01389 
01390 /// Checks to see if store \p B has a lazy binding for region \p R.
01391 ///
01392 /// If \p AllowSubregionBindings is \c false, a lazy binding will be rejected
01393 /// if there are additional bindings within \p R.
01394 ///
01395 /// Note that unlike RegionStoreManager::findLazyBinding, this will not search
01396 /// for lazy bindings for super-regions of \p R.
01397 static Optional<nonloc::LazyCompoundVal>
01398 getExistingLazyBinding(SValBuilder &SVB, RegionBindingsConstRef B,
01399                        const SubRegion *R, bool AllowSubregionBindings) {
01400   Optional<SVal> V = B.getDefaultBinding(R);
01401   if (!V)
01402     return None;
01403 
01404   Optional<nonloc::LazyCompoundVal> LCV = V->getAs<nonloc::LazyCompoundVal>();
01405   if (!LCV)
01406     return None;
01407 
01408   // If the LCV is for a subregion, the types might not match, and we shouldn't
01409   // reuse the binding.
01410   QualType RegionTy = getUnderlyingType(R);
01411   if (!RegionTy.isNull() &&
01412       !RegionTy->isVoidPointerType()) {
01413     QualType SourceRegionTy = LCV->getRegion()->getValueType();
01414     if (!SVB.getContext().hasSameUnqualifiedType(RegionTy, SourceRegionTy))
01415       return None;
01416   }
01417 
01418   if (!AllowSubregionBindings) {
01419     // If there are any other bindings within this region, we shouldn't reuse
01420     // the top-level binding.
01421     SmallVector<BindingPair, 16> Bindings;
01422     collectSubRegionBindings(Bindings, SVB, *B.lookup(R->getBaseRegion()), R,
01423                              /*IncludeAllDefaultBindings=*/true);
01424     if (Bindings.size() > 1)
01425       return None;
01426   }
01427 
01428   return *LCV;
01429 }
01430 
01431 
01432 std::pair<Store, const SubRegion *>
01433 RegionStoreManager::findLazyBinding(RegionBindingsConstRef B,
01434                                    const SubRegion *R,
01435                                    const SubRegion *originalRegion) {
01436   if (originalRegion != R) {
01437     if (Optional<nonloc::LazyCompoundVal> V =
01438           getExistingLazyBinding(svalBuilder, B, R, true))
01439       return std::make_pair(V->getStore(), V->getRegion());
01440   }
01441 
01442   typedef std::pair<Store, const SubRegion *> StoreRegionPair;
01443   StoreRegionPair Result = StoreRegionPair();
01444 
01445   if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
01446     Result = findLazyBinding(B, cast<SubRegion>(ER->getSuperRegion()),
01447                              originalRegion);
01448 
01449     if (Result.second)
01450       Result.second = MRMgr.getElementRegionWithSuper(ER, Result.second);
01451 
01452   } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) {
01453     Result = findLazyBinding(B, cast<SubRegion>(FR->getSuperRegion()),
01454                                        originalRegion);
01455 
01456     if (Result.second)
01457       Result.second = MRMgr.getFieldRegionWithSuper(FR, Result.second);
01458 
01459   } else if (const CXXBaseObjectRegion *BaseReg =
01460                dyn_cast<CXXBaseObjectRegion>(R)) {
01461     // C++ base object region is another kind of region that we should blast
01462     // through to look for lazy compound value. It is like a field region.
01463     Result = findLazyBinding(B, cast<SubRegion>(BaseReg->getSuperRegion()),
01464                              originalRegion);
01465     
01466     if (Result.second)
01467       Result.second = MRMgr.getCXXBaseObjectRegionWithSuper(BaseReg,
01468                                                             Result.second);
01469   }
01470 
01471   return Result;
01472 }
01473 
01474 SVal RegionStoreManager::getBindingForElement(RegionBindingsConstRef B,
01475                                               const ElementRegion* R) {
01476   // We do not currently model bindings of the CompoundLiteralregion.
01477   if (isa<CompoundLiteralRegion>(R->getBaseRegion()))
01478     return UnknownVal();
01479 
01480   // Check if the region has a binding.
01481   if (const Optional<SVal> &V = B.getDirectBinding(R))
01482     return *V;
01483 
01484   const MemRegion* superR = R->getSuperRegion();
01485 
01486   // Check if the region is an element region of a string literal.
01487   if (const StringRegion *StrR=dyn_cast<StringRegion>(superR)) {
01488     // FIXME: Handle loads from strings where the literal is treated as
01489     // an integer, e.g., *((unsigned int*)"hello")
01490     QualType T = Ctx.getAsArrayType(StrR->getValueType())->getElementType();
01491     if (!Ctx.hasSameUnqualifiedType(T, R->getElementType()))
01492       return UnknownVal();
01493 
01494     const StringLiteral *Str = StrR->getStringLiteral();
01495     SVal Idx = R->getIndex();
01496     if (Optional<nonloc::ConcreteInt> CI = Idx.getAs<nonloc::ConcreteInt>()) {
01497       int64_t i = CI->getValue().getSExtValue();
01498       // Abort on string underrun.  This can be possible by arbitrary
01499       // clients of getBindingForElement().
01500       if (i < 0)
01501         return UndefinedVal();
01502       int64_t length = Str->getLength();
01503       // Technically, only i == length is guaranteed to be null.
01504       // However, such overflows should be caught before reaching this point;
01505       // the only time such an access would be made is if a string literal was
01506       // used to initialize a larger array.
01507       char c = (i >= length) ? '\0' : Str->getCodeUnit(i);
01508       return svalBuilder.makeIntVal(c, T);
01509     }
01510   }
01511   
01512   // Check for loads from a code text region.  For such loads, just give up.
01513   if (isa<CodeTextRegion>(superR))
01514     return UnknownVal();
01515 
01516   // Handle the case where we are indexing into a larger scalar object.
01517   // For example, this handles:
01518   //   int x = ...
01519   //   char *y = &x;
01520   //   return *y;
01521   // FIXME: This is a hack, and doesn't do anything really intelligent yet.
01522   const RegionRawOffset &O = R->getAsArrayOffset();
01523   
01524   // If we cannot reason about the offset, return an unknown value.
01525   if (!O.getRegion())
01526     return UnknownVal();
01527   
01528   if (const TypedValueRegion *baseR = 
01529         dyn_cast_or_null<TypedValueRegion>(O.getRegion())) {
01530     QualType baseT = baseR->getValueType();
01531     if (baseT->isScalarType()) {
01532       QualType elemT = R->getElementType();
01533       if (elemT->isScalarType()) {
01534         if (Ctx.getTypeSizeInChars(baseT) >= Ctx.getTypeSizeInChars(elemT)) {
01535           if (const Optional<SVal> &V = B.getDirectBinding(superR)) {
01536             if (SymbolRef parentSym = V->getAsSymbol())
01537               return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
01538 
01539             if (V->isUnknownOrUndef())
01540               return *V;
01541             // Other cases: give up.  We are indexing into a larger object
01542             // that has some value, but we don't know how to handle that yet.
01543             return UnknownVal();
01544           }
01545         }
01546       }
01547     }
01548   }
01549   return getBindingForFieldOrElementCommon(B, R, R->getElementType());
01550 }
01551 
01552 SVal RegionStoreManager::getBindingForField(RegionBindingsConstRef B,
01553                                             const FieldRegion* R) {
01554 
01555   // Check if the region has a binding.
01556   if (const Optional<SVal> &V = B.getDirectBinding(R))
01557     return *V;
01558 
01559   QualType Ty = R->getValueType();
01560   return getBindingForFieldOrElementCommon(B, R, Ty);
01561 }
01562 
01563 Optional<SVal>
01564 RegionStoreManager::getBindingForDerivedDefaultValue(RegionBindingsConstRef B,
01565                                                      const MemRegion *superR,
01566                                                      const TypedValueRegion *R,
01567                                                      QualType Ty) {
01568 
01569   if (const Optional<SVal> &D = B.getDefaultBinding(superR)) {
01570     const SVal &val = D.getValue();
01571     if (SymbolRef parentSym = val.getAsSymbol())
01572       return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
01573 
01574     if (val.isZeroConstant())
01575       return svalBuilder.makeZeroVal(Ty);
01576 
01577     if (val.isUnknownOrUndef())
01578       return val;
01579 
01580     // Lazy bindings are usually handled through getExistingLazyBinding().
01581     // We should unify these two code paths at some point.
01582     if (val.getAs<nonloc::LazyCompoundVal>())
01583       return val;
01584 
01585     llvm_unreachable("Unknown default value");
01586   }
01587 
01588   return None;
01589 }
01590 
01591 SVal RegionStoreManager::getLazyBinding(const SubRegion *LazyBindingRegion,
01592                                         RegionBindingsRef LazyBinding) {
01593   SVal Result;
01594   if (const ElementRegion *ER = dyn_cast<ElementRegion>(LazyBindingRegion))
01595     Result = getBindingForElement(LazyBinding, ER);
01596   else
01597     Result = getBindingForField(LazyBinding,
01598                                 cast<FieldRegion>(LazyBindingRegion));
01599 
01600   // FIXME: This is a hack to deal with RegionStore's inability to distinguish a
01601   // default value for /part/ of an aggregate from a default value for the
01602   // /entire/ aggregate. The most common case of this is when struct Outer
01603   // has as its first member a struct Inner, which is copied in from a stack
01604   // variable. In this case, even if the Outer's default value is symbolic, 0,
01605   // or unknown, it gets overridden by the Inner's default value of undefined.
01606   //
01607   // This is a general problem -- if the Inner is zero-initialized, the Outer
01608   // will now look zero-initialized. The proper way to solve this is with a
01609   // new version of RegionStore that tracks the extent of a binding as well
01610   // as the offset.
01611   //
01612   // This hack only takes care of the undefined case because that can very
01613   // quickly result in a warning.
01614   if (Result.isUndef())
01615     Result = UnknownVal();
01616 
01617   return Result;
01618 }
01619                                         
01620 SVal
01621 RegionStoreManager::getBindingForFieldOrElementCommon(RegionBindingsConstRef B,
01622                                                       const TypedValueRegion *R,
01623                                                       QualType Ty) {
01624 
01625   // At this point we have already checked in either getBindingForElement or
01626   // getBindingForField if 'R' has a direct binding.
01627 
01628   // Lazy binding?
01629   Store lazyBindingStore = nullptr;
01630   const SubRegion *lazyBindingRegion = nullptr;
01631   std::tie(lazyBindingStore, lazyBindingRegion) = findLazyBinding(B, R, R);
01632   if (lazyBindingRegion)
01633     return getLazyBinding(lazyBindingRegion,
01634                           getRegionBindings(lazyBindingStore));
01635 
01636   // Record whether or not we see a symbolic index.  That can completely
01637   // be out of scope of our lookup.
01638   bool hasSymbolicIndex = false;
01639 
01640   // FIXME: This is a hack to deal with RegionStore's inability to distinguish a
01641   // default value for /part/ of an aggregate from a default value for the
01642   // /entire/ aggregate. The most common case of this is when struct Outer
01643   // has as its first member a struct Inner, which is copied in from a stack
01644   // variable. In this case, even if the Outer's default value is symbolic, 0,
01645   // or unknown, it gets overridden by the Inner's default value of undefined.
01646   //
01647   // This is a general problem -- if the Inner is zero-initialized, the Outer
01648   // will now look zero-initialized. The proper way to solve this is with a
01649   // new version of RegionStore that tracks the extent of a binding as well
01650   // as the offset.
01651   //
01652   // This hack only takes care of the undefined case because that can very
01653   // quickly result in a warning.
01654   bool hasPartialLazyBinding = false;
01655 
01656   const SubRegion *SR = dyn_cast<SubRegion>(R);
01657   while (SR) {
01658     const MemRegion *Base = SR->getSuperRegion();
01659     if (Optional<SVal> D = getBindingForDerivedDefaultValue(B, Base, R, Ty)) {
01660       if (D->getAs<nonloc::LazyCompoundVal>()) {
01661         hasPartialLazyBinding = true;
01662         break;
01663       }
01664 
01665       return *D;
01666     }
01667 
01668     if (const ElementRegion *ER = dyn_cast<ElementRegion>(Base)) {
01669       NonLoc index = ER->getIndex();
01670       if (!index.isConstant())
01671         hasSymbolicIndex = true;
01672     }
01673     
01674     // If our super region is a field or element itself, walk up the region
01675     // hierarchy to see if there is a default value installed in an ancestor.
01676     SR = dyn_cast<SubRegion>(Base);
01677   }
01678 
01679   if (R->hasStackNonParametersStorage()) {
01680     if (isa<ElementRegion>(R)) {
01681       // Currently we don't reason specially about Clang-style vectors.  Check
01682       // if superR is a vector and if so return Unknown.
01683       if (const TypedValueRegion *typedSuperR = 
01684             dyn_cast<TypedValueRegion>(R->getSuperRegion())) {
01685         if (typedSuperR->getValueType()->isVectorType())
01686           return UnknownVal();
01687       }
01688     }
01689 
01690     // FIXME: We also need to take ElementRegions with symbolic indexes into
01691     // account.  This case handles both directly accessing an ElementRegion
01692     // with a symbolic offset, but also fields within an element with
01693     // a symbolic offset.
01694     if (hasSymbolicIndex)
01695       return UnknownVal();
01696 
01697     if (!hasPartialLazyBinding)
01698       return UndefinedVal();
01699   }
01700 
01701   // All other values are symbolic.
01702   return svalBuilder.getRegionValueSymbolVal(R);
01703 }
01704 
01705 SVal RegionStoreManager::getBindingForObjCIvar(RegionBindingsConstRef B,
01706                                                const ObjCIvarRegion* R) {
01707   // Check if the region has a binding.
01708   if (const Optional<SVal> &V = B.getDirectBinding(R))
01709     return *V;
01710 
01711   const MemRegion *superR = R->getSuperRegion();
01712 
01713   // Check if the super region has a default binding.
01714   if (const Optional<SVal> &V = B.getDefaultBinding(superR)) {
01715     if (SymbolRef parentSym = V->getAsSymbol())
01716       return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
01717 
01718     // Other cases: give up.
01719     return UnknownVal();
01720   }
01721 
01722   return getBindingForLazySymbol(R);
01723 }
01724 
01725 SVal RegionStoreManager::getBindingForVar(RegionBindingsConstRef B,
01726                                           const VarRegion *R) {
01727 
01728   // Check if the region has a binding.
01729   if (const Optional<SVal> &V = B.getDirectBinding(R))
01730     return *V;
01731 
01732   // Lazily derive a value for the VarRegion.
01733   const VarDecl *VD = R->getDecl();
01734   const MemSpaceRegion *MS = R->getMemorySpace();
01735 
01736   // Arguments are always symbolic.
01737   if (isa<StackArgumentsSpaceRegion>(MS))
01738     return svalBuilder.getRegionValueSymbolVal(R);
01739 
01740   // Is 'VD' declared constant?  If so, retrieve the constant value.
01741   if (VD->getType().isConstQualified())
01742     if (const Expr *Init = VD->getInit())
01743       if (Optional<SVal> V = svalBuilder.getConstantVal(Init))
01744         return *V;
01745 
01746   // This must come after the check for constants because closure-captured
01747   // constant variables may appear in UnknownSpaceRegion.
01748   if (isa<UnknownSpaceRegion>(MS))
01749     return svalBuilder.getRegionValueSymbolVal(R);
01750 
01751   if (isa<GlobalsSpaceRegion>(MS)) {
01752     QualType T = VD->getType();
01753 
01754     // Function-scoped static variables are default-initialized to 0; if they
01755     // have an initializer, it would have been processed by now.
01756     if (isa<StaticGlobalSpaceRegion>(MS))
01757       return svalBuilder.makeZeroVal(T);
01758 
01759     if (Optional<SVal> V = getBindingForDerivedDefaultValue(B, MS, R, T)) {
01760       assert(!V->getAs<nonloc::LazyCompoundVal>());
01761       return V.getValue();
01762     }
01763 
01764     return svalBuilder.getRegionValueSymbolVal(R);
01765   }
01766 
01767   return UndefinedVal();
01768 }
01769 
01770 SVal RegionStoreManager::getBindingForLazySymbol(const TypedValueRegion *R) {
01771   // All other values are symbolic.
01772   return svalBuilder.getRegionValueSymbolVal(R);
01773 }
01774 
01775 const RegionStoreManager::SValListTy &
01776 RegionStoreManager::getInterestingValues(nonloc::LazyCompoundVal LCV) {
01777   // First, check the cache.
01778   LazyBindingsMapTy::iterator I = LazyBindingsMap.find(LCV.getCVData());
01779   if (I != LazyBindingsMap.end())
01780     return I->second;
01781 
01782   // If we don't have a list of values cached, start constructing it.
01783   SValListTy List;
01784 
01785   const SubRegion *LazyR = LCV.getRegion();
01786   RegionBindingsRef B = getRegionBindings(LCV.getStore());
01787 
01788   // If this region had /no/ bindings at the time, there are no interesting
01789   // values to return.
01790   const ClusterBindings *Cluster = B.lookup(LazyR->getBaseRegion());
01791   if (!Cluster)
01792     return (LazyBindingsMap[LCV.getCVData()] = std::move(List));
01793 
01794   SmallVector<BindingPair, 32> Bindings;
01795   collectSubRegionBindings(Bindings, svalBuilder, *Cluster, LazyR,
01796                            /*IncludeAllDefaultBindings=*/true);
01797   for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(),
01798                                                     E = Bindings.end();
01799        I != E; ++I) {
01800     SVal V = I->second;
01801     if (V.isUnknownOrUndef() || V.isConstant())
01802       continue;
01803 
01804     if (Optional<nonloc::LazyCompoundVal> InnerLCV =
01805             V.getAs<nonloc::LazyCompoundVal>()) {
01806       const SValListTy &InnerList = getInterestingValues(*InnerLCV);
01807       List.insert(List.end(), InnerList.begin(), InnerList.end());
01808       continue;
01809     }
01810     
01811     List.push_back(V);
01812   }
01813 
01814   return (LazyBindingsMap[LCV.getCVData()] = std::move(List));
01815 }
01816 
01817 NonLoc RegionStoreManager::createLazyBinding(RegionBindingsConstRef B,
01818                                              const TypedValueRegion *R) {
01819   if (Optional<nonloc::LazyCompoundVal> V =
01820         getExistingLazyBinding(svalBuilder, B, R, false))
01821     return *V;
01822 
01823   return svalBuilder.makeLazyCompoundVal(StoreRef(B.asStore(), *this), R);
01824 }
01825 
01826 static bool isRecordEmpty(const RecordDecl *RD) {
01827   if (!RD->field_empty())
01828     return false;
01829   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD))
01830     return CRD->getNumBases() == 0;
01831   return true;
01832 }
01833 
01834 SVal RegionStoreManager::getBindingForStruct(RegionBindingsConstRef B,
01835                                              const TypedValueRegion *R) {
01836   const RecordDecl *RD = R->getValueType()->castAs<RecordType>()->getDecl();
01837   if (!RD->getDefinition() || isRecordEmpty(RD))
01838     return UnknownVal();
01839 
01840   return createLazyBinding(B, R);
01841 }
01842 
01843 SVal RegionStoreManager::getBindingForArray(RegionBindingsConstRef B,
01844                                             const TypedValueRegion *R) {
01845   assert(Ctx.getAsConstantArrayType(R->getValueType()) &&
01846          "Only constant array types can have compound bindings.");
01847   
01848   return createLazyBinding(B, R);
01849 }
01850 
01851 bool RegionStoreManager::includedInBindings(Store store,
01852                                             const MemRegion *region) const {
01853   RegionBindingsRef B = getRegionBindings(store);
01854   region = region->getBaseRegion();
01855 
01856   // Quick path: if the base is the head of a cluster, the region is live.
01857   if (B.lookup(region))
01858     return true;
01859 
01860   // Slow path: if the region is the VALUE of any binding, it is live.
01861   for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI) {
01862     const ClusterBindings &Cluster = RI.getData();
01863     for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
01864          CI != CE; ++CI) {
01865       const SVal &D = CI.getData();
01866       if (const MemRegion *R = D.getAsRegion())
01867         if (R->getBaseRegion() == region)
01868           return true;
01869     }
01870   }
01871 
01872   return false;
01873 }
01874 
01875 //===----------------------------------------------------------------------===//
01876 // Binding values to regions.
01877 //===----------------------------------------------------------------------===//
01878 
01879 StoreRef RegionStoreManager::killBinding(Store ST, Loc L) {
01880   if (Optional<loc::MemRegionVal> LV = L.getAs<loc::MemRegionVal>())
01881     if (const MemRegion* R = LV->getRegion())
01882       return StoreRef(getRegionBindings(ST).removeBinding(R)
01883                                            .asImmutableMap()
01884                                            .getRootWithoutRetain(),
01885                       *this);
01886 
01887   return StoreRef(ST, *this);
01888 }
01889 
01890 RegionBindingsRef
01891 RegionStoreManager::bind(RegionBindingsConstRef B, Loc L, SVal V) {
01892   if (L.getAs<loc::ConcreteInt>())
01893     return B;
01894 
01895   // If we get here, the location should be a region.
01896   const MemRegion *R = L.castAs<loc::MemRegionVal>().getRegion();
01897 
01898   // Check if the region is a struct region.
01899   if (const TypedValueRegion* TR = dyn_cast<TypedValueRegion>(R)) {
01900     QualType Ty = TR->getValueType();
01901     if (Ty->isArrayType())
01902       return bindArray(B, TR, V);
01903     if (Ty->isStructureOrClassType())
01904       return bindStruct(B, TR, V);
01905     if (Ty->isVectorType())
01906       return bindVector(B, TR, V);
01907     if (Ty->isUnionType())
01908       return bindAggregate(B, TR, V);
01909   }
01910 
01911   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) {
01912     // Binding directly to a symbolic region should be treated as binding
01913     // to element 0.
01914     QualType T = SR->getSymbol()->getType();
01915     if (T->isAnyPointerType() || T->isReferenceType())
01916       T = T->getPointeeType();
01917 
01918     R = GetElementZeroRegion(SR, T);
01919   }
01920 
01921   // Clear out bindings that may overlap with this binding.
01922   RegionBindingsRef NewB = removeSubRegionBindings(B, cast<SubRegion>(R));
01923   return NewB.addBinding(BindingKey::Make(R, BindingKey::Direct), V);
01924 }
01925 
01926 RegionBindingsRef
01927 RegionStoreManager::setImplicitDefaultValue(RegionBindingsConstRef B,
01928                                             const MemRegion *R,
01929                                             QualType T) {
01930   SVal V;
01931 
01932   if (Loc::isLocType(T))
01933     V = svalBuilder.makeNull();
01934   else if (T->isIntegralOrEnumerationType())
01935     V = svalBuilder.makeZeroVal(T);
01936   else if (T->isStructureOrClassType() || T->isArrayType()) {
01937     // Set the default value to a zero constant when it is a structure
01938     // or array.  The type doesn't really matter.
01939     V = svalBuilder.makeZeroVal(Ctx.IntTy);
01940   }
01941   else {
01942     // We can't represent values of this type, but we still need to set a value
01943     // to record that the region has been initialized.
01944     // If this assertion ever fires, a new case should be added above -- we
01945     // should know how to default-initialize any value we can symbolicate.
01946     assert(!SymbolManager::canSymbolicate(T) && "This type is representable");
01947     V = UnknownVal();
01948   }
01949 
01950   return B.addBinding(R, BindingKey::Default, V);
01951 }
01952 
01953 RegionBindingsRef
01954 RegionStoreManager::bindArray(RegionBindingsConstRef B,
01955                               const TypedValueRegion* R,
01956                               SVal Init) {
01957 
01958   const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType()));
01959   QualType ElementTy = AT->getElementType();
01960   Optional<uint64_t> Size;
01961 
01962   if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT))
01963     Size = CAT->getSize().getZExtValue();
01964 
01965   // Check if the init expr is a string literal.
01966   if (Optional<loc::MemRegionVal> MRV = Init.getAs<loc::MemRegionVal>()) {
01967     const StringRegion *S = cast<StringRegion>(MRV->getRegion());
01968 
01969     // Treat the string as a lazy compound value.
01970     StoreRef store(B.asStore(), *this);
01971     nonloc::LazyCompoundVal LCV = svalBuilder.makeLazyCompoundVal(store, S)
01972         .castAs<nonloc::LazyCompoundVal>();
01973     return bindAggregate(B, R, LCV);
01974   }
01975 
01976   // Handle lazy compound values.
01977   if (Init.getAs<nonloc::LazyCompoundVal>())
01978     return bindAggregate(B, R, Init);
01979 
01980   // Remaining case: explicit compound values.
01981 
01982   if (Init.isUnknown())
01983     return setImplicitDefaultValue(B, R, ElementTy);
01984 
01985   const nonloc::CompoundVal& CV = Init.castAs<nonloc::CompoundVal>();
01986   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
01987   uint64_t i = 0;
01988 
01989   RegionBindingsRef NewB(B);
01990 
01991   for (; Size.hasValue() ? i < Size.getValue() : true ; ++i, ++VI) {
01992     // The init list might be shorter than the array length.
01993     if (VI == VE)
01994       break;
01995 
01996     const NonLoc &Idx = svalBuilder.makeArrayIndex(i);
01997     const ElementRegion *ER = MRMgr.getElementRegion(ElementTy, Idx, R, Ctx);
01998 
01999     if (ElementTy->isStructureOrClassType())
02000       NewB = bindStruct(NewB, ER, *VI);
02001     else if (ElementTy->isArrayType())
02002       NewB = bindArray(NewB, ER, *VI);
02003     else
02004       NewB = bind(NewB, loc::MemRegionVal(ER), *VI);
02005   }
02006 
02007   // If the init list is shorter than the array length, set the
02008   // array default value.
02009   if (Size.hasValue() && i < Size.getValue())
02010     NewB = setImplicitDefaultValue(NewB, R, ElementTy);
02011 
02012   return NewB;
02013 }
02014 
02015 RegionBindingsRef RegionStoreManager::bindVector(RegionBindingsConstRef B,
02016                                                  const TypedValueRegion* R,
02017                                                  SVal V) {
02018   QualType T = R->getValueType();
02019   assert(T->isVectorType());
02020   const VectorType *VT = T->getAs<VectorType>(); // Use getAs for typedefs.
02021  
02022   // Handle lazy compound values and symbolic values.
02023   if (V.getAs<nonloc::LazyCompoundVal>() || V.getAs<nonloc::SymbolVal>())
02024     return bindAggregate(B, R, V);
02025   
02026   // We may get non-CompoundVal accidentally due to imprecise cast logic or
02027   // that we are binding symbolic struct value. Kill the field values, and if
02028   // the value is symbolic go and bind it as a "default" binding.
02029   if (!V.getAs<nonloc::CompoundVal>()) {
02030     return bindAggregate(B, R, UnknownVal());
02031   }
02032 
02033   QualType ElemType = VT->getElementType();
02034   nonloc::CompoundVal CV = V.castAs<nonloc::CompoundVal>();
02035   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
02036   unsigned index = 0, numElements = VT->getNumElements();
02037   RegionBindingsRef NewB(B);
02038 
02039   for ( ; index != numElements ; ++index) {
02040     if (VI == VE)
02041       break;
02042     
02043     NonLoc Idx = svalBuilder.makeArrayIndex(index);
02044     const ElementRegion *ER = MRMgr.getElementRegion(ElemType, Idx, R, Ctx);
02045 
02046     if (ElemType->isArrayType())
02047       NewB = bindArray(NewB, ER, *VI);
02048     else if (ElemType->isStructureOrClassType())
02049       NewB = bindStruct(NewB, ER, *VI);
02050     else
02051       NewB = bind(NewB, loc::MemRegionVal(ER), *VI);
02052   }
02053   return NewB;
02054 }
02055 
02056 Optional<RegionBindingsRef>
02057 RegionStoreManager::tryBindSmallStruct(RegionBindingsConstRef B,
02058                                        const TypedValueRegion *R,
02059                                        const RecordDecl *RD,
02060                                        nonloc::LazyCompoundVal LCV) {
02061   FieldVector Fields;
02062 
02063   if (const CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(RD))
02064     if (Class->getNumBases() != 0 || Class->getNumVBases() != 0)
02065       return None;
02066 
02067   for (const auto *FD : RD->fields()) {
02068     if (FD->isUnnamedBitfield())
02069       continue;
02070 
02071     // If there are too many fields, or if any of the fields are aggregates,
02072     // just use the LCV as a default binding.
02073     if (Fields.size() == SmallStructLimit)
02074       return None;
02075 
02076     QualType Ty = FD->getType();
02077     if (!(Ty->isScalarType() || Ty->isReferenceType()))
02078       return None;
02079 
02080     Fields.push_back(FD);
02081   }
02082 
02083   RegionBindingsRef NewB = B;
02084   
02085   for (FieldVector::iterator I = Fields.begin(), E = Fields.end(); I != E; ++I){
02086     const FieldRegion *SourceFR = MRMgr.getFieldRegion(*I, LCV.getRegion());
02087     SVal V = getBindingForField(getRegionBindings(LCV.getStore()), SourceFR);
02088 
02089     const FieldRegion *DestFR = MRMgr.getFieldRegion(*I, R);
02090     NewB = bind(NewB, loc::MemRegionVal(DestFR), V);
02091   }
02092 
02093   return NewB;
02094 }
02095 
02096 RegionBindingsRef RegionStoreManager::bindStruct(RegionBindingsConstRef B,
02097                                                  const TypedValueRegion* R,
02098                                                  SVal V) {
02099   if (!Features.supportsFields())
02100     return B;
02101 
02102   QualType T = R->getValueType();
02103   assert(T->isStructureOrClassType());
02104 
02105   const RecordType* RT = T->getAs<RecordType>();
02106   const RecordDecl *RD = RT->getDecl();
02107 
02108   if (!RD->isCompleteDefinition())
02109     return B;
02110 
02111   // Handle lazy compound values and symbolic values.
02112   if (Optional<nonloc::LazyCompoundVal> LCV =
02113         V.getAs<nonloc::LazyCompoundVal>()) {
02114     if (Optional<RegionBindingsRef> NewB = tryBindSmallStruct(B, R, RD, *LCV))
02115       return *NewB;
02116     return bindAggregate(B, R, V);
02117   }
02118   if (V.getAs<nonloc::SymbolVal>())
02119     return bindAggregate(B, R, V);
02120 
02121   // We may get non-CompoundVal accidentally due to imprecise cast logic or
02122   // that we are binding symbolic struct value. Kill the field values, and if
02123   // the value is symbolic go and bind it as a "default" binding.
02124   if (V.isUnknown() || !V.getAs<nonloc::CompoundVal>())
02125     return bindAggregate(B, R, UnknownVal());
02126 
02127   const nonloc::CompoundVal& CV = V.castAs<nonloc::CompoundVal>();
02128   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
02129 
02130   RecordDecl::field_iterator FI, FE;
02131   RegionBindingsRef NewB(B);
02132 
02133   for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; ++FI) {
02134 
02135     if (VI == VE)
02136       break;
02137 
02138     // Skip any unnamed bitfields to stay in sync with the initializers.
02139     if (FI->isUnnamedBitfield())
02140       continue;
02141 
02142     QualType FTy = FI->getType();
02143     const FieldRegion* FR = MRMgr.getFieldRegion(*FI, R);
02144 
02145     if (FTy->isArrayType())
02146       NewB = bindArray(NewB, FR, *VI);
02147     else if (FTy->isStructureOrClassType())
02148       NewB = bindStruct(NewB, FR, *VI);
02149     else
02150       NewB = bind(NewB, loc::MemRegionVal(FR), *VI);
02151     ++VI;
02152   }
02153 
02154   // There may be fewer values in the initialize list than the fields of struct.
02155   if (FI != FE) {
02156     NewB = NewB.addBinding(R, BindingKey::Default,
02157                            svalBuilder.makeIntVal(0, false));
02158   }
02159 
02160   return NewB;
02161 }
02162 
02163 RegionBindingsRef
02164 RegionStoreManager::bindAggregate(RegionBindingsConstRef B,
02165                                   const TypedRegion *R,
02166                                   SVal Val) {
02167   // Remove the old bindings, using 'R' as the root of all regions
02168   // we will invalidate. Then add the new binding.
02169   return removeSubRegionBindings(B, R).addBinding(R, BindingKey::Default, Val);
02170 }
02171 
02172 //===----------------------------------------------------------------------===//
02173 // State pruning.
02174 //===----------------------------------------------------------------------===//
02175 
02176 namespace {
02177 class removeDeadBindingsWorker :
02178   public ClusterAnalysis<removeDeadBindingsWorker> {
02179   SmallVector<const SymbolicRegion*, 12> Postponed;
02180   SymbolReaper &SymReaper;
02181   const StackFrameContext *CurrentLCtx;
02182 
02183 public:
02184   removeDeadBindingsWorker(RegionStoreManager &rm,
02185                            ProgramStateManager &stateMgr,
02186                            RegionBindingsRef b, SymbolReaper &symReaper,
02187                            const StackFrameContext *LCtx)
02188     : ClusterAnalysis<removeDeadBindingsWorker>(rm, stateMgr, b, GFK_None),
02189       SymReaper(symReaper), CurrentLCtx(LCtx) {}
02190 
02191   // Called by ClusterAnalysis.
02192   void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C);
02193   void VisitCluster(const MemRegion *baseR, const ClusterBindings *C);
02194   using ClusterAnalysis<removeDeadBindingsWorker>::VisitCluster;
02195 
02196   bool UpdatePostponed();
02197   void VisitBinding(SVal V);
02198 };
02199 }
02200 
02201 void removeDeadBindingsWorker::VisitAddedToCluster(const MemRegion *baseR,
02202                                                    const ClusterBindings &C) {
02203 
02204   if (const VarRegion *VR = dyn_cast<VarRegion>(baseR)) {
02205     if (SymReaper.isLive(VR))
02206       AddToWorkList(baseR, &C);
02207 
02208     return;
02209   }
02210 
02211   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) {
02212     if (SymReaper.isLive(SR->getSymbol()))
02213       AddToWorkList(SR, &C);
02214     else
02215       Postponed.push_back(SR);
02216 
02217     return;
02218   }
02219 
02220   if (isa<NonStaticGlobalSpaceRegion>(baseR)) {
02221     AddToWorkList(baseR, &C);
02222     return;
02223   }
02224 
02225   // CXXThisRegion in the current or parent location context is live.
02226   if (const CXXThisRegion *TR = dyn_cast<CXXThisRegion>(baseR)) {
02227     const StackArgumentsSpaceRegion *StackReg =
02228       cast<StackArgumentsSpaceRegion>(TR->getSuperRegion());
02229     const StackFrameContext *RegCtx = StackReg->getStackFrame();
02230     if (CurrentLCtx &&
02231         (RegCtx == CurrentLCtx || RegCtx->isParentOf(CurrentLCtx)))
02232       AddToWorkList(TR, &C);
02233   }
02234 }
02235 
02236 void removeDeadBindingsWorker::VisitCluster(const MemRegion *baseR,
02237                                             const ClusterBindings *C) {
02238   if (!C)
02239     return;
02240 
02241   // Mark the symbol for any SymbolicRegion with live bindings as live itself.
02242   // This means we should continue to track that symbol.
02243   if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(baseR))
02244     SymReaper.markLive(SymR->getSymbol());
02245 
02246   for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I)
02247     VisitBinding(I.getData());
02248 }
02249 
02250 void removeDeadBindingsWorker::VisitBinding(SVal V) {
02251   // Is it a LazyCompoundVal?  All referenced regions are live as well.
02252   if (Optional<nonloc::LazyCompoundVal> LCS =
02253           V.getAs<nonloc::LazyCompoundVal>()) {
02254 
02255     const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS);
02256 
02257     for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(),
02258                                                         E = Vals.end();
02259          I != E; ++I)
02260       VisitBinding(*I);
02261 
02262     return;
02263   }
02264 
02265   // If V is a region, then add it to the worklist.
02266   if (const MemRegion *R = V.getAsRegion()) {
02267     AddToWorkList(R);
02268     
02269     // All regions captured by a block are also live.
02270     if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(R)) {
02271       BlockDataRegion::referenced_vars_iterator I = BR->referenced_vars_begin(),
02272                                                 E = BR->referenced_vars_end();
02273       for ( ; I != E; ++I)
02274         AddToWorkList(I.getCapturedRegion());
02275     }
02276   }
02277     
02278 
02279   // Update the set of live symbols.
02280   for (SymExpr::symbol_iterator SI = V.symbol_begin(), SE = V.symbol_end();
02281        SI!=SE; ++SI)
02282     SymReaper.markLive(*SI);
02283 }
02284 
02285 bool removeDeadBindingsWorker::UpdatePostponed() {
02286   // See if any postponed SymbolicRegions are actually live now, after
02287   // having done a scan.
02288   bool changed = false;
02289 
02290   for (SmallVectorImpl<const SymbolicRegion*>::iterator
02291         I = Postponed.begin(), E = Postponed.end() ; I != E ; ++I) {
02292     if (const SymbolicRegion *SR = *I) {
02293       if (SymReaper.isLive(SR->getSymbol())) {
02294         changed |= AddToWorkList(SR);
02295         *I = nullptr;
02296       }
02297     }
02298   }
02299 
02300   return changed;
02301 }
02302 
02303 StoreRef RegionStoreManager::removeDeadBindings(Store store,
02304                                                 const StackFrameContext *LCtx,
02305                                                 SymbolReaper& SymReaper) {
02306   RegionBindingsRef B = getRegionBindings(store);
02307   removeDeadBindingsWorker W(*this, StateMgr, B, SymReaper, LCtx);
02308   W.GenerateClusters();
02309 
02310   // Enqueue the region roots onto the worklist.
02311   for (SymbolReaper::region_iterator I = SymReaper.region_begin(),
02312        E = SymReaper.region_end(); I != E; ++I) {
02313     W.AddToWorkList(*I);
02314   }
02315 
02316   do W.RunWorkList(); while (W.UpdatePostponed());
02317 
02318   // We have now scanned the store, marking reachable regions and symbols
02319   // as live.  We now remove all the regions that are dead from the store
02320   // as well as update DSymbols with the set symbols that are now dead.
02321   for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; ++I) {
02322     const MemRegion *Base = I.getKey();
02323 
02324     // If the cluster has been visited, we know the region has been marked.
02325     if (W.isVisited(Base))
02326       continue;
02327 
02328     // Remove the dead entry.
02329     B = B.remove(Base);
02330 
02331     if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(Base))
02332       SymReaper.maybeDead(SymR->getSymbol());
02333 
02334     // Mark all non-live symbols that this binding references as dead.
02335     const ClusterBindings &Cluster = I.getData();
02336     for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
02337          CI != CE; ++CI) {
02338       SVal X = CI.getData();
02339       SymExpr::symbol_iterator SI = X.symbol_begin(), SE = X.symbol_end();
02340       for (; SI != SE; ++SI)
02341         SymReaper.maybeDead(*SI);
02342     }
02343   }
02344 
02345   return StoreRef(B.asStore(), *this);
02346 }
02347 
02348 //===----------------------------------------------------------------------===//
02349 // Utility methods.
02350 //===----------------------------------------------------------------------===//
02351 
02352 void RegionStoreManager::print(Store store, raw_ostream &OS,
02353                                const char* nl, const char *sep) {
02354   RegionBindingsRef B = getRegionBindings(store);
02355   OS << "Store (direct and default bindings), "
02356      << B.asStore()
02357      << " :" << nl;
02358   B.dump(OS, nl);
02359 }