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