1 //== RegionStore.cpp - Field-sensitive store model --------------*- C++ -*--==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
16 //===----------------------------------------------------------------------===//
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/Analysis/Analyses/LiveVariables.h"
21 #include "clang/Analysis/AnalysisContext.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
29 #include "llvm/ADT/ImmutableMap.h"
30 #include "llvm/ADT/Optional.h"
31 #include "llvm/Support/raw_ostream.h"
34 using namespace clang;
37 //===----------------------------------------------------------------------===//
38 // Representation of binding keys.
39 //===----------------------------------------------------------------------===//
44 enum Kind { Default = 0x0, Direct = 0x1 };
46 enum { Symbolic = 0x2 };
48 llvm::PointerIntPair<const MemRegion *, 2> P;
51 /// Create a key for a binding to region \p r, which has a symbolic offset
52 /// from region \p Base.
53 explicit BindingKey(const SubRegion *r, const SubRegion *Base, Kind k)
54 : P(r, k | Symbolic), Data(reinterpret_cast<uintptr_t>(Base)) {
55 assert(r && Base && "Must have known regions.");
56 assert(getConcreteOffsetRegion() == Base && "Failed to store base region");
59 /// Create a key for a binding at \p offset from base region \p r.
60 explicit BindingKey(const MemRegion *r, uint64_t offset, Kind k)
61 : P(r, k), Data(offset) {
62 assert(r && "Must have known regions.");
63 assert(getOffset() == offset && "Failed to store offset");
64 assert((r == r->getBaseRegion() || isa<ObjCIvarRegion>(r)) && "Not a base");
68 bool isDirect() const { return P.getInt() & Direct; }
69 bool hasSymbolicOffset() const { return P.getInt() & Symbolic; }
71 const MemRegion *getRegion() const { return P.getPointer(); }
72 uint64_t getOffset() const {
73 assert(!hasSymbolicOffset());
77 const SubRegion *getConcreteOffsetRegion() const {
78 assert(hasSymbolicOffset());
79 return reinterpret_cast<const SubRegion *>(static_cast<uintptr_t>(Data));
82 const MemRegion *getBaseRegion() const {
83 if (hasSymbolicOffset())
84 return getConcreteOffsetRegion()->getBaseRegion();
85 return getRegion()->getBaseRegion();
88 void Profile(llvm::FoldingSetNodeID& ID) const {
89 ID.AddPointer(P.getOpaqueValue());
93 static BindingKey Make(const MemRegion *R, Kind k);
95 bool operator<(const BindingKey &X) const {
96 if (P.getOpaqueValue() < X.P.getOpaqueValue())
98 if (P.getOpaqueValue() > X.P.getOpaqueValue())
100 return Data < X.Data;
103 bool operator==(const BindingKey &X) const {
104 return P.getOpaqueValue() == X.P.getOpaqueValue() &&
110 } // end anonymous namespace
112 BindingKey BindingKey::Make(const MemRegion *R, Kind k) {
113 const RegionOffset &RO = R->getAsOffset();
114 if (RO.hasSymbolicOffset())
115 return BindingKey(cast<SubRegion>(R), cast<SubRegion>(RO.getRegion()), k);
117 return BindingKey(RO.getRegion(), RO.getOffset(), k);
122 raw_ostream &operator<<(raw_ostream &os, BindingKey K) {
123 os << '(' << K.getRegion();
124 if (!K.hasSymbolicOffset())
125 os << ',' << K.getOffset();
126 os << ',' << (K.isDirect() ? "direct" : "default")
131 template <typename T> struct isPodLike;
132 template <> struct isPodLike<BindingKey> {
133 static const bool value = true;
135 } // end llvm namespace
137 LLVM_DUMP_METHOD void BindingKey::dump() const { llvm::errs() << *this; }
139 //===----------------------------------------------------------------------===//
140 // Actual Store type.
141 //===----------------------------------------------------------------------===//
143 typedef llvm::ImmutableMap<BindingKey, SVal> ClusterBindings;
144 typedef llvm::ImmutableMapRef<BindingKey, SVal> ClusterBindingsRef;
145 typedef std::pair<BindingKey, SVal> BindingPair;
147 typedef llvm::ImmutableMap<const MemRegion *, ClusterBindings>
151 class RegionBindingsRef : public llvm::ImmutableMapRef<const MemRegion *,
153 ClusterBindings::Factory *CBFactory;
156 typedef llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>
159 RegionBindingsRef(ClusterBindings::Factory &CBFactory,
160 const RegionBindings::TreeTy *T,
161 RegionBindings::TreeTy::Factory *F)
162 : llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>(T, F),
163 CBFactory(&CBFactory) {}
165 RegionBindingsRef(const ParentTy &P, ClusterBindings::Factory &CBFactory)
166 : llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>(P),
167 CBFactory(&CBFactory) {}
169 RegionBindingsRef add(key_type_ref K, data_type_ref D) const {
170 return RegionBindingsRef(static_cast<const ParentTy *>(this)->add(K, D),
174 RegionBindingsRef remove(key_type_ref K) const {
175 return RegionBindingsRef(static_cast<const ParentTy *>(this)->remove(K),
179 RegionBindingsRef addBinding(BindingKey K, SVal V) const;
181 RegionBindingsRef addBinding(const MemRegion *R,
182 BindingKey::Kind k, SVal V) const;
184 const SVal *lookup(BindingKey K) const;
185 const SVal *lookup(const MemRegion *R, BindingKey::Kind k) const;
186 using llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>::lookup;
188 RegionBindingsRef removeBinding(BindingKey K);
190 RegionBindingsRef removeBinding(const MemRegion *R,
193 RegionBindingsRef removeBinding(const MemRegion *R) {
194 return removeBinding(R, BindingKey::Direct).
195 removeBinding(R, BindingKey::Default);
198 Optional<SVal> getDirectBinding(const MemRegion *R) const;
200 /// getDefaultBinding - Returns an SVal* representing an optional default
201 /// binding associated with a region and its subregions.
202 Optional<SVal> getDefaultBinding(const MemRegion *R) const;
204 /// Return the internal tree as a Store.
205 Store asStore() const {
206 return asImmutableMap().getRootWithoutRetain();
209 void dump(raw_ostream &OS, const char *nl) const {
210 for (iterator I = begin(), E = end(); I != E; ++I) {
211 const ClusterBindings &Cluster = I.getData();
212 for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
214 OS << ' ' << CI.getKey() << " : " << CI.getData() << nl;
220 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs(), "\n"); }
222 } // end anonymous namespace
224 typedef const RegionBindingsRef& RegionBindingsConstRef;
226 Optional<SVal> RegionBindingsRef::getDirectBinding(const MemRegion *R) const {
227 return Optional<SVal>::create(lookup(R, BindingKey::Direct));
230 Optional<SVal> RegionBindingsRef::getDefaultBinding(const MemRegion *R) const {
231 if (R->isBoundable())
232 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R))
233 if (TR->getValueType()->isUnionType())
236 return Optional<SVal>::create(lookup(R, BindingKey::Default));
239 RegionBindingsRef RegionBindingsRef::addBinding(BindingKey K, SVal V) const {
240 const MemRegion *Base = K.getBaseRegion();
242 const ClusterBindings *ExistingCluster = lookup(Base);
243 ClusterBindings Cluster =
244 (ExistingCluster ? *ExistingCluster : CBFactory->getEmptyMap());
246 ClusterBindings NewCluster = CBFactory->add(Cluster, K, V);
247 return add(Base, NewCluster);
251 RegionBindingsRef RegionBindingsRef::addBinding(const MemRegion *R,
254 return addBinding(BindingKey::Make(R, k), V);
257 const SVal *RegionBindingsRef::lookup(BindingKey K) const {
258 const ClusterBindings *Cluster = lookup(K.getBaseRegion());
261 return Cluster->lookup(K);
264 const SVal *RegionBindingsRef::lookup(const MemRegion *R,
265 BindingKey::Kind k) const {
266 return lookup(BindingKey::Make(R, k));
269 RegionBindingsRef RegionBindingsRef::removeBinding(BindingKey K) {
270 const MemRegion *Base = K.getBaseRegion();
271 const ClusterBindings *Cluster = lookup(Base);
275 ClusterBindings NewCluster = CBFactory->remove(*Cluster, K);
276 if (NewCluster.isEmpty())
278 return add(Base, NewCluster);
281 RegionBindingsRef RegionBindingsRef::removeBinding(const MemRegion *R,
283 return removeBinding(BindingKey::Make(R, k));
286 //===----------------------------------------------------------------------===//
287 // Fine-grained control of RegionStoreManager.
288 //===----------------------------------------------------------------------===//
291 struct minimal_features_tag {};
292 struct maximal_features_tag {};
294 class RegionStoreFeatures {
297 RegionStoreFeatures(minimal_features_tag) :
298 SupportsFields(false) {}
300 RegionStoreFeatures(maximal_features_tag) :
301 SupportsFields(true) {}
303 void enableFields(bool t) { SupportsFields = t; }
305 bool supportsFields() const { return SupportsFields; }
309 //===----------------------------------------------------------------------===//
310 // Main RegionStore logic.
311 //===----------------------------------------------------------------------===//
314 class invalidateRegionsWorker;
316 class RegionStoreManager : public StoreManager {
318 const RegionStoreFeatures Features;
320 RegionBindings::Factory RBFactory;
321 mutable ClusterBindings::Factory CBFactory;
323 typedef std::vector<SVal> SValListTy;
325 typedef llvm::DenseMap<const LazyCompoundValData *,
326 SValListTy> LazyBindingsMapTy;
327 LazyBindingsMapTy LazyBindingsMap;
329 /// The largest number of fields a struct can have and still be
330 /// considered "small".
332 /// This is currently used to decide whether or not it is worth "forcing" a
333 /// LazyCompoundVal on bind.
335 /// This is controlled by 'region-store-small-struct-limit' option.
336 /// To disable all small-struct-dependent behavior, set the option to "0".
337 unsigned SmallStructLimit;
339 /// \brief A helper used to populate the work list with the given set of
341 void populateWorkList(invalidateRegionsWorker &W,
342 ArrayRef<SVal> Values,
343 InvalidatedRegions *TopLevelRegions);
346 RegionStoreManager(ProgramStateManager& mgr, const RegionStoreFeatures &f)
347 : StoreManager(mgr), Features(f),
348 RBFactory(mgr.getAllocator()), CBFactory(mgr.getAllocator()),
349 SmallStructLimit(0) {
350 if (SubEngine *Eng = StateMgr.getOwningEngine()) {
351 AnalyzerOptions &Options = Eng->getAnalysisManager().options;
353 Options.getOptionAsInteger("region-store-small-struct-limit", 2);
358 /// setImplicitDefaultValue - Set the default binding for the provided
359 /// MemRegion to the value implicitly defined for compound literals when
360 /// the value is not specified.
361 RegionBindingsRef setImplicitDefaultValue(RegionBindingsConstRef B,
362 const MemRegion *R, QualType T);
364 /// ArrayToPointer - Emulates the "decay" of an array to a pointer
365 /// type. 'Array' represents the lvalue of the array being decayed
366 /// to a pointer, and the returned SVal represents the decayed
367 /// version of that lvalue (i.e., a pointer to the first element of
368 /// the array). This is called by ExprEngine when evaluating
369 /// casts from arrays to pointers.
370 SVal ArrayToPointer(Loc Array, QualType ElementTy) override;
372 StoreRef getInitialStore(const LocationContext *InitLoc) override {
373 return StoreRef(RBFactory.getEmptyMap().getRootWithoutRetain(), *this);
376 //===-------------------------------------------------------------------===//
377 // Binding values to regions.
378 //===-------------------------------------------------------------------===//
379 RegionBindingsRef invalidateGlobalRegion(MemRegion::Kind K,
382 const LocationContext *LCtx,
384 InvalidatedRegions *Invalidated);
386 StoreRef invalidateRegions(Store store,
387 ArrayRef<SVal> Values,
388 const Expr *E, unsigned Count,
389 const LocationContext *LCtx,
390 const CallEvent *Call,
391 InvalidatedSymbols &IS,
392 RegionAndSymbolInvalidationTraits &ITraits,
393 InvalidatedRegions *Invalidated,
394 InvalidatedRegions *InvalidatedTopLevel) override;
396 bool scanReachableSymbols(Store S, const MemRegion *R,
397 ScanReachableSymbols &Callbacks) override;
399 RegionBindingsRef removeSubRegionBindings(RegionBindingsConstRef B,
402 public: // Part of public interface to class.
404 StoreRef Bind(Store store, Loc LV, SVal V) override {
405 return StoreRef(bind(getRegionBindings(store), LV, V).asStore(), *this);
408 RegionBindingsRef bind(RegionBindingsConstRef B, Loc LV, SVal V);
410 // BindDefault is only used to initialize a region with a default value.
411 StoreRef BindDefault(Store store, const MemRegion *R, SVal V) override {
412 RegionBindingsRef B = getRegionBindings(store);
413 assert(!B.lookup(R, BindingKey::Direct));
415 BindingKey Key = BindingKey::Make(R, BindingKey::Default);
417 const SubRegion *SR = cast<SubRegion>(R);
418 assert(SR->getAsOffset().getOffset() ==
419 SR->getSuperRegion()->getAsOffset().getOffset() &&
420 "A default value must come from a super-region");
421 B = removeSubRegionBindings(B, SR);
423 B = B.addBinding(Key, V);
426 return StoreRef(B.asImmutableMap().getRootWithoutRetain(), *this);
429 /// Attempt to extract the fields of \p LCV and bind them to the struct region
432 /// This path is used when it seems advantageous to "force" loading the values
433 /// within a LazyCompoundVal to bind memberwise to the struct region, rather
434 /// than using a Default binding at the base of the entire region. This is a
435 /// heuristic attempting to avoid building long chains of LazyCompoundVals.
437 /// \returns The updated store bindings, or \c None if binding non-lazily
438 /// would be too expensive.
439 Optional<RegionBindingsRef> tryBindSmallStruct(RegionBindingsConstRef B,
440 const TypedValueRegion *R,
441 const RecordDecl *RD,
442 nonloc::LazyCompoundVal LCV);
444 /// BindStruct - Bind a compound value to a structure.
445 RegionBindingsRef bindStruct(RegionBindingsConstRef B,
446 const TypedValueRegion* R, SVal V);
448 /// BindVector - Bind a compound value to a vector.
449 RegionBindingsRef bindVector(RegionBindingsConstRef B,
450 const TypedValueRegion* R, SVal V);
452 RegionBindingsRef bindArray(RegionBindingsConstRef B,
453 const TypedValueRegion* R,
456 /// Clears out all bindings in the given region and assigns a new value
457 /// as a Default binding.
458 RegionBindingsRef bindAggregate(RegionBindingsConstRef B,
459 const TypedRegion *R,
462 /// \brief Create a new store with the specified binding removed.
463 /// \param ST the original store, that is the basis for the new store.
464 /// \param L the location whose binding should be removed.
465 StoreRef killBinding(Store ST, Loc L) override;
467 void incrementReferenceCount(Store store) override {
468 getRegionBindings(store).manualRetain();
471 /// If the StoreManager supports it, decrement the reference count of
472 /// the specified Store object. If the reference count hits 0, the memory
473 /// associated with the object is recycled.
474 void decrementReferenceCount(Store store) override {
475 getRegionBindings(store).manualRelease();
478 bool includedInBindings(Store store, const MemRegion *region) const override;
480 /// \brief Return the value bound to specified location in a given state.
482 /// The high level logic for this method is this:
485 /// return L's binding
486 /// else if L is in killset
489 /// if L is on stack or heap
493 SVal getBinding(Store S, Loc L, QualType T) override {
494 return getBinding(getRegionBindings(S), L, T);
497 Optional<SVal> getDefaultBinding(Store S, const MemRegion *R) override {
498 RegionBindingsRef B = getRegionBindings(S);
499 return B.getDefaultBinding(R);
502 SVal getBinding(RegionBindingsConstRef B, Loc L, QualType T = QualType());
504 SVal getBindingForElement(RegionBindingsConstRef B, const ElementRegion *R);
506 SVal getBindingForField(RegionBindingsConstRef B, const FieldRegion *R);
508 SVal getBindingForObjCIvar(RegionBindingsConstRef B, const ObjCIvarRegion *R);
510 SVal getBindingForVar(RegionBindingsConstRef B, const VarRegion *R);
512 SVal getBindingForLazySymbol(const TypedValueRegion *R);
514 SVal getBindingForFieldOrElementCommon(RegionBindingsConstRef B,
515 const TypedValueRegion *R,
518 SVal getLazyBinding(const SubRegion *LazyBindingRegion,
519 RegionBindingsRef LazyBinding);
521 /// Get bindings for the values in a struct and return a CompoundVal, used
522 /// when doing struct copy:
525 /// y's value is retrieved by this method.
526 SVal getBindingForStruct(RegionBindingsConstRef B, const TypedValueRegion *R);
527 SVal getBindingForArray(RegionBindingsConstRef B, const TypedValueRegion *R);
528 NonLoc createLazyBinding(RegionBindingsConstRef B, const TypedValueRegion *R);
530 /// Used to lazily generate derived symbols for bindings that are defined
531 /// implicitly by default bindings in a super region.
533 /// Note that callers may need to specially handle LazyCompoundVals, which
534 /// are returned as is in case the caller needs to treat them differently.
535 Optional<SVal> getBindingForDerivedDefaultValue(RegionBindingsConstRef B,
536 const MemRegion *superR,
537 const TypedValueRegion *R,
540 /// Get the state and region whose binding this region \p R corresponds to.
542 /// If there is no lazy binding for \p R, the returned value will have a null
543 /// \c second. Note that a null pointer can represents a valid Store.
544 std::pair<Store, const SubRegion *>
545 findLazyBinding(RegionBindingsConstRef B, const SubRegion *R,
546 const SubRegion *originalRegion);
548 /// Returns the cached set of interesting SVals contained within a lazy
551 /// The precise value of "interesting" is determined for the purposes of
552 /// RegionStore's internal analysis. It must always contain all regions and
553 /// symbols, but may omit constants and other kinds of SVal.
554 const SValListTy &getInterestingValues(nonloc::LazyCompoundVal LCV);
556 //===------------------------------------------------------------------===//
558 //===------------------------------------------------------------------===//
560 /// removeDeadBindings - Scans the RegionStore of 'state' for dead values.
561 /// It returns a new Store with these values removed.
562 StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx,
563 SymbolReaper& SymReaper) override;
565 //===------------------------------------------------------------------===//
567 //===------------------------------------------------------------------===//
569 // FIXME: This method will soon be eliminated; see the note in Store.h.
570 DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state,
572 QualType EleTy) override;
574 //===------------------------------------------------------------------===//
576 //===------------------------------------------------------------------===//
578 RegionBindingsRef getRegionBindings(Store store) const {
579 return RegionBindingsRef(CBFactory,
580 static_cast<const RegionBindings::TreeTy*>(store),
581 RBFactory.getTreeFactory());
584 void print(Store store, raw_ostream &Out, const char* nl,
585 const char *sep) override;
587 void iterBindings(Store store, BindingsHandler& f) override {
588 RegionBindingsRef B = getRegionBindings(store);
589 for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; ++I) {
590 const ClusterBindings &Cluster = I.getData();
591 for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
593 const BindingKey &K = CI.getKey();
596 if (const SubRegion *R = dyn_cast<SubRegion>(K.getRegion())) {
597 // FIXME: Possibly incorporate the offset?
598 if (!f.HandleBinding(*this, store, R, CI.getData()))
606 } // end anonymous namespace
608 //===----------------------------------------------------------------------===//
609 // RegionStore creation.
610 //===----------------------------------------------------------------------===//
612 std::unique_ptr<StoreManager>
613 ento::CreateRegionStoreManager(ProgramStateManager &StMgr) {
614 RegionStoreFeatures F = maximal_features_tag();
615 return llvm::make_unique<RegionStoreManager>(StMgr, F);
618 std::unique_ptr<StoreManager>
619 ento::CreateFieldsOnlyRegionStoreManager(ProgramStateManager &StMgr) {
620 RegionStoreFeatures F = minimal_features_tag();
621 F.enableFields(true);
622 return llvm::make_unique<RegionStoreManager>(StMgr, F);
626 //===----------------------------------------------------------------------===//
627 // Region Cluster analysis.
628 //===----------------------------------------------------------------------===//
631 /// Used to determine which global regions are automatically included in the
632 /// initial worklist of a ClusterAnalysis.
633 enum GlobalsFilterKind {
634 /// Don't include any global regions.
636 /// Only include system globals.
638 /// Include all global regions.
642 template <typename DERIVED>
643 class ClusterAnalysis {
645 typedef llvm::DenseMap<const MemRegion *, const ClusterBindings *> ClusterMap;
646 typedef const MemRegion * WorkListElement;
647 typedef SmallVector<WorkListElement, 10> WorkList;
649 llvm::SmallPtrSet<const ClusterBindings *, 16> Visited;
653 RegionStoreManager &RM;
655 SValBuilder &svalBuilder;
661 const ClusterBindings *getCluster(const MemRegion *R) {
665 /// Returns true if all clusters in the given memspace should be initially
666 /// included in the cluster analysis. Subclasses may provide their
667 /// own implementation.
668 bool includeEntireMemorySpace(const MemRegion *Base) {
673 ClusterAnalysis(RegionStoreManager &rm, ProgramStateManager &StateMgr,
675 : RM(rm), Ctx(StateMgr.getContext()),
676 svalBuilder(StateMgr.getSValBuilder()), B(std::move(b)) {}
678 RegionBindingsRef getRegionBindings() const { return B; }
680 bool isVisited(const MemRegion *R) {
681 return Visited.count(getCluster(R));
684 void GenerateClusters() {
685 // Scan the entire set of bindings and record the region clusters.
686 for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end();
688 const MemRegion *Base = RI.getKey();
690 const ClusterBindings &Cluster = RI.getData();
691 assert(!Cluster.isEmpty() && "Empty clusters should be removed");
692 static_cast<DERIVED*>(this)->VisitAddedToCluster(Base, Cluster);
694 // If the base's memspace should be entirely invalidated, add the cluster
695 // to the workspace up front.
696 if (static_cast<DERIVED*>(this)->includeEntireMemorySpace(Base))
697 AddToWorkList(WorkListElement(Base), &Cluster);
701 bool AddToWorkList(WorkListElement E, const ClusterBindings *C) {
702 if (C && !Visited.insert(C).second)
708 bool AddToWorkList(const MemRegion *R) {
709 return static_cast<DERIVED*>(this)->AddToWorkList(R);
713 while (!WL.empty()) {
714 WorkListElement E = WL.pop_back_val();
715 const MemRegion *BaseR = E;
717 static_cast<DERIVED*>(this)->VisitCluster(BaseR, getCluster(BaseR));
721 void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C) {}
722 void VisitCluster(const MemRegion *baseR, const ClusterBindings *C) {}
724 void VisitCluster(const MemRegion *BaseR, const ClusterBindings *C,
726 static_cast<DERIVED*>(this)->VisitCluster(BaseR, C);
731 //===----------------------------------------------------------------------===//
732 // Binding invalidation.
733 //===----------------------------------------------------------------------===//
735 bool RegionStoreManager::scanReachableSymbols(Store S, const MemRegion *R,
736 ScanReachableSymbols &Callbacks) {
737 assert(R == R->getBaseRegion() && "Should only be called for base regions");
738 RegionBindingsRef B = getRegionBindings(S);
739 const ClusterBindings *Cluster = B.lookup(R);
744 for (ClusterBindings::iterator RI = Cluster->begin(), RE = Cluster->end();
746 if (!Callbacks.scan(RI.getData()))
753 static inline bool isUnionField(const FieldRegion *FR) {
754 return FR->getDecl()->getParent()->isUnion();
757 typedef SmallVector<const FieldDecl *, 8> FieldVector;
759 static void getSymbolicOffsetFields(BindingKey K, FieldVector &Fields) {
760 assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys");
762 const MemRegion *Base = K.getConcreteOffsetRegion();
763 const MemRegion *R = K.getRegion();
766 if (const FieldRegion *FR = dyn_cast<FieldRegion>(R))
767 if (!isUnionField(FR))
768 Fields.push_back(FR->getDecl());
770 R = cast<SubRegion>(R)->getSuperRegion();
774 static bool isCompatibleWithFields(BindingKey K, const FieldVector &Fields) {
775 assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys");
780 FieldVector FieldsInBindingKey;
781 getSymbolicOffsetFields(K, FieldsInBindingKey);
783 ptrdiff_t Delta = FieldsInBindingKey.size() - Fields.size();
785 return std::equal(FieldsInBindingKey.begin() + Delta,
786 FieldsInBindingKey.end(),
789 return std::equal(FieldsInBindingKey.begin(), FieldsInBindingKey.end(),
790 Fields.begin() - Delta);
793 /// Collects all bindings in \p Cluster that may refer to bindings within
796 /// Each binding is a pair whose \c first is the key (a BindingKey) and whose
797 /// \c second is the value (an SVal).
799 /// The \p IncludeAllDefaultBindings parameter specifies whether to include
800 /// default bindings that may extend beyond \p Top itself, e.g. if \p Top is
801 /// an aggregate within a larger aggregate with a default binding.
803 collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings,
804 SValBuilder &SVB, const ClusterBindings &Cluster,
805 const SubRegion *Top, BindingKey TopKey,
806 bool IncludeAllDefaultBindings) {
807 FieldVector FieldsInSymbolicSubregions;
808 if (TopKey.hasSymbolicOffset()) {
809 getSymbolicOffsetFields(TopKey, FieldsInSymbolicSubregions);
810 Top = cast<SubRegion>(TopKey.getConcreteOffsetRegion());
811 TopKey = BindingKey::Make(Top, BindingKey::Default);
814 // Find the length (in bits) of the region being invalidated.
815 uint64_t Length = UINT64_MAX;
816 SVal Extent = Top->getExtent(SVB);
817 if (Optional<nonloc::ConcreteInt> ExtentCI =
818 Extent.getAs<nonloc::ConcreteInt>()) {
819 const llvm::APSInt &ExtentInt = ExtentCI->getValue();
820 assert(ExtentInt.isNonNegative() || ExtentInt.isUnsigned());
821 // Extents are in bytes but region offsets are in bits. Be careful!
822 Length = ExtentInt.getLimitedValue() * SVB.getContext().getCharWidth();
823 } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(Top)) {
824 if (FR->getDecl()->isBitField())
825 Length = FR->getDecl()->getBitWidthValue(SVB.getContext());
828 for (ClusterBindings::iterator I = Cluster.begin(), E = Cluster.end();
830 BindingKey NextKey = I.getKey();
831 if (NextKey.getRegion() == TopKey.getRegion()) {
832 // FIXME: This doesn't catch the case where we're really invalidating a
833 // region with a symbolic offset. Example:
837 if (NextKey.getOffset() > TopKey.getOffset() &&
838 NextKey.getOffset() - TopKey.getOffset() < Length) {
839 // Case 1: The next binding is inside the region we're invalidating.
841 Bindings.push_back(*I);
843 } else if (NextKey.getOffset() == TopKey.getOffset()) {
844 // Case 2: The next binding is at the same offset as the region we're
845 // invalidating. In this case, we need to leave default bindings alone,
846 // since they may be providing a default value for a regions beyond what
847 // we're invalidating.
848 // FIXME: This is probably incorrect; consider invalidating an outer
849 // struct whose first field is bound to a LazyCompoundVal.
850 if (IncludeAllDefaultBindings || NextKey.isDirect())
851 Bindings.push_back(*I);
854 } else if (NextKey.hasSymbolicOffset()) {
855 const MemRegion *Base = NextKey.getConcreteOffsetRegion();
856 if (Top->isSubRegionOf(Base)) {
857 // Case 3: The next key is symbolic and we just changed something within
858 // its concrete region. We don't know if the binding is still valid, so
859 // we'll be conservative and include it.
860 if (IncludeAllDefaultBindings || NextKey.isDirect())
861 if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions))
862 Bindings.push_back(*I);
863 } else if (const SubRegion *BaseSR = dyn_cast<SubRegion>(Base)) {
864 // Case 4: The next key is symbolic, but we changed a known
865 // super-region. In this case the binding is certainly included.
866 if (Top == Base || BaseSR->isSubRegionOf(Top))
867 if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions))
868 Bindings.push_back(*I);
875 collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings,
876 SValBuilder &SVB, const ClusterBindings &Cluster,
877 const SubRegion *Top, bool IncludeAllDefaultBindings) {
878 collectSubRegionBindings(Bindings, SVB, Cluster, Top,
879 BindingKey::Make(Top, BindingKey::Default),
880 IncludeAllDefaultBindings);
884 RegionStoreManager::removeSubRegionBindings(RegionBindingsConstRef B,
885 const SubRegion *Top) {
886 BindingKey TopKey = BindingKey::Make(Top, BindingKey::Default);
887 const MemRegion *ClusterHead = TopKey.getBaseRegion();
889 if (Top == ClusterHead) {
890 // We can remove an entire cluster's bindings all in one go.
891 return B.remove(Top);
894 const ClusterBindings *Cluster = B.lookup(ClusterHead);
896 // If we're invalidating a region with a symbolic offset, we need to make
897 // sure we don't treat the base region as uninitialized anymore.
898 if (TopKey.hasSymbolicOffset()) {
899 const SubRegion *Concrete = TopKey.getConcreteOffsetRegion();
900 return B.addBinding(Concrete, BindingKey::Default, UnknownVal());
905 SmallVector<BindingPair, 32> Bindings;
906 collectSubRegionBindings(Bindings, svalBuilder, *Cluster, Top, TopKey,
907 /*IncludeAllDefaultBindings=*/false);
909 ClusterBindingsRef Result(*Cluster, CBFactory);
910 for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(),
913 Result = Result.remove(I->first);
915 // If we're invalidating a region with a symbolic offset, we need to make sure
916 // we don't treat the base region as uninitialized anymore.
917 // FIXME: This isn't very precise; see the example in
918 // collectSubRegionBindings.
919 if (TopKey.hasSymbolicOffset()) {
920 const SubRegion *Concrete = TopKey.getConcreteOffsetRegion();
921 Result = Result.add(BindingKey::Make(Concrete, BindingKey::Default),
925 if (Result.isEmpty())
926 return B.remove(ClusterHead);
927 return B.add(ClusterHead, Result.asImmutableMap());
931 class invalidateRegionsWorker : public ClusterAnalysis<invalidateRegionsWorker>
935 const LocationContext *LCtx;
936 InvalidatedSymbols &IS;
937 RegionAndSymbolInvalidationTraits &ITraits;
938 StoreManager::InvalidatedRegions *Regions;
939 GlobalsFilterKind GlobalsFilter;
941 invalidateRegionsWorker(RegionStoreManager &rm,
942 ProgramStateManager &stateMgr,
944 const Expr *ex, unsigned count,
945 const LocationContext *lctx,
946 InvalidatedSymbols &is,
947 RegionAndSymbolInvalidationTraits &ITraitsIn,
948 StoreManager::InvalidatedRegions *r,
949 GlobalsFilterKind GFK)
950 : ClusterAnalysis<invalidateRegionsWorker>(rm, stateMgr, b),
951 Ex(ex), Count(count), LCtx(lctx), IS(is), ITraits(ITraitsIn), Regions(r),
952 GlobalsFilter(GFK) {}
954 void VisitCluster(const MemRegion *baseR, const ClusterBindings *C);
955 void VisitBinding(SVal V);
957 using ClusterAnalysis::AddToWorkList;
959 bool AddToWorkList(const MemRegion *R);
961 /// Returns true if all clusters in the memory space for \p Base should be
963 bool includeEntireMemorySpace(const MemRegion *Base);
965 /// Returns true if the memory space of the given region is one of the global
966 /// regions specially included at the start of invalidation.
967 bool isInitiallyIncludedGlobalRegion(const MemRegion *R);
971 bool invalidateRegionsWorker::AddToWorkList(const MemRegion *R) {
972 bool doNotInvalidateSuperRegion = ITraits.hasTrait(
973 R, RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
974 const MemRegion *BaseR = doNotInvalidateSuperRegion ? R : R->getBaseRegion();
975 return AddToWorkList(WorkListElement(BaseR), getCluster(BaseR));
978 void invalidateRegionsWorker::VisitBinding(SVal V) {
979 // A symbol? Mark it touched by the invalidation.
980 if (SymbolRef Sym = V.getAsSymbol())
983 if (const MemRegion *R = V.getAsRegion()) {
988 // Is it a LazyCompoundVal? All references get invalidated as well.
989 if (Optional<nonloc::LazyCompoundVal> LCS =
990 V.getAs<nonloc::LazyCompoundVal>()) {
992 const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS);
994 for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(),
1003 void invalidateRegionsWorker::VisitCluster(const MemRegion *baseR,
1004 const ClusterBindings *C) {
1006 bool PreserveRegionsContents =
1007 ITraits.hasTrait(baseR,
1008 RegionAndSymbolInvalidationTraits::TK_PreserveContents);
1011 for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I)
1012 VisitBinding(I.getData());
1014 // Invalidate regions contents.
1015 if (!PreserveRegionsContents)
1016 B = B.remove(baseR);
1019 // BlockDataRegion? If so, invalidate captured variables that are passed
1021 if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) {
1022 for (BlockDataRegion::referenced_vars_iterator
1023 BI = BR->referenced_vars_begin(), BE = BR->referenced_vars_end() ;
1025 const VarRegion *VR = BI.getCapturedRegion();
1026 const VarDecl *VD = VR->getDecl();
1027 if (VD->hasAttr<BlocksAttr>() || !VD->hasLocalStorage()) {
1030 else if (Loc::isLocType(VR->getValueType())) {
1031 // Map the current bindings to a Store to retrieve the value
1032 // of the binding. If that binding itself is a region, we should
1033 // invalidate that region. This is because a block may capture
1034 // a pointer value, but the thing pointed by that pointer may
1036 SVal V = RM.getBinding(B, loc::MemRegionVal(VR));
1037 if (Optional<Loc> L = V.getAs<Loc>()) {
1038 if (const MemRegion *LR = L->getAsRegion())
1047 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR))
1048 IS.insert(SR->getSymbol());
1050 // Nothing else should be done in the case when we preserve regions context.
1051 if (PreserveRegionsContents)
1054 // Otherwise, we have a normal data region. Record that we touched the region.
1056 Regions->push_back(baseR);
1058 if (isa<AllocaRegion>(baseR) || isa<SymbolicRegion>(baseR)) {
1059 // Invalidate the region by setting its default value to
1060 // conjured symbol. The type of the symbol is irrelevant.
1061 DefinedOrUnknownSVal V =
1062 svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count);
1063 B = B.addBinding(baseR, BindingKey::Default, V);
1067 if (!baseR->isBoundable())
1070 const TypedValueRegion *TR = cast<TypedValueRegion>(baseR);
1071 QualType T = TR->getValueType();
1073 if (isInitiallyIncludedGlobalRegion(baseR)) {
1074 // If the region is a global and we are invalidating all globals,
1075 // erasing the entry is good enough. This causes all globals to be lazily
1076 // symbolicated from the same base symbol.
1080 if (T->isStructureOrClassType()) {
1081 // Invalidate the region by setting its default value to
1082 // conjured symbol. The type of the symbol is irrelevant.
1083 DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
1085 B = B.addBinding(baseR, BindingKey::Default, V);
1089 if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
1090 bool doNotInvalidateSuperRegion = ITraits.hasTrait(
1092 RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
1094 if (doNotInvalidateSuperRegion) {
1095 // We are not doing blank invalidation of the whole array region so we
1096 // have to manually invalidate each elements.
1097 Optional<uint64_t> NumElements;
1099 // Compute lower and upper offsets for region within array.
1100 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1101 NumElements = CAT->getSize().getZExtValue();
1102 if (!NumElements) // We are not dealing with a constant size array
1103 goto conjure_default;
1104 QualType ElementTy = AT->getElementType();
1105 uint64_t ElemSize = Ctx.getTypeSize(ElementTy);
1106 const RegionOffset &RO = baseR->getAsOffset();
1107 const MemRegion *SuperR = baseR->getBaseRegion();
1108 if (RO.hasSymbolicOffset()) {
1109 // If base region has a symbolic offset,
1110 // we revert to invalidating the super region.
1112 AddToWorkList(SuperR);
1113 goto conjure_default;
1116 uint64_t LowerOffset = RO.getOffset();
1117 uint64_t UpperOffset = LowerOffset + *NumElements * ElemSize;
1118 bool UpperOverflow = UpperOffset < LowerOffset;
1120 // Invalidate regions which are within array boundaries,
1121 // or have a symbolic offset.
1123 goto conjure_default;
1125 const ClusterBindings *C = B.lookup(SuperR);
1127 goto conjure_default;
1129 for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E;
1131 const BindingKey &BK = I.getKey();
1132 Optional<uint64_t> ROffset =
1133 BK.hasSymbolicOffset() ? Optional<uint64_t>() : BK.getOffset();
1135 // Check offset is not symbolic and within array's boundaries.
1136 // Handles arrays of 0 elements and of 0-sized elements as well.
1138 ((*ROffset >= LowerOffset && *ROffset < UpperOffset) ||
1140 (*ROffset >= LowerOffset || *ROffset < UpperOffset)) ||
1141 (LowerOffset == UpperOffset && *ROffset == LowerOffset))) {
1142 B = B.removeBinding(I.getKey());
1143 // Bound symbolic regions need to be invalidated for dead symbol
1145 SVal V = I.getData();
1146 const MemRegion *R = V.getAsRegion();
1147 if (R && isa<SymbolicRegion>(R))
1153 // Set the default value of the array to conjured symbol.
1154 DefinedOrUnknownSVal V =
1155 svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
1156 AT->getElementType(), Count);
1157 B = B.addBinding(baseR, BindingKey::Default, V);
1161 DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
1163 assert(SymbolManager::canSymbolicate(T) || V.isUnknown());
1164 B = B.addBinding(baseR, BindingKey::Direct, V);
1167 bool invalidateRegionsWorker::isInitiallyIncludedGlobalRegion(
1168 const MemRegion *R) {
1169 switch (GlobalsFilter) {
1172 case GFK_SystemOnly:
1173 return isa<GlobalSystemSpaceRegion>(R->getMemorySpace());
1175 return isa<NonStaticGlobalSpaceRegion>(R->getMemorySpace());
1178 llvm_unreachable("unknown globals filter");
1181 bool invalidateRegionsWorker::includeEntireMemorySpace(const MemRegion *Base) {
1182 if (isInitiallyIncludedGlobalRegion(Base))
1185 const MemSpaceRegion *MemSpace = Base->getMemorySpace();
1186 return ITraits.hasTrait(MemSpace,
1187 RegionAndSymbolInvalidationTraits::TK_EntireMemSpace);
1191 RegionStoreManager::invalidateGlobalRegion(MemRegion::Kind K,
1194 const LocationContext *LCtx,
1195 RegionBindingsRef B,
1196 InvalidatedRegions *Invalidated) {
1197 // Bind the globals memory space to a new symbol that we will use to derive
1198 // the bindings for all globals.
1199 const GlobalsSpaceRegion *GS = MRMgr.getGlobalsRegion(K);
1200 SVal V = svalBuilder.conjureSymbolVal(/* SymbolTag = */ (const void*) GS, Ex, LCtx,
1201 /* type does not matter */ Ctx.IntTy,
1204 B = B.removeBinding(GS)
1205 .addBinding(BindingKey::Make(GS, BindingKey::Default), V);
1207 // Even if there are no bindings in the global scope, we still need to
1208 // record that we touched it.
1210 Invalidated->push_back(GS);
1215 void RegionStoreManager::populateWorkList(invalidateRegionsWorker &W,
1216 ArrayRef<SVal> Values,
1217 InvalidatedRegions *TopLevelRegions) {
1218 for (ArrayRef<SVal>::iterator I = Values.begin(),
1219 E = Values.end(); I != E; ++I) {
1221 if (Optional<nonloc::LazyCompoundVal> LCS =
1222 V.getAs<nonloc::LazyCompoundVal>()) {
1224 const SValListTy &Vals = getInterestingValues(*LCS);
1226 for (SValListTy::const_iterator I = Vals.begin(),
1227 E = Vals.end(); I != E; ++I) {
1228 // Note: the last argument is false here because these are
1229 // non-top-level regions.
1230 if (const MemRegion *R = (*I).getAsRegion())
1236 if (const MemRegion *R = V.getAsRegion()) {
1237 if (TopLevelRegions)
1238 TopLevelRegions->push_back(R);
1246 RegionStoreManager::invalidateRegions(Store store,
1247 ArrayRef<SVal> Values,
1248 const Expr *Ex, unsigned Count,
1249 const LocationContext *LCtx,
1250 const CallEvent *Call,
1251 InvalidatedSymbols &IS,
1252 RegionAndSymbolInvalidationTraits &ITraits,
1253 InvalidatedRegions *TopLevelRegions,
1254 InvalidatedRegions *Invalidated) {
1255 GlobalsFilterKind GlobalsFilter;
1257 if (Call->isInSystemHeader())
1258 GlobalsFilter = GFK_SystemOnly;
1260 GlobalsFilter = GFK_All;
1262 GlobalsFilter = GFK_None;
1265 RegionBindingsRef B = getRegionBindings(store);
1266 invalidateRegionsWorker W(*this, StateMgr, B, Ex, Count, LCtx, IS, ITraits,
1267 Invalidated, GlobalsFilter);
1269 // Scan the bindings and generate the clusters.
1270 W.GenerateClusters();
1272 // Add the regions to the worklist.
1273 populateWorkList(W, Values, TopLevelRegions);
1277 // Return the new bindings.
1278 B = W.getRegionBindings();
1280 // For calls, determine which global regions should be invalidated and
1281 // invalidate them. (Note that function-static and immutable globals are never
1282 // invalidated by this.)
1283 // TODO: This could possibly be more precise with modules.
1284 switch (GlobalsFilter) {
1286 B = invalidateGlobalRegion(MemRegion::GlobalInternalSpaceRegionKind,
1287 Ex, Count, LCtx, B, Invalidated);
1289 case GFK_SystemOnly:
1290 B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind,
1291 Ex, Count, LCtx, B, Invalidated);
1297 return StoreRef(B.asStore(), *this);
1300 //===----------------------------------------------------------------------===//
1301 // Extents for regions.
1302 //===----------------------------------------------------------------------===//
1304 DefinedOrUnknownSVal
1305 RegionStoreManager::getSizeInElements(ProgramStateRef state,
1308 SVal Size = cast<SubRegion>(R)->getExtent(svalBuilder);
1309 const llvm::APSInt *SizeInt = svalBuilder.getKnownValue(state, Size);
1311 return UnknownVal();
1313 CharUnits RegionSize = CharUnits::fromQuantity(SizeInt->getSExtValue());
1315 if (Ctx.getAsVariableArrayType(EleTy)) {
1316 // FIXME: We need to track extra state to properly record the size
1317 // of VLAs. Returning UnknownVal here, however, is a stop-gap so that
1318 // we don't have a divide-by-zero below.
1319 return UnknownVal();
1322 CharUnits EleSize = Ctx.getTypeSizeInChars(EleTy);
1324 // If a variable is reinterpreted as a type that doesn't fit into a larger
1325 // type evenly, round it down.
1326 // This is a signed value, since it's used in arithmetic with signed indices.
1327 return svalBuilder.makeIntVal(RegionSize / EleSize, false);
1330 //===----------------------------------------------------------------------===//
1331 // Location and region casting.
1332 //===----------------------------------------------------------------------===//
1334 /// ArrayToPointer - Emulates the "decay" of an array to a pointer
1335 /// type. 'Array' represents the lvalue of the array being decayed
1336 /// to a pointer, and the returned SVal represents the decayed
1337 /// version of that lvalue (i.e., a pointer to the first element of
1338 /// the array). This is called by ExprEngine when evaluating casts
1339 /// from arrays to pointers.
1340 SVal RegionStoreManager::ArrayToPointer(Loc Array, QualType T) {
1341 if (Array.getAs<loc::ConcreteInt>())
1344 if (!Array.getAs<loc::MemRegionVal>())
1345 return UnknownVal();
1347 const SubRegion *R =
1348 cast<SubRegion>(Array.castAs<loc::MemRegionVal>().getRegion());
1349 NonLoc ZeroIdx = svalBuilder.makeZeroArrayIndex();
1350 return loc::MemRegionVal(MRMgr.getElementRegion(T, ZeroIdx, R, Ctx));
1353 //===----------------------------------------------------------------------===//
1354 // Loading values from regions.
1355 //===----------------------------------------------------------------------===//
1357 SVal RegionStoreManager::getBinding(RegionBindingsConstRef B, Loc L, QualType T) {
1358 assert(!L.getAs<UnknownVal>() && "location unknown");
1359 assert(!L.getAs<UndefinedVal>() && "location undefined");
1361 // For access to concrete addresses, return UnknownVal. Checks
1362 // for null dereferences (and similar errors) are done by checkers, not
1364 // FIXME: We can consider lazily symbolicating such memory, but we really
1365 // should defer this when we can reason easily about symbolicating arrays
1367 if (L.getAs<loc::ConcreteInt>()) {
1368 return UnknownVal();
1370 if (!L.getAs<loc::MemRegionVal>()) {
1371 return UnknownVal();
1374 const MemRegion *MR = L.castAs<loc::MemRegionVal>().getRegion();
1376 if (isa<BlockDataRegion>(MR)) {
1377 return UnknownVal();
1380 if (isa<AllocaRegion>(MR) ||
1381 isa<SymbolicRegion>(MR) ||
1382 isa<CodeTextRegion>(MR)) {
1384 if (const TypedRegion *TR = dyn_cast<TypedRegion>(MR))
1385 T = TR->getLocationType();
1387 const SymbolicRegion *SR = cast<SymbolicRegion>(MR);
1388 T = SR->getSymbol()->getType();
1391 MR = GetElementZeroRegion(cast<SubRegion>(MR), T);
1394 // FIXME: Perhaps this method should just take a 'const MemRegion*' argument
1395 // instead of 'Loc', and have the other Loc cases handled at a higher level.
1396 const TypedValueRegion *R = cast<TypedValueRegion>(MR);
1397 QualType RTy = R->getValueType();
1399 // FIXME: we do not yet model the parts of a complex type, so treat the
1400 // whole thing as "unknown".
1401 if (RTy->isAnyComplexType())
1402 return UnknownVal();
1404 // FIXME: We should eventually handle funny addressing. e.g.:
1408 // char *q = (char*) p;
1409 // char c = *q; // returns the first byte of 'x'.
1411 // Such funny addressing will occur due to layering of regions.
1412 if (RTy->isStructureOrClassType())
1413 return getBindingForStruct(B, R);
1415 // FIXME: Handle unions.
1416 if (RTy->isUnionType())
1417 return createLazyBinding(B, R);
1419 if (RTy->isArrayType()) {
1420 if (RTy->isConstantArrayType())
1421 return getBindingForArray(B, R);
1423 return UnknownVal();
1426 // FIXME: handle Vector types.
1427 if (RTy->isVectorType())
1428 return UnknownVal();
1430 if (const FieldRegion* FR = dyn_cast<FieldRegion>(R))
1431 return CastRetrievedVal(getBindingForField(B, FR), FR, T, false);
1433 if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) {
1434 // FIXME: Here we actually perform an implicit conversion from the loaded
1435 // value to the element type. Eventually we want to compose these values
1436 // more intelligently. For example, an 'element' can encompass multiple
1437 // bound regions (e.g., several bound bytes), or could be a subset of
1439 return CastRetrievedVal(getBindingForElement(B, ER), ER, T, false);
1442 if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) {
1443 // FIXME: Here we actually perform an implicit conversion from the loaded
1444 // value to the ivar type. What we should model is stores to ivars
1445 // that blow past the extent of the ivar. If the address of the ivar is
1446 // reinterpretted, it is possible we stored a different value that could
1447 // fit within the ivar. Either we need to cast these when storing them
1448 // or reinterpret them lazily (as we do here).
1449 return CastRetrievedVal(getBindingForObjCIvar(B, IVR), IVR, T, false);
1452 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
1453 // FIXME: Here we actually perform an implicit conversion from the loaded
1454 // value to the variable type. What we should model is stores to variables
1455 // that blow past the extent of the variable. If the address of the
1456 // variable is reinterpretted, it is possible we stored a different value
1457 // that could fit within the variable. Either we need to cast these when
1458 // storing them or reinterpret them lazily (as we do here).
1459 return CastRetrievedVal(getBindingForVar(B, VR), VR, T, false);
1462 const SVal *V = B.lookup(R, BindingKey::Direct);
1464 // Check if the region has a binding.
1468 // The location does not have a bound value. This means that it has
1469 // the value it had upon its creation and/or entry to the analyzed
1470 // function/method. These are either symbolic values or 'undefined'.
1471 if (R->hasStackNonParametersStorage()) {
1472 // All stack variables are considered to have undefined values
1473 // upon creation. All heap allocated blocks are considered to
1474 // have undefined values as well unless they are explicitly bound
1475 // to specific values.
1476 return UndefinedVal();
1479 // All other values are symbolic.
1480 return svalBuilder.getRegionValueSymbolVal(R);
1483 static QualType getUnderlyingType(const SubRegion *R) {
1485 if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(R))
1486 RegionTy = TVR->getValueType();
1488 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
1489 RegionTy = SR->getSymbol()->getType();
1494 /// Checks to see if store \p B has a lazy binding for region \p R.
1496 /// If \p AllowSubregionBindings is \c false, a lazy binding will be rejected
1497 /// if there are additional bindings within \p R.
1499 /// Note that unlike RegionStoreManager::findLazyBinding, this will not search
1500 /// for lazy bindings for super-regions of \p R.
1501 static Optional<nonloc::LazyCompoundVal>
1502 getExistingLazyBinding(SValBuilder &SVB, RegionBindingsConstRef B,
1503 const SubRegion *R, bool AllowSubregionBindings) {
1504 Optional<SVal> V = B.getDefaultBinding(R);
1508 Optional<nonloc::LazyCompoundVal> LCV = V->getAs<nonloc::LazyCompoundVal>();
1512 // If the LCV is for a subregion, the types might not match, and we shouldn't
1513 // reuse the binding.
1514 QualType RegionTy = getUnderlyingType(R);
1515 if (!RegionTy.isNull() &&
1516 !RegionTy->isVoidPointerType()) {
1517 QualType SourceRegionTy = LCV->getRegion()->getValueType();
1518 if (!SVB.getContext().hasSameUnqualifiedType(RegionTy, SourceRegionTy))
1522 if (!AllowSubregionBindings) {
1523 // If there are any other bindings within this region, we shouldn't reuse
1524 // the top-level binding.
1525 SmallVector<BindingPair, 16> Bindings;
1526 collectSubRegionBindings(Bindings, SVB, *B.lookup(R->getBaseRegion()), R,
1527 /*IncludeAllDefaultBindings=*/true);
1528 if (Bindings.size() > 1)
1536 std::pair<Store, const SubRegion *>
1537 RegionStoreManager::findLazyBinding(RegionBindingsConstRef B,
1539 const SubRegion *originalRegion) {
1540 if (originalRegion != R) {
1541 if (Optional<nonloc::LazyCompoundVal> V =
1542 getExistingLazyBinding(svalBuilder, B, R, true))
1543 return std::make_pair(V->getStore(), V->getRegion());
1546 typedef std::pair<Store, const SubRegion *> StoreRegionPair;
1547 StoreRegionPair Result = StoreRegionPair();
1549 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
1550 Result = findLazyBinding(B, cast<SubRegion>(ER->getSuperRegion()),
1554 Result.second = MRMgr.getElementRegionWithSuper(ER, Result.second);
1556 } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) {
1557 Result = findLazyBinding(B, cast<SubRegion>(FR->getSuperRegion()),
1561 Result.second = MRMgr.getFieldRegionWithSuper(FR, Result.second);
1563 } else if (const CXXBaseObjectRegion *BaseReg =
1564 dyn_cast<CXXBaseObjectRegion>(R)) {
1565 // C++ base object region is another kind of region that we should blast
1566 // through to look for lazy compound value. It is like a field region.
1567 Result = findLazyBinding(B, cast<SubRegion>(BaseReg->getSuperRegion()),
1571 Result.second = MRMgr.getCXXBaseObjectRegionWithSuper(BaseReg,
1578 SVal RegionStoreManager::getBindingForElement(RegionBindingsConstRef B,
1579 const ElementRegion* R) {
1580 // We do not currently model bindings of the CompoundLiteralregion.
1581 if (isa<CompoundLiteralRegion>(R->getBaseRegion()))
1582 return UnknownVal();
1584 // Check if the region has a binding.
1585 if (const Optional<SVal> &V = B.getDirectBinding(R))
1588 const MemRegion* superR = R->getSuperRegion();
1590 // Check if the region is an element region of a string literal.
1591 if (const StringRegion *StrR=dyn_cast<StringRegion>(superR)) {
1592 // FIXME: Handle loads from strings where the literal is treated as
1593 // an integer, e.g., *((unsigned int*)"hello")
1594 QualType T = Ctx.getAsArrayType(StrR->getValueType())->getElementType();
1595 if (!Ctx.hasSameUnqualifiedType(T, R->getElementType()))
1596 return UnknownVal();
1598 const StringLiteral *Str = StrR->getStringLiteral();
1599 SVal Idx = R->getIndex();
1600 if (Optional<nonloc::ConcreteInt> CI = Idx.getAs<nonloc::ConcreteInt>()) {
1601 int64_t i = CI->getValue().getSExtValue();
1602 // Abort on string underrun. This can be possible by arbitrary
1603 // clients of getBindingForElement().
1605 return UndefinedVal();
1606 int64_t length = Str->getLength();
1607 // Technically, only i == length is guaranteed to be null.
1608 // However, such overflows should be caught before reaching this point;
1609 // the only time such an access would be made is if a string literal was
1610 // used to initialize a larger array.
1611 char c = (i >= length) ? '\0' : Str->getCodeUnit(i);
1612 return svalBuilder.makeIntVal(c, T);
1616 // Check for loads from a code text region. For such loads, just give up.
1617 if (isa<CodeTextRegion>(superR))
1618 return UnknownVal();
1620 // Handle the case where we are indexing into a larger scalar object.
1621 // For example, this handles:
1625 // FIXME: This is a hack, and doesn't do anything really intelligent yet.
1626 const RegionRawOffset &O = R->getAsArrayOffset();
1628 // If we cannot reason about the offset, return an unknown value.
1630 return UnknownVal();
1632 if (const TypedValueRegion *baseR =
1633 dyn_cast_or_null<TypedValueRegion>(O.getRegion())) {
1634 QualType baseT = baseR->getValueType();
1635 if (baseT->isScalarType()) {
1636 QualType elemT = R->getElementType();
1637 if (elemT->isScalarType()) {
1638 if (Ctx.getTypeSizeInChars(baseT) >= Ctx.getTypeSizeInChars(elemT)) {
1639 if (const Optional<SVal> &V = B.getDirectBinding(superR)) {
1640 if (SymbolRef parentSym = V->getAsSymbol())
1641 return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1643 if (V->isUnknownOrUndef())
1645 // Other cases: give up. We are indexing into a larger object
1646 // that has some value, but we don't know how to handle that yet.
1647 return UnknownVal();
1653 return getBindingForFieldOrElementCommon(B, R, R->getElementType());
1656 SVal RegionStoreManager::getBindingForField(RegionBindingsConstRef B,
1657 const FieldRegion* R) {
1659 // Check if the region has a binding.
1660 if (const Optional<SVal> &V = B.getDirectBinding(R))
1663 QualType Ty = R->getValueType();
1664 return getBindingForFieldOrElementCommon(B, R, Ty);
1668 RegionStoreManager::getBindingForDerivedDefaultValue(RegionBindingsConstRef B,
1669 const MemRegion *superR,
1670 const TypedValueRegion *R,
1673 if (const Optional<SVal> &D = B.getDefaultBinding(superR)) {
1674 const SVal &val = D.getValue();
1675 if (SymbolRef parentSym = val.getAsSymbol())
1676 return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1678 if (val.isZeroConstant())
1679 return svalBuilder.makeZeroVal(Ty);
1681 if (val.isUnknownOrUndef())
1684 // Lazy bindings are usually handled through getExistingLazyBinding().
1685 // We should unify these two code paths at some point.
1686 if (val.getAs<nonloc::LazyCompoundVal>() ||
1687 val.getAs<nonloc::CompoundVal>())
1690 llvm_unreachable("Unknown default value");
1696 SVal RegionStoreManager::getLazyBinding(const SubRegion *LazyBindingRegion,
1697 RegionBindingsRef LazyBinding) {
1699 if (const ElementRegion *ER = dyn_cast<ElementRegion>(LazyBindingRegion))
1700 Result = getBindingForElement(LazyBinding, ER);
1702 Result = getBindingForField(LazyBinding,
1703 cast<FieldRegion>(LazyBindingRegion));
1705 // FIXME: This is a hack to deal with RegionStore's inability to distinguish a
1706 // default value for /part/ of an aggregate from a default value for the
1707 // /entire/ aggregate. The most common case of this is when struct Outer
1708 // has as its first member a struct Inner, which is copied in from a stack
1709 // variable. In this case, even if the Outer's default value is symbolic, 0,
1710 // or unknown, it gets overridden by the Inner's default value of undefined.
1712 // This is a general problem -- if the Inner is zero-initialized, the Outer
1713 // will now look zero-initialized. The proper way to solve this is with a
1714 // new version of RegionStore that tracks the extent of a binding as well
1717 // This hack only takes care of the undefined case because that can very
1718 // quickly result in a warning.
1719 if (Result.isUndef())
1720 Result = UnknownVal();
1726 RegionStoreManager::getBindingForFieldOrElementCommon(RegionBindingsConstRef B,
1727 const TypedValueRegion *R,
1730 // At this point we have already checked in either getBindingForElement or
1731 // getBindingForField if 'R' has a direct binding.
1734 Store lazyBindingStore = nullptr;
1735 const SubRegion *lazyBindingRegion = nullptr;
1736 std::tie(lazyBindingStore, lazyBindingRegion) = findLazyBinding(B, R, R);
1737 if (lazyBindingRegion)
1738 return getLazyBinding(lazyBindingRegion,
1739 getRegionBindings(lazyBindingStore));
1741 // Record whether or not we see a symbolic index. That can completely
1742 // be out of scope of our lookup.
1743 bool hasSymbolicIndex = false;
1745 // FIXME: This is a hack to deal with RegionStore's inability to distinguish a
1746 // default value for /part/ of an aggregate from a default value for the
1747 // /entire/ aggregate. The most common case of this is when struct Outer
1748 // has as its first member a struct Inner, which is copied in from a stack
1749 // variable. In this case, even if the Outer's default value is symbolic, 0,
1750 // or unknown, it gets overridden by the Inner's default value of undefined.
1752 // This is a general problem -- if the Inner is zero-initialized, the Outer
1753 // will now look zero-initialized. The proper way to solve this is with a
1754 // new version of RegionStore that tracks the extent of a binding as well
1757 // This hack only takes care of the undefined case because that can very
1758 // quickly result in a warning.
1759 bool hasPartialLazyBinding = false;
1761 const SubRegion *SR = dyn_cast<SubRegion>(R);
1763 const MemRegion *Base = SR->getSuperRegion();
1764 if (Optional<SVal> D = getBindingForDerivedDefaultValue(B, Base, R, Ty)) {
1765 if (D->getAs<nonloc::LazyCompoundVal>()) {
1766 hasPartialLazyBinding = true;
1773 if (const ElementRegion *ER = dyn_cast<ElementRegion>(Base)) {
1774 NonLoc index = ER->getIndex();
1775 if (!index.isConstant())
1776 hasSymbolicIndex = true;
1779 // If our super region is a field or element itself, walk up the region
1780 // hierarchy to see if there is a default value installed in an ancestor.
1781 SR = dyn_cast<SubRegion>(Base);
1784 if (R->hasStackNonParametersStorage()) {
1785 if (isa<ElementRegion>(R)) {
1786 // Currently we don't reason specially about Clang-style vectors. Check
1787 // if superR is a vector and if so return Unknown.
1788 if (const TypedValueRegion *typedSuperR =
1789 dyn_cast<TypedValueRegion>(R->getSuperRegion())) {
1790 if (typedSuperR->getValueType()->isVectorType())
1791 return UnknownVal();
1795 // FIXME: We also need to take ElementRegions with symbolic indexes into
1796 // account. This case handles both directly accessing an ElementRegion
1797 // with a symbolic offset, but also fields within an element with
1798 // a symbolic offset.
1799 if (hasSymbolicIndex)
1800 return UnknownVal();
1802 if (!hasPartialLazyBinding)
1803 return UndefinedVal();
1806 // All other values are symbolic.
1807 return svalBuilder.getRegionValueSymbolVal(R);
1810 SVal RegionStoreManager::getBindingForObjCIvar(RegionBindingsConstRef B,
1811 const ObjCIvarRegion* R) {
1812 // Check if the region has a binding.
1813 if (const Optional<SVal> &V = B.getDirectBinding(R))
1816 const MemRegion *superR = R->getSuperRegion();
1818 // Check if the super region has a default binding.
1819 if (const Optional<SVal> &V = B.getDefaultBinding(superR)) {
1820 if (SymbolRef parentSym = V->getAsSymbol())
1821 return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1823 // Other cases: give up.
1824 return UnknownVal();
1827 return getBindingForLazySymbol(R);
1830 SVal RegionStoreManager::getBindingForVar(RegionBindingsConstRef B,
1831 const VarRegion *R) {
1833 // Check if the region has a binding.
1834 if (const Optional<SVal> &V = B.getDirectBinding(R))
1837 // Lazily derive a value for the VarRegion.
1838 const VarDecl *VD = R->getDecl();
1839 const MemSpaceRegion *MS = R->getMemorySpace();
1841 // Arguments are always symbolic.
1842 if (isa<StackArgumentsSpaceRegion>(MS))
1843 return svalBuilder.getRegionValueSymbolVal(R);
1845 // Is 'VD' declared constant? If so, retrieve the constant value.
1846 if (VD->getType().isConstQualified())
1847 if (const Expr *Init = VD->getInit())
1848 if (Optional<SVal> V = svalBuilder.getConstantVal(Init))
1851 // This must come after the check for constants because closure-captured
1852 // constant variables may appear in UnknownSpaceRegion.
1853 if (isa<UnknownSpaceRegion>(MS))
1854 return svalBuilder.getRegionValueSymbolVal(R);
1856 if (isa<GlobalsSpaceRegion>(MS)) {
1857 QualType T = VD->getType();
1859 // Function-scoped static variables are default-initialized to 0; if they
1860 // have an initializer, it would have been processed by now.
1861 // FIXME: This is only true when we're starting analysis from main().
1862 // We're losing a lot of coverage here.
1863 if (isa<StaticGlobalSpaceRegion>(MS))
1864 return svalBuilder.makeZeroVal(T);
1866 if (Optional<SVal> V = getBindingForDerivedDefaultValue(B, MS, R, T)) {
1867 assert(!V->getAs<nonloc::LazyCompoundVal>());
1868 return V.getValue();
1871 return svalBuilder.getRegionValueSymbolVal(R);
1874 return UndefinedVal();
1877 SVal RegionStoreManager::getBindingForLazySymbol(const TypedValueRegion *R) {
1878 // All other values are symbolic.
1879 return svalBuilder.getRegionValueSymbolVal(R);
1882 const RegionStoreManager::SValListTy &
1883 RegionStoreManager::getInterestingValues(nonloc::LazyCompoundVal LCV) {
1884 // First, check the cache.
1885 LazyBindingsMapTy::iterator I = LazyBindingsMap.find(LCV.getCVData());
1886 if (I != LazyBindingsMap.end())
1889 // If we don't have a list of values cached, start constructing it.
1892 const SubRegion *LazyR = LCV.getRegion();
1893 RegionBindingsRef B = getRegionBindings(LCV.getStore());
1895 // If this region had /no/ bindings at the time, there are no interesting
1896 // values to return.
1897 const ClusterBindings *Cluster = B.lookup(LazyR->getBaseRegion());
1899 return (LazyBindingsMap[LCV.getCVData()] = std::move(List));
1901 SmallVector<BindingPair, 32> Bindings;
1902 collectSubRegionBindings(Bindings, svalBuilder, *Cluster, LazyR,
1903 /*IncludeAllDefaultBindings=*/true);
1904 for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(),
1908 if (V.isUnknownOrUndef() || V.isConstant())
1911 if (Optional<nonloc::LazyCompoundVal> InnerLCV =
1912 V.getAs<nonloc::LazyCompoundVal>()) {
1913 const SValListTy &InnerList = getInterestingValues(*InnerLCV);
1914 List.insert(List.end(), InnerList.begin(), InnerList.end());
1921 return (LazyBindingsMap[LCV.getCVData()] = std::move(List));
1924 NonLoc RegionStoreManager::createLazyBinding(RegionBindingsConstRef B,
1925 const TypedValueRegion *R) {
1926 if (Optional<nonloc::LazyCompoundVal> V =
1927 getExistingLazyBinding(svalBuilder, B, R, false))
1930 return svalBuilder.makeLazyCompoundVal(StoreRef(B.asStore(), *this), R);
1933 static bool isRecordEmpty(const RecordDecl *RD) {
1934 if (!RD->field_empty())
1936 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD))
1937 return CRD->getNumBases() == 0;
1941 SVal RegionStoreManager::getBindingForStruct(RegionBindingsConstRef B,
1942 const TypedValueRegion *R) {
1943 const RecordDecl *RD = R->getValueType()->castAs<RecordType>()->getDecl();
1944 if (!RD->getDefinition() || isRecordEmpty(RD))
1945 return UnknownVal();
1947 return createLazyBinding(B, R);
1950 SVal RegionStoreManager::getBindingForArray(RegionBindingsConstRef B,
1951 const TypedValueRegion *R) {
1952 assert(Ctx.getAsConstantArrayType(R->getValueType()) &&
1953 "Only constant array types can have compound bindings.");
1955 return createLazyBinding(B, R);
1958 bool RegionStoreManager::includedInBindings(Store store,
1959 const MemRegion *region) const {
1960 RegionBindingsRef B = getRegionBindings(store);
1961 region = region->getBaseRegion();
1963 // Quick path: if the base is the head of a cluster, the region is live.
1964 if (B.lookup(region))
1967 // Slow path: if the region is the VALUE of any binding, it is live.
1968 for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI) {
1969 const ClusterBindings &Cluster = RI.getData();
1970 for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
1972 const SVal &D = CI.getData();
1973 if (const MemRegion *R = D.getAsRegion())
1974 if (R->getBaseRegion() == region)
1982 //===----------------------------------------------------------------------===//
1983 // Binding values to regions.
1984 //===----------------------------------------------------------------------===//
1986 StoreRef RegionStoreManager::killBinding(Store ST, Loc L) {
1987 if (Optional<loc::MemRegionVal> LV = L.getAs<loc::MemRegionVal>())
1988 if (const MemRegion* R = LV->getRegion())
1989 return StoreRef(getRegionBindings(ST).removeBinding(R)
1991 .getRootWithoutRetain(),
1994 return StoreRef(ST, *this);
1998 RegionStoreManager::bind(RegionBindingsConstRef B, Loc L, SVal V) {
1999 if (L.getAs<loc::ConcreteInt>())
2002 // If we get here, the location should be a region.
2003 const MemRegion *R = L.castAs<loc::MemRegionVal>().getRegion();
2005 // Check if the region is a struct region.
2006 if (const TypedValueRegion* TR = dyn_cast<TypedValueRegion>(R)) {
2007 QualType Ty = TR->getValueType();
2008 if (Ty->isArrayType())
2009 return bindArray(B, TR, V);
2010 if (Ty->isStructureOrClassType())
2011 return bindStruct(B, TR, V);
2012 if (Ty->isVectorType())
2013 return bindVector(B, TR, V);
2014 if (Ty->isUnionType())
2015 return bindAggregate(B, TR, V);
2018 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) {
2019 // Binding directly to a symbolic region should be treated as binding
2021 QualType T = SR->getSymbol()->getType();
2022 if (T->isAnyPointerType() || T->isReferenceType())
2023 T = T->getPointeeType();
2025 R = GetElementZeroRegion(SR, T);
2028 // Clear out bindings that may overlap with this binding.
2029 RegionBindingsRef NewB = removeSubRegionBindings(B, cast<SubRegion>(R));
2030 return NewB.addBinding(BindingKey::Make(R, BindingKey::Direct), V);
2034 RegionStoreManager::setImplicitDefaultValue(RegionBindingsConstRef B,
2039 if (Loc::isLocType(T))
2040 V = svalBuilder.makeNull();
2041 else if (T->isIntegralOrEnumerationType())
2042 V = svalBuilder.makeZeroVal(T);
2043 else if (T->isStructureOrClassType() || T->isArrayType()) {
2044 // Set the default value to a zero constant when it is a structure
2045 // or array. The type doesn't really matter.
2046 V = svalBuilder.makeZeroVal(Ctx.IntTy);
2049 // We can't represent values of this type, but we still need to set a value
2050 // to record that the region has been initialized.
2051 // If this assertion ever fires, a new case should be added above -- we
2052 // should know how to default-initialize any value we can symbolicate.
2053 assert(!SymbolManager::canSymbolicate(T) && "This type is representable");
2057 return B.addBinding(R, BindingKey::Default, V);
2061 RegionStoreManager::bindArray(RegionBindingsConstRef B,
2062 const TypedValueRegion* R,
2065 const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType()));
2066 QualType ElementTy = AT->getElementType();
2067 Optional<uint64_t> Size;
2069 if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT))
2070 Size = CAT->getSize().getZExtValue();
2072 // Check if the init expr is a string literal.
2073 if (Optional<loc::MemRegionVal> MRV = Init.getAs<loc::MemRegionVal>()) {
2074 const StringRegion *S = cast<StringRegion>(MRV->getRegion());
2076 // Treat the string as a lazy compound value.
2077 StoreRef store(B.asStore(), *this);
2078 nonloc::LazyCompoundVal LCV = svalBuilder.makeLazyCompoundVal(store, S)
2079 .castAs<nonloc::LazyCompoundVal>();
2080 return bindAggregate(B, R, LCV);
2083 // Handle lazy compound values.
2084 if (Init.getAs<nonloc::LazyCompoundVal>())
2085 return bindAggregate(B, R, Init);
2087 if (Init.isUnknown())
2088 return bindAggregate(B, R, UnknownVal());
2090 // Remaining case: explicit compound values.
2091 const nonloc::CompoundVal& CV = Init.castAs<nonloc::CompoundVal>();
2092 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
2095 RegionBindingsRef NewB(B);
2097 for (; Size.hasValue() ? i < Size.getValue() : true ; ++i, ++VI) {
2098 // The init list might be shorter than the array length.
2102 const NonLoc &Idx = svalBuilder.makeArrayIndex(i);
2103 const ElementRegion *ER = MRMgr.getElementRegion(ElementTy, Idx, R, Ctx);
2105 if (ElementTy->isStructureOrClassType())
2106 NewB = bindStruct(NewB, ER, *VI);
2107 else if (ElementTy->isArrayType())
2108 NewB = bindArray(NewB, ER, *VI);
2110 NewB = bind(NewB, loc::MemRegionVal(ER), *VI);
2113 // If the init list is shorter than the array length, set the
2114 // array default value.
2115 if (Size.hasValue() && i < Size.getValue())
2116 NewB = setImplicitDefaultValue(NewB, R, ElementTy);
2121 RegionBindingsRef RegionStoreManager::bindVector(RegionBindingsConstRef B,
2122 const TypedValueRegion* R,
2124 QualType T = R->getValueType();
2125 assert(T->isVectorType());
2126 const VectorType *VT = T->getAs<VectorType>(); // Use getAs for typedefs.
2128 // Handle lazy compound values and symbolic values.
2129 if (V.getAs<nonloc::LazyCompoundVal>() || V.getAs<nonloc::SymbolVal>())
2130 return bindAggregate(B, R, V);
2132 // We may get non-CompoundVal accidentally due to imprecise cast logic or
2133 // that we are binding symbolic struct value. Kill the field values, and if
2134 // the value is symbolic go and bind it as a "default" binding.
2135 if (!V.getAs<nonloc::CompoundVal>()) {
2136 return bindAggregate(B, R, UnknownVal());
2139 QualType ElemType = VT->getElementType();
2140 nonloc::CompoundVal CV = V.castAs<nonloc::CompoundVal>();
2141 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
2142 unsigned index = 0, numElements = VT->getNumElements();
2143 RegionBindingsRef NewB(B);
2145 for ( ; index != numElements ; ++index) {
2149 NonLoc Idx = svalBuilder.makeArrayIndex(index);
2150 const ElementRegion *ER = MRMgr.getElementRegion(ElemType, Idx, R, Ctx);
2152 if (ElemType->isArrayType())
2153 NewB = bindArray(NewB, ER, *VI);
2154 else if (ElemType->isStructureOrClassType())
2155 NewB = bindStruct(NewB, ER, *VI);
2157 NewB = bind(NewB, loc::MemRegionVal(ER), *VI);
2162 Optional<RegionBindingsRef>
2163 RegionStoreManager::tryBindSmallStruct(RegionBindingsConstRef B,
2164 const TypedValueRegion *R,
2165 const RecordDecl *RD,
2166 nonloc::LazyCompoundVal LCV) {
2169 if (const CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(RD))
2170 if (Class->getNumBases() != 0 || Class->getNumVBases() != 0)
2173 for (const auto *FD : RD->fields()) {
2174 if (FD->isUnnamedBitfield())
2177 // If there are too many fields, or if any of the fields are aggregates,
2178 // just use the LCV as a default binding.
2179 if (Fields.size() == SmallStructLimit)
2182 QualType Ty = FD->getType();
2183 if (!(Ty->isScalarType() || Ty->isReferenceType()))
2186 Fields.push_back(FD);
2189 RegionBindingsRef NewB = B;
2191 for (FieldVector::iterator I = Fields.begin(), E = Fields.end(); I != E; ++I){
2192 const FieldRegion *SourceFR = MRMgr.getFieldRegion(*I, LCV.getRegion());
2193 SVal V = getBindingForField(getRegionBindings(LCV.getStore()), SourceFR);
2195 const FieldRegion *DestFR = MRMgr.getFieldRegion(*I, R);
2196 NewB = bind(NewB, loc::MemRegionVal(DestFR), V);
2202 RegionBindingsRef RegionStoreManager::bindStruct(RegionBindingsConstRef B,
2203 const TypedValueRegion* R,
2205 if (!Features.supportsFields())
2208 QualType T = R->getValueType();
2209 assert(T->isStructureOrClassType());
2211 const RecordType* RT = T->getAs<RecordType>();
2212 const RecordDecl *RD = RT->getDecl();
2214 if (!RD->isCompleteDefinition())
2217 // Handle lazy compound values and symbolic values.
2218 if (Optional<nonloc::LazyCompoundVal> LCV =
2219 V.getAs<nonloc::LazyCompoundVal>()) {
2220 if (Optional<RegionBindingsRef> NewB = tryBindSmallStruct(B, R, RD, *LCV))
2222 return bindAggregate(B, R, V);
2224 if (V.getAs<nonloc::SymbolVal>())
2225 return bindAggregate(B, R, V);
2227 // We may get non-CompoundVal accidentally due to imprecise cast logic or
2228 // that we are binding symbolic struct value. Kill the field values, and if
2229 // the value is symbolic go and bind it as a "default" binding.
2230 if (V.isUnknown() || !V.getAs<nonloc::CompoundVal>())
2231 return bindAggregate(B, R, UnknownVal());
2233 const nonloc::CompoundVal& CV = V.castAs<nonloc::CompoundVal>();
2234 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
2236 RecordDecl::field_iterator FI, FE;
2237 RegionBindingsRef NewB(B);
2239 for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; ++FI) {
2244 // Skip any unnamed bitfields to stay in sync with the initializers.
2245 if (FI->isUnnamedBitfield())
2248 QualType FTy = FI->getType();
2249 const FieldRegion* FR = MRMgr.getFieldRegion(*FI, R);
2251 if (FTy->isArrayType())
2252 NewB = bindArray(NewB, FR, *VI);
2253 else if (FTy->isStructureOrClassType())
2254 NewB = bindStruct(NewB, FR, *VI);
2256 NewB = bind(NewB, loc::MemRegionVal(FR), *VI);
2260 // There may be fewer values in the initialize list than the fields of struct.
2262 NewB = NewB.addBinding(R, BindingKey::Default,
2263 svalBuilder.makeIntVal(0, false));
2270 RegionStoreManager::bindAggregate(RegionBindingsConstRef B,
2271 const TypedRegion *R,
2273 // Remove the old bindings, using 'R' as the root of all regions
2274 // we will invalidate. Then add the new binding.
2275 return removeSubRegionBindings(B, R).addBinding(R, BindingKey::Default, Val);
2278 //===----------------------------------------------------------------------===//
2280 //===----------------------------------------------------------------------===//
2283 class removeDeadBindingsWorker :
2284 public ClusterAnalysis<removeDeadBindingsWorker> {
2285 SmallVector<const SymbolicRegion*, 12> Postponed;
2286 SymbolReaper &SymReaper;
2287 const StackFrameContext *CurrentLCtx;
2290 removeDeadBindingsWorker(RegionStoreManager &rm,
2291 ProgramStateManager &stateMgr,
2292 RegionBindingsRef b, SymbolReaper &symReaper,
2293 const StackFrameContext *LCtx)
2294 : ClusterAnalysis<removeDeadBindingsWorker>(rm, stateMgr, b),
2295 SymReaper(symReaper), CurrentLCtx(LCtx) {}
2297 // Called by ClusterAnalysis.
2298 void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C);
2299 void VisitCluster(const MemRegion *baseR, const ClusterBindings *C);
2300 using ClusterAnalysis<removeDeadBindingsWorker>::VisitCluster;
2302 using ClusterAnalysis::AddToWorkList;
2304 bool AddToWorkList(const MemRegion *R);
2306 bool UpdatePostponed();
2307 void VisitBinding(SVal V);
2311 bool removeDeadBindingsWorker::AddToWorkList(const MemRegion *R) {
2312 const MemRegion *BaseR = R->getBaseRegion();
2313 return AddToWorkList(WorkListElement(BaseR), getCluster(BaseR));
2316 void removeDeadBindingsWorker::VisitAddedToCluster(const MemRegion *baseR,
2317 const ClusterBindings &C) {
2319 if (const VarRegion *VR = dyn_cast<VarRegion>(baseR)) {
2320 if (SymReaper.isLive(VR))
2321 AddToWorkList(baseR, &C);
2326 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) {
2327 if (SymReaper.isLive(SR->getSymbol()))
2328 AddToWorkList(SR, &C);
2330 Postponed.push_back(SR);
2335 if (isa<NonStaticGlobalSpaceRegion>(baseR)) {
2336 AddToWorkList(baseR, &C);
2340 // CXXThisRegion in the current or parent location context is live.
2341 if (const CXXThisRegion *TR = dyn_cast<CXXThisRegion>(baseR)) {
2342 const StackArgumentsSpaceRegion *StackReg =
2343 cast<StackArgumentsSpaceRegion>(TR->getSuperRegion());
2344 const StackFrameContext *RegCtx = StackReg->getStackFrame();
2346 (RegCtx == CurrentLCtx || RegCtx->isParentOf(CurrentLCtx)))
2347 AddToWorkList(TR, &C);
2351 void removeDeadBindingsWorker::VisitCluster(const MemRegion *baseR,
2352 const ClusterBindings *C) {
2356 // Mark the symbol for any SymbolicRegion with live bindings as live itself.
2357 // This means we should continue to track that symbol.
2358 if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(baseR))
2359 SymReaper.markLive(SymR->getSymbol());
2361 for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I) {
2362 // Element index of a binding key is live.
2363 SymReaper.markElementIndicesLive(I.getKey().getRegion());
2365 VisitBinding(I.getData());
2369 void removeDeadBindingsWorker::VisitBinding(SVal V) {
2370 // Is it a LazyCompoundVal? All referenced regions are live as well.
2371 if (Optional<nonloc::LazyCompoundVal> LCS =
2372 V.getAs<nonloc::LazyCompoundVal>()) {
2374 const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS);
2376 for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(),
2384 // If V is a region, then add it to the worklist.
2385 if (const MemRegion *R = V.getAsRegion()) {
2387 SymReaper.markLive(R);
2389 // All regions captured by a block are also live.
2390 if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(R)) {
2391 BlockDataRegion::referenced_vars_iterator I = BR->referenced_vars_begin(),
2392 E = BR->referenced_vars_end();
2393 for ( ; I != E; ++I)
2394 AddToWorkList(I.getCapturedRegion());
2399 // Update the set of live symbols.
2400 for (SymExpr::symbol_iterator SI = V.symbol_begin(), SE = V.symbol_end();
2402 SymReaper.markLive(*SI);
2405 bool removeDeadBindingsWorker::UpdatePostponed() {
2406 // See if any postponed SymbolicRegions are actually live now, after
2407 // having done a scan.
2408 bool changed = false;
2410 for (SmallVectorImpl<const SymbolicRegion*>::iterator
2411 I = Postponed.begin(), E = Postponed.end() ; I != E ; ++I) {
2412 if (const SymbolicRegion *SR = *I) {
2413 if (SymReaper.isLive(SR->getSymbol())) {
2414 changed |= AddToWorkList(SR);
2423 StoreRef RegionStoreManager::removeDeadBindings(Store store,
2424 const StackFrameContext *LCtx,
2425 SymbolReaper& SymReaper) {
2426 RegionBindingsRef B = getRegionBindings(store);
2427 removeDeadBindingsWorker W(*this, StateMgr, B, SymReaper, LCtx);
2428 W.GenerateClusters();
2430 // Enqueue the region roots onto the worklist.
2431 for (SymbolReaper::region_iterator I = SymReaper.region_begin(),
2432 E = SymReaper.region_end(); I != E; ++I) {
2433 W.AddToWorkList(*I);
2436 do W.RunWorkList(); while (W.UpdatePostponed());
2438 // We have now scanned the store, marking reachable regions and symbols
2439 // as live. We now remove all the regions that are dead from the store
2440 // as well as update DSymbols with the set symbols that are now dead.
2441 for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; ++I) {
2442 const MemRegion *Base = I.getKey();
2444 // If the cluster has been visited, we know the region has been marked.
2445 if (W.isVisited(Base))
2448 // Remove the dead entry.
2451 if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(Base))
2452 SymReaper.maybeDead(SymR->getSymbol());
2454 // Mark all non-live symbols that this binding references as dead.
2455 const ClusterBindings &Cluster = I.getData();
2456 for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
2458 SVal X = CI.getData();
2459 SymExpr::symbol_iterator SI = X.symbol_begin(), SE = X.symbol_end();
2460 for (; SI != SE; ++SI)
2461 SymReaper.maybeDead(*SI);
2465 return StoreRef(B.asStore(), *this);
2468 //===----------------------------------------------------------------------===//
2470 //===----------------------------------------------------------------------===//
2472 void RegionStoreManager::print(Store store, raw_ostream &OS,
2473 const char* nl, const char *sep) {
2474 RegionBindingsRef B = getRegionBindings(store);
2475 OS << "Store (direct and default bindings), "