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/CharUnits.h"
00018 #include "clang/AST/DeclCXX.h"
00019 #include "clang/AST/ExprCXX.h"
00020 #include "clang/Analysis/Analyses/LiveVariables.h"
00021 #include "clang/Analysis/AnalysisContext.h"
00022 #include "clang/Basic/TargetInfo.h"
00023 #include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
00024 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
00025 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
00026 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
00027 #include "llvm/ADT/ImmutableList.h"
00028 #include "llvm/ADT/ImmutableMap.h"
00029 #include "llvm/ADT/Optional.h"
00030 #include "llvm/Support/raw_ostream.h"
00031 
00032 using namespace clang;
00033 using namespace ento;
00034 using llvm::Optional;
00035 
00036 //===----------------------------------------------------------------------===//
00037 // Representation of binding keys.
00038 //===----------------------------------------------------------------------===//
00039 
00040 namespace {
00041 class BindingKey {
00042 public:
00043   enum Kind { Direct = 0x0, Default = 0x1 };
00044 private:
00045   llvm ::PointerIntPair<const MemRegion*, 1> P;
00046   uint64_t Offset;
00047 
00048   explicit BindingKey(const MemRegion *r, uint64_t offset, Kind k)
00049     : P(r, (unsigned) k), Offset(offset) {}
00050 public:
00051 
00052   bool isDirect() const { return P.getInt() == Direct; }
00053 
00054   const MemRegion *getRegion() const { return P.getPointer(); }
00055   uint64_t getOffset() const { return Offset; }
00056 
00057   void Profile(llvm::FoldingSetNodeID& ID) const {
00058     ID.AddPointer(P.getOpaqueValue());
00059     ID.AddInteger(Offset);
00060   }
00061 
00062   static BindingKey Make(const MemRegion *R, Kind k);
00063 
00064   bool operator<(const BindingKey &X) const {
00065     if (P.getOpaqueValue() < X.P.getOpaqueValue())
00066       return true;
00067     if (P.getOpaqueValue() > X.P.getOpaqueValue())
00068       return false;
00069     return Offset < X.Offset;
00070   }
00071 
00072   bool operator==(const BindingKey &X) const {
00073     return P.getOpaqueValue() == X.P.getOpaqueValue() &&
00074            Offset == X.Offset;
00075   }
00076 
00077   bool isValid() const {
00078     return getRegion() != NULL;
00079   }
00080 };
00081 } // end anonymous namespace
00082 
00083 BindingKey BindingKey::Make(const MemRegion *R, Kind k) {
00084   const RegionOffset &RO = R->getAsOffset();
00085   if (RO.getRegion())
00086     return BindingKey(RO.getRegion(), RO.getOffset(), k);
00087 
00088   return BindingKey(R, 0, k);
00089 }
00090 
00091 namespace llvm {
00092   static inline
00093   raw_ostream &operator<<(raw_ostream &os, BindingKey K) {
00094     os << '(' << K.getRegion() << ',' << K.getOffset()
00095        << ',' << (K.isDirect() ? "direct" : "default")
00096        << ')';
00097     return os;
00098   }
00099 } // end llvm namespace
00100 
00101 //===----------------------------------------------------------------------===//
00102 // Actual Store type.
00103 //===----------------------------------------------------------------------===//
00104 
00105 typedef llvm::ImmutableMap<BindingKey, SVal> RegionBindings;
00106 
00107 //===----------------------------------------------------------------------===//
00108 // Fine-grained control of RegionStoreManager.
00109 //===----------------------------------------------------------------------===//
00110 
00111 namespace {
00112 struct minimal_features_tag {};
00113 struct maximal_features_tag {};
00114 
00115 class RegionStoreFeatures {
00116   bool SupportsFields;
00117 public:
00118   RegionStoreFeatures(minimal_features_tag) :
00119     SupportsFields(false) {}
00120 
00121   RegionStoreFeatures(maximal_features_tag) :
00122     SupportsFields(true) {}
00123 
00124   void enableFields(bool t) { SupportsFields = t; }
00125 
00126   bool supportsFields() const { return SupportsFields; }
00127 };
00128 }
00129 
00130 //===----------------------------------------------------------------------===//
00131 // Main RegionStore logic.
00132 //===----------------------------------------------------------------------===//
00133 
00134 namespace {
00135 
00136 class RegionStoreSubRegionMap : public SubRegionMap {
00137 public:
00138   typedef llvm::ImmutableSet<const MemRegion*> Set;
00139   typedef llvm::DenseMap<const MemRegion*, Set> Map;
00140 private:
00141   Set::Factory F;
00142   Map M;
00143 public:
00144   bool add(const MemRegion* Parent, const MemRegion* SubRegion) {
00145     Map::iterator I = M.find(Parent);
00146 
00147     if (I == M.end()) {
00148       M.insert(std::make_pair(Parent, F.add(F.getEmptySet(), SubRegion)));
00149       return true;
00150     }
00151 
00152     I->second = F.add(I->second, SubRegion);
00153     return false;
00154   }
00155 
00156   void process(SmallVectorImpl<const SubRegion*> &WL, const SubRegion *R);
00157 
00158   ~RegionStoreSubRegionMap() {}
00159 
00160   const Set *getSubRegions(const MemRegion *Parent) const {
00161     Map::const_iterator I = M.find(Parent);
00162     return I == M.end() ? NULL : &I->second;
00163   }
00164 
00165   bool iterSubRegions(const MemRegion* Parent, Visitor& V) const {
00166     Map::const_iterator I = M.find(Parent);
00167 
00168     if (I == M.end())
00169       return true;
00170 
00171     Set S = I->second;
00172     for (Set::iterator SI=S.begin(),SE=S.end(); SI != SE; ++SI) {
00173       if (!V.Visit(Parent, *SI))
00174         return false;
00175     }
00176 
00177     return true;
00178   }
00179 };
00180 
00181 void
00182 RegionStoreSubRegionMap::process(SmallVectorImpl<const SubRegion*> &WL,
00183                                  const SubRegion *R) {
00184   const MemRegion *superR = R->getSuperRegion();
00185   if (add(superR, R))
00186     if (const SubRegion *sr = dyn_cast<SubRegion>(superR))
00187       WL.push_back(sr);
00188 }
00189 
00190 class RegionStoreManager : public StoreManager {
00191   const RegionStoreFeatures Features;
00192   RegionBindings::Factory RBFactory;
00193 
00194 public:
00195   RegionStoreManager(ProgramStateManager& mgr, const RegionStoreFeatures &f)
00196     : StoreManager(mgr),
00197       Features(f),
00198       RBFactory(mgr.getAllocator()) {}
00199 
00200   SubRegionMap *getSubRegionMap(Store store) {
00201     return getRegionStoreSubRegionMap(store);
00202   }
00203 
00204   RegionStoreSubRegionMap *getRegionStoreSubRegionMap(Store store);
00205 
00206   Optional<SVal> getDirectBinding(RegionBindings B, const MemRegion *R);
00207   /// getDefaultBinding - Returns an SVal* representing an optional default
00208   ///  binding associated with a region and its subregions.
00209   Optional<SVal> getDefaultBinding(RegionBindings B, const MemRegion *R);
00210 
00211   /// setImplicitDefaultValue - Set the default binding for the provided
00212   ///  MemRegion to the value implicitly defined for compound literals when
00213   ///  the value is not specified.
00214   StoreRef setImplicitDefaultValue(Store store, const MemRegion *R, QualType T);
00215 
00216   /// ArrayToPointer - Emulates the "decay" of an array to a pointer
00217   ///  type.  'Array' represents the lvalue of the array being decayed
00218   ///  to a pointer, and the returned SVal represents the decayed
00219   ///  version of that lvalue (i.e., a pointer to the first element of
00220   ///  the array).  This is called by ExprEngine when evaluating
00221   ///  casts from arrays to pointers.
00222   SVal ArrayToPointer(Loc Array);
00223 
00224   /// For DerivedToBase casts, create a CXXBaseObjectRegion and return it.
00225   virtual SVal evalDerivedToBase(SVal derived, QualType basePtrType);
00226 
00227   /// \brief Evaluates C++ dynamic_cast cast.
00228   /// The callback may result in the following 3 scenarios:
00229   ///  - Successful cast (ex: derived is subclass of base).
00230   ///  - Failed cast (ex: derived is definitely not a subclass of base).
00231   ///  - We don't know (base is a symbolic region and we don't have 
00232   ///    enough info to determine if the cast will succeed at run time).
00233   /// The function returns an SVal representing the derived class; it's
00234   /// valid only if Failed flag is set to false.
00235   virtual SVal evalDynamicCast(SVal base, QualType derivedPtrType,bool &Failed);
00236 
00237   StoreRef getInitialStore(const LocationContext *InitLoc) {
00238     return StoreRef(RBFactory.getEmptyMap().getRootWithoutRetain(), *this);
00239   }
00240 
00241   //===-------------------------------------------------------------------===//
00242   // Binding values to regions.
00243   //===-------------------------------------------------------------------===//
00244   RegionBindings invalidateGlobalRegion(MemRegion::Kind K,
00245                                         const Expr *Ex,
00246                                         unsigned Count,
00247                                         const LocationContext *LCtx,
00248                                         RegionBindings B,
00249                                         InvalidatedRegions *Invalidated);
00250 
00251   StoreRef invalidateRegions(Store store, ArrayRef<const MemRegion *> Regions,
00252                              const Expr *E, unsigned Count,
00253                              const LocationContext *LCtx,
00254                              InvalidatedSymbols &IS,
00255                              const CallOrObjCMessage *Call,
00256                              InvalidatedRegions *Invalidated);
00257 
00258 public:   // Made public for helper classes.
00259 
00260   void RemoveSubRegionBindings(RegionBindings &B, const MemRegion *R,
00261                                RegionStoreSubRegionMap &M);
00262 
00263   RegionBindings addBinding(RegionBindings B, BindingKey K, SVal V);
00264 
00265   RegionBindings addBinding(RegionBindings B, const MemRegion *R,
00266                      BindingKey::Kind k, SVal V);
00267 
00268   const SVal *lookup(RegionBindings B, BindingKey K);
00269   const SVal *lookup(RegionBindings B, const MemRegion *R, BindingKey::Kind k);
00270 
00271   RegionBindings removeBinding(RegionBindings B, BindingKey K);
00272   RegionBindings removeBinding(RegionBindings B, const MemRegion *R,
00273                         BindingKey::Kind k);
00274 
00275   RegionBindings removeBinding(RegionBindings B, const MemRegion *R) {
00276     return removeBinding(removeBinding(B, R, BindingKey::Direct), R,
00277                         BindingKey::Default);
00278   }
00279 
00280 public: // Part of public interface to class.
00281 
00282   StoreRef Bind(Store store, Loc LV, SVal V);
00283 
00284   // BindDefault is only used to initialize a region with a default value.
00285   StoreRef BindDefault(Store store, const MemRegion *R, SVal V) {
00286     RegionBindings B = GetRegionBindings(store);
00287     assert(!lookup(B, R, BindingKey::Default));
00288     assert(!lookup(B, R, BindingKey::Direct));
00289     return StoreRef(addBinding(B, R, BindingKey::Default, V)
00290                       .getRootWithoutRetain(), *this);
00291   }
00292 
00293   StoreRef BindCompoundLiteral(Store store, const CompoundLiteralExpr *CL,
00294                                const LocationContext *LC, SVal V);
00295 
00296   StoreRef BindDecl(Store store, const VarRegion *VR, SVal InitVal);
00297 
00298   StoreRef BindDeclWithNoInit(Store store, const VarRegion *) {
00299     return StoreRef(store, *this);
00300   }
00301 
00302   /// BindStruct - Bind a compound value to a structure.
00303   StoreRef BindStruct(Store store, const TypedValueRegion* R, SVal V);
00304 
00305   /// BindVector - Bind a compound value to a vector.
00306   StoreRef BindVector(Store store, const TypedValueRegion* R, SVal V);
00307 
00308   StoreRef BindArray(Store store, const TypedValueRegion* R, SVal V);
00309 
00310   /// KillStruct - Set the entire struct to unknown.
00311   StoreRef KillStruct(Store store, const TypedRegion* R, SVal DefaultVal);
00312 
00313   StoreRef Remove(Store store, Loc LV);
00314 
00315   void incrementReferenceCount(Store store) {
00316     GetRegionBindings(store).manualRetain();    
00317   }
00318   
00319   /// If the StoreManager supports it, decrement the reference count of
00320   /// the specified Store object.  If the reference count hits 0, the memory
00321   /// associated with the object is recycled.
00322   void decrementReferenceCount(Store store) {
00323     GetRegionBindings(store).manualRelease();
00324   }
00325   
00326   bool includedInBindings(Store store, const MemRegion *region) const;
00327 
00328   /// \brief Return the value bound to specified location in a given state.
00329   ///
00330   /// The high level logic for this method is this:
00331   /// getBinding (L)
00332   ///   if L has binding
00333   ///     return L's binding
00334   ///   else if L is in killset
00335   ///     return unknown
00336   ///   else
00337   ///     if L is on stack or heap
00338   ///       return undefined
00339   ///     else
00340   ///       return symbolic
00341   SVal getBinding(Store store, Loc L, QualType T = QualType());
00342 
00343   SVal getBindingForElement(Store store, const ElementRegion *R);
00344 
00345   SVal getBindingForField(Store store, const FieldRegion *R);
00346 
00347   SVal getBindingForObjCIvar(Store store, const ObjCIvarRegion *R);
00348 
00349   SVal getBindingForVar(Store store, const VarRegion *R);
00350 
00351   SVal getBindingForLazySymbol(const TypedValueRegion *R);
00352 
00353   SVal getBindingForFieldOrElementCommon(Store store, const TypedValueRegion *R,
00354                                          QualType Ty, const MemRegion *superR);
00355   
00356   SVal getLazyBinding(const MemRegion *lazyBindingRegion,
00357                       Store lazyBindingStore);
00358 
00359   /// Get bindings for the values in a struct and return a CompoundVal, used
00360   /// when doing struct copy:
00361   /// struct s x, y;
00362   /// x = y;
00363   /// y's value is retrieved by this method.
00364   SVal getBindingForStruct(Store store, const TypedValueRegion* R);
00365 
00366   SVal getBindingForArray(Store store, const TypedValueRegion* R);
00367 
00368   /// Used to lazily generate derived symbols for bindings that are defined
00369   ///  implicitly by default bindings in a super region.
00370   Optional<SVal> getBindingForDerivedDefaultValue(RegionBindings B,
00371                                                   const MemRegion *superR,
00372                                                   const TypedValueRegion *R,
00373                                                   QualType Ty);
00374 
00375   /// Get the state and region whose binding this region R corresponds to.
00376   std::pair<Store, const MemRegion*>
00377   GetLazyBinding(RegionBindings B, const MemRegion *R,
00378                  const MemRegion *originalRegion,
00379                  bool includeSuffix = false);
00380 
00381   StoreRef CopyLazyBindings(nonloc::LazyCompoundVal V, Store store,
00382                             const TypedRegion *R);
00383 
00384   //===------------------------------------------------------------------===//
00385   // State pruning.
00386   //===------------------------------------------------------------------===//
00387 
00388   /// removeDeadBindings - Scans the RegionStore of 'state' for dead values.
00389   ///  It returns a new Store with these values removed.
00390   StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx,
00391                               SymbolReaper& SymReaper);
00392 
00393   StoreRef enterStackFrame(ProgramStateRef state,
00394                            const LocationContext *callerCtx,
00395                            const StackFrameContext *calleeCtx);
00396 
00397   //===------------------------------------------------------------------===//
00398   // Region "extents".
00399   //===------------------------------------------------------------------===//
00400 
00401   // FIXME: This method will soon be eliminated; see the note in Store.h.
00402   DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state,
00403                                          const MemRegion* R, QualType EleTy);
00404 
00405   //===------------------------------------------------------------------===//
00406   // Utility methods.
00407   //===------------------------------------------------------------------===//
00408 
00409   static inline RegionBindings GetRegionBindings(Store store) {
00410     return RegionBindings(static_cast<const RegionBindings::TreeTy*>(store));
00411   }
00412 
00413   void print(Store store, raw_ostream &Out, const char* nl,
00414              const char *sep);
00415 
00416   void iterBindings(Store store, BindingsHandler& f) {
00417     RegionBindings B = GetRegionBindings(store);
00418     for (RegionBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
00419       const BindingKey &K = I.getKey();
00420       if (!K.isDirect())
00421         continue;
00422       if (const SubRegion *R = dyn_cast<SubRegion>(I.getKey().getRegion())) {
00423         // FIXME: Possibly incorporate the offset?
00424         if (!f.HandleBinding(*this, store, R, I.getData()))
00425           return;
00426       }
00427     }
00428   }
00429 };
00430 
00431 } // end anonymous namespace
00432 
00433 //===----------------------------------------------------------------------===//
00434 // RegionStore creation.
00435 //===----------------------------------------------------------------------===//
00436 
00437 StoreManager *ento::CreateRegionStoreManager(ProgramStateManager& StMgr) {
00438   RegionStoreFeatures F = maximal_features_tag();
00439   return new RegionStoreManager(StMgr, F);
00440 }
00441 
00442 StoreManager *
00443 ento::CreateFieldsOnlyRegionStoreManager(ProgramStateManager &StMgr) {
00444   RegionStoreFeatures F = minimal_features_tag();
00445   F.enableFields(true);
00446   return new RegionStoreManager(StMgr, F);
00447 }
00448 
00449 
00450 RegionStoreSubRegionMap*
00451 RegionStoreManager::getRegionStoreSubRegionMap(Store store) {
00452   RegionBindings B = GetRegionBindings(store);
00453   RegionStoreSubRegionMap *M = new RegionStoreSubRegionMap();
00454 
00455   SmallVector<const SubRegion*, 10> WL;
00456 
00457   for (RegionBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I)
00458     if (const SubRegion *R = dyn_cast<SubRegion>(I.getKey().getRegion()))
00459       M->process(WL, R);
00460 
00461   // We also need to record in the subregion map "intermediate" regions that
00462   // don't have direct bindings but are super regions of those that do.
00463   while (!WL.empty()) {
00464     const SubRegion *R = WL.back();
00465     WL.pop_back();
00466     M->process(WL, R);
00467   }
00468 
00469   return M;
00470 }
00471 
00472 //===----------------------------------------------------------------------===//
00473 // Region Cluster analysis.
00474 //===----------------------------------------------------------------------===//
00475 
00476 namespace {
00477 template <typename DERIVED>
00478 class ClusterAnalysis  {
00479 protected:
00480   typedef BumpVector<BindingKey> RegionCluster;
00481   typedef llvm::DenseMap<const MemRegion *, RegionCluster *> ClusterMap;
00482   llvm::DenseMap<const RegionCluster*, unsigned> Visited;
00483   typedef SmallVector<std::pair<const MemRegion *, RegionCluster*>, 10>
00484     WorkList;
00485 
00486   BumpVectorContext BVC;
00487   ClusterMap ClusterM;
00488   WorkList WL;
00489 
00490   RegionStoreManager &RM;
00491   ASTContext &Ctx;
00492   SValBuilder &svalBuilder;
00493 
00494   RegionBindings B;
00495   
00496   const bool includeGlobals;
00497 
00498 public:
00499   ClusterAnalysis(RegionStoreManager &rm, ProgramStateManager &StateMgr,
00500                   RegionBindings b, const bool includeGlobals)
00501     : RM(rm), Ctx(StateMgr.getContext()),
00502       svalBuilder(StateMgr.getSValBuilder()),
00503       B(b), includeGlobals(includeGlobals) {}
00504 
00505   RegionBindings getRegionBindings() const { return B; }
00506 
00507   RegionCluster &AddToCluster(BindingKey K) {
00508     const MemRegion *R = K.getRegion();
00509     const MemRegion *baseR = R->getBaseRegion();
00510     RegionCluster &C = getCluster(baseR);
00511     C.push_back(K, BVC);
00512     static_cast<DERIVED*>(this)->VisitAddedToCluster(baseR, C);
00513     return C;
00514   }
00515 
00516   bool isVisited(const MemRegion *R) {
00517     return (bool) Visited[&getCluster(R->getBaseRegion())];
00518   }
00519 
00520   RegionCluster& getCluster(const MemRegion *R) {
00521     RegionCluster *&CRef = ClusterM[R];
00522     if (!CRef) {
00523       void *Mem = BVC.getAllocator().template Allocate<RegionCluster>();
00524       CRef = new (Mem) RegionCluster(BVC, 10);
00525     }
00526     return *CRef;
00527   }
00528 
00529   void GenerateClusters() {
00530       // Scan the entire set of bindings and make the region clusters.
00531     for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){
00532       RegionCluster &C = AddToCluster(RI.getKey());
00533       if (const MemRegion *R = RI.getData().getAsRegion()) {
00534         // Generate a cluster, but don't add the region to the cluster
00535         // if there aren't any bindings.
00536         getCluster(R->getBaseRegion());
00537       }
00538       if (includeGlobals) {
00539         const MemRegion *R = RI.getKey().getRegion();
00540         if (isa<NonStaticGlobalSpaceRegion>(R->getMemorySpace()))
00541           AddToWorkList(R, C);
00542       }
00543     }
00544   }
00545 
00546   bool AddToWorkList(const MemRegion *R, RegionCluster &C) {
00547     if (unsigned &visited = Visited[&C])
00548       return false;
00549     else
00550       visited = 1;
00551 
00552     WL.push_back(std::make_pair(R, &C));
00553     return true;
00554   }
00555 
00556   bool AddToWorkList(BindingKey K) {
00557     return AddToWorkList(K.getRegion());
00558   }
00559 
00560   bool AddToWorkList(const MemRegion *R) {
00561     const MemRegion *baseR = R->getBaseRegion();
00562     return AddToWorkList(baseR, getCluster(baseR));
00563   }
00564 
00565   void RunWorkList() {
00566     while (!WL.empty()) {
00567       const MemRegion *baseR;
00568       RegionCluster *C;
00569       llvm::tie(baseR, C) = WL.back();
00570       WL.pop_back();
00571 
00572         // First visit the cluster.
00573       static_cast<DERIVED*>(this)->VisitCluster(baseR, C->begin(), C->end());
00574 
00575         // Next, visit the base region.
00576       static_cast<DERIVED*>(this)->VisitBaseRegion(baseR);
00577     }
00578   }
00579 
00580 public:
00581   void VisitAddedToCluster(const MemRegion *baseR, RegionCluster &C) {}
00582   void VisitCluster(const MemRegion *baseR, BindingKey *I, BindingKey *E) {}
00583   void VisitBaseRegion(const MemRegion *baseR) {}
00584 };
00585 }
00586 
00587 //===----------------------------------------------------------------------===//
00588 // Binding invalidation.
00589 //===----------------------------------------------------------------------===//
00590 
00591 void RegionStoreManager::RemoveSubRegionBindings(RegionBindings &B,
00592                                                  const MemRegion *R,
00593                                                  RegionStoreSubRegionMap &M) {
00594 
00595   if (const RegionStoreSubRegionMap::Set *S = M.getSubRegions(R))
00596     for (RegionStoreSubRegionMap::Set::iterator I = S->begin(), E = S->end();
00597          I != E; ++I)
00598       RemoveSubRegionBindings(B, *I, M);
00599 
00600   B = removeBinding(B, R);
00601 }
00602 
00603 namespace {
00604 class invalidateRegionsWorker : public ClusterAnalysis<invalidateRegionsWorker>
00605 {
00606   const Expr *Ex;
00607   unsigned Count;
00608   const LocationContext *LCtx;
00609   StoreManager::InvalidatedSymbols &IS;
00610   StoreManager::InvalidatedRegions *Regions;
00611 public:
00612   invalidateRegionsWorker(RegionStoreManager &rm,
00613                           ProgramStateManager &stateMgr,
00614                           RegionBindings b,
00615                           const Expr *ex, unsigned count,
00616                           const LocationContext *lctx,
00617                           StoreManager::InvalidatedSymbols &is,
00618                           StoreManager::InvalidatedRegions *r,
00619                           bool includeGlobals)
00620     : ClusterAnalysis<invalidateRegionsWorker>(rm, stateMgr, b, includeGlobals),
00621       Ex(ex), Count(count), LCtx(lctx), IS(is), Regions(r) {}
00622 
00623   void VisitCluster(const MemRegion *baseR, BindingKey *I, BindingKey *E);
00624   void VisitBaseRegion(const MemRegion *baseR);
00625 
00626 private:
00627   void VisitBinding(SVal V);
00628 };
00629 }
00630 
00631 void invalidateRegionsWorker::VisitBinding(SVal V) {
00632   // A symbol?  Mark it touched by the invalidation.
00633   if (SymbolRef Sym = V.getAsSymbol())
00634     IS.insert(Sym);
00635 
00636   if (const MemRegion *R = V.getAsRegion()) {
00637     AddToWorkList(R);
00638     return;
00639   }
00640 
00641   // Is it a LazyCompoundVal?  All references get invalidated as well.
00642   if (const nonloc::LazyCompoundVal *LCS =
00643         dyn_cast<nonloc::LazyCompoundVal>(&V)) {
00644 
00645     const MemRegion *LazyR = LCS->getRegion();
00646     RegionBindings B = RegionStoreManager::GetRegionBindings(LCS->getStore());
00647 
00648     for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){
00649       const SubRegion *baseR = dyn_cast<SubRegion>(RI.getKey().getRegion());
00650       if (baseR && (baseR == LazyR || baseR->isSubRegionOf(LazyR)))
00651         VisitBinding(RI.getData());
00652     }
00653 
00654     return;
00655   }
00656 }
00657 
00658 void invalidateRegionsWorker::VisitCluster(const MemRegion *baseR,
00659                                            BindingKey *I, BindingKey *E) {
00660   for ( ; I != E; ++I) {
00661     // Get the old binding.  Is it a region?  If so, add it to the worklist.
00662     const BindingKey &K = *I;
00663     if (const SVal *V = RM.lookup(B, K))
00664       VisitBinding(*V);
00665 
00666     B = RM.removeBinding(B, K);
00667   }
00668 }
00669 
00670 void invalidateRegionsWorker::VisitBaseRegion(const MemRegion *baseR) {
00671   // Symbolic region?  Mark that symbol touched by the invalidation.
00672   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR))
00673     IS.insert(SR->getSymbol());
00674 
00675   // BlockDataRegion?  If so, invalidate captured variables that are passed
00676   // by reference.
00677   if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) {
00678     for (BlockDataRegion::referenced_vars_iterator
00679          BI = BR->referenced_vars_begin(), BE = BR->referenced_vars_end() ;
00680          BI != BE; ++BI) {
00681       const VarRegion *VR = *BI;
00682       const VarDecl *VD = VR->getDecl();
00683       if (VD->getAttr<BlocksAttr>() || !VD->hasLocalStorage()) {
00684         AddToWorkList(VR);
00685       }
00686       else if (Loc::isLocType(VR->getValueType())) {
00687         // Map the current bindings to a Store to retrieve the value
00688         // of the binding.  If that binding itself is a region, we should
00689         // invalidate that region.  This is because a block may capture
00690         // a pointer value, but the thing pointed by that pointer may
00691         // get invalidated.
00692         Store store = B.getRootWithoutRetain();
00693         SVal V = RM.getBinding(store, loc::MemRegionVal(VR));
00694         if (const Loc *L = dyn_cast<Loc>(&V)) {
00695           if (const MemRegion *LR = L->getAsRegion())
00696             AddToWorkList(LR);
00697         }
00698       }
00699     }
00700     return;
00701   }
00702 
00703   // Otherwise, we have a normal data region. Record that we touched the region.
00704   if (Regions)
00705     Regions->push_back(baseR);
00706 
00707   if (isa<AllocaRegion>(baseR) || isa<SymbolicRegion>(baseR)) {
00708     // Invalidate the region by setting its default value to
00709     // conjured symbol. The type of the symbol is irrelavant.
00710     DefinedOrUnknownSVal V =
00711       svalBuilder.getConjuredSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count);
00712     B = RM.addBinding(B, baseR, BindingKey::Default, V);
00713     return;
00714   }
00715 
00716   if (!baseR->isBoundable())
00717     return;
00718 
00719   const TypedValueRegion *TR = cast<TypedValueRegion>(baseR);
00720   QualType T = TR->getValueType();
00721 
00722     // Invalidate the binding.
00723   if (T->isStructureOrClassType()) {
00724     // Invalidate the region by setting its default value to
00725     // conjured symbol. The type of the symbol is irrelavant.
00726     DefinedOrUnknownSVal V =
00727       svalBuilder.getConjuredSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count);
00728     B = RM.addBinding(B, baseR, BindingKey::Default, V);
00729     return;
00730   }
00731 
00732   if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
00733       // Set the default value of the array to conjured symbol.
00734     DefinedOrUnknownSVal V =
00735     svalBuilder.getConjuredSymbolVal(baseR, Ex, LCtx,
00736                                      AT->getElementType(), Count);
00737     B = RM.addBinding(B, baseR, BindingKey::Default, V);
00738     return;
00739   }
00740   
00741   if (includeGlobals && 
00742       isa<NonStaticGlobalSpaceRegion>(baseR->getMemorySpace())) {
00743     // If the region is a global and we are invalidating all globals,
00744     // just erase the entry.  This causes all globals to be lazily
00745     // symbolicated from the same base symbol.
00746     B = RM.removeBinding(B, baseR);
00747     return;
00748   }
00749   
00750 
00751   DefinedOrUnknownSVal V = svalBuilder.getConjuredSymbolVal(baseR, Ex, LCtx,
00752                                                             T,Count);
00753   assert(SymbolManager::canSymbolicate(T) || V.isUnknown());
00754   B = RM.addBinding(B, baseR, BindingKey::Direct, V);
00755 }
00756 
00757 RegionBindings RegionStoreManager::invalidateGlobalRegion(MemRegion::Kind K,
00758                                                           const Expr *Ex,
00759                                                           unsigned Count,
00760                                                     const LocationContext *LCtx,
00761                                                           RegionBindings B,
00762                                             InvalidatedRegions *Invalidated) {
00763   // Bind the globals memory space to a new symbol that we will use to derive
00764   // the bindings for all globals.
00765   const GlobalsSpaceRegion *GS = MRMgr.getGlobalsRegion(K);
00766   SVal V =
00767       svalBuilder.getConjuredSymbolVal(/* SymbolTag = */ (void*) GS, Ex, LCtx,
00768           /* symbol type, doesn't matter */ Ctx.IntTy,
00769           Count);
00770 
00771   B = removeBinding(B, GS);
00772   B = addBinding(B, BindingKey::Make(GS, BindingKey::Default), V);
00773 
00774   // Even if there are no bindings in the global scope, we still need to
00775   // record that we touched it.
00776   if (Invalidated)
00777     Invalidated->push_back(GS);
00778 
00779   return B;
00780 }
00781 
00782 StoreRef RegionStoreManager::invalidateRegions(Store store,
00783                                             ArrayRef<const MemRegion *> Regions,
00784                                                const Expr *Ex, unsigned Count,
00785                                                const LocationContext *LCtx,
00786                                                InvalidatedSymbols &IS,
00787                                                const CallOrObjCMessage *Call,
00788                                               InvalidatedRegions *Invalidated) {
00789   invalidateRegionsWorker W(*this, StateMgr,
00790                             RegionStoreManager::GetRegionBindings(store),
00791                             Ex, Count, LCtx, IS, Invalidated, false);
00792 
00793   // Scan the bindings and generate the clusters.
00794   W.GenerateClusters();
00795 
00796   // Add the regions to the worklist.
00797   for (ArrayRef<const MemRegion *>::iterator
00798        I = Regions.begin(), E = Regions.end(); I != E; ++I)
00799     W.AddToWorkList(*I);
00800 
00801   W.RunWorkList();
00802 
00803   // Return the new bindings.
00804   RegionBindings B = W.getRegionBindings();
00805 
00806   // For all globals which are not static nor immutable: determine which global
00807   // regions should be invalidated and invalidate them.
00808   // TODO: This could possibly be more precise with modules.
00809   //
00810   // System calls invalidate only system globals.
00811   if (Call && Call->isInSystemHeader()) {
00812     B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind,
00813                                Ex, Count, LCtx, B, Invalidated);
00814   // Internal calls might invalidate both system and internal globals.
00815   } else {
00816     B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind,
00817                                Ex, Count, LCtx, B, Invalidated);
00818     B = invalidateGlobalRegion(MemRegion::GlobalInternalSpaceRegionKind,
00819                                Ex, Count, LCtx, B, Invalidated);
00820   }
00821 
00822   return StoreRef(B.getRootWithoutRetain(), *this);
00823 }
00824 
00825 //===----------------------------------------------------------------------===//
00826 // Extents for regions.
00827 //===----------------------------------------------------------------------===//
00828 
00829 DefinedOrUnknownSVal
00830 RegionStoreManager::getSizeInElements(ProgramStateRef state,
00831                                       const MemRegion *R,
00832                                       QualType EleTy) {
00833   SVal Size = cast<SubRegion>(R)->getExtent(svalBuilder);
00834   const llvm::APSInt *SizeInt = svalBuilder.getKnownValue(state, Size);
00835   if (!SizeInt)
00836     return UnknownVal();
00837 
00838   CharUnits RegionSize = CharUnits::fromQuantity(SizeInt->getSExtValue());
00839 
00840   if (Ctx.getAsVariableArrayType(EleTy)) {
00841     // FIXME: We need to track extra state to properly record the size
00842     // of VLAs.  Returning UnknownVal here, however, is a stop-gap so that
00843     // we don't have a divide-by-zero below.
00844     return UnknownVal();
00845   }
00846 
00847   CharUnits EleSize = Ctx.getTypeSizeInChars(EleTy);
00848 
00849   // If a variable is reinterpreted as a type that doesn't fit into a larger
00850   // type evenly, round it down.
00851   // This is a signed value, since it's used in arithmetic with signed indices.
00852   return svalBuilder.makeIntVal(RegionSize / EleSize, false);
00853 }
00854 
00855 //===----------------------------------------------------------------------===//
00856 // Location and region casting.
00857 //===----------------------------------------------------------------------===//
00858 
00859 /// ArrayToPointer - Emulates the "decay" of an array to a pointer
00860 ///  type.  'Array' represents the lvalue of the array being decayed
00861 ///  to a pointer, and the returned SVal represents the decayed
00862 ///  version of that lvalue (i.e., a pointer to the first element of
00863 ///  the array).  This is called by ExprEngine when evaluating casts
00864 ///  from arrays to pointers.
00865 SVal RegionStoreManager::ArrayToPointer(Loc Array) {
00866   if (!isa<loc::MemRegionVal>(Array))
00867     return UnknownVal();
00868 
00869   const MemRegion* R = cast<loc::MemRegionVal>(&Array)->getRegion();
00870   const TypedValueRegion* ArrayR = dyn_cast<TypedValueRegion>(R);
00871 
00872   if (!ArrayR)
00873     return UnknownVal();
00874 
00875   // Strip off typedefs from the ArrayRegion's ValueType.
00876   QualType T = ArrayR->getValueType().getDesugaredType(Ctx);
00877   const ArrayType *AT = cast<ArrayType>(T);
00878   T = AT->getElementType();
00879 
00880   NonLoc ZeroIdx = svalBuilder.makeZeroArrayIndex();
00881   return loc::MemRegionVal(MRMgr.getElementRegion(T, ZeroIdx, ArrayR, Ctx));
00882 }
00883 
00884 SVal RegionStoreManager::evalDerivedToBase(SVal derived, QualType baseType) {
00885   const CXXRecordDecl *baseDecl;
00886   if (baseType->isPointerType())
00887     baseDecl = baseType->getCXXRecordDeclForPointerType();
00888   else
00889     baseDecl = baseType->getAsCXXRecordDecl();
00890 
00891   assert(baseDecl && "not a CXXRecordDecl?");
00892 
00893   loc::MemRegionVal *derivedRegVal = dyn_cast<loc::MemRegionVal>(&derived);
00894   if (!derivedRegVal)
00895     return derived;
00896 
00897   const MemRegion *baseReg = 
00898     MRMgr.getCXXBaseObjectRegion(baseDecl, derivedRegVal->getRegion()); 
00899 
00900   return loc::MemRegionVal(baseReg);
00901 }
00902 
00903 SVal RegionStoreManager::evalDynamicCast(SVal base, QualType derivedType,
00904                                          bool &Failed) {
00905   Failed = false;
00906 
00907   loc::MemRegionVal *baseRegVal = dyn_cast<loc::MemRegionVal>(&base);
00908   if (!baseRegVal)
00909     return UnknownVal();
00910   const MemRegion *BaseRegion = baseRegVal->stripCasts();
00911 
00912   // Assume the derived class is a pointer or a reference to a CXX record.
00913   derivedType = derivedType->getPointeeType();
00914   assert(!derivedType.isNull());
00915   const CXXRecordDecl *DerivedDecl = derivedType->getAsCXXRecordDecl();
00916   if (!DerivedDecl && !derivedType->isVoidType())
00917     return UnknownVal();
00918 
00919   // Drill down the CXXBaseObject chains, which represent upcasts (casts from
00920   // derived to base).
00921   const MemRegion *SR = BaseRegion;
00922   while (const TypedRegion *TSR = dyn_cast_or_null<TypedRegion>(SR)) {
00923     QualType BaseType = TSR->getLocationType()->getPointeeType();
00924     assert(!BaseType.isNull());
00925     const CXXRecordDecl *SRDecl = BaseType->getAsCXXRecordDecl();
00926     if (!SRDecl)
00927       return UnknownVal();
00928 
00929     // If found the derived class, the cast succeeds.
00930     if (SRDecl == DerivedDecl)
00931       return loc::MemRegionVal(TSR);
00932 
00933     // If the region type is a subclass of the derived type.
00934     if (!derivedType->isVoidType() && SRDecl->isDerivedFrom(DerivedDecl)) {
00935       // This occurs in two cases.
00936       // 1) We are processing an upcast.
00937       // 2) We are processing a downcast but we jumped directly from the
00938       // ancestor to a child of the cast value, so conjure the
00939       // appropriate region to represent value (the intermediate node).
00940       return loc::MemRegionVal(MRMgr.getCXXBaseObjectRegion(DerivedDecl,
00941                                                             BaseRegion));
00942     }
00943 
00944     // If super region is not a parent of derived class, the cast definitely
00945     // fails.
00946     if (!derivedType->isVoidType() &&
00947         DerivedDecl->isProvablyNotDerivedFrom(SRDecl)) {
00948       Failed = true;
00949       return UnknownVal();
00950     }
00951 
00952     if (const CXXBaseObjectRegion *R = dyn_cast<CXXBaseObjectRegion>(TSR))
00953       // Drill down the chain to get the derived classes.
00954       SR = R->getSuperRegion();
00955     else {
00956       // We reached the bottom of the hierarchy.
00957 
00958       // If this is a cast to void*, return the region.
00959       if (derivedType->isVoidType())
00960         return loc::MemRegionVal(TSR);
00961 
00962       // We did not find the derived class. We we must be casting the base to
00963       // derived, so the cast should fail.
00964       Failed = true;
00965       return UnknownVal();
00966     }
00967   }
00968 
00969   return UnknownVal();
00970 }
00971 
00972 //===----------------------------------------------------------------------===//
00973 // Loading values from regions.
00974 //===----------------------------------------------------------------------===//
00975 
00976 Optional<SVal> RegionStoreManager::getDirectBinding(RegionBindings B,
00977                                                     const MemRegion *R) {
00978 
00979   if (const SVal *V = lookup(B, R, BindingKey::Direct))
00980     return *V;
00981 
00982   return Optional<SVal>();
00983 }
00984 
00985 Optional<SVal> RegionStoreManager::getDefaultBinding(RegionBindings B,
00986                                                      const MemRegion *R) {
00987   if (R->isBoundable())
00988     if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R))
00989       if (TR->getValueType()->isUnionType())
00990         return UnknownVal();
00991 
00992   if (const SVal *V = lookup(B, R, BindingKey::Default))
00993     return *V;
00994 
00995   return Optional<SVal>();
00996 }
00997 
00998 SVal RegionStoreManager::getBinding(Store store, Loc L, QualType T) {
00999   assert(!isa<UnknownVal>(L) && "location unknown");
01000   assert(!isa<UndefinedVal>(L) && "location undefined");
01001 
01002   // For access to concrete addresses, return UnknownVal.  Checks
01003   // for null dereferences (and similar errors) are done by checkers, not
01004   // the Store.
01005   // FIXME: We can consider lazily symbolicating such memory, but we really
01006   // should defer this when we can reason easily about symbolicating arrays
01007   // of bytes.
01008   if (isa<loc::ConcreteInt>(L)) {
01009     return UnknownVal();
01010   }
01011   if (!isa<loc::MemRegionVal>(L)) {
01012     return UnknownVal();
01013   }
01014 
01015   const MemRegion *MR = cast<loc::MemRegionVal>(L).getRegion();
01016 
01017   if (isa<AllocaRegion>(MR) ||
01018       isa<SymbolicRegion>(MR) ||
01019       isa<CodeTextRegion>(MR)) {
01020     if (T.isNull()) {
01021       if (const TypedRegion *TR = dyn_cast<TypedRegion>(MR))
01022         T = TR->getLocationType();
01023       else {
01024         const SymbolicRegion *SR = cast<SymbolicRegion>(MR);
01025         T = SR->getSymbol()->getType(Ctx);
01026       }
01027     }
01028     MR = GetElementZeroRegion(MR, T);
01029   }
01030 
01031   // FIXME: Perhaps this method should just take a 'const MemRegion*' argument
01032   //  instead of 'Loc', and have the other Loc cases handled at a higher level.
01033   const TypedValueRegion *R = cast<TypedValueRegion>(MR);
01034   QualType RTy = R->getValueType();
01035 
01036   // FIXME: We should eventually handle funny addressing.  e.g.:
01037   //
01038   //   int x = ...;
01039   //   int *p = &x;
01040   //   char *q = (char*) p;
01041   //   char c = *q;  // returns the first byte of 'x'.
01042   //
01043   // Such funny addressing will occur due to layering of regions.
01044 
01045   if (RTy->isStructureOrClassType())
01046     return getBindingForStruct(store, R);
01047 
01048   // FIXME: Handle unions.
01049   if (RTy->isUnionType())
01050     return UnknownVal();
01051 
01052   if (RTy->isArrayType())
01053     return getBindingForArray(store, R);
01054 
01055   // FIXME: handle Vector types.
01056   if (RTy->isVectorType())
01057     return UnknownVal();
01058 
01059   if (const FieldRegion* FR = dyn_cast<FieldRegion>(R))
01060     return CastRetrievedVal(getBindingForField(store, FR), FR, T, false);
01061 
01062   if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) {
01063     // FIXME: Here we actually perform an implicit conversion from the loaded
01064     // value to the element type.  Eventually we want to compose these values
01065     // more intelligently.  For example, an 'element' can encompass multiple
01066     // bound regions (e.g., several bound bytes), or could be a subset of
01067     // a larger value.
01068     return CastRetrievedVal(getBindingForElement(store, ER), ER, T, false);
01069   }
01070 
01071   if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) {
01072     // FIXME: Here we actually perform an implicit conversion from the loaded
01073     // value to the ivar type.  What we should model is stores to ivars
01074     // that blow past the extent of the ivar.  If the address of the ivar is
01075     // reinterpretted, it is possible we stored a different value that could
01076     // fit within the ivar.  Either we need to cast these when storing them
01077     // or reinterpret them lazily (as we do here).
01078     return CastRetrievedVal(getBindingForObjCIvar(store, IVR), IVR, T, false);
01079   }
01080 
01081   if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
01082     // FIXME: Here we actually perform an implicit conversion from the loaded
01083     // value to the variable type.  What we should model is stores to variables
01084     // that blow past the extent of the variable.  If the address of the
01085     // variable is reinterpretted, it is possible we stored a different value
01086     // that could fit within the variable.  Either we need to cast these when
01087     // storing them or reinterpret them lazily (as we do here).
01088     return CastRetrievedVal(getBindingForVar(store, VR), VR, T, false);
01089   }
01090 
01091   RegionBindings B = GetRegionBindings(store);
01092   const SVal *V = lookup(B, R, BindingKey::Direct);
01093 
01094   // Check if the region has a binding.
01095   if (V)
01096     return *V;
01097 
01098   // The location does not have a bound value.  This means that it has
01099   // the value it had upon its creation and/or entry to the analyzed
01100   // function/method.  These are either symbolic values or 'undefined'.
01101   if (R->hasStackNonParametersStorage()) {
01102     // All stack variables are considered to have undefined values
01103     // upon creation.  All heap allocated blocks are considered to
01104     // have undefined values as well unless they are explicitly bound
01105     // to specific values.
01106     return UndefinedVal();
01107   }
01108 
01109   // All other values are symbolic.
01110   return svalBuilder.getRegionValueSymbolVal(R);
01111 }
01112 
01113 std::pair<Store, const MemRegion *>
01114 RegionStoreManager::GetLazyBinding(RegionBindings B, const MemRegion *R,
01115                                    const MemRegion *originalRegion,
01116                                    bool includeSuffix) {
01117   
01118   if (originalRegion != R) {
01119     if (Optional<SVal> OV = getDefaultBinding(B, R)) {
01120       if (const nonloc::LazyCompoundVal *V =
01121           dyn_cast<nonloc::LazyCompoundVal>(OV.getPointer()))
01122         return std::make_pair(V->getStore(), V->getRegion());
01123     }
01124   }
01125   
01126   if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
01127     const std::pair<Store, const MemRegion *> &X =
01128       GetLazyBinding(B, ER->getSuperRegion(), originalRegion);
01129 
01130     if (X.second)
01131       return std::make_pair(X.first,
01132                             MRMgr.getElementRegionWithSuper(ER, X.second));
01133   }
01134   else if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) {
01135     const std::pair<Store, const MemRegion *> &X =
01136       GetLazyBinding(B, FR->getSuperRegion(), originalRegion);
01137 
01138     if (X.second) {
01139       if (includeSuffix)
01140         return std::make_pair(X.first,
01141                               MRMgr.getFieldRegionWithSuper(FR, X.second));
01142       return X;
01143     }
01144         
01145   }
01146   // C++ base object region is another kind of region that we should blast
01147   // through to look for lazy compound value. It is like a field region.
01148   else if (const CXXBaseObjectRegion *baseReg = 
01149                             dyn_cast<CXXBaseObjectRegion>(R)) {
01150     const std::pair<Store, const MemRegion *> &X =
01151       GetLazyBinding(B, baseReg->getSuperRegion(), originalRegion);
01152     
01153     if (X.second) {
01154       if (includeSuffix)
01155         return std::make_pair(X.first,
01156                               MRMgr.getCXXBaseObjectRegionWithSuper(baseReg,
01157                                                                     X.second));
01158       return X;
01159     }
01160   }
01161 
01162   // The NULL MemRegion indicates an non-existent lazy binding. A NULL Store is
01163   // possible for a valid lazy binding.
01164   return std::make_pair((Store) 0, (const MemRegion *) 0);
01165 }
01166 
01167 SVal RegionStoreManager::getBindingForElement(Store store,
01168                                               const ElementRegion* R) {
01169   // We do not currently model bindings of the CompoundLiteralregion.
01170   if (isa<CompoundLiteralRegion>(R->getBaseRegion()))
01171     return UnknownVal();
01172 
01173   // Check if the region has a binding.
01174   RegionBindings B = GetRegionBindings(store);
01175   if (const Optional<SVal> &V = getDirectBinding(B, R))
01176     return *V;
01177 
01178   const MemRegion* superR = R->getSuperRegion();
01179 
01180   // Check if the region is an element region of a string literal.
01181   if (const StringRegion *StrR=dyn_cast<StringRegion>(superR)) {
01182     // FIXME: Handle loads from strings where the literal is treated as
01183     // an integer, e.g., *((unsigned int*)"hello")
01184     QualType T = Ctx.getAsArrayType(StrR->getValueType())->getElementType();
01185     if (T != Ctx.getCanonicalType(R->getElementType()))
01186       return UnknownVal();
01187 
01188     const StringLiteral *Str = StrR->getStringLiteral();
01189     SVal Idx = R->getIndex();
01190     if (nonloc::ConcreteInt *CI = dyn_cast<nonloc::ConcreteInt>(&Idx)) {
01191       int64_t i = CI->getValue().getSExtValue();
01192       // Abort on string underrun.  This can be possible by arbitrary
01193       // clients of getBindingForElement().
01194       if (i < 0)
01195         return UndefinedVal();
01196       int64_t length = Str->getLength();
01197       // Technically, only i == length is guaranteed to be null.
01198       // However, such overflows should be caught before reaching this point;
01199       // the only time such an access would be made is if a string literal was
01200       // used to initialize a larger array.
01201       char c = (i >= length) ? '\0' : Str->getCodeUnit(i);
01202       return svalBuilder.makeIntVal(c, T);
01203     }
01204   }
01205   
01206   // Check for loads from a code text region.  For such loads, just give up.
01207   if (isa<CodeTextRegion>(superR))
01208     return UnknownVal();
01209 
01210   // Handle the case where we are indexing into a larger scalar object.
01211   // For example, this handles:
01212   //   int x = ...
01213   //   char *y = &x;
01214   //   return *y;
01215   // FIXME: This is a hack, and doesn't do anything really intelligent yet.
01216   const RegionRawOffset &O = R->getAsArrayOffset();
01217   
01218   // If we cannot reason about the offset, return an unknown value.
01219   if (!O.getRegion())
01220     return UnknownVal();
01221   
01222   if (const TypedValueRegion *baseR = 
01223         dyn_cast_or_null<TypedValueRegion>(O.getRegion())) {
01224     QualType baseT = baseR->getValueType();
01225     if (baseT->isScalarType()) {
01226       QualType elemT = R->getElementType();
01227       if (elemT->isScalarType()) {
01228         if (Ctx.getTypeSizeInChars(baseT) >= Ctx.getTypeSizeInChars(elemT)) {
01229           if (const Optional<SVal> &V = getDirectBinding(B, superR)) {
01230             if (SymbolRef parentSym = V->getAsSymbol())
01231               return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
01232 
01233             if (V->isUnknownOrUndef())
01234               return *V;
01235             // Other cases: give up.  We are indexing into a larger object
01236             // that has some value, but we don't know how to handle that yet.
01237             return UnknownVal();
01238           }
01239         }
01240       }
01241     }
01242   }
01243   return getBindingForFieldOrElementCommon(store, R, R->getElementType(),
01244                                            superR);
01245 }
01246 
01247 SVal RegionStoreManager::getBindingForField(Store store,
01248                                        const FieldRegion* R) {
01249 
01250   // Check if the region has a binding.
01251   RegionBindings B = GetRegionBindings(store);
01252   if (const Optional<SVal> &V = getDirectBinding(B, R))
01253     return *V;
01254 
01255   QualType Ty = R->getValueType();
01256   return getBindingForFieldOrElementCommon(store, R, Ty, R->getSuperRegion());
01257 }
01258 
01259 Optional<SVal>
01260 RegionStoreManager::getBindingForDerivedDefaultValue(RegionBindings B,
01261                                                      const MemRegion *superR,
01262                                                      const TypedValueRegion *R,
01263                                                      QualType Ty) {
01264 
01265   if (const Optional<SVal> &D = getDefaultBinding(B, superR)) {
01266     const SVal &val = D.getValue();
01267     if (SymbolRef parentSym = val.getAsSymbol())
01268       return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
01269 
01270     if (val.isZeroConstant())
01271       return svalBuilder.makeZeroVal(Ty);
01272 
01273     if (val.isUnknownOrUndef())
01274       return val;
01275 
01276     // Lazy bindings are handled later.
01277     if (isa<nonloc::LazyCompoundVal>(val))
01278       return Optional<SVal>();
01279 
01280     llvm_unreachable("Unknown default value");
01281   }
01282 
01283   return Optional<SVal>();
01284 }
01285 
01286 SVal RegionStoreManager::getLazyBinding(const MemRegion *lazyBindingRegion,
01287                                              Store lazyBindingStore) {
01288   if (const ElementRegion *ER = dyn_cast<ElementRegion>(lazyBindingRegion))
01289     return getBindingForElement(lazyBindingStore, ER);
01290   
01291   return getBindingForField(lazyBindingStore,
01292                             cast<FieldRegion>(lazyBindingRegion));
01293 }
01294                                         
01295 SVal RegionStoreManager::getBindingForFieldOrElementCommon(Store store,
01296                                                       const TypedValueRegion *R,
01297                                                       QualType Ty,
01298                                                       const MemRegion *superR) {
01299 
01300   // At this point we have already checked in either getBindingForElement or
01301   // getBindingForField if 'R' has a direct binding.
01302   RegionBindings B = GetRegionBindings(store);
01303 
01304   // Lazy binding?
01305   Store lazyBindingStore = NULL;
01306   const MemRegion *lazyBindingRegion = NULL;
01307   llvm::tie(lazyBindingStore, lazyBindingRegion) = GetLazyBinding(B, R, R,
01308                                                                   true);
01309   
01310   if (lazyBindingRegion)
01311     return getLazyBinding(lazyBindingRegion, lazyBindingStore);
01312 
01313   // Record whether or not we see a symbolic index.  That can completely
01314   // be out of scope of our lookup.
01315   bool hasSymbolicIndex = false;
01316 
01317   while (superR) {
01318     if (const Optional<SVal> &D =
01319         getBindingForDerivedDefaultValue(B, superR, R, Ty))
01320       return *D;
01321 
01322     if (const ElementRegion *ER = dyn_cast<ElementRegion>(superR)) {
01323       NonLoc index = ER->getIndex();
01324       if (!index.isConstant())
01325         hasSymbolicIndex = true;
01326     }
01327     
01328     // If our super region is a field or element itself, walk up the region
01329     // hierarchy to see if there is a default value installed in an ancestor.
01330     if (const SubRegion *SR = dyn_cast<SubRegion>(superR)) {
01331       superR = SR->getSuperRegion();
01332       continue;
01333     }
01334     break;
01335   }
01336 
01337   if (R->hasStackNonParametersStorage()) {
01338     if (isa<ElementRegion>(R)) {
01339       // Currently we don't reason specially about Clang-style vectors.  Check
01340       // if superR is a vector and if so return Unknown.
01341       if (const TypedValueRegion *typedSuperR = 
01342             dyn_cast<TypedValueRegion>(superR)) {
01343         if (typedSuperR->getValueType()->isVectorType())
01344           return UnknownVal();
01345       }
01346     }
01347 
01348     // FIXME: We also need to take ElementRegions with symbolic indexes into
01349     // account.  This case handles both directly accessing an ElementRegion
01350     // with a symbolic offset, but also fields within an element with
01351     // a symbolic offset.
01352     if (hasSymbolicIndex)
01353       return UnknownVal();
01354     
01355     return UndefinedVal();
01356   }
01357 
01358   // All other values are symbolic.
01359   return svalBuilder.getRegionValueSymbolVal(R);
01360 }
01361 
01362 SVal RegionStoreManager::getBindingForObjCIvar(Store store,
01363                                                const ObjCIvarRegion* R) {
01364 
01365     // Check if the region has a binding.
01366   RegionBindings B = GetRegionBindings(store);
01367 
01368   if (const Optional<SVal> &V = getDirectBinding(B, R))
01369     return *V;
01370 
01371   const MemRegion *superR = R->getSuperRegion();
01372 
01373   // Check if the super region has a default binding.
01374   if (const Optional<SVal> &V = getDefaultBinding(B, superR)) {
01375     if (SymbolRef parentSym = V->getAsSymbol())
01376       return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
01377 
01378     // Other cases: give up.
01379     return UnknownVal();
01380   }
01381 
01382   return getBindingForLazySymbol(R);
01383 }
01384 
01385 SVal RegionStoreManager::getBindingForVar(Store store, const VarRegion *R) {
01386 
01387   // Check if the region has a binding.
01388   RegionBindings B = GetRegionBindings(store);
01389 
01390   if (const Optional<SVal> &V = getDirectBinding(B, R))
01391     return *V;
01392 
01393   // Lazily derive a value for the VarRegion.
01394   const VarDecl *VD = R->getDecl();
01395   QualType T = VD->getType();
01396   const MemSpaceRegion *MS = R->getMemorySpace();
01397 
01398   if (isa<UnknownSpaceRegion>(MS) ||
01399       isa<StackArgumentsSpaceRegion>(MS))
01400     return svalBuilder.getRegionValueSymbolVal(R);
01401 
01402   if (isa<GlobalsSpaceRegion>(MS)) {
01403     if (isa<NonStaticGlobalSpaceRegion>(MS)) {
01404       // Is 'VD' declared constant?  If so, retrieve the constant value.
01405       QualType CT = Ctx.getCanonicalType(T);
01406       if (CT.isConstQualified()) {
01407         const Expr *Init = VD->getInit();
01408         // Do the null check first, as we want to call 'IgnoreParenCasts'.
01409         if (Init)
01410           if (const IntegerLiteral *IL =
01411               dyn_cast<IntegerLiteral>(Init->IgnoreParenCasts())) {
01412             const nonloc::ConcreteInt &V = svalBuilder.makeIntVal(IL);
01413             return svalBuilder.evalCast(V, Init->getType(), IL->getType());
01414           }
01415       }
01416 
01417       if (const Optional<SVal> &V
01418             = getBindingForDerivedDefaultValue(B, MS, R, CT))
01419         return V.getValue();
01420 
01421       return svalBuilder.getRegionValueSymbolVal(R);
01422     }
01423 
01424     if (T->isIntegerType())
01425       return svalBuilder.makeIntVal(0, T);
01426     if (T->isPointerType())
01427       return svalBuilder.makeNull();
01428 
01429     return UnknownVal();
01430   }
01431 
01432   return UndefinedVal();
01433 }
01434 
01435 SVal RegionStoreManager::getBindingForLazySymbol(const TypedValueRegion *R) {
01436   // All other values are symbolic.
01437   return svalBuilder.getRegionValueSymbolVal(R);
01438 }
01439 
01440 SVal RegionStoreManager::getBindingForStruct(Store store, 
01441                                         const TypedValueRegion* R) {
01442   assert(R->getValueType()->isStructureOrClassType());
01443   
01444   // If we already have a lazy binding, don't create a new one.
01445   RegionBindings B = GetRegionBindings(store);
01446   BindingKey K = BindingKey::Make(R, BindingKey::Default);
01447   if (const nonloc::LazyCompoundVal *V =
01448       dyn_cast_or_null<nonloc::LazyCompoundVal>(lookup(B, K))) {
01449     return *V;
01450   }
01451 
01452   return svalBuilder.makeLazyCompoundVal(StoreRef(store, *this), R);
01453 }
01454 
01455 SVal RegionStoreManager::getBindingForArray(Store store,
01456                                        const TypedValueRegion * R) {
01457   assert(Ctx.getAsConstantArrayType(R->getValueType()));
01458   
01459   // If we already have a lazy binding, don't create a new one.
01460   RegionBindings B = GetRegionBindings(store);
01461   BindingKey K = BindingKey::Make(R, BindingKey::Default);
01462   if (const nonloc::LazyCompoundVal *V =
01463       dyn_cast_or_null<nonloc::LazyCompoundVal>(lookup(B, K))) {
01464     return *V;
01465   }
01466 
01467   return svalBuilder.makeLazyCompoundVal(StoreRef(store, *this), R);
01468 }
01469 
01470 bool RegionStoreManager::includedInBindings(Store store,
01471                                             const MemRegion *region) const {
01472   RegionBindings B = GetRegionBindings(store);
01473   region = region->getBaseRegion();
01474   
01475   for (RegionBindings::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
01476     const BindingKey &K = it.getKey();
01477     if (region == K.getRegion())
01478       return true;
01479     const SVal &D = it.getData();
01480     if (const MemRegion *r = D.getAsRegion())
01481       if (r == region)
01482         return true;
01483   }
01484   return false;
01485 }
01486 
01487 //===----------------------------------------------------------------------===//
01488 // Binding values to regions.
01489 //===----------------------------------------------------------------------===//
01490 
01491 StoreRef RegionStoreManager::Remove(Store store, Loc L) {
01492   if (isa<loc::MemRegionVal>(L))
01493     if (const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion())
01494       return StoreRef(removeBinding(GetRegionBindings(store),
01495                                     R).getRootWithoutRetain(),
01496                       *this);
01497 
01498   return StoreRef(store, *this);
01499 }
01500 
01501 StoreRef RegionStoreManager::Bind(Store store, Loc L, SVal V) {
01502   if (isa<loc::ConcreteInt>(L))
01503     return StoreRef(store, *this);
01504 
01505   // If we get here, the location should be a region.
01506   const MemRegion *R = cast<loc::MemRegionVal>(L).getRegion();
01507 
01508   // Check if the region is a struct region.
01509   if (const TypedValueRegion* TR = dyn_cast<TypedValueRegion>(R)) {
01510     QualType Ty = TR->getValueType();
01511     if (Ty->isStructureOrClassType())
01512       return BindStruct(store, TR, V);
01513     if (Ty->isVectorType())
01514       return BindVector(store, TR, V);
01515   }
01516 
01517   if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
01518     if (ER->getIndex().isZeroConstant()) {
01519       if (const TypedValueRegion *superR =
01520             dyn_cast<TypedValueRegion>(ER->getSuperRegion())) {
01521         QualType superTy = superR->getValueType();
01522         // For now, just invalidate the fields of the struct/union/class.
01523         // This is for test rdar_test_7185607 in misc-ps-region-store.m.
01524         // FIXME: Precisely handle the fields of the record.
01525         if (superTy->isStructureOrClassType())
01526           return KillStruct(store, superR, UnknownVal());
01527       }
01528     }
01529   }
01530   else if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) {
01531     // Binding directly to a symbolic region should be treated as binding
01532     // to element 0.
01533     QualType T = SR->getSymbol()->getType(Ctx);
01534 
01535     // FIXME: Is this the right way to handle symbols that are references?
01536     if (const PointerType *PT = T->getAs<PointerType>())
01537       T = PT->getPointeeType();
01538     else
01539       T = T->getAs<ReferenceType>()->getPointeeType();
01540 
01541     R = GetElementZeroRegion(SR, T);
01542   }
01543 
01544   // Perform the binding.
01545   RegionBindings B = GetRegionBindings(store);
01546   return StoreRef(addBinding(B, R, BindingKey::Direct,
01547                              V).getRootWithoutRetain(), *this);
01548 }
01549 
01550 StoreRef RegionStoreManager::BindDecl(Store store, const VarRegion *VR,
01551                                       SVal InitVal) {
01552 
01553   QualType T = VR->getDecl()->getType();
01554 
01555   if (T->isArrayType())
01556     return BindArray(store, VR, InitVal);
01557   if (T->isStructureOrClassType())
01558     return BindStruct(store, VR, InitVal);
01559 
01560   return Bind(store, svalBuilder.makeLoc(VR), InitVal);
01561 }
01562 
01563 // FIXME: this method should be merged into Bind().
01564 StoreRef RegionStoreManager::BindCompoundLiteral(Store store,
01565                                                  const CompoundLiteralExpr *CL,
01566                                                  const LocationContext *LC,
01567                                                  SVal V) {
01568   return Bind(store, loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CL, LC)),
01569               V);
01570 }
01571 
01572 StoreRef RegionStoreManager::setImplicitDefaultValue(Store store,
01573                                                      const MemRegion *R,
01574                                                      QualType T) {
01575   RegionBindings B = GetRegionBindings(store);
01576   SVal V;
01577 
01578   if (Loc::isLocType(T))
01579     V = svalBuilder.makeNull();
01580   else if (T->isIntegerType())
01581     V = svalBuilder.makeZeroVal(T);
01582   else if (T->isStructureOrClassType() || T->isArrayType()) {
01583     // Set the default value to a zero constant when it is a structure
01584     // or array.  The type doesn't really matter.
01585     V = svalBuilder.makeZeroVal(Ctx.IntTy);
01586   }
01587   else {
01588     // We can't represent values of this type, but we still need to set a value
01589     // to record that the region has been initialized.
01590     // If this assertion ever fires, a new case should be added above -- we
01591     // should know how to default-initialize any value we can symbolicate.
01592     assert(!SymbolManager::canSymbolicate(T) && "This type is representable");
01593     V = UnknownVal();
01594   }
01595 
01596   return StoreRef(addBinding(B, R, BindingKey::Default,
01597                              V).getRootWithoutRetain(), *this);
01598 }
01599 
01600 StoreRef RegionStoreManager::BindArray(Store store, const TypedValueRegion* R,
01601                                        SVal Init) {
01602 
01603   const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType()));
01604   QualType ElementTy = AT->getElementType();
01605   Optional<uint64_t> Size;
01606 
01607   if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT))
01608     Size = CAT->getSize().getZExtValue();
01609 
01610   // Check if the init expr is a string literal.
01611   if (loc::MemRegionVal *MRV = dyn_cast<loc::MemRegionVal>(&Init)) {
01612     const StringRegion *S = cast<StringRegion>(MRV->getRegion());
01613 
01614     // Treat the string as a lazy compound value.
01615     nonloc::LazyCompoundVal LCV =
01616       cast<nonloc::LazyCompoundVal>(svalBuilder.
01617                                 makeLazyCompoundVal(StoreRef(store, *this), S));
01618     return CopyLazyBindings(LCV, store, R);
01619   }
01620 
01621   // Handle lazy compound values.
01622   if (nonloc::LazyCompoundVal *LCV = dyn_cast<nonloc::LazyCompoundVal>(&Init))
01623     return CopyLazyBindings(*LCV, store, R);
01624 
01625   // Remaining case: explicit compound values.
01626 
01627   if (Init.isUnknown())
01628     return setImplicitDefaultValue(store, R, ElementTy);
01629 
01630   nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(Init);
01631   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
01632   uint64_t i = 0;
01633 
01634   StoreRef newStore(store, *this);
01635   for (; Size.hasValue() ? i < Size.getValue() : true ; ++i, ++VI) {
01636     // The init list might be shorter than the array length.
01637     if (VI == VE)
01638       break;
01639 
01640     const NonLoc &Idx = svalBuilder.makeArrayIndex(i);
01641     const ElementRegion *ER = MRMgr.getElementRegion(ElementTy, Idx, R, Ctx);
01642 
01643     if (ElementTy->isStructureOrClassType())
01644       newStore = BindStruct(newStore.getStore(), ER, *VI);
01645     else if (ElementTy->isArrayType())
01646       newStore = BindArray(newStore.getStore(), ER, *VI);
01647     else
01648       newStore = Bind(newStore.getStore(), svalBuilder.makeLoc(ER), *VI);
01649   }
01650 
01651   // If the init list is shorter than the array length, set the
01652   // array default value.
01653   if (Size.hasValue() && i < Size.getValue())
01654     newStore = setImplicitDefaultValue(newStore.getStore(), R, ElementTy);
01655 
01656   return newStore;
01657 }
01658 
01659 StoreRef RegionStoreManager::BindVector(Store store, const TypedValueRegion* R,
01660                                         SVal V) {
01661   QualType T = R->getValueType();
01662   assert(T->isVectorType());
01663   const VectorType *VT = T->getAs<VectorType>(); // Use getAs for typedefs.
01664  
01665   // Handle lazy compound values.
01666   if (nonloc::LazyCompoundVal *LCV = dyn_cast<nonloc::LazyCompoundVal>(&V))
01667     return CopyLazyBindings(*LCV, store, R);
01668   
01669   // We may get non-CompoundVal accidentally due to imprecise cast logic or
01670   // that we are binding symbolic struct value. Kill the field values, and if
01671   // the value is symbolic go and bind it as a "default" binding.
01672   if (V.isUnknown() || !isa<nonloc::CompoundVal>(V)) {
01673     SVal SV = isa<nonloc::SymbolVal>(V) ? V : UnknownVal();
01674     return KillStruct(store, R, SV);
01675   }
01676 
01677   QualType ElemType = VT->getElementType();
01678   nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(V);
01679   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
01680   unsigned index = 0, numElements = VT->getNumElements();
01681   StoreRef newStore(store, *this);
01682   
01683   for ( ; index != numElements ; ++index) {
01684     if (VI == VE)
01685       break;
01686     
01687     NonLoc Idx = svalBuilder.makeArrayIndex(index);
01688     const ElementRegion *ER = MRMgr.getElementRegion(ElemType, Idx, R, Ctx);
01689     
01690     if (ElemType->isArrayType())
01691       newStore = BindArray(newStore.getStore(), ER, *VI);
01692     else if (ElemType->isStructureOrClassType())
01693       newStore = BindStruct(newStore.getStore(), ER, *VI);
01694     else
01695       newStore = Bind(newStore.getStore(), svalBuilder.makeLoc(ER), *VI);
01696   }
01697   return newStore;
01698 }
01699 
01700 StoreRef RegionStoreManager::BindStruct(Store store, const TypedValueRegion* R,
01701                                         SVal V) {
01702 
01703   if (!Features.supportsFields())
01704     return StoreRef(store, *this);
01705 
01706   QualType T = R->getValueType();
01707   assert(T->isStructureOrClassType());
01708 
01709   const RecordType* RT = T->getAs<RecordType>();
01710   RecordDecl *RD = RT->getDecl();
01711 
01712   if (!RD->isCompleteDefinition())
01713     return StoreRef(store, *this);
01714 
01715   // Handle lazy compound values.
01716   if (const nonloc::LazyCompoundVal *LCV=dyn_cast<nonloc::LazyCompoundVal>(&V))
01717     return CopyLazyBindings(*LCV, store, R);
01718 
01719   // We may get non-CompoundVal accidentally due to imprecise cast logic or
01720   // that we are binding symbolic struct value. Kill the field values, and if
01721   // the value is symbolic go and bind it as a "default" binding.
01722   if (V.isUnknown() || !isa<nonloc::CompoundVal>(V)) {
01723     SVal SV = isa<nonloc::SymbolVal>(V) ? V : UnknownVal();
01724     return KillStruct(store, R, SV);
01725   }
01726 
01727   nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(V);
01728   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
01729 
01730   RecordDecl::field_iterator FI, FE;
01731   StoreRef newStore(store, *this);
01732   
01733   for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; ++FI) {
01734 
01735     if (VI == VE)
01736       break;
01737 
01738     // Skip any unnamed bitfields to stay in sync with the initializers.
01739     if (FI->isUnnamedBitfield())
01740       continue;
01741 
01742     QualType FTy = FI->getType();
01743     const FieldRegion* FR = MRMgr.getFieldRegion(&*FI, R);
01744 
01745     if (FTy->isArrayType())
01746       newStore = BindArray(newStore.getStore(), FR, *VI);
01747     else if (FTy->isStructureOrClassType())
01748       newStore = BindStruct(newStore.getStore(), FR, *VI);
01749     else
01750       newStore = Bind(newStore.getStore(), svalBuilder.makeLoc(FR), *VI);
01751     ++VI;
01752   }
01753 
01754   // There may be fewer values in the initialize list than the fields of struct.
01755   if (FI != FE) {
01756     RegionBindings B = GetRegionBindings(newStore.getStore());
01757     B = addBinding(B, R, BindingKey::Default, svalBuilder.makeIntVal(0, false));
01758     newStore = StoreRef(B.getRootWithoutRetain(), *this);
01759   }
01760 
01761   return newStore;
01762 }
01763 
01764 StoreRef RegionStoreManager::KillStruct(Store store, const TypedRegion* R,
01765                                      SVal DefaultVal) {
01766   BindingKey key = BindingKey::Make(R, BindingKey::Default);
01767   
01768   // The BindingKey may be "invalid" if we cannot handle the region binding
01769   // explicitly.  One example is something like array[index], where index
01770   // is a symbolic value.  In such cases, we want to invalidate the entire
01771   // array, as the index assignment could have been to any element.  In
01772   // the case of nested symbolic indices, we need to march up the region
01773   // hierarchy untile we reach a region whose binding we can reason about.
01774   const SubRegion *subReg = R;
01775 
01776   while (!key.isValid()) {
01777     if (const SubRegion *tmp = dyn_cast<SubRegion>(subReg->getSuperRegion())) {
01778       subReg = tmp;
01779       key = BindingKey::Make(tmp, BindingKey::Default);
01780     }
01781     else
01782       break;
01783   }                                 
01784 
01785   // Remove the old bindings, using 'subReg' as the root of all regions
01786   // we will invalidate.
01787   RegionBindings B = GetRegionBindings(store);
01788   OwningPtr<RegionStoreSubRegionMap>
01789     SubRegions(getRegionStoreSubRegionMap(store));
01790   RemoveSubRegionBindings(B, subReg, *SubRegions);
01791 
01792   // Set the default value of the struct region to "unknown".
01793   if (!key.isValid())
01794     return StoreRef(B.getRootWithoutRetain(), *this);
01795   
01796   return StoreRef(addBinding(B, key, DefaultVal).getRootWithoutRetain(), *this);
01797 }
01798 
01799 StoreRef RegionStoreManager::CopyLazyBindings(nonloc::LazyCompoundVal V,
01800                                               Store store,
01801                                               const TypedRegion *R) {
01802 
01803   // Nuke the old bindings stemming from R.
01804   RegionBindings B = GetRegionBindings(store);
01805 
01806   OwningPtr<RegionStoreSubRegionMap>
01807     SubRegions(getRegionStoreSubRegionMap(store));
01808 
01809   // B and DVM are updated after the call to RemoveSubRegionBindings.
01810   RemoveSubRegionBindings(B, R, *SubRegions.get());
01811 
01812   // Now copy the bindings.  This amounts to just binding 'V' to 'R'.  This
01813   // results in a zero-copy algorithm.
01814   return StoreRef(addBinding(B, R, BindingKey::Default,
01815                              V).getRootWithoutRetain(), *this);
01816 }
01817 
01818 //===----------------------------------------------------------------------===//
01819 // "Raw" retrievals and bindings.
01820 //===----------------------------------------------------------------------===//
01821 
01822 
01823 RegionBindings RegionStoreManager::addBinding(RegionBindings B, BindingKey K,
01824                                               SVal V) {
01825   if (!K.isValid())
01826     return B;
01827   return RBFactory.add(B, K, V);
01828 }
01829 
01830 RegionBindings RegionStoreManager::addBinding(RegionBindings B,
01831                                               const MemRegion *R,
01832                                               BindingKey::Kind k, SVal V) {
01833   return addBinding(B, BindingKey::Make(R, k), V);
01834 }
01835 
01836 const SVal *RegionStoreManager::lookup(RegionBindings B, BindingKey K) {
01837   if (!K.isValid())
01838     return NULL;
01839   return B.lookup(K);
01840 }
01841 
01842 const SVal *RegionStoreManager::lookup(RegionBindings B,
01843                                        const MemRegion *R,
01844                                        BindingKey::Kind k) {
01845   return lookup(B, BindingKey::Make(R, k));
01846 }
01847 
01848 RegionBindings RegionStoreManager::removeBinding(RegionBindings B,
01849                                                  BindingKey K) {
01850   if (!K.isValid())
01851     return B;
01852   return RBFactory.remove(B, K);
01853 }
01854 
01855 RegionBindings RegionStoreManager::removeBinding(RegionBindings B,
01856                                                  const MemRegion *R,
01857                                                 BindingKey::Kind k){
01858   return removeBinding(B, BindingKey::Make(R, k));
01859 }
01860 
01861 //===----------------------------------------------------------------------===//
01862 // State pruning.
01863 //===----------------------------------------------------------------------===//
01864 
01865 namespace {
01866 class removeDeadBindingsWorker :
01867   public ClusterAnalysis<removeDeadBindingsWorker> {
01868   SmallVector<const SymbolicRegion*, 12> Postponed;
01869   SymbolReaper &SymReaper;
01870   const StackFrameContext *CurrentLCtx;
01871 
01872 public:
01873   removeDeadBindingsWorker(RegionStoreManager &rm,
01874                            ProgramStateManager &stateMgr,
01875                            RegionBindings b, SymbolReaper &symReaper,
01876                            const StackFrameContext *LCtx)
01877     : ClusterAnalysis<removeDeadBindingsWorker>(rm, stateMgr, b,
01878                                                 /* includeGlobals = */ false),
01879       SymReaper(symReaper), CurrentLCtx(LCtx) {}
01880 
01881   // Called by ClusterAnalysis.
01882   void VisitAddedToCluster(const MemRegion *baseR, RegionCluster &C);
01883   void VisitCluster(const MemRegion *baseR, BindingKey *I, BindingKey *E);
01884 
01885   void VisitBindingKey(BindingKey K);
01886   bool UpdatePostponed();
01887   void VisitBinding(SVal V);
01888 };
01889 }
01890 
01891 void removeDeadBindingsWorker::VisitAddedToCluster(const MemRegion *baseR,
01892                                                    RegionCluster &C) {
01893 
01894   if (const VarRegion *VR = dyn_cast<VarRegion>(baseR)) {
01895     if (SymReaper.isLive(VR))
01896       AddToWorkList(baseR, C);
01897 
01898     return;
01899   }
01900 
01901   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) {
01902     if (SymReaper.isLive(SR->getSymbol()))
01903       AddToWorkList(SR, C);
01904     else
01905       Postponed.push_back(SR);
01906 
01907     return;
01908   }
01909 
01910   if (isa<NonStaticGlobalSpaceRegion>(baseR)) {
01911     AddToWorkList(baseR, C);
01912     return;
01913   }
01914 
01915   // CXXThisRegion in the current or parent location context is live.
01916   if (const CXXThisRegion *TR = dyn_cast<CXXThisRegion>(baseR)) {
01917     const StackArgumentsSpaceRegion *StackReg =
01918       cast<StackArgumentsSpaceRegion>(TR->getSuperRegion());
01919     const StackFrameContext *RegCtx = StackReg->getStackFrame();
01920     if (RegCtx == CurrentLCtx || RegCtx->isParentOf(CurrentLCtx))
01921       AddToWorkList(TR, C);
01922   }
01923 }
01924 
01925 void removeDeadBindingsWorker::VisitCluster(const MemRegion *baseR,
01926                                             BindingKey *I, BindingKey *E) {
01927   for ( ; I != E; ++I)
01928     VisitBindingKey(*I);
01929 }
01930 
01931 void removeDeadBindingsWorker::VisitBinding(SVal V) {
01932   // Is it a LazyCompoundVal?  All referenced regions are live as well.
01933   if (const nonloc::LazyCompoundVal *LCS =
01934       dyn_cast<nonloc::LazyCompoundVal>(&V)) {
01935 
01936     const MemRegion *LazyR = LCS->getRegion();
01937     RegionBindings B = RegionStoreManager::GetRegionBindings(LCS->getStore());
01938     for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){
01939       const SubRegion *baseR = dyn_cast<SubRegion>(RI.getKey().getRegion());
01940       if (baseR && baseR->isSubRegionOf(LazyR))
01941         VisitBinding(RI.getData());
01942     }
01943     return;
01944   }
01945 
01946   // If V is a region, then add it to the worklist.
01947   if (const MemRegion *R = V.getAsRegion())
01948     AddToWorkList(R);
01949 
01950   // Update the set of live symbols.
01951   for (SymExpr::symbol_iterator SI = V.symbol_begin(), SE = V.symbol_end();
01952        SI!=SE; ++SI)
01953     SymReaper.markLive(*SI);
01954 }
01955 
01956 void removeDeadBindingsWorker::VisitBindingKey(BindingKey K) {
01957   const MemRegion *R = K.getRegion();
01958 
01959   // Mark this region "live" by adding it to the worklist.  This will cause
01960   // use to visit all regions in the cluster (if we haven't visited them
01961   // already).
01962   if (AddToWorkList(R)) {
01963     // Mark the symbol for any live SymbolicRegion as "live".  This means we
01964     // should continue to track that symbol.
01965     if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(R))
01966       SymReaper.markLive(SymR->getSymbol());
01967 
01968     // For BlockDataRegions, enqueue the VarRegions for variables marked
01969     // with __block (passed-by-reference).
01970     // via BlockDeclRefExprs.
01971     if (const BlockDataRegion *BD = dyn_cast<BlockDataRegion>(R)) {
01972       for (BlockDataRegion::referenced_vars_iterator
01973            RI = BD->referenced_vars_begin(), RE = BD->referenced_vars_end();
01974            RI != RE; ++RI) {
01975         if ((*RI)->getDecl()->getAttr<BlocksAttr>())
01976           AddToWorkList(*RI);
01977       }
01978 
01979       // No possible data bindings on a BlockDataRegion.
01980       return;
01981     }
01982   }
01983 
01984   // Visit the data binding for K.
01985   if (const SVal *V = RM.lookup(B, K))
01986     VisitBinding(*V);
01987 }
01988 
01989 bool removeDeadBindingsWorker::UpdatePostponed() {
01990   // See if any postponed SymbolicRegions are actually live now, after
01991   // having done a scan.
01992   bool changed = false;
01993 
01994   for (SmallVectorImpl<const SymbolicRegion*>::iterator
01995         I = Postponed.begin(), E = Postponed.end() ; I != E ; ++I) {
01996     if (const SymbolicRegion *SR = cast_or_null<SymbolicRegion>(*I)) {
01997       if (SymReaper.isLive(SR->getSymbol())) {
01998         changed |= AddToWorkList(SR);
01999         *I = NULL;
02000       }
02001     }
02002   }
02003 
02004   return changed;
02005 }
02006 
02007 StoreRef RegionStoreManager::removeDeadBindings(Store store,
02008                                                 const StackFrameContext *LCtx,
02009                                                 SymbolReaper& SymReaper) {
02010   RegionBindings B = GetRegionBindings(store);
02011   removeDeadBindingsWorker W(*this, StateMgr, B, SymReaper, LCtx);
02012   W.GenerateClusters();
02013 
02014   // Enqueue the region roots onto the worklist.
02015   for (SymbolReaper::region_iterator I = SymReaper.region_begin(),
02016        E = SymReaper.region_end(); I != E; ++I) {
02017     W.AddToWorkList(*I);
02018   }
02019 
02020   do W.RunWorkList(); while (W.UpdatePostponed());
02021 
02022   // We have now scanned the store, marking reachable regions and symbols
02023   // as live.  We now remove all the regions that are dead from the store
02024   // as well as update DSymbols with the set symbols that are now dead.
02025   for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
02026     const BindingKey &K = I.getKey();
02027 
02028     // If the cluster has been visited, we know the region has been marked.
02029     if (W.isVisited(K.getRegion()))
02030       continue;
02031 
02032     // Remove the dead entry.
02033     B = removeBinding(B, K);
02034 
02035     // Mark all non-live symbols that this binding references as dead.
02036     if (const SymbolicRegion* SymR = dyn_cast<SymbolicRegion>(K.getRegion()))
02037       SymReaper.maybeDead(SymR->getSymbol());
02038 
02039     SVal X = I.getData();
02040     SymExpr::symbol_iterator SI = X.symbol_begin(), SE = X.symbol_end();
02041     for (; SI != SE; ++SI)
02042       SymReaper.maybeDead(*SI);
02043   }
02044 
02045   return StoreRef(B.getRootWithoutRetain(), *this);
02046 }
02047 
02048 
02049 StoreRef RegionStoreManager::enterStackFrame(ProgramStateRef state,
02050                                              const LocationContext *callerCtx,
02051                                              const StackFrameContext *calleeCtx)
02052 {
02053   FunctionDecl const *FD = cast<FunctionDecl>(calleeCtx->getDecl());
02054   FunctionDecl::param_const_iterator PI = FD->param_begin(), 
02055                                      PE = FD->param_end();
02056   StoreRef store = StoreRef(state->getStore(), *this);
02057 
02058   if (CallExpr const *CE = dyn_cast<CallExpr>(calleeCtx->getCallSite())) {
02059     CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end();
02060 
02061     // Copy the arg expression value to the arg variables.  We check that
02062     // PI != PE because the actual number of arguments may be different than
02063     // the function declaration.
02064     for (; AI != AE && PI != PE; ++AI, ++PI) {
02065       SVal ArgVal = state->getSVal(*AI, callerCtx);
02066       store = Bind(store.getStore(),
02067                    svalBuilder.makeLoc(MRMgr.getVarRegion(*PI, calleeCtx)),
02068                    ArgVal);
02069     }
02070   } else if (const CXXConstructExpr *CE =
02071                dyn_cast<CXXConstructExpr>(calleeCtx->getCallSite())) {
02072     CXXConstructExpr::const_arg_iterator AI = CE->arg_begin(),
02073       AE = CE->arg_end();
02074 
02075     // Copy the arg expression value to the arg variables.
02076     for (; AI != AE; ++AI, ++PI) {
02077       SVal ArgVal = state->getSVal(*AI, callerCtx);
02078       store = Bind(store.getStore(),
02079                    svalBuilder.makeLoc(MRMgr.getVarRegion(*PI, calleeCtx)),
02080                    ArgVal);
02081     }
02082   } else
02083     assert(isa<CXXDestructorDecl>(calleeCtx->getDecl()));
02084 
02085   return store;
02086 }
02087 
02088 //===----------------------------------------------------------------------===//
02089 // Utility methods.
02090 //===----------------------------------------------------------------------===//
02091 
02092 void RegionStoreManager::print(Store store, raw_ostream &OS,
02093                                const char* nl, const char *sep) {
02094   RegionBindings B = GetRegionBindings(store);
02095   OS << "Store (direct and default bindings), "
02096      << (void*) B.getRootWithoutRetain()
02097      << " :" << nl;
02098 
02099   for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
02100     OS << ' ' << I.getKey() << " : " << I.getData() << nl;
02101 }