xref: /llvm-project/clang/lib/StaticAnalyzer/Core/RegionStore.cpp (revision a1580d7b59b65b17f2ce7fdb95f46379e7df4089)
1 //== RegionStore.cpp - Field-sensitive store model --------------*- C++ -*--==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines a basic region store model. In this model, we do have field
10 // sensitivity. But we assume nothing about the heap shape. So recursive data
11 // structures are largely ignored. Basically we do 1-limiting analysis.
12 // Parameter pointers are assumed with no aliasing. Pointee objects of
13 // parameters are created lazily.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/ASTMatchers/ASTMatchFinder.h"
20 #include "clang/Analysis/Analyses/LiveVariables.h"
21 #include "clang/Analysis/AnalysisDeclContext.h"
22 #include "clang/Basic/JsonSupport.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
29 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
30 #include "llvm/ADT/ImmutableMap.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <optional>
34 #include <utility>
35 
36 using namespace clang;
37 using namespace ento;
38 
39 //===----------------------------------------------------------------------===//
40 // Representation of binding keys.
41 //===----------------------------------------------------------------------===//
42 
43 namespace {
44 class BindingKey {
45 public:
46   enum Kind { Default = 0x0, Direct = 0x1 };
47 private:
48   enum { Symbolic = 0x2 };
49 
50   llvm::PointerIntPair<const MemRegion *, 2> P;
51   uint64_t Data;
52 
53   /// Create a key for a binding to region \p r, which has a symbolic offset
54   /// from region \p Base.
55   explicit BindingKey(const SubRegion *r, const SubRegion *Base, Kind k)
56     : P(r, k | Symbolic), Data(reinterpret_cast<uintptr_t>(Base)) {
57     assert(r && Base && "Must have known regions.");
58     assert(getConcreteOffsetRegion() == Base && "Failed to store base region");
59   }
60 
61   /// Create a key for a binding at \p offset from base region \p r.
62   explicit BindingKey(const MemRegion *r, uint64_t offset, Kind k)
63     : P(r, k), Data(offset) {
64     assert(r && "Must have known regions.");
65     assert(getOffset() == offset && "Failed to store offset");
66     assert((r == r->getBaseRegion() ||
67             isa<ObjCIvarRegion, CXXDerivedObjectRegion>(r)) &&
68            "Not a base");
69   }
70 public:
71 
72   bool isDirect() const { return P.getInt() & Direct; }
73   bool hasSymbolicOffset() const { return P.getInt() & Symbolic; }
74 
75   const MemRegion *getRegion() const { return P.getPointer(); }
76   uint64_t getOffset() const {
77     assert(!hasSymbolicOffset());
78     return Data;
79   }
80 
81   const SubRegion *getConcreteOffsetRegion() const {
82     assert(hasSymbolicOffset());
83     return reinterpret_cast<const SubRegion *>(static_cast<uintptr_t>(Data));
84   }
85 
86   const MemRegion *getBaseRegion() const {
87     if (hasSymbolicOffset())
88       return getConcreteOffsetRegion()->getBaseRegion();
89     return getRegion()->getBaseRegion();
90   }
91 
92   void Profile(llvm::FoldingSetNodeID& ID) const {
93     ID.AddPointer(P.getOpaqueValue());
94     ID.AddInteger(Data);
95   }
96 
97   static BindingKey Make(const MemRegion *R, Kind k);
98 
99   bool operator<(const BindingKey &X) const {
100     if (P.getOpaqueValue() < X.P.getOpaqueValue())
101       return true;
102     if (P.getOpaqueValue() > X.P.getOpaqueValue())
103       return false;
104     return Data < X.Data;
105   }
106 
107   bool operator==(const BindingKey &X) const {
108     return P.getOpaqueValue() == X.P.getOpaqueValue() &&
109            Data == X.Data;
110   }
111 
112   LLVM_DUMP_METHOD void dump() const;
113 };
114 } // end anonymous namespace
115 
116 BindingKey BindingKey::Make(const MemRegion *R, Kind k) {
117   const RegionOffset &RO = R->getAsOffset();
118   if (RO.hasSymbolicOffset())
119     return BindingKey(cast<SubRegion>(R), cast<SubRegion>(RO.getRegion()), k);
120 
121   return BindingKey(RO.getRegion(), RO.getOffset(), k);
122 }
123 
124 namespace llvm {
125 static inline raw_ostream &operator<<(raw_ostream &Out, BindingKey K) {
126   Out << "\"kind\": \"" << (K.isDirect() ? "Direct" : "Default")
127       << "\", \"offset\": ";
128 
129   if (!K.hasSymbolicOffset())
130     Out << K.getOffset();
131   else
132     Out << "null";
133 
134   return Out;
135 }
136 
137 } // namespace llvm
138 
139 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
140 void BindingKey::dump() const { llvm::errs() << *this; }
141 #endif
142 
143 //===----------------------------------------------------------------------===//
144 // Actual Store type.
145 //===----------------------------------------------------------------------===//
146 
147 typedef llvm::ImmutableMap<BindingKey, SVal>    ClusterBindings;
148 typedef llvm::ImmutableMapRef<BindingKey, SVal> ClusterBindingsRef;
149 typedef std::pair<BindingKey, SVal> BindingPair;
150 
151 typedef llvm::ImmutableMap<const MemRegion *, ClusterBindings>
152         RegionBindings;
153 
154 namespace {
155 class RegionBindingsRef : public llvm::ImmutableMapRef<const MemRegion *,
156                                  ClusterBindings> {
157   ClusterBindings::Factory *CBFactory;
158 
159   // This flag indicates whether the current bindings are within the analysis
160   // that has started from main(). It affects how we perform loads from
161   // global variables that have initializers: if we have observed the
162   // program execution from the start and we know that these variables
163   // have not been overwritten yet, we can be sure that their initializers
164   // are still relevant. This flag never gets changed when the bindings are
165   // updated, so it could potentially be moved into RegionStoreManager
166   // (as if it's the same bindings but a different loading procedure)
167   // however that would have made the manager needlessly stateful.
168   bool IsMainAnalysis;
169 
170 public:
171   typedef llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>
172           ParentTy;
173 
174   RegionBindingsRef(ClusterBindings::Factory &CBFactory,
175                     const RegionBindings::TreeTy *T,
176                     RegionBindings::TreeTy::Factory *F,
177                     bool IsMainAnalysis)
178       : llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>(T, F),
179         CBFactory(&CBFactory), IsMainAnalysis(IsMainAnalysis) {}
180 
181   RegionBindingsRef(const ParentTy &P,
182                     ClusterBindings::Factory &CBFactory,
183                     bool IsMainAnalysis)
184       : llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>(P),
185         CBFactory(&CBFactory), IsMainAnalysis(IsMainAnalysis) {}
186 
187   RegionBindingsRef add(key_type_ref K, data_type_ref D) const {
188     return RegionBindingsRef(static_cast<const ParentTy *>(this)->add(K, D),
189                              *CBFactory, IsMainAnalysis);
190   }
191 
192   RegionBindingsRef remove(key_type_ref K) const {
193     return RegionBindingsRef(static_cast<const ParentTy *>(this)->remove(K),
194                              *CBFactory, IsMainAnalysis);
195   }
196 
197   RegionBindingsRef addBinding(BindingKey K, SVal V) const;
198 
199   RegionBindingsRef addBinding(const MemRegion *R,
200                                BindingKey::Kind k, SVal V) const;
201 
202   const SVal *lookup(BindingKey K) const;
203   const SVal *lookup(const MemRegion *R, BindingKey::Kind k) const;
204   using llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>::lookup;
205 
206   RegionBindingsRef removeBinding(BindingKey K);
207 
208   RegionBindingsRef removeBinding(const MemRegion *R,
209                                   BindingKey::Kind k);
210 
211   RegionBindingsRef removeBinding(const MemRegion *R) {
212     return removeBinding(R, BindingKey::Direct).
213            removeBinding(R, BindingKey::Default);
214   }
215 
216   Optional<SVal> getDirectBinding(const MemRegion *R) const;
217 
218   /// getDefaultBinding - Returns an SVal* representing an optional default
219   ///  binding associated with a region and its subregions.
220   Optional<SVal> getDefaultBinding(const MemRegion *R) const;
221 
222   /// Return the internal tree as a Store.
223   Store asStore() const {
224     llvm::PointerIntPair<Store, 1, bool> Ptr = {
225         asImmutableMap().getRootWithoutRetain(), IsMainAnalysis};
226     return reinterpret_cast<Store>(Ptr.getOpaqueValue());
227   }
228 
229   bool isMainAnalysis() const {
230     return IsMainAnalysis;
231   }
232 
233   void printJson(raw_ostream &Out, const char *NL = "\n",
234                  unsigned int Space = 0, bool IsDot = false) const {
235     for (iterator I = begin(); I != end(); ++I) {
236       // TODO: We might need a .printJson for I.getKey() as well.
237       Indent(Out, Space, IsDot)
238           << "{ \"cluster\": \"" << I.getKey() << "\", \"pointer\": \""
239           << (const void *)I.getKey() << "\", \"items\": [" << NL;
240 
241       ++Space;
242       const ClusterBindings &CB = I.getData();
243       for (ClusterBindings::iterator CI = CB.begin(); CI != CB.end(); ++CI) {
244         Indent(Out, Space, IsDot) << "{ " << CI.getKey() << ", \"value\": ";
245         CI.getData().printJson(Out, /*AddQuotes=*/true);
246         Out << " }";
247         if (std::next(CI) != CB.end())
248           Out << ',';
249         Out << NL;
250       }
251 
252       --Space;
253       Indent(Out, Space, IsDot) << "]}";
254       if (std::next(I) != end())
255         Out << ',';
256       Out << NL;
257     }
258   }
259 
260   LLVM_DUMP_METHOD void dump() const { printJson(llvm::errs()); }
261 };
262 } // end anonymous namespace
263 
264 typedef const RegionBindingsRef& RegionBindingsConstRef;
265 
266 Optional<SVal> RegionBindingsRef::getDirectBinding(const MemRegion *R) const {
267   const SVal *V = lookup(R, BindingKey::Direct);
268   return V ? Optional<SVal>(*V) : std::nullopt;
269 }
270 
271 Optional<SVal> RegionBindingsRef::getDefaultBinding(const MemRegion *R) const {
272   const SVal *V = lookup(R, BindingKey::Default);
273   return V ? Optional<SVal>(*V) : std::nullopt;
274 }
275 
276 RegionBindingsRef RegionBindingsRef::addBinding(BindingKey K, SVal V) const {
277   const MemRegion *Base = K.getBaseRegion();
278 
279   const ClusterBindings *ExistingCluster = lookup(Base);
280   ClusterBindings Cluster =
281       (ExistingCluster ? *ExistingCluster : CBFactory->getEmptyMap());
282 
283   ClusterBindings NewCluster = CBFactory->add(Cluster, K, V);
284   return add(Base, NewCluster);
285 }
286 
287 
288 RegionBindingsRef RegionBindingsRef::addBinding(const MemRegion *R,
289                                                 BindingKey::Kind k,
290                                                 SVal V) const {
291   return addBinding(BindingKey::Make(R, k), V);
292 }
293 
294 const SVal *RegionBindingsRef::lookup(BindingKey K) const {
295   const ClusterBindings *Cluster = lookup(K.getBaseRegion());
296   if (!Cluster)
297     return nullptr;
298   return Cluster->lookup(K);
299 }
300 
301 const SVal *RegionBindingsRef::lookup(const MemRegion *R,
302                                       BindingKey::Kind k) const {
303   return lookup(BindingKey::Make(R, k));
304 }
305 
306 RegionBindingsRef RegionBindingsRef::removeBinding(BindingKey K) {
307   const MemRegion *Base = K.getBaseRegion();
308   const ClusterBindings *Cluster = lookup(Base);
309   if (!Cluster)
310     return *this;
311 
312   ClusterBindings NewCluster = CBFactory->remove(*Cluster, K);
313   if (NewCluster.isEmpty())
314     return remove(Base);
315   return add(Base, NewCluster);
316 }
317 
318 RegionBindingsRef RegionBindingsRef::removeBinding(const MemRegion *R,
319                                                 BindingKey::Kind k){
320   return removeBinding(BindingKey::Make(R, k));
321 }
322 
323 //===----------------------------------------------------------------------===//
324 // Main RegionStore logic.
325 //===----------------------------------------------------------------------===//
326 
327 namespace {
328 class InvalidateRegionsWorker;
329 
330 class RegionStoreManager : public StoreManager {
331 public:
332   RegionBindings::Factory RBFactory;
333   mutable ClusterBindings::Factory CBFactory;
334 
335   typedef std::vector<SVal> SValListTy;
336 private:
337   typedef llvm::DenseMap<const LazyCompoundValData *,
338                          SValListTy> LazyBindingsMapTy;
339   LazyBindingsMapTy LazyBindingsMap;
340 
341   /// The largest number of fields a struct can have and still be
342   /// considered "small".
343   ///
344   /// This is currently used to decide whether or not it is worth "forcing" a
345   /// LazyCompoundVal on bind.
346   ///
347   /// This is controlled by 'region-store-small-struct-limit' option.
348   /// To disable all small-struct-dependent behavior, set the option to "0".
349   unsigned SmallStructLimit;
350 
351   /// The largest number of element an array can have and still be
352   /// considered "small".
353   ///
354   /// This is currently used to decide whether or not it is worth "forcing" a
355   /// LazyCompoundVal on bind.
356   ///
357   /// This is controlled by 'region-store-small-struct-limit' option.
358   /// To disable all small-struct-dependent behavior, set the option to "0".
359   unsigned SmallArrayLimit;
360 
361   /// A helper used to populate the work list with the given set of
362   /// regions.
363   void populateWorkList(InvalidateRegionsWorker &W,
364                         ArrayRef<SVal> Values,
365                         InvalidatedRegions *TopLevelRegions);
366 
367 public:
368   RegionStoreManager(ProgramStateManager &mgr)
369       : StoreManager(mgr), RBFactory(mgr.getAllocator()),
370         CBFactory(mgr.getAllocator()), SmallStructLimit(0), SmallArrayLimit(0) {
371     ExprEngine &Eng = StateMgr.getOwningEngine();
372     AnalyzerOptions &Options = Eng.getAnalysisManager().options;
373     SmallStructLimit = Options.RegionStoreSmallStructLimit;
374     SmallArrayLimit = Options.RegionStoreSmallArrayLimit;
375   }
376 
377   /// setImplicitDefaultValue - Set the default binding for the provided
378   ///  MemRegion to the value implicitly defined for compound literals when
379   ///  the value is not specified.
380   RegionBindingsRef setImplicitDefaultValue(RegionBindingsConstRef B,
381                                             const MemRegion *R, QualType T);
382 
383   /// ArrayToPointer - Emulates the "decay" of an array to a pointer
384   ///  type.  'Array' represents the lvalue of the array being decayed
385   ///  to a pointer, and the returned SVal represents the decayed
386   ///  version of that lvalue (i.e., a pointer to the first element of
387   ///  the array).  This is called by ExprEngine when evaluating
388   ///  casts from arrays to pointers.
389   SVal ArrayToPointer(Loc Array, QualType ElementTy) override;
390 
391   /// Creates the Store that correctly represents memory contents before
392   /// the beginning of the analysis of the given top-level stack frame.
393   StoreRef getInitialStore(const LocationContext *InitLoc) override {
394     bool IsMainAnalysis = false;
395     if (const auto *FD = dyn_cast<FunctionDecl>(InitLoc->getDecl()))
396       IsMainAnalysis = FD->isMain() && !Ctx.getLangOpts().CPlusPlus;
397     return StoreRef(RegionBindingsRef(
398         RegionBindingsRef::ParentTy(RBFactory.getEmptyMap(), RBFactory),
399         CBFactory, IsMainAnalysis).asStore(), *this);
400   }
401 
402   //===-------------------------------------------------------------------===//
403   // Binding values to regions.
404   //===-------------------------------------------------------------------===//
405   RegionBindingsRef invalidateGlobalRegion(MemRegion::Kind K,
406                                            const Expr *Ex,
407                                            unsigned Count,
408                                            const LocationContext *LCtx,
409                                            RegionBindingsRef B,
410                                            InvalidatedRegions *Invalidated);
411 
412   StoreRef invalidateRegions(Store store,
413                              ArrayRef<SVal> Values,
414                              const Expr *E, unsigned Count,
415                              const LocationContext *LCtx,
416                              const CallEvent *Call,
417                              InvalidatedSymbols &IS,
418                              RegionAndSymbolInvalidationTraits &ITraits,
419                              InvalidatedRegions *Invalidated,
420                              InvalidatedRegions *InvalidatedTopLevel) override;
421 
422   bool scanReachableSymbols(Store S, const MemRegion *R,
423                             ScanReachableSymbols &Callbacks) override;
424 
425   RegionBindingsRef removeSubRegionBindings(RegionBindingsConstRef B,
426                                             const SubRegion *R);
427   Optional<SVal>
428   getConstantValFromConstArrayInitializer(RegionBindingsConstRef B,
429                                           const ElementRegion *R);
430   Optional<SVal>
431   getSValFromInitListExpr(const InitListExpr *ILE,
432                           const SmallVector<uint64_t, 2> &ConcreteOffsets,
433                           QualType ElemT);
434   SVal getSValFromStringLiteral(const StringLiteral *SL, uint64_t Offset,
435                                 QualType ElemT);
436 
437 public: // Part of public interface to class.
438 
439   StoreRef Bind(Store store, Loc LV, SVal V) override {
440     return StoreRef(bind(getRegionBindings(store), LV, V).asStore(), *this);
441   }
442 
443   RegionBindingsRef bind(RegionBindingsConstRef B, Loc LV, SVal V);
444 
445   // BindDefaultInitial is only used to initialize a region with
446   // a default value.
447   StoreRef BindDefaultInitial(Store store, const MemRegion *R,
448                               SVal V) override {
449     RegionBindingsRef B = getRegionBindings(store);
450     // Use other APIs when you have to wipe the region that was initialized
451     // earlier.
452     assert(!(B.getDefaultBinding(R) || B.getDirectBinding(R)) &&
453            "Double initialization!");
454     B = B.addBinding(BindingKey::Make(R, BindingKey::Default), V);
455     return StoreRef(B.asImmutableMap().getRootWithoutRetain(), *this);
456   }
457 
458   // BindDefaultZero is used for zeroing constructors that may accidentally
459   // overwrite existing bindings.
460   StoreRef BindDefaultZero(Store store, const MemRegion *R) override {
461     // FIXME: The offsets of empty bases can be tricky because of
462     // of the so called "empty base class optimization".
463     // If a base class has been optimized out
464     // we should not try to create a binding, otherwise we should.
465     // Unfortunately, at the moment ASTRecordLayout doesn't expose
466     // the actual sizes of the empty bases
467     // and trying to infer them from offsets/alignments
468     // seems to be error-prone and non-trivial because of the trailing padding.
469     // As a temporary mitigation we don't create bindings for empty bases.
470     if (const auto *BR = dyn_cast<CXXBaseObjectRegion>(R))
471       if (BR->getDecl()->isEmpty())
472         return StoreRef(store, *this);
473 
474     RegionBindingsRef B = getRegionBindings(store);
475     SVal V = svalBuilder.makeZeroVal(Ctx.CharTy);
476     B = removeSubRegionBindings(B, cast<SubRegion>(R));
477     B = B.addBinding(BindingKey::Make(R, BindingKey::Default), V);
478     return StoreRef(B.asImmutableMap().getRootWithoutRetain(), *this);
479   }
480 
481   /// Attempt to extract the fields of \p LCV and bind them to the struct region
482   /// \p R.
483   ///
484   /// This path is used when it seems advantageous to "force" loading the values
485   /// within a LazyCompoundVal to bind memberwise to the struct region, rather
486   /// than using a Default binding at the base of the entire region. This is a
487   /// heuristic attempting to avoid building long chains of LazyCompoundVals.
488   ///
489   /// \returns The updated store bindings, or \c std::nullopt if binding
490   ///          non-lazily would be too expensive.
491   Optional<RegionBindingsRef> tryBindSmallStruct(RegionBindingsConstRef B,
492                                                  const TypedValueRegion *R,
493                                                  const RecordDecl *RD,
494                                                  nonloc::LazyCompoundVal LCV);
495 
496   /// BindStruct - Bind a compound value to a structure.
497   RegionBindingsRef bindStruct(RegionBindingsConstRef B,
498                                const TypedValueRegion* R, SVal V);
499 
500   /// BindVector - Bind a compound value to a vector.
501   RegionBindingsRef bindVector(RegionBindingsConstRef B,
502                                const TypedValueRegion* R, SVal V);
503 
504   Optional<RegionBindingsRef> tryBindSmallArray(RegionBindingsConstRef B,
505                                                 const TypedValueRegion *R,
506                                                 const ArrayType *AT,
507                                                 nonloc::LazyCompoundVal LCV);
508 
509   RegionBindingsRef bindArray(RegionBindingsConstRef B,
510                               const TypedValueRegion* R,
511                               SVal V);
512 
513   /// Clears out all bindings in the given region and assigns a new value
514   /// as a Default binding.
515   RegionBindingsRef bindAggregate(RegionBindingsConstRef B,
516                                   const TypedRegion *R,
517                                   SVal DefaultVal);
518 
519   /// Create a new store with the specified binding removed.
520   /// \param ST the original store, that is the basis for the new store.
521   /// \param L the location whose binding should be removed.
522   StoreRef killBinding(Store ST, Loc L) override;
523 
524   void incrementReferenceCount(Store store) override {
525     getRegionBindings(store).manualRetain();
526   }
527 
528   /// If the StoreManager supports it, decrement the reference count of
529   /// the specified Store object.  If the reference count hits 0, the memory
530   /// associated with the object is recycled.
531   void decrementReferenceCount(Store store) override {
532     getRegionBindings(store).manualRelease();
533   }
534 
535   bool includedInBindings(Store store, const MemRegion *region) const override;
536 
537   /// Return the value bound to specified location in a given state.
538   ///
539   /// The high level logic for this method is this:
540   /// getBinding (L)
541   ///   if L has binding
542   ///     return L's binding
543   ///   else if L is in killset
544   ///     return unknown
545   ///   else
546   ///     if L is on stack or heap
547   ///       return undefined
548   ///     else
549   ///       return symbolic
550   SVal getBinding(Store S, Loc L, QualType T) override {
551     return getBinding(getRegionBindings(S), L, T);
552   }
553 
554   Optional<SVal> getDefaultBinding(Store S, const MemRegion *R) override {
555     RegionBindingsRef B = getRegionBindings(S);
556     // Default bindings are always applied over a base region so look up the
557     // base region's default binding, otherwise the lookup will fail when R
558     // is at an offset from R->getBaseRegion().
559     return B.getDefaultBinding(R->getBaseRegion());
560   }
561 
562   SVal getBinding(RegionBindingsConstRef B, Loc L, QualType T = QualType());
563 
564   SVal getBindingForElement(RegionBindingsConstRef B, const ElementRegion *R);
565 
566   SVal getBindingForField(RegionBindingsConstRef B, const FieldRegion *R);
567 
568   SVal getBindingForObjCIvar(RegionBindingsConstRef B, const ObjCIvarRegion *R);
569 
570   SVal getBindingForVar(RegionBindingsConstRef B, const VarRegion *R);
571 
572   SVal getBindingForLazySymbol(const TypedValueRegion *R);
573 
574   SVal getBindingForFieldOrElementCommon(RegionBindingsConstRef B,
575                                          const TypedValueRegion *R,
576                                          QualType Ty);
577 
578   SVal getLazyBinding(const SubRegion *LazyBindingRegion,
579                       RegionBindingsRef LazyBinding);
580 
581   /// Get bindings for the values in a struct and return a CompoundVal, used
582   /// when doing struct copy:
583   /// struct s x, y;
584   /// x = y;
585   /// y's value is retrieved by this method.
586   SVal getBindingForStruct(RegionBindingsConstRef B, const TypedValueRegion *R);
587   SVal getBindingForArray(RegionBindingsConstRef B, const TypedValueRegion *R);
588   NonLoc createLazyBinding(RegionBindingsConstRef B, const TypedValueRegion *R);
589 
590   /// Used to lazily generate derived symbols for bindings that are defined
591   /// implicitly by default bindings in a super region.
592   ///
593   /// Note that callers may need to specially handle LazyCompoundVals, which
594   /// are returned as is in case the caller needs to treat them differently.
595   Optional<SVal> getBindingForDerivedDefaultValue(RegionBindingsConstRef B,
596                                                   const MemRegion *superR,
597                                                   const TypedValueRegion *R,
598                                                   QualType Ty);
599 
600   /// Get the state and region whose binding this region \p R corresponds to.
601   ///
602   /// If there is no lazy binding for \p R, the returned value will have a null
603   /// \c second. Note that a null pointer can represents a valid Store.
604   std::pair<Store, const SubRegion *>
605   findLazyBinding(RegionBindingsConstRef B, const SubRegion *R,
606                   const SubRegion *originalRegion);
607 
608   /// Returns the cached set of interesting SVals contained within a lazy
609   /// binding.
610   ///
611   /// The precise value of "interesting" is determined for the purposes of
612   /// RegionStore's internal analysis. It must always contain all regions and
613   /// symbols, but may omit constants and other kinds of SVal.
614   ///
615   /// In contrast to compound values, LazyCompoundVals are also added
616   /// to the 'interesting values' list in addition to the child interesting
617   /// values.
618   const SValListTy &getInterestingValues(nonloc::LazyCompoundVal LCV);
619 
620   //===------------------------------------------------------------------===//
621   // State pruning.
622   //===------------------------------------------------------------------===//
623 
624   /// removeDeadBindings - Scans the RegionStore of 'state' for dead values.
625   ///  It returns a new Store with these values removed.
626   StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx,
627                               SymbolReaper& SymReaper) override;
628 
629   //===------------------------------------------------------------------===//
630   // Utility methods.
631   //===------------------------------------------------------------------===//
632 
633   RegionBindingsRef getRegionBindings(Store store) const {
634     llvm::PointerIntPair<Store, 1, bool> Ptr;
635     Ptr.setFromOpaqueValue(const_cast<void *>(store));
636     return RegionBindingsRef(
637         CBFactory,
638         static_cast<const RegionBindings::TreeTy *>(Ptr.getPointer()),
639         RBFactory.getTreeFactory(),
640         Ptr.getInt());
641   }
642 
643   void printJson(raw_ostream &Out, Store S, const char *NL = "\n",
644                  unsigned int Space = 0, bool IsDot = false) const override;
645 
646   void iterBindings(Store store, BindingsHandler& f) override {
647     RegionBindingsRef B = getRegionBindings(store);
648     for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; ++I) {
649       const ClusterBindings &Cluster = I.getData();
650       for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
651            CI != CE; ++CI) {
652         const BindingKey &K = CI.getKey();
653         if (!K.isDirect())
654           continue;
655         if (const SubRegion *R = dyn_cast<SubRegion>(K.getRegion())) {
656           // FIXME: Possibly incorporate the offset?
657           if (!f.HandleBinding(*this, store, R, CI.getData()))
658             return;
659         }
660       }
661     }
662   }
663 };
664 
665 } // end anonymous namespace
666 
667 //===----------------------------------------------------------------------===//
668 // RegionStore creation.
669 //===----------------------------------------------------------------------===//
670 
671 std::unique_ptr<StoreManager>
672 ento::CreateRegionStoreManager(ProgramStateManager &StMgr) {
673   return std::make_unique<RegionStoreManager>(StMgr);
674 }
675 
676 //===----------------------------------------------------------------------===//
677 // Region Cluster analysis.
678 //===----------------------------------------------------------------------===//
679 
680 namespace {
681 /// Used to determine which global regions are automatically included in the
682 /// initial worklist of a ClusterAnalysis.
683 enum GlobalsFilterKind {
684   /// Don't include any global regions.
685   GFK_None,
686   /// Only include system globals.
687   GFK_SystemOnly,
688   /// Include all global regions.
689   GFK_All
690 };
691 
692 template <typename DERIVED>
693 class ClusterAnalysis  {
694 protected:
695   typedef llvm::DenseMap<const MemRegion *, const ClusterBindings *> ClusterMap;
696   typedef const MemRegion * WorkListElement;
697   typedef SmallVector<WorkListElement, 10> WorkList;
698 
699   llvm::SmallPtrSet<const ClusterBindings *, 16> Visited;
700 
701   WorkList WL;
702 
703   RegionStoreManager &RM;
704   ASTContext &Ctx;
705   SValBuilder &svalBuilder;
706 
707   RegionBindingsRef B;
708 
709 
710 protected:
711   const ClusterBindings *getCluster(const MemRegion *R) {
712     return B.lookup(R);
713   }
714 
715   /// Returns true if all clusters in the given memspace should be initially
716   /// included in the cluster analysis. Subclasses may provide their
717   /// own implementation.
718   bool includeEntireMemorySpace(const MemRegion *Base) {
719     return false;
720   }
721 
722 public:
723   ClusterAnalysis(RegionStoreManager &rm, ProgramStateManager &StateMgr,
724                   RegionBindingsRef b)
725       : RM(rm), Ctx(StateMgr.getContext()),
726         svalBuilder(StateMgr.getSValBuilder()), B(std::move(b)) {}
727 
728   RegionBindingsRef getRegionBindings() const { return B; }
729 
730   bool isVisited(const MemRegion *R) {
731     return Visited.count(getCluster(R));
732   }
733 
734   void GenerateClusters() {
735     // Scan the entire set of bindings and record the region clusters.
736     for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end();
737          RI != RE; ++RI){
738       const MemRegion *Base = RI.getKey();
739 
740       const ClusterBindings &Cluster = RI.getData();
741       assert(!Cluster.isEmpty() && "Empty clusters should be removed");
742       static_cast<DERIVED*>(this)->VisitAddedToCluster(Base, Cluster);
743 
744       // If the base's memspace should be entirely invalidated, add the cluster
745       // to the workspace up front.
746       if (static_cast<DERIVED*>(this)->includeEntireMemorySpace(Base))
747         AddToWorkList(WorkListElement(Base), &Cluster);
748     }
749   }
750 
751   bool AddToWorkList(WorkListElement E, const ClusterBindings *C) {
752     if (C && !Visited.insert(C).second)
753       return false;
754     WL.push_back(E);
755     return true;
756   }
757 
758   bool AddToWorkList(const MemRegion *R) {
759     return static_cast<DERIVED*>(this)->AddToWorkList(R);
760   }
761 
762   void RunWorkList() {
763     while (!WL.empty()) {
764       WorkListElement E = WL.pop_back_val();
765       const MemRegion *BaseR = E;
766 
767       static_cast<DERIVED*>(this)->VisitCluster(BaseR, getCluster(BaseR));
768     }
769   }
770 
771   void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C) {}
772   void VisitCluster(const MemRegion *baseR, const ClusterBindings *C) {}
773 
774   void VisitCluster(const MemRegion *BaseR, const ClusterBindings *C,
775                     bool Flag) {
776     static_cast<DERIVED*>(this)->VisitCluster(BaseR, C);
777   }
778 };
779 }
780 
781 //===----------------------------------------------------------------------===//
782 // Binding invalidation.
783 //===----------------------------------------------------------------------===//
784 
785 bool RegionStoreManager::scanReachableSymbols(Store S, const MemRegion *R,
786                                               ScanReachableSymbols &Callbacks) {
787   assert(R == R->getBaseRegion() && "Should only be called for base regions");
788   RegionBindingsRef B = getRegionBindings(S);
789   const ClusterBindings *Cluster = B.lookup(R);
790 
791   if (!Cluster)
792     return true;
793 
794   for (ClusterBindings::iterator RI = Cluster->begin(), RE = Cluster->end();
795        RI != RE; ++RI) {
796     if (!Callbacks.scan(RI.getData()))
797       return false;
798   }
799 
800   return true;
801 }
802 
803 static inline bool isUnionField(const FieldRegion *FR) {
804   return FR->getDecl()->getParent()->isUnion();
805 }
806 
807 typedef SmallVector<const FieldDecl *, 8> FieldVector;
808 
809 static void getSymbolicOffsetFields(BindingKey K, FieldVector &Fields) {
810   assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys");
811 
812   const MemRegion *Base = K.getConcreteOffsetRegion();
813   const MemRegion *R = K.getRegion();
814 
815   while (R != Base) {
816     if (const FieldRegion *FR = dyn_cast<FieldRegion>(R))
817       if (!isUnionField(FR))
818         Fields.push_back(FR->getDecl());
819 
820     R = cast<SubRegion>(R)->getSuperRegion();
821   }
822 }
823 
824 static bool isCompatibleWithFields(BindingKey K, const FieldVector &Fields) {
825   assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys");
826 
827   if (Fields.empty())
828     return true;
829 
830   FieldVector FieldsInBindingKey;
831   getSymbolicOffsetFields(K, FieldsInBindingKey);
832 
833   ptrdiff_t Delta = FieldsInBindingKey.size() - Fields.size();
834   if (Delta >= 0)
835     return std::equal(FieldsInBindingKey.begin() + Delta,
836                       FieldsInBindingKey.end(),
837                       Fields.begin());
838   else
839     return std::equal(FieldsInBindingKey.begin(), FieldsInBindingKey.end(),
840                       Fields.begin() - Delta);
841 }
842 
843 /// Collects all bindings in \p Cluster that may refer to bindings within
844 /// \p Top.
845 ///
846 /// Each binding is a pair whose \c first is the key (a BindingKey) and whose
847 /// \c second is the value (an SVal).
848 ///
849 /// The \p IncludeAllDefaultBindings parameter specifies whether to include
850 /// default bindings that may extend beyond \p Top itself, e.g. if \p Top is
851 /// an aggregate within a larger aggregate with a default binding.
852 static void
853 collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings,
854                          SValBuilder &SVB, const ClusterBindings &Cluster,
855                          const SubRegion *Top, BindingKey TopKey,
856                          bool IncludeAllDefaultBindings) {
857   FieldVector FieldsInSymbolicSubregions;
858   if (TopKey.hasSymbolicOffset()) {
859     getSymbolicOffsetFields(TopKey, FieldsInSymbolicSubregions);
860     Top = TopKey.getConcreteOffsetRegion();
861     TopKey = BindingKey::Make(Top, BindingKey::Default);
862   }
863 
864   // Find the length (in bits) of the region being invalidated.
865   uint64_t Length = UINT64_MAX;
866   SVal Extent = Top->getMemRegionManager().getStaticSize(Top, SVB);
867   if (Optional<nonloc::ConcreteInt> ExtentCI =
868           Extent.getAs<nonloc::ConcreteInt>()) {
869     const llvm::APSInt &ExtentInt = ExtentCI->getValue();
870     assert(ExtentInt.isNonNegative() || ExtentInt.isUnsigned());
871     // Extents are in bytes but region offsets are in bits. Be careful!
872     Length = ExtentInt.getLimitedValue() * SVB.getContext().getCharWidth();
873   } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(Top)) {
874     if (FR->getDecl()->isBitField())
875       Length = FR->getDecl()->getBitWidthValue(SVB.getContext());
876   }
877 
878   for (ClusterBindings::iterator I = Cluster.begin(), E = Cluster.end();
879        I != E; ++I) {
880     BindingKey NextKey = I.getKey();
881     if (NextKey.getRegion() == TopKey.getRegion()) {
882       // FIXME: This doesn't catch the case where we're really invalidating a
883       // region with a symbolic offset. Example:
884       //      R: points[i].y
885       //   Next: points[0].x
886 
887       if (NextKey.getOffset() > TopKey.getOffset() &&
888           NextKey.getOffset() - TopKey.getOffset() < Length) {
889         // Case 1: The next binding is inside the region we're invalidating.
890         // Include it.
891         Bindings.push_back(*I);
892 
893       } else if (NextKey.getOffset() == TopKey.getOffset()) {
894         // Case 2: The next binding is at the same offset as the region we're
895         // invalidating. In this case, we need to leave default bindings alone,
896         // since they may be providing a default value for a regions beyond what
897         // we're invalidating.
898         // FIXME: This is probably incorrect; consider invalidating an outer
899         // struct whose first field is bound to a LazyCompoundVal.
900         if (IncludeAllDefaultBindings || NextKey.isDirect())
901           Bindings.push_back(*I);
902       }
903 
904     } else if (NextKey.hasSymbolicOffset()) {
905       const MemRegion *Base = NextKey.getConcreteOffsetRegion();
906       if (Top->isSubRegionOf(Base) && Top != Base) {
907         // Case 3: The next key is symbolic and we just changed something within
908         // its concrete region. We don't know if the binding is still valid, so
909         // we'll be conservative and include it.
910         if (IncludeAllDefaultBindings || NextKey.isDirect())
911           if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions))
912             Bindings.push_back(*I);
913       } else if (const SubRegion *BaseSR = dyn_cast<SubRegion>(Base)) {
914         // Case 4: The next key is symbolic, but we changed a known
915         // super-region. In this case the binding is certainly included.
916         if (BaseSR->isSubRegionOf(Top))
917           if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions))
918             Bindings.push_back(*I);
919       }
920     }
921   }
922 }
923 
924 static void
925 collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings,
926                          SValBuilder &SVB, const ClusterBindings &Cluster,
927                          const SubRegion *Top, bool IncludeAllDefaultBindings) {
928   collectSubRegionBindings(Bindings, SVB, Cluster, Top,
929                            BindingKey::Make(Top, BindingKey::Default),
930                            IncludeAllDefaultBindings);
931 }
932 
933 RegionBindingsRef
934 RegionStoreManager::removeSubRegionBindings(RegionBindingsConstRef B,
935                                             const SubRegion *Top) {
936   BindingKey TopKey = BindingKey::Make(Top, BindingKey::Default);
937   const MemRegion *ClusterHead = TopKey.getBaseRegion();
938 
939   if (Top == ClusterHead) {
940     // We can remove an entire cluster's bindings all in one go.
941     return B.remove(Top);
942   }
943 
944   const ClusterBindings *Cluster = B.lookup(ClusterHead);
945   if (!Cluster) {
946     // If we're invalidating a region with a symbolic offset, we need to make
947     // sure we don't treat the base region as uninitialized anymore.
948     if (TopKey.hasSymbolicOffset()) {
949       const SubRegion *Concrete = TopKey.getConcreteOffsetRegion();
950       return B.addBinding(Concrete, BindingKey::Default, UnknownVal());
951     }
952     return B;
953   }
954 
955   SmallVector<BindingPair, 32> Bindings;
956   collectSubRegionBindings(Bindings, svalBuilder, *Cluster, Top, TopKey,
957                            /*IncludeAllDefaultBindings=*/false);
958 
959   ClusterBindingsRef Result(*Cluster, CBFactory);
960   for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(),
961                                                     E = Bindings.end();
962        I != E; ++I)
963     Result = Result.remove(I->first);
964 
965   // If we're invalidating a region with a symbolic offset, we need to make sure
966   // we don't treat the base region as uninitialized anymore.
967   // FIXME: This isn't very precise; see the example in
968   // collectSubRegionBindings.
969   if (TopKey.hasSymbolicOffset()) {
970     const SubRegion *Concrete = TopKey.getConcreteOffsetRegion();
971     Result = Result.add(BindingKey::Make(Concrete, BindingKey::Default),
972                         UnknownVal());
973   }
974 
975   if (Result.isEmpty())
976     return B.remove(ClusterHead);
977   return B.add(ClusterHead, Result.asImmutableMap());
978 }
979 
980 namespace {
981 class InvalidateRegionsWorker : public ClusterAnalysis<InvalidateRegionsWorker>
982 {
983   const Expr *Ex;
984   unsigned Count;
985   const LocationContext *LCtx;
986   InvalidatedSymbols &IS;
987   RegionAndSymbolInvalidationTraits &ITraits;
988   StoreManager::InvalidatedRegions *Regions;
989   GlobalsFilterKind GlobalsFilter;
990 public:
991   InvalidateRegionsWorker(RegionStoreManager &rm,
992                           ProgramStateManager &stateMgr,
993                           RegionBindingsRef b,
994                           const Expr *ex, unsigned count,
995                           const LocationContext *lctx,
996                           InvalidatedSymbols &is,
997                           RegionAndSymbolInvalidationTraits &ITraitsIn,
998                           StoreManager::InvalidatedRegions *r,
999                           GlobalsFilterKind GFK)
1000      : ClusterAnalysis<InvalidateRegionsWorker>(rm, stateMgr, b),
1001        Ex(ex), Count(count), LCtx(lctx), IS(is), ITraits(ITraitsIn), Regions(r),
1002        GlobalsFilter(GFK) {}
1003 
1004   void VisitCluster(const MemRegion *baseR, const ClusterBindings *C);
1005   void VisitBinding(SVal V);
1006 
1007   using ClusterAnalysis::AddToWorkList;
1008 
1009   bool AddToWorkList(const MemRegion *R);
1010 
1011   /// Returns true if all clusters in the memory space for \p Base should be
1012   /// be invalidated.
1013   bool includeEntireMemorySpace(const MemRegion *Base);
1014 
1015   /// Returns true if the memory space of the given region is one of the global
1016   /// regions specially included at the start of invalidation.
1017   bool isInitiallyIncludedGlobalRegion(const MemRegion *R);
1018 };
1019 }
1020 
1021 bool InvalidateRegionsWorker::AddToWorkList(const MemRegion *R) {
1022   bool doNotInvalidateSuperRegion = ITraits.hasTrait(
1023       R, RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
1024   const MemRegion *BaseR = doNotInvalidateSuperRegion ? R : R->getBaseRegion();
1025   return AddToWorkList(WorkListElement(BaseR), getCluster(BaseR));
1026 }
1027 
1028 void InvalidateRegionsWorker::VisitBinding(SVal V) {
1029   // A symbol?  Mark it touched by the invalidation.
1030   if (SymbolRef Sym = V.getAsSymbol())
1031     IS.insert(Sym);
1032 
1033   if (const MemRegion *R = V.getAsRegion()) {
1034     AddToWorkList(R);
1035     return;
1036   }
1037 
1038   // Is it a LazyCompoundVal?  All references get invalidated as well.
1039   if (Optional<nonloc::LazyCompoundVal> LCS =
1040           V.getAs<nonloc::LazyCompoundVal>()) {
1041 
1042     // `getInterestingValues()` returns SVals contained within LazyCompoundVals,
1043     // so there is no need to visit them.
1044     for (SVal V : RM.getInterestingValues(*LCS))
1045       if (!isa<nonloc::LazyCompoundVal>(V))
1046         VisitBinding(V);
1047 
1048     return;
1049   }
1050 }
1051 
1052 void InvalidateRegionsWorker::VisitCluster(const MemRegion *baseR,
1053                                            const ClusterBindings *C) {
1054 
1055   bool PreserveRegionsContents =
1056       ITraits.hasTrait(baseR,
1057                        RegionAndSymbolInvalidationTraits::TK_PreserveContents);
1058 
1059   if (C) {
1060     for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I)
1061       VisitBinding(I.getData());
1062 
1063     // Invalidate regions contents.
1064     if (!PreserveRegionsContents)
1065       B = B.remove(baseR);
1066   }
1067 
1068   if (const auto *TO = dyn_cast<TypedValueRegion>(baseR)) {
1069     if (const auto *RD = TO->getValueType()->getAsCXXRecordDecl()) {
1070 
1071       // Lambdas can affect all static local variables without explicitly
1072       // capturing those.
1073       // We invalidate all static locals referenced inside the lambda body.
1074       if (RD->isLambda() && RD->getLambdaCallOperator()->getBody()) {
1075         using namespace ast_matchers;
1076 
1077         const char *DeclBind = "DeclBind";
1078         StatementMatcher RefToStatic = stmt(hasDescendant(declRefExpr(
1079               to(varDecl(hasStaticStorageDuration()).bind(DeclBind)))));
1080         auto Matches =
1081             match(RefToStatic, *RD->getLambdaCallOperator()->getBody(),
1082                   RD->getASTContext());
1083 
1084         for (BoundNodes &Match : Matches) {
1085           auto *VD = Match.getNodeAs<VarDecl>(DeclBind);
1086           const VarRegion *ToInvalidate =
1087               RM.getRegionManager().getVarRegion(VD, LCtx);
1088           AddToWorkList(ToInvalidate);
1089         }
1090       }
1091     }
1092   }
1093 
1094   // BlockDataRegion?  If so, invalidate captured variables that are passed
1095   // by reference.
1096   if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) {
1097     for (BlockDataRegion::referenced_vars_iterator
1098          BI = BR->referenced_vars_begin(), BE = BR->referenced_vars_end() ;
1099          BI != BE; ++BI) {
1100       const VarRegion *VR = BI.getCapturedRegion();
1101       const VarDecl *VD = VR->getDecl();
1102       if (VD->hasAttr<BlocksAttr>() || !VD->hasLocalStorage()) {
1103         AddToWorkList(VR);
1104       }
1105       else if (Loc::isLocType(VR->getValueType())) {
1106         // Map the current bindings to a Store to retrieve the value
1107         // of the binding.  If that binding itself is a region, we should
1108         // invalidate that region.  This is because a block may capture
1109         // a pointer value, but the thing pointed by that pointer may
1110         // get invalidated.
1111         SVal V = RM.getBinding(B, loc::MemRegionVal(VR));
1112         if (Optional<Loc> L = V.getAs<Loc>()) {
1113           if (const MemRegion *LR = L->getAsRegion())
1114             AddToWorkList(LR);
1115         }
1116       }
1117     }
1118     return;
1119   }
1120 
1121   // Symbolic region?
1122   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR))
1123     IS.insert(SR->getSymbol());
1124 
1125   // Nothing else should be done in the case when we preserve regions context.
1126   if (PreserveRegionsContents)
1127     return;
1128 
1129   // Otherwise, we have a normal data region. Record that we touched the region.
1130   if (Regions)
1131     Regions->push_back(baseR);
1132 
1133   if (isa<AllocaRegion, SymbolicRegion>(baseR)) {
1134     // Invalidate the region by setting its default value to
1135     // conjured symbol. The type of the symbol is irrelevant.
1136     DefinedOrUnknownSVal V =
1137       svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count);
1138     B = B.addBinding(baseR, BindingKey::Default, V);
1139     return;
1140   }
1141 
1142   if (!baseR->isBoundable())
1143     return;
1144 
1145   const TypedValueRegion *TR = cast<TypedValueRegion>(baseR);
1146   QualType T = TR->getValueType();
1147 
1148   if (isInitiallyIncludedGlobalRegion(baseR)) {
1149     // If the region is a global and we are invalidating all globals,
1150     // erasing the entry is good enough.  This causes all globals to be lazily
1151     // symbolicated from the same base symbol.
1152     return;
1153   }
1154 
1155   if (T->isRecordType()) {
1156     // Invalidate the region by setting its default value to
1157     // conjured symbol. The type of the symbol is irrelevant.
1158     DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
1159                                                           Ctx.IntTy, Count);
1160     B = B.addBinding(baseR, BindingKey::Default, V);
1161     return;
1162   }
1163 
1164   if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
1165     bool doNotInvalidateSuperRegion = ITraits.hasTrait(
1166         baseR,
1167         RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
1168 
1169     if (doNotInvalidateSuperRegion) {
1170       // We are not doing blank invalidation of the whole array region so we
1171       // have to manually invalidate each elements.
1172       Optional<uint64_t> NumElements;
1173 
1174       // Compute lower and upper offsets for region within array.
1175       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1176         NumElements = CAT->getSize().getZExtValue();
1177       if (!NumElements) // We are not dealing with a constant size array
1178         goto conjure_default;
1179       QualType ElementTy = AT->getElementType();
1180       uint64_t ElemSize = Ctx.getTypeSize(ElementTy);
1181       const RegionOffset &RO = baseR->getAsOffset();
1182       const MemRegion *SuperR = baseR->getBaseRegion();
1183       if (RO.hasSymbolicOffset()) {
1184         // If base region has a symbolic offset,
1185         // we revert to invalidating the super region.
1186         if (SuperR)
1187           AddToWorkList(SuperR);
1188         goto conjure_default;
1189       }
1190 
1191       uint64_t LowerOffset = RO.getOffset();
1192       uint64_t UpperOffset = LowerOffset + *NumElements * ElemSize;
1193       bool UpperOverflow = UpperOffset < LowerOffset;
1194 
1195       // Invalidate regions which are within array boundaries,
1196       // or have a symbolic offset.
1197       if (!SuperR)
1198         goto conjure_default;
1199 
1200       const ClusterBindings *C = B.lookup(SuperR);
1201       if (!C)
1202         goto conjure_default;
1203 
1204       for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E;
1205            ++I) {
1206         const BindingKey &BK = I.getKey();
1207         Optional<uint64_t> ROffset =
1208             BK.hasSymbolicOffset() ? Optional<uint64_t>() : BK.getOffset();
1209 
1210         // Check offset is not symbolic and within array's boundaries.
1211         // Handles arrays of 0 elements and of 0-sized elements as well.
1212         if (!ROffset ||
1213             ((*ROffset >= LowerOffset && *ROffset < UpperOffset) ||
1214              (UpperOverflow &&
1215               (*ROffset >= LowerOffset || *ROffset < UpperOffset)) ||
1216              (LowerOffset == UpperOffset && *ROffset == LowerOffset))) {
1217           B = B.removeBinding(I.getKey());
1218           // Bound symbolic regions need to be invalidated for dead symbol
1219           // detection.
1220           SVal V = I.getData();
1221           const MemRegion *R = V.getAsRegion();
1222           if (isa_and_nonnull<SymbolicRegion>(R))
1223             VisitBinding(V);
1224         }
1225       }
1226     }
1227   conjure_default:
1228       // Set the default value of the array to conjured symbol.
1229     DefinedOrUnknownSVal V =
1230     svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
1231                                      AT->getElementType(), Count);
1232     B = B.addBinding(baseR, BindingKey::Default, V);
1233     return;
1234   }
1235 
1236   DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
1237                                                         T,Count);
1238   assert(SymbolManager::canSymbolicate(T) || V.isUnknown());
1239   B = B.addBinding(baseR, BindingKey::Direct, V);
1240 }
1241 
1242 bool InvalidateRegionsWorker::isInitiallyIncludedGlobalRegion(
1243     const MemRegion *R) {
1244   switch (GlobalsFilter) {
1245   case GFK_None:
1246     return false;
1247   case GFK_SystemOnly:
1248     return isa<GlobalSystemSpaceRegion>(R->getMemorySpace());
1249   case GFK_All:
1250     return isa<NonStaticGlobalSpaceRegion>(R->getMemorySpace());
1251   }
1252 
1253   llvm_unreachable("unknown globals filter");
1254 }
1255 
1256 bool InvalidateRegionsWorker::includeEntireMemorySpace(const MemRegion *Base) {
1257   if (isInitiallyIncludedGlobalRegion(Base))
1258     return true;
1259 
1260   const MemSpaceRegion *MemSpace = Base->getMemorySpace();
1261   return ITraits.hasTrait(MemSpace,
1262                           RegionAndSymbolInvalidationTraits::TK_EntireMemSpace);
1263 }
1264 
1265 RegionBindingsRef
1266 RegionStoreManager::invalidateGlobalRegion(MemRegion::Kind K,
1267                                            const Expr *Ex,
1268                                            unsigned Count,
1269                                            const LocationContext *LCtx,
1270                                            RegionBindingsRef B,
1271                                            InvalidatedRegions *Invalidated) {
1272   // Bind the globals memory space to a new symbol that we will use to derive
1273   // the bindings for all globals.
1274   const GlobalsSpaceRegion *GS = MRMgr.getGlobalsRegion(K);
1275   SVal V = svalBuilder.conjureSymbolVal(/* symbolTag = */ (const void*) GS, Ex, LCtx,
1276                                         /* type does not matter */ Ctx.IntTy,
1277                                         Count);
1278 
1279   B = B.removeBinding(GS)
1280        .addBinding(BindingKey::Make(GS, BindingKey::Default), V);
1281 
1282   // Even if there are no bindings in the global scope, we still need to
1283   // record that we touched it.
1284   if (Invalidated)
1285     Invalidated->push_back(GS);
1286 
1287   return B;
1288 }
1289 
1290 void RegionStoreManager::populateWorkList(InvalidateRegionsWorker &W,
1291                                           ArrayRef<SVal> Values,
1292                                           InvalidatedRegions *TopLevelRegions) {
1293   for (ArrayRef<SVal>::iterator I = Values.begin(),
1294                                 E = Values.end(); I != E; ++I) {
1295     SVal V = *I;
1296     if (Optional<nonloc::LazyCompoundVal> LCS =
1297         V.getAs<nonloc::LazyCompoundVal>()) {
1298 
1299       for (SVal S : getInterestingValues(*LCS))
1300         if (const MemRegion *R = S.getAsRegion())
1301           W.AddToWorkList(R);
1302 
1303       continue;
1304     }
1305 
1306     if (const MemRegion *R = V.getAsRegion()) {
1307       if (TopLevelRegions)
1308         TopLevelRegions->push_back(R);
1309       W.AddToWorkList(R);
1310       continue;
1311     }
1312   }
1313 }
1314 
1315 StoreRef
1316 RegionStoreManager::invalidateRegions(Store store,
1317                                      ArrayRef<SVal> Values,
1318                                      const Expr *Ex, unsigned Count,
1319                                      const LocationContext *LCtx,
1320                                      const CallEvent *Call,
1321                                      InvalidatedSymbols &IS,
1322                                      RegionAndSymbolInvalidationTraits &ITraits,
1323                                      InvalidatedRegions *TopLevelRegions,
1324                                      InvalidatedRegions *Invalidated) {
1325   GlobalsFilterKind GlobalsFilter;
1326   if (Call) {
1327     if (Call->isInSystemHeader())
1328       GlobalsFilter = GFK_SystemOnly;
1329     else
1330       GlobalsFilter = GFK_All;
1331   } else {
1332     GlobalsFilter = GFK_None;
1333   }
1334 
1335   RegionBindingsRef B = getRegionBindings(store);
1336   InvalidateRegionsWorker W(*this, StateMgr, B, Ex, Count, LCtx, IS, ITraits,
1337                             Invalidated, GlobalsFilter);
1338 
1339   // Scan the bindings and generate the clusters.
1340   W.GenerateClusters();
1341 
1342   // Add the regions to the worklist.
1343   populateWorkList(W, Values, TopLevelRegions);
1344 
1345   W.RunWorkList();
1346 
1347   // Return the new bindings.
1348   B = W.getRegionBindings();
1349 
1350   // For calls, determine which global regions should be invalidated and
1351   // invalidate them. (Note that function-static and immutable globals are never
1352   // invalidated by this.)
1353   // TODO: This could possibly be more precise with modules.
1354   switch (GlobalsFilter) {
1355   case GFK_All:
1356     B = invalidateGlobalRegion(MemRegion::GlobalInternalSpaceRegionKind,
1357                                Ex, Count, LCtx, B, Invalidated);
1358     [[fallthrough]];
1359   case GFK_SystemOnly:
1360     B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind,
1361                                Ex, Count, LCtx, B, Invalidated);
1362     [[fallthrough]];
1363   case GFK_None:
1364     break;
1365   }
1366 
1367   return StoreRef(B.asStore(), *this);
1368 }
1369 
1370 //===----------------------------------------------------------------------===//
1371 // Location and region casting.
1372 //===----------------------------------------------------------------------===//
1373 
1374 /// ArrayToPointer - Emulates the "decay" of an array to a pointer
1375 ///  type.  'Array' represents the lvalue of the array being decayed
1376 ///  to a pointer, and the returned SVal represents the decayed
1377 ///  version of that lvalue (i.e., a pointer to the first element of
1378 ///  the array).  This is called by ExprEngine when evaluating casts
1379 ///  from arrays to pointers.
1380 SVal RegionStoreManager::ArrayToPointer(Loc Array, QualType T) {
1381   if (isa<loc::ConcreteInt>(Array))
1382     return Array;
1383 
1384   if (!isa<loc::MemRegionVal>(Array))
1385     return UnknownVal();
1386 
1387   const SubRegion *R =
1388       cast<SubRegion>(Array.castAs<loc::MemRegionVal>().getRegion());
1389   NonLoc ZeroIdx = svalBuilder.makeZeroArrayIndex();
1390   return loc::MemRegionVal(MRMgr.getElementRegion(T, ZeroIdx, R, Ctx));
1391 }
1392 
1393 //===----------------------------------------------------------------------===//
1394 // Loading values from regions.
1395 //===----------------------------------------------------------------------===//
1396 
1397 SVal RegionStoreManager::getBinding(RegionBindingsConstRef B, Loc L, QualType T) {
1398   assert(!isa<UnknownVal>(L) && "location unknown");
1399   assert(!isa<UndefinedVal>(L) && "location undefined");
1400 
1401   // For access to concrete addresses, return UnknownVal.  Checks
1402   // for null dereferences (and similar errors) are done by checkers, not
1403   // the Store.
1404   // FIXME: We can consider lazily symbolicating such memory, but we really
1405   // should defer this when we can reason easily about symbolicating arrays
1406   // of bytes.
1407   if (L.getAs<loc::ConcreteInt>()) {
1408     return UnknownVal();
1409   }
1410   if (!L.getAs<loc::MemRegionVal>()) {
1411     return UnknownVal();
1412   }
1413 
1414   const MemRegion *MR = L.castAs<loc::MemRegionVal>().getRegion();
1415 
1416   if (isa<BlockDataRegion>(MR)) {
1417     return UnknownVal();
1418   }
1419 
1420   // Auto-detect the binding type.
1421   if (T.isNull()) {
1422     if (const auto *TVR = dyn_cast<TypedValueRegion>(MR))
1423       T = TVR->getValueType();
1424     else if (const auto *TR = dyn_cast<TypedRegion>(MR))
1425       T = TR->getLocationType()->getPointeeType();
1426     else if (const auto *SR = dyn_cast<SymbolicRegion>(MR))
1427       T = SR->getPointeeStaticType();
1428   }
1429   assert(!T.isNull() && "Unable to auto-detect binding type!");
1430   assert(!T->isVoidType() && "Attempting to dereference a void pointer!");
1431 
1432   if (!isa<TypedValueRegion>(MR))
1433     MR = GetElementZeroRegion(cast<SubRegion>(MR), T);
1434 
1435   // FIXME: Perhaps this method should just take a 'const MemRegion*' argument
1436   //  instead of 'Loc', and have the other Loc cases handled at a higher level.
1437   const TypedValueRegion *R = cast<TypedValueRegion>(MR);
1438   QualType RTy = R->getValueType();
1439 
1440   // FIXME: we do not yet model the parts of a complex type, so treat the
1441   // whole thing as "unknown".
1442   if (RTy->isAnyComplexType())
1443     return UnknownVal();
1444 
1445   // FIXME: We should eventually handle funny addressing.  e.g.:
1446   //
1447   //   int x = ...;
1448   //   int *p = &x;
1449   //   char *q = (char*) p;
1450   //   char c = *q;  // returns the first byte of 'x'.
1451   //
1452   // Such funny addressing will occur due to layering of regions.
1453   if (RTy->isStructureOrClassType())
1454     return getBindingForStruct(B, R);
1455 
1456   // FIXME: Handle unions.
1457   if (RTy->isUnionType())
1458     return createLazyBinding(B, R);
1459 
1460   if (RTy->isArrayType()) {
1461     if (RTy->isConstantArrayType())
1462       return getBindingForArray(B, R);
1463     else
1464       return UnknownVal();
1465   }
1466 
1467   // FIXME: handle Vector types.
1468   if (RTy->isVectorType())
1469     return UnknownVal();
1470 
1471   if (const FieldRegion* FR = dyn_cast<FieldRegion>(R))
1472     return svalBuilder.evalCast(getBindingForField(B, FR), T, QualType{});
1473 
1474   if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) {
1475     // FIXME: Here we actually perform an implicit conversion from the loaded
1476     // value to the element type.  Eventually we want to compose these values
1477     // more intelligently.  For example, an 'element' can encompass multiple
1478     // bound regions (e.g., several bound bytes), or could be a subset of
1479     // a larger value.
1480     return svalBuilder.evalCast(getBindingForElement(B, ER), T, QualType{});
1481   }
1482 
1483   if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) {
1484     // FIXME: Here we actually perform an implicit conversion from the loaded
1485     // value to the ivar type.  What we should model is stores to ivars
1486     // that blow past the extent of the ivar.  If the address of the ivar is
1487     // reinterpretted, it is possible we stored a different value that could
1488     // fit within the ivar.  Either we need to cast these when storing them
1489     // or reinterpret them lazily (as we do here).
1490     return svalBuilder.evalCast(getBindingForObjCIvar(B, IVR), T, QualType{});
1491   }
1492 
1493   if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
1494     // FIXME: Here we actually perform an implicit conversion from the loaded
1495     // value to the variable type.  What we should model is stores to variables
1496     // that blow past the extent of the variable.  If the address of the
1497     // variable is reinterpretted, it is possible we stored a different value
1498     // that could fit within the variable.  Either we need to cast these when
1499     // storing them or reinterpret them lazily (as we do here).
1500     return svalBuilder.evalCast(getBindingForVar(B, VR), T, QualType{});
1501   }
1502 
1503   const SVal *V = B.lookup(R, BindingKey::Direct);
1504 
1505   // Check if the region has a binding.
1506   if (V)
1507     return *V;
1508 
1509   // The location does not have a bound value.  This means that it has
1510   // the value it had upon its creation and/or entry to the analyzed
1511   // function/method.  These are either symbolic values or 'undefined'.
1512   if (R->hasStackNonParametersStorage()) {
1513     // All stack variables are considered to have undefined values
1514     // upon creation.  All heap allocated blocks are considered to
1515     // have undefined values as well unless they are explicitly bound
1516     // to specific values.
1517     return UndefinedVal();
1518   }
1519 
1520   // All other values are symbolic.
1521   return svalBuilder.getRegionValueSymbolVal(R);
1522 }
1523 
1524 static QualType getUnderlyingType(const SubRegion *R) {
1525   QualType RegionTy;
1526   if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(R))
1527     RegionTy = TVR->getValueType();
1528 
1529   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
1530     RegionTy = SR->getSymbol()->getType();
1531 
1532   return RegionTy;
1533 }
1534 
1535 /// Checks to see if store \p B has a lazy binding for region \p R.
1536 ///
1537 /// If \p AllowSubregionBindings is \c false, a lazy binding will be rejected
1538 /// if there are additional bindings within \p R.
1539 ///
1540 /// Note that unlike RegionStoreManager::findLazyBinding, this will not search
1541 /// for lazy bindings for super-regions of \p R.
1542 static Optional<nonloc::LazyCompoundVal>
1543 getExistingLazyBinding(SValBuilder &SVB, RegionBindingsConstRef B,
1544                        const SubRegion *R, bool AllowSubregionBindings) {
1545   Optional<SVal> V = B.getDefaultBinding(R);
1546   if (!V)
1547     return std::nullopt;
1548 
1549   Optional<nonloc::LazyCompoundVal> LCV = V->getAs<nonloc::LazyCompoundVal>();
1550   if (!LCV)
1551     return std::nullopt;
1552 
1553   // If the LCV is for a subregion, the types might not match, and we shouldn't
1554   // reuse the binding.
1555   QualType RegionTy = getUnderlyingType(R);
1556   if (!RegionTy.isNull() &&
1557       !RegionTy->isVoidPointerType()) {
1558     QualType SourceRegionTy = LCV->getRegion()->getValueType();
1559     if (!SVB.getContext().hasSameUnqualifiedType(RegionTy, SourceRegionTy))
1560       return std::nullopt;
1561   }
1562 
1563   if (!AllowSubregionBindings) {
1564     // If there are any other bindings within this region, we shouldn't reuse
1565     // the top-level binding.
1566     SmallVector<BindingPair, 16> Bindings;
1567     collectSubRegionBindings(Bindings, SVB, *B.lookup(R->getBaseRegion()), R,
1568                              /*IncludeAllDefaultBindings=*/true);
1569     if (Bindings.size() > 1)
1570       return std::nullopt;
1571   }
1572 
1573   return *LCV;
1574 }
1575 
1576 
1577 std::pair<Store, const SubRegion *>
1578 RegionStoreManager::findLazyBinding(RegionBindingsConstRef B,
1579                                    const SubRegion *R,
1580                                    const SubRegion *originalRegion) {
1581   if (originalRegion != R) {
1582     if (Optional<nonloc::LazyCompoundVal> V =
1583           getExistingLazyBinding(svalBuilder, B, R, true))
1584       return std::make_pair(V->getStore(), V->getRegion());
1585   }
1586 
1587   typedef std::pair<Store, const SubRegion *> StoreRegionPair;
1588   StoreRegionPair Result = StoreRegionPair();
1589 
1590   if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
1591     Result = findLazyBinding(B, cast<SubRegion>(ER->getSuperRegion()),
1592                              originalRegion);
1593 
1594     if (Result.second)
1595       Result.second = MRMgr.getElementRegionWithSuper(ER, Result.second);
1596 
1597   } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) {
1598     Result = findLazyBinding(B, cast<SubRegion>(FR->getSuperRegion()),
1599                                        originalRegion);
1600 
1601     if (Result.second)
1602       Result.second = MRMgr.getFieldRegionWithSuper(FR, Result.second);
1603 
1604   } else if (const CXXBaseObjectRegion *BaseReg =
1605                dyn_cast<CXXBaseObjectRegion>(R)) {
1606     // C++ base object region is another kind of region that we should blast
1607     // through to look for lazy compound value. It is like a field region.
1608     Result = findLazyBinding(B, cast<SubRegion>(BaseReg->getSuperRegion()),
1609                              originalRegion);
1610 
1611     if (Result.second)
1612       Result.second = MRMgr.getCXXBaseObjectRegionWithSuper(BaseReg,
1613                                                             Result.second);
1614   }
1615 
1616   return Result;
1617 }
1618 
1619 /// This is a helper function for `getConstantValFromConstArrayInitializer`.
1620 ///
1621 /// Return an array of extents of the declared array type.
1622 ///
1623 /// E.g. for `int x[1][2][3];` returns { 1, 2, 3 }.
1624 static SmallVector<uint64_t, 2>
1625 getConstantArrayExtents(const ConstantArrayType *CAT) {
1626   assert(CAT && "ConstantArrayType should not be null");
1627   CAT = cast<ConstantArrayType>(CAT->getCanonicalTypeInternal());
1628   SmallVector<uint64_t, 2> Extents;
1629   do {
1630     Extents.push_back(CAT->getSize().getZExtValue());
1631   } while ((CAT = dyn_cast<ConstantArrayType>(CAT->getElementType())));
1632   return Extents;
1633 }
1634 
1635 /// This is a helper function for `getConstantValFromConstArrayInitializer`.
1636 ///
1637 /// Return an array of offsets from nested ElementRegions and a root base
1638 /// region. The array is never empty and a base region is never null.
1639 ///
1640 /// E.g. for `Element{Element{Element{VarRegion},1},2},3}` returns { 3, 2, 1 }.
1641 /// This represents an access through indirection: `arr[1][2][3];`
1642 ///
1643 /// \param ER The given (possibly nested) ElementRegion.
1644 ///
1645 /// \note The result array is in the reverse order of indirection expression:
1646 /// arr[1][2][3] -> { 3, 2, 1 }. This helps to provide complexity O(n), where n
1647 /// is a number of indirections. It may not affect performance in real-life
1648 /// code, though.
1649 static std::pair<SmallVector<SVal, 2>, const MemRegion *>
1650 getElementRegionOffsetsWithBase(const ElementRegion *ER) {
1651   assert(ER && "ConstantArrayType should not be null");
1652   const MemRegion *Base;
1653   SmallVector<SVal, 2> SValOffsets;
1654   do {
1655     SValOffsets.push_back(ER->getIndex());
1656     Base = ER->getSuperRegion();
1657     ER = dyn_cast<ElementRegion>(Base);
1658   } while (ER);
1659   return {SValOffsets, Base};
1660 }
1661 
1662 /// This is a helper function for `getConstantValFromConstArrayInitializer`.
1663 ///
1664 /// Convert array of offsets from `SVal` to `uint64_t` in consideration of
1665 /// respective array extents.
1666 /// \param SrcOffsets [in]   The array of offsets of type `SVal` in reversed
1667 ///   order (expectedly received from `getElementRegionOffsetsWithBase`).
1668 /// \param ArrayExtents [in] The array of extents.
1669 /// \param DstOffsets [out]  The array of offsets of type `uint64_t`.
1670 /// \returns:
1671 /// - `std::nullopt` for successful convertion.
1672 /// - `UndefinedVal` or `UnknownVal` otherwise. It's expected that this SVal
1673 ///   will be returned as a suitable value of the access operation.
1674 ///   which should be returned as a correct
1675 ///
1676 /// \example:
1677 ///   const int arr[10][20][30] = {}; // ArrayExtents { 10, 20, 30 }
1678 ///   int x1 = arr[4][5][6]; // SrcOffsets { NonLoc(6), NonLoc(5), NonLoc(4) }
1679 ///                          // DstOffsets { 4, 5, 6 }
1680 ///                          // returns std::nullopt
1681 ///   int x2 = arr[42][5][-6]; // returns UndefinedVal
1682 ///   int x3 = arr[4][5][x2];  // returns UnknownVal
1683 static Optional<SVal>
1684 convertOffsetsFromSvalToUnsigneds(const SmallVector<SVal, 2> &SrcOffsets,
1685                                   const SmallVector<uint64_t, 2> ArrayExtents,
1686                                   SmallVector<uint64_t, 2> &DstOffsets) {
1687   // Check offsets for being out of bounds.
1688   // C++20 [expr.add] 7.6.6.4 (excerpt):
1689   //   If P points to an array element i of an array object x with n
1690   //   elements, where i < 0 or i > n, the behavior is undefined.
1691   //   Dereferencing is not allowed on the "one past the last
1692   //   element", when i == n.
1693   // Example:
1694   //  const int arr[3][2] = {{1, 2}, {3, 4}};
1695   //  arr[0][0];  // 1
1696   //  arr[0][1];  // 2
1697   //  arr[0][2];  // UB
1698   //  arr[1][0];  // 3
1699   //  arr[1][1];  // 4
1700   //  arr[1][-1]; // UB
1701   //  arr[2][0];  // 0
1702   //  arr[2][1];  // 0
1703   //  arr[-2][0]; // UB
1704   DstOffsets.resize(SrcOffsets.size());
1705   auto ExtentIt = ArrayExtents.begin();
1706   auto OffsetIt = DstOffsets.begin();
1707   // Reverse `SValOffsets` to make it consistent with `ArrayExtents`.
1708   for (SVal V : llvm::reverse(SrcOffsets)) {
1709     if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
1710       // When offset is out of array's bounds, result is UB.
1711       const llvm::APSInt &Offset = CI->getValue();
1712       if (Offset.isNegative() || Offset.uge(*(ExtentIt++)))
1713         return UndefinedVal();
1714       // Store index in a reversive order.
1715       *(OffsetIt++) = Offset.getZExtValue();
1716       continue;
1717     }
1718     // Symbolic index presented. Return Unknown value.
1719     // FIXME: We also need to take ElementRegions with symbolic indexes into
1720     // account.
1721     return UnknownVal();
1722   }
1723   return std::nullopt;
1724 }
1725 
1726 Optional<SVal> RegionStoreManager::getConstantValFromConstArrayInitializer(
1727     RegionBindingsConstRef B, const ElementRegion *R) {
1728   assert(R && "ElementRegion should not be null");
1729 
1730   // Treat an n-dimensional array.
1731   SmallVector<SVal, 2> SValOffsets;
1732   const MemRegion *Base;
1733   std::tie(SValOffsets, Base) = getElementRegionOffsetsWithBase(R);
1734   const VarRegion *VR = dyn_cast<VarRegion>(Base);
1735   if (!VR)
1736     return std::nullopt;
1737 
1738   assert(!SValOffsets.empty() && "getElementRegionOffsets guarantees the "
1739                                  "offsets vector is not empty.");
1740 
1741   // Check if the containing array has an initialized value that we can trust.
1742   // We can trust a const value or a value of a global initializer in main().
1743   const VarDecl *VD = VR->getDecl();
1744   if (!VD->getType().isConstQualified() &&
1745       !R->getElementType().isConstQualified() &&
1746       (!B.isMainAnalysis() || !VD->hasGlobalStorage()))
1747     return std::nullopt;
1748 
1749   // Array's declaration should have `ConstantArrayType` type, because only this
1750   // type contains an array extent. It may happen that array type can be of
1751   // `IncompleteArrayType` type. To get the declaration of `ConstantArrayType`
1752   // type, we should find the declaration in the redeclarations chain that has
1753   // the initialization expression.
1754   // NOTE: `getAnyInitializer` has an out-parameter, which returns a new `VD`
1755   // from which an initializer is obtained. We replace current `VD` with the new
1756   // `VD`. If the return value of the function is null than `VD` won't be
1757   // replaced.
1758   const Expr *Init = VD->getAnyInitializer(VD);
1759   // NOTE: If `Init` is non-null, then a new `VD` is non-null for sure. So check
1760   // `Init` for null only and don't worry about the replaced `VD`.
1761   if (!Init)
1762     return std::nullopt;
1763 
1764   // Array's declaration should have ConstantArrayType type, because only this
1765   // type contains an array extent.
1766   const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(VD->getType());
1767   if (!CAT)
1768     return std::nullopt;
1769 
1770   // Get array extents.
1771   SmallVector<uint64_t, 2> Extents = getConstantArrayExtents(CAT);
1772 
1773   // The number of offsets should equal to the numbers of extents,
1774   // otherwise wrong type punning occurred. For instance:
1775   //  int arr[1][2][3];
1776   //  auto ptr = (int(*)[42])arr;
1777   //  auto x = ptr[4][2]; // UB
1778   // FIXME: Should return UndefinedVal.
1779   if (SValOffsets.size() != Extents.size())
1780     return std::nullopt;
1781 
1782   SmallVector<uint64_t, 2> ConcreteOffsets;
1783   if (Optional<SVal> V = convertOffsetsFromSvalToUnsigneds(SValOffsets, Extents,
1784                                                            ConcreteOffsets))
1785     return *V;
1786 
1787   // Handle InitListExpr.
1788   // Example:
1789   //   const char arr[4][2] = { { 1, 2 }, { 3 }, 4, 5 };
1790   if (const auto *ILE = dyn_cast<InitListExpr>(Init))
1791     return getSValFromInitListExpr(ILE, ConcreteOffsets, R->getElementType());
1792 
1793   // Handle StringLiteral.
1794   // Example:
1795   //   const char arr[] = "abc";
1796   if (const auto *SL = dyn_cast<StringLiteral>(Init))
1797     return getSValFromStringLiteral(SL, ConcreteOffsets.front(),
1798                                     R->getElementType());
1799 
1800   // FIXME: Handle CompoundLiteralExpr.
1801 
1802   return std::nullopt;
1803 }
1804 
1805 /// Returns an SVal, if possible, for the specified position of an
1806 /// initialization list.
1807 ///
1808 /// \param ILE The given initialization list.
1809 /// \param Offsets The array of unsigned offsets. E.g. for the expression
1810 ///  `int x = arr[1][2][3];` an array should be { 1, 2, 3 }.
1811 /// \param ElemT The type of the result SVal expression.
1812 /// \return Optional SVal for the particular position in the initialization
1813 ///   list. E.g. for the list `{{1, 2},[3, 4],{5, 6}, {}}` offsets:
1814 ///   - {1, 1} returns SVal{4}, because it's the second position in the second
1815 ///     sublist;
1816 ///   - {3, 0} returns SVal{0}, because there's no explicit value at this
1817 ///     position in the sublist.
1818 ///
1819 /// NOTE: Inorder to get a valid SVal, a caller shall guarantee valid offsets
1820 /// for the given initialization list. Otherwise SVal can be an equivalent to 0
1821 /// or lead to assertion.
1822 Optional<SVal> RegionStoreManager::getSValFromInitListExpr(
1823     const InitListExpr *ILE, const SmallVector<uint64_t, 2> &Offsets,
1824     QualType ElemT) {
1825   assert(ILE && "InitListExpr should not be null");
1826 
1827   for (uint64_t Offset : Offsets) {
1828     // C++20 [dcl.init.string] 9.4.2.1:
1829     //   An array of ordinary character type [...] can be initialized by [...]
1830     //   an appropriately-typed string-literal enclosed in braces.
1831     // Example:
1832     //   const char arr[] = { "abc" };
1833     if (ILE->isStringLiteralInit())
1834       if (const auto *SL = dyn_cast<StringLiteral>(ILE->getInit(0)))
1835         return getSValFromStringLiteral(SL, Offset, ElemT);
1836 
1837     // C++20 [expr.add] 9.4.17.5 (excerpt):
1838     //   i-th array element is value-initialized for each k < i ≤ n,
1839     //   where k is an expression-list size and n is an array extent.
1840     if (Offset >= ILE->getNumInits())
1841       return svalBuilder.makeZeroVal(ElemT);
1842 
1843     const Expr *E = ILE->getInit(Offset);
1844     const auto *IL = dyn_cast<InitListExpr>(E);
1845     if (!IL)
1846       // Return a constant value, if it is presented.
1847       // FIXME: Support other SVals.
1848       return svalBuilder.getConstantVal(E);
1849 
1850     // Go to the nested initializer list.
1851     ILE = IL;
1852   }
1853   llvm_unreachable(
1854       "Unhandled InitListExpr sub-expressions or invalid offsets.");
1855 }
1856 
1857 /// Returns an SVal, if possible, for the specified position in a string
1858 /// literal.
1859 ///
1860 /// \param SL The given string literal.
1861 /// \param Offset The unsigned offset. E.g. for the expression
1862 ///   `char x = str[42];` an offset should be 42.
1863 ///   E.g. for the string "abc" offset:
1864 ///   - 1 returns SVal{b}, because it's the second position in the string.
1865 ///   - 42 returns SVal{0}, because there's no explicit value at this
1866 ///     position in the string.
1867 /// \param ElemT The type of the result SVal expression.
1868 ///
1869 /// NOTE: We return `0` for every offset >= the literal length for array
1870 /// declarations, like:
1871 ///   const char str[42] = "123"; // Literal length is 4.
1872 ///   char c = str[41];           // Offset is 41.
1873 /// FIXME: Nevertheless, we can't do the same for pointer declaraions, like:
1874 ///   const char * const str = "123"; // Literal length is 4.
1875 ///   char c = str[41];               // Offset is 41. Returns `0`, but Undef
1876 ///                                   // expected.
1877 /// It should be properly handled before reaching this point.
1878 /// The main problem is that we can't distinguish between these declarations,
1879 /// because in case of array we can get the Decl from VarRegion, but in case
1880 /// of pointer the region is a StringRegion, which doesn't contain a Decl.
1881 /// Possible solution could be passing an array extent along with the offset.
1882 SVal RegionStoreManager::getSValFromStringLiteral(const StringLiteral *SL,
1883                                                   uint64_t Offset,
1884                                                   QualType ElemT) {
1885   assert(SL && "StringLiteral should not be null");
1886   // C++20 [dcl.init.string] 9.4.2.3:
1887   //   If there are fewer initializers than there are array elements, each
1888   //   element not explicitly initialized shall be zero-initialized [dcl.init].
1889   uint32_t Code = (Offset >= SL->getLength()) ? 0 : SL->getCodeUnit(Offset);
1890   return svalBuilder.makeIntVal(Code, ElemT);
1891 }
1892 
1893 static Optional<SVal> getDerivedSymbolForBinding(
1894     RegionBindingsConstRef B, const TypedValueRegion *BaseRegion,
1895     const TypedValueRegion *SubReg, const ASTContext &Ctx, SValBuilder &SVB) {
1896   assert(BaseRegion);
1897   QualType BaseTy = BaseRegion->getValueType();
1898   QualType Ty = SubReg->getValueType();
1899   if (BaseTy->isScalarType() && Ty->isScalarType()) {
1900     if (Ctx.getTypeSizeInChars(BaseTy) >= Ctx.getTypeSizeInChars(Ty)) {
1901       if (const Optional<SVal> &ParentValue = B.getDirectBinding(BaseRegion)) {
1902         if (SymbolRef ParentValueAsSym = ParentValue->getAsSymbol())
1903           return SVB.getDerivedRegionValueSymbolVal(ParentValueAsSym, SubReg);
1904 
1905         if (ParentValue->isUndef())
1906           return UndefinedVal();
1907 
1908         // Other cases: give up.  We are indexing into a larger object
1909         // that has some value, but we don't know how to handle that yet.
1910         return UnknownVal();
1911       }
1912     }
1913   }
1914   return std::nullopt;
1915 }
1916 
1917 SVal RegionStoreManager::getBindingForElement(RegionBindingsConstRef B,
1918                                               const ElementRegion* R) {
1919   // Check if the region has a binding.
1920   if (const Optional<SVal> &V = B.getDirectBinding(R))
1921     return *V;
1922 
1923   const MemRegion* superR = R->getSuperRegion();
1924 
1925   // Check if the region is an element region of a string literal.
1926   if (const StringRegion *StrR = dyn_cast<StringRegion>(superR)) {
1927     // FIXME: Handle loads from strings where the literal is treated as
1928     // an integer, e.g., *((unsigned int*)"hello"). Such loads are UB according
1929     // to C++20 7.2.1.11 [basic.lval].
1930     QualType T = Ctx.getAsArrayType(StrR->getValueType())->getElementType();
1931     if (!Ctx.hasSameUnqualifiedType(T, R->getElementType()))
1932       return UnknownVal();
1933     if (const auto CI = R->getIndex().getAs<nonloc::ConcreteInt>()) {
1934       const llvm::APSInt &Idx = CI->getValue();
1935       if (Idx < 0)
1936         return UndefinedVal();
1937       const StringLiteral *SL = StrR->getStringLiteral();
1938       return getSValFromStringLiteral(SL, Idx.getZExtValue(), T);
1939     }
1940   } else if (isa<ElementRegion, VarRegion>(superR)) {
1941     if (Optional<SVal> V = getConstantValFromConstArrayInitializer(B, R))
1942       return *V;
1943   }
1944 
1945   // Check for loads from a code text region.  For such loads, just give up.
1946   if (isa<CodeTextRegion>(superR))
1947     return UnknownVal();
1948 
1949   // Handle the case where we are indexing into a larger scalar object.
1950   // For example, this handles:
1951   //   int x = ...
1952   //   char *y = &x;
1953   //   return *y;
1954   // FIXME: This is a hack, and doesn't do anything really intelligent yet.
1955   const RegionRawOffset &O = R->getAsArrayOffset();
1956 
1957   // If we cannot reason about the offset, return an unknown value.
1958   if (!O.getRegion())
1959     return UnknownVal();
1960 
1961   if (const TypedValueRegion *baseR = dyn_cast<TypedValueRegion>(O.getRegion()))
1962     if (auto V = getDerivedSymbolForBinding(B, baseR, R, Ctx, svalBuilder))
1963       return *V;
1964 
1965   return getBindingForFieldOrElementCommon(B, R, R->getElementType());
1966 }
1967 
1968 SVal RegionStoreManager::getBindingForField(RegionBindingsConstRef B,
1969                                             const FieldRegion* R) {
1970 
1971   // Check if the region has a binding.
1972   if (const Optional<SVal> &V = B.getDirectBinding(R))
1973     return *V;
1974 
1975   // If the containing record was initialized, try to get its constant value.
1976   const FieldDecl *FD = R->getDecl();
1977   QualType Ty = FD->getType();
1978   const MemRegion* superR = R->getSuperRegion();
1979   if (const auto *VR = dyn_cast<VarRegion>(superR)) {
1980     const VarDecl *VD = VR->getDecl();
1981     QualType RecordVarTy = VD->getType();
1982     unsigned Index = FD->getFieldIndex();
1983     // Either the record variable or the field has an initializer that we can
1984     // trust. We trust initializers of constants and, additionally, respect
1985     // initializers of globals when analyzing main().
1986     if (RecordVarTy.isConstQualified() || Ty.isConstQualified() ||
1987         (B.isMainAnalysis() && VD->hasGlobalStorage()))
1988       if (const Expr *Init = VD->getAnyInitializer())
1989         if (const auto *InitList = dyn_cast<InitListExpr>(Init)) {
1990           if (Index < InitList->getNumInits()) {
1991             if (const Expr *FieldInit = InitList->getInit(Index))
1992               if (Optional<SVal> V = svalBuilder.getConstantVal(FieldInit))
1993                 return *V;
1994           } else {
1995             return svalBuilder.makeZeroVal(Ty);
1996           }
1997         }
1998   }
1999 
2000   // Handle the case where we are accessing into a larger scalar object.
2001   // For example, this handles:
2002   //   struct header {
2003   //     unsigned a : 1;
2004   //     unsigned b : 1;
2005   //   };
2006   //   struct parse_t {
2007   //     unsigned bits0 : 1;
2008   //     unsigned bits2 : 2; // <-- header
2009   //     unsigned bits4 : 4;
2010   //   };
2011   //   int parse(parse_t *p) {
2012   //     unsigned copy = p->bits2;
2013   //     header *bits = (header *)&copy;
2014   //     return bits->b;  <-- here
2015   //   }
2016   if (const auto *Base = dyn_cast<TypedValueRegion>(R->getBaseRegion()))
2017     if (auto V = getDerivedSymbolForBinding(B, Base, R, Ctx, svalBuilder))
2018       return *V;
2019 
2020   return getBindingForFieldOrElementCommon(B, R, Ty);
2021 }
2022 
2023 Optional<SVal>
2024 RegionStoreManager::getBindingForDerivedDefaultValue(RegionBindingsConstRef B,
2025                                                      const MemRegion *superR,
2026                                                      const TypedValueRegion *R,
2027                                                      QualType Ty) {
2028 
2029   if (const Optional<SVal> &D = B.getDefaultBinding(superR)) {
2030     const SVal &val = *D;
2031     if (SymbolRef parentSym = val.getAsSymbol())
2032       return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
2033 
2034     if (val.isZeroConstant())
2035       return svalBuilder.makeZeroVal(Ty);
2036 
2037     if (val.isUnknownOrUndef())
2038       return val;
2039 
2040     // Lazy bindings are usually handled through getExistingLazyBinding().
2041     // We should unify these two code paths at some point.
2042     if (isa<nonloc::LazyCompoundVal, nonloc::CompoundVal>(val))
2043       return val;
2044 
2045     llvm_unreachable("Unknown default value");
2046   }
2047 
2048   return std::nullopt;
2049 }
2050 
2051 SVal RegionStoreManager::getLazyBinding(const SubRegion *LazyBindingRegion,
2052                                         RegionBindingsRef LazyBinding) {
2053   SVal Result;
2054   if (const ElementRegion *ER = dyn_cast<ElementRegion>(LazyBindingRegion))
2055     Result = getBindingForElement(LazyBinding, ER);
2056   else
2057     Result = getBindingForField(LazyBinding,
2058                                 cast<FieldRegion>(LazyBindingRegion));
2059 
2060   // FIXME: This is a hack to deal with RegionStore's inability to distinguish a
2061   // default value for /part/ of an aggregate from a default value for the
2062   // /entire/ aggregate. The most common case of this is when struct Outer
2063   // has as its first member a struct Inner, which is copied in from a stack
2064   // variable. In this case, even if the Outer's default value is symbolic, 0,
2065   // or unknown, it gets overridden by the Inner's default value of undefined.
2066   //
2067   // This is a general problem -- if the Inner is zero-initialized, the Outer
2068   // will now look zero-initialized. The proper way to solve this is with a
2069   // new version of RegionStore that tracks the extent of a binding as well
2070   // as the offset.
2071   //
2072   // This hack only takes care of the undefined case because that can very
2073   // quickly result in a warning.
2074   if (Result.isUndef())
2075     Result = UnknownVal();
2076 
2077   return Result;
2078 }
2079 
2080 SVal
2081 RegionStoreManager::getBindingForFieldOrElementCommon(RegionBindingsConstRef B,
2082                                                       const TypedValueRegion *R,
2083                                                       QualType Ty) {
2084 
2085   // At this point we have already checked in either getBindingForElement or
2086   // getBindingForField if 'R' has a direct binding.
2087 
2088   // Lazy binding?
2089   Store lazyBindingStore = nullptr;
2090   const SubRegion *lazyBindingRegion = nullptr;
2091   std::tie(lazyBindingStore, lazyBindingRegion) = findLazyBinding(B, R, R);
2092   if (lazyBindingRegion)
2093     return getLazyBinding(lazyBindingRegion,
2094                           getRegionBindings(lazyBindingStore));
2095 
2096   // Record whether or not we see a symbolic index.  That can completely
2097   // be out of scope of our lookup.
2098   bool hasSymbolicIndex = false;
2099 
2100   // FIXME: This is a hack to deal with RegionStore's inability to distinguish a
2101   // default value for /part/ of an aggregate from a default value for the
2102   // /entire/ aggregate. The most common case of this is when struct Outer
2103   // has as its first member a struct Inner, which is copied in from a stack
2104   // variable. In this case, even if the Outer's default value is symbolic, 0,
2105   // or unknown, it gets overridden by the Inner's default value of undefined.
2106   //
2107   // This is a general problem -- if the Inner is zero-initialized, the Outer
2108   // will now look zero-initialized. The proper way to solve this is with a
2109   // new version of RegionStore that tracks the extent of a binding as well
2110   // as the offset.
2111   //
2112   // This hack only takes care of the undefined case because that can very
2113   // quickly result in a warning.
2114   bool hasPartialLazyBinding = false;
2115 
2116   const SubRegion *SR = R;
2117   while (SR) {
2118     const MemRegion *Base = SR->getSuperRegion();
2119     if (Optional<SVal> D = getBindingForDerivedDefaultValue(B, Base, R, Ty)) {
2120       if (D->getAs<nonloc::LazyCompoundVal>()) {
2121         hasPartialLazyBinding = true;
2122         break;
2123       }
2124 
2125       return *D;
2126     }
2127 
2128     if (const ElementRegion *ER = dyn_cast<ElementRegion>(Base)) {
2129       NonLoc index = ER->getIndex();
2130       if (!index.isConstant())
2131         hasSymbolicIndex = true;
2132     }
2133 
2134     // If our super region is a field or element itself, walk up the region
2135     // hierarchy to see if there is a default value installed in an ancestor.
2136     SR = dyn_cast<SubRegion>(Base);
2137   }
2138 
2139   if (R->hasStackNonParametersStorage()) {
2140     if (isa<ElementRegion>(R)) {
2141       // Currently we don't reason specially about Clang-style vectors.  Check
2142       // if superR is a vector and if so return Unknown.
2143       if (const TypedValueRegion *typedSuperR =
2144             dyn_cast<TypedValueRegion>(R->getSuperRegion())) {
2145         if (typedSuperR->getValueType()->isVectorType())
2146           return UnknownVal();
2147       }
2148     }
2149 
2150     // FIXME: We also need to take ElementRegions with symbolic indexes into
2151     // account.  This case handles both directly accessing an ElementRegion
2152     // with a symbolic offset, but also fields within an element with
2153     // a symbolic offset.
2154     if (hasSymbolicIndex)
2155       return UnknownVal();
2156 
2157     // Additionally allow introspection of a block's internal layout.
2158     // Try to get direct binding if all other attempts failed thus far.
2159     // Else, return UndefinedVal()
2160     if (!hasPartialLazyBinding && !isa<BlockDataRegion>(R->getBaseRegion())) {
2161       if (const Optional<SVal> &V = B.getDefaultBinding(R))
2162         return *V;
2163       return UndefinedVal();
2164     }
2165   }
2166 
2167   // All other values are symbolic.
2168   return svalBuilder.getRegionValueSymbolVal(R);
2169 }
2170 
2171 SVal RegionStoreManager::getBindingForObjCIvar(RegionBindingsConstRef B,
2172                                                const ObjCIvarRegion* R) {
2173   // Check if the region has a binding.
2174   if (const Optional<SVal> &V = B.getDirectBinding(R))
2175     return *V;
2176 
2177   const MemRegion *superR = R->getSuperRegion();
2178 
2179   // Check if the super region has a default binding.
2180   if (const Optional<SVal> &V = B.getDefaultBinding(superR)) {
2181     if (SymbolRef parentSym = V->getAsSymbol())
2182       return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
2183 
2184     // Other cases: give up.
2185     return UnknownVal();
2186   }
2187 
2188   return getBindingForLazySymbol(R);
2189 }
2190 
2191 SVal RegionStoreManager::getBindingForVar(RegionBindingsConstRef B,
2192                                           const VarRegion *R) {
2193 
2194   // Check if the region has a binding.
2195   if (Optional<SVal> V = B.getDirectBinding(R))
2196     return *V;
2197 
2198   if (Optional<SVal> V = B.getDefaultBinding(R))
2199     return *V;
2200 
2201   // Lazily derive a value for the VarRegion.
2202   const VarDecl *VD = R->getDecl();
2203   const MemSpaceRegion *MS = R->getMemorySpace();
2204 
2205   // Arguments are always symbolic.
2206   if (isa<StackArgumentsSpaceRegion>(MS))
2207     return svalBuilder.getRegionValueSymbolVal(R);
2208 
2209   // Is 'VD' declared constant?  If so, retrieve the constant value.
2210   if (VD->getType().isConstQualified()) {
2211     if (const Expr *Init = VD->getAnyInitializer()) {
2212       if (Optional<SVal> V = svalBuilder.getConstantVal(Init))
2213         return *V;
2214 
2215       // If the variable is const qualified and has an initializer but
2216       // we couldn't evaluate initializer to a value, treat the value as
2217       // unknown.
2218       return UnknownVal();
2219     }
2220   }
2221 
2222   // This must come after the check for constants because closure-captured
2223   // constant variables may appear in UnknownSpaceRegion.
2224   if (isa<UnknownSpaceRegion>(MS))
2225     return svalBuilder.getRegionValueSymbolVal(R);
2226 
2227   if (isa<GlobalsSpaceRegion>(MS)) {
2228     QualType T = VD->getType();
2229 
2230     // If we're in main(), then global initializers have not become stale yet.
2231     if (B.isMainAnalysis())
2232       if (const Expr *Init = VD->getAnyInitializer())
2233         if (Optional<SVal> V = svalBuilder.getConstantVal(Init))
2234           return *V;
2235 
2236     // Function-scoped static variables are default-initialized to 0; if they
2237     // have an initializer, it would have been processed by now.
2238     // FIXME: This is only true when we're starting analysis from main().
2239     // We're losing a lot of coverage here.
2240     if (isa<StaticGlobalSpaceRegion>(MS))
2241       return svalBuilder.makeZeroVal(T);
2242 
2243     if (Optional<SVal> V = getBindingForDerivedDefaultValue(B, MS, R, T)) {
2244       assert(!V->getAs<nonloc::LazyCompoundVal>());
2245       return *V;
2246     }
2247 
2248     return svalBuilder.getRegionValueSymbolVal(R);
2249   }
2250 
2251   return UndefinedVal();
2252 }
2253 
2254 SVal RegionStoreManager::getBindingForLazySymbol(const TypedValueRegion *R) {
2255   // All other values are symbolic.
2256   return svalBuilder.getRegionValueSymbolVal(R);
2257 }
2258 
2259 const RegionStoreManager::SValListTy &
2260 RegionStoreManager::getInterestingValues(nonloc::LazyCompoundVal LCV) {
2261   // First, check the cache.
2262   LazyBindingsMapTy::iterator I = LazyBindingsMap.find(LCV.getCVData());
2263   if (I != LazyBindingsMap.end())
2264     return I->second;
2265 
2266   // If we don't have a list of values cached, start constructing it.
2267   SValListTy List;
2268 
2269   const SubRegion *LazyR = LCV.getRegion();
2270   RegionBindingsRef B = getRegionBindings(LCV.getStore());
2271 
2272   // If this region had /no/ bindings at the time, there are no interesting
2273   // values to return.
2274   const ClusterBindings *Cluster = B.lookup(LazyR->getBaseRegion());
2275   if (!Cluster)
2276     return (LazyBindingsMap[LCV.getCVData()] = std::move(List));
2277 
2278   SmallVector<BindingPair, 32> Bindings;
2279   collectSubRegionBindings(Bindings, svalBuilder, *Cluster, LazyR,
2280                            /*IncludeAllDefaultBindings=*/true);
2281   for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(),
2282                                                     E = Bindings.end();
2283        I != E; ++I) {
2284     SVal V = I->second;
2285     if (V.isUnknownOrUndef() || V.isConstant())
2286       continue;
2287 
2288     if (auto InnerLCV = V.getAs<nonloc::LazyCompoundVal>()) {
2289       const SValListTy &InnerList = getInterestingValues(*InnerLCV);
2290       List.insert(List.end(), InnerList.begin(), InnerList.end());
2291     }
2292 
2293     List.push_back(V);
2294   }
2295 
2296   return (LazyBindingsMap[LCV.getCVData()] = std::move(List));
2297 }
2298 
2299 NonLoc RegionStoreManager::createLazyBinding(RegionBindingsConstRef B,
2300                                              const TypedValueRegion *R) {
2301   if (Optional<nonloc::LazyCompoundVal> V =
2302         getExistingLazyBinding(svalBuilder, B, R, false))
2303     return *V;
2304 
2305   return svalBuilder.makeLazyCompoundVal(StoreRef(B.asStore(), *this), R);
2306 }
2307 
2308 static bool isRecordEmpty(const RecordDecl *RD) {
2309   if (!RD->field_empty())
2310     return false;
2311   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD))
2312     return CRD->getNumBases() == 0;
2313   return true;
2314 }
2315 
2316 SVal RegionStoreManager::getBindingForStruct(RegionBindingsConstRef B,
2317                                              const TypedValueRegion *R) {
2318   const RecordDecl *RD = R->getValueType()->castAs<RecordType>()->getDecl();
2319   if (!RD->getDefinition() || isRecordEmpty(RD))
2320     return UnknownVal();
2321 
2322   return createLazyBinding(B, R);
2323 }
2324 
2325 SVal RegionStoreManager::getBindingForArray(RegionBindingsConstRef B,
2326                                             const TypedValueRegion *R) {
2327   assert(Ctx.getAsConstantArrayType(R->getValueType()) &&
2328          "Only constant array types can have compound bindings.");
2329 
2330   return createLazyBinding(B, R);
2331 }
2332 
2333 bool RegionStoreManager::includedInBindings(Store store,
2334                                             const MemRegion *region) const {
2335   RegionBindingsRef B = getRegionBindings(store);
2336   region = region->getBaseRegion();
2337 
2338   // Quick path: if the base is the head of a cluster, the region is live.
2339   if (B.lookup(region))
2340     return true;
2341 
2342   // Slow path: if the region is the VALUE of any binding, it is live.
2343   for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI) {
2344     const ClusterBindings &Cluster = RI.getData();
2345     for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
2346          CI != CE; ++CI) {
2347       const SVal &D = CI.getData();
2348       if (const MemRegion *R = D.getAsRegion())
2349         if (R->getBaseRegion() == region)
2350           return true;
2351     }
2352   }
2353 
2354   return false;
2355 }
2356 
2357 //===----------------------------------------------------------------------===//
2358 // Binding values to regions.
2359 //===----------------------------------------------------------------------===//
2360 
2361 StoreRef RegionStoreManager::killBinding(Store ST, Loc L) {
2362   if (Optional<loc::MemRegionVal> LV = L.getAs<loc::MemRegionVal>())
2363     if (const MemRegion* R = LV->getRegion())
2364       return StoreRef(getRegionBindings(ST).removeBinding(R)
2365                                            .asImmutableMap()
2366                                            .getRootWithoutRetain(),
2367                       *this);
2368 
2369   return StoreRef(ST, *this);
2370 }
2371 
2372 RegionBindingsRef
2373 RegionStoreManager::bind(RegionBindingsConstRef B, Loc L, SVal V) {
2374   if (L.getAs<loc::ConcreteInt>())
2375     return B;
2376 
2377   // If we get here, the location should be a region.
2378   const MemRegion *R = L.castAs<loc::MemRegionVal>().getRegion();
2379 
2380   // Check if the region is a struct region.
2381   if (const TypedValueRegion* TR = dyn_cast<TypedValueRegion>(R)) {
2382     QualType Ty = TR->getValueType();
2383     if (Ty->isArrayType())
2384       return bindArray(B, TR, V);
2385     if (Ty->isStructureOrClassType())
2386       return bindStruct(B, TR, V);
2387     if (Ty->isVectorType())
2388       return bindVector(B, TR, V);
2389     if (Ty->isUnionType())
2390       return bindAggregate(B, TR, V);
2391   }
2392 
2393   // Binding directly to a symbolic region should be treated as binding
2394   // to element 0.
2395   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
2396     R = GetElementZeroRegion(SR, SR->getPointeeStaticType());
2397 
2398   assert((!isa<CXXThisRegion>(R) || !B.lookup(R)) &&
2399          "'this' pointer is not an l-value and is not assignable");
2400 
2401   // Clear out bindings that may overlap with this binding.
2402   RegionBindingsRef NewB = removeSubRegionBindings(B, cast<SubRegion>(R));
2403 
2404   // LazyCompoundVals should be always bound as 'default' bindings.
2405   auto KeyKind = isa<nonloc::LazyCompoundVal>(V) ? BindingKey::Default
2406                                                  : BindingKey::Direct;
2407   return NewB.addBinding(BindingKey::Make(R, KeyKind), V);
2408 }
2409 
2410 RegionBindingsRef
2411 RegionStoreManager::setImplicitDefaultValue(RegionBindingsConstRef B,
2412                                             const MemRegion *R,
2413                                             QualType T) {
2414   SVal V;
2415 
2416   if (Loc::isLocType(T))
2417     V = svalBuilder.makeNullWithType(T);
2418   else if (T->isIntegralOrEnumerationType())
2419     V = svalBuilder.makeZeroVal(T);
2420   else if (T->isStructureOrClassType() || T->isArrayType()) {
2421     // Set the default value to a zero constant when it is a structure
2422     // or array.  The type doesn't really matter.
2423     V = svalBuilder.makeZeroVal(Ctx.IntTy);
2424   }
2425   else {
2426     // We can't represent values of this type, but we still need to set a value
2427     // to record that the region has been initialized.
2428     // If this assertion ever fires, a new case should be added above -- we
2429     // should know how to default-initialize any value we can symbolicate.
2430     assert(!SymbolManager::canSymbolicate(T) && "This type is representable");
2431     V = UnknownVal();
2432   }
2433 
2434   return B.addBinding(R, BindingKey::Default, V);
2435 }
2436 
2437 Optional<RegionBindingsRef> RegionStoreManager::tryBindSmallArray(
2438     RegionBindingsConstRef B, const TypedValueRegion *R, const ArrayType *AT,
2439     nonloc::LazyCompoundVal LCV) {
2440 
2441   auto CAT = dyn_cast<ConstantArrayType>(AT);
2442 
2443   // If we don't know the size, create a lazyCompoundVal instead.
2444   if (!CAT)
2445     return std::nullopt;
2446 
2447   QualType Ty = CAT->getElementType();
2448   if (!(Ty->isScalarType() || Ty->isReferenceType()))
2449     return std::nullopt;
2450 
2451   // If the array is too big, create a LCV instead.
2452   uint64_t ArrSize = CAT->getSize().getLimitedValue();
2453   if (ArrSize > SmallArrayLimit)
2454     return std::nullopt;
2455 
2456   RegionBindingsRef NewB = B;
2457 
2458   for (uint64_t i = 0; i < ArrSize; ++i) {
2459     auto Idx = svalBuilder.makeArrayIndex(i);
2460     const ElementRegion *SrcER =
2461         MRMgr.getElementRegion(Ty, Idx, LCV.getRegion(), Ctx);
2462     SVal V = getBindingForElement(getRegionBindings(LCV.getStore()), SrcER);
2463 
2464     const ElementRegion *DstER = MRMgr.getElementRegion(Ty, Idx, R, Ctx);
2465     NewB = bind(NewB, loc::MemRegionVal(DstER), V);
2466   }
2467 
2468   return NewB;
2469 }
2470 
2471 RegionBindingsRef
2472 RegionStoreManager::bindArray(RegionBindingsConstRef B,
2473                               const TypedValueRegion* R,
2474                               SVal Init) {
2475 
2476   const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType()));
2477   QualType ElementTy = AT->getElementType();
2478   Optional<uint64_t> Size;
2479 
2480   if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT))
2481     Size = CAT->getSize().getZExtValue();
2482 
2483   // Check if the init expr is a literal. If so, bind the rvalue instead.
2484   // FIXME: It's not responsibility of the Store to transform this lvalue
2485   // to rvalue. ExprEngine or maybe even CFG should do this before binding.
2486   if (Optional<loc::MemRegionVal> MRV = Init.getAs<loc::MemRegionVal>()) {
2487     SVal V = getBinding(B.asStore(), *MRV, R->getValueType());
2488     return bindAggregate(B, R, V);
2489   }
2490 
2491   // Handle lazy compound values.
2492   if (Optional<nonloc::LazyCompoundVal> LCV =
2493           Init.getAs<nonloc::LazyCompoundVal>()) {
2494     if (Optional<RegionBindingsRef> NewB = tryBindSmallArray(B, R, AT, *LCV))
2495       return *NewB;
2496 
2497     return bindAggregate(B, R, Init);
2498   }
2499 
2500   if (Init.isUnknown())
2501     return bindAggregate(B, R, UnknownVal());
2502 
2503   // Remaining case: explicit compound values.
2504   const nonloc::CompoundVal& CV = Init.castAs<nonloc::CompoundVal>();
2505   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
2506   uint64_t i = 0;
2507 
2508   RegionBindingsRef NewB(B);
2509 
2510   for (; Size ? i < *Size : true; ++i, ++VI) {
2511     // The init list might be shorter than the array length.
2512     if (VI == VE)
2513       break;
2514 
2515     const NonLoc &Idx = svalBuilder.makeArrayIndex(i);
2516     const ElementRegion *ER = MRMgr.getElementRegion(ElementTy, Idx, R, Ctx);
2517 
2518     if (ElementTy->isStructureOrClassType())
2519       NewB = bindStruct(NewB, ER, *VI);
2520     else if (ElementTy->isArrayType())
2521       NewB = bindArray(NewB, ER, *VI);
2522     else
2523       NewB = bind(NewB, loc::MemRegionVal(ER), *VI);
2524   }
2525 
2526   // If the init list is shorter than the array length (or the array has
2527   // variable length), set the array default value. Values that are already set
2528   // are not overwritten.
2529   if (!Size || i < *Size)
2530     NewB = setImplicitDefaultValue(NewB, R, ElementTy);
2531 
2532   return NewB;
2533 }
2534 
2535 RegionBindingsRef RegionStoreManager::bindVector(RegionBindingsConstRef B,
2536                                                  const TypedValueRegion* R,
2537                                                  SVal V) {
2538   QualType T = R->getValueType();
2539   const VectorType *VT = T->castAs<VectorType>(); // Use castAs for typedefs.
2540 
2541   // Handle lazy compound values and symbolic values.
2542   if (isa<nonloc::LazyCompoundVal, nonloc::SymbolVal>(V))
2543     return bindAggregate(B, R, V);
2544 
2545   // We may get non-CompoundVal accidentally due to imprecise cast logic or
2546   // that we are binding symbolic struct value. Kill the field values, and if
2547   // the value is symbolic go and bind it as a "default" binding.
2548   if (!isa<nonloc::CompoundVal>(V)) {
2549     return bindAggregate(B, R, UnknownVal());
2550   }
2551 
2552   QualType ElemType = VT->getElementType();
2553   nonloc::CompoundVal CV = V.castAs<nonloc::CompoundVal>();
2554   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
2555   unsigned index = 0, numElements = VT->getNumElements();
2556   RegionBindingsRef NewB(B);
2557 
2558   for ( ; index != numElements ; ++index) {
2559     if (VI == VE)
2560       break;
2561 
2562     NonLoc Idx = svalBuilder.makeArrayIndex(index);
2563     const ElementRegion *ER = MRMgr.getElementRegion(ElemType, Idx, R, Ctx);
2564 
2565     if (ElemType->isArrayType())
2566       NewB = bindArray(NewB, ER, *VI);
2567     else if (ElemType->isStructureOrClassType())
2568       NewB = bindStruct(NewB, ER, *VI);
2569     else
2570       NewB = bind(NewB, loc::MemRegionVal(ER), *VI);
2571   }
2572   return NewB;
2573 }
2574 
2575 Optional<RegionBindingsRef>
2576 RegionStoreManager::tryBindSmallStruct(RegionBindingsConstRef B,
2577                                        const TypedValueRegion *R,
2578                                        const RecordDecl *RD,
2579                                        nonloc::LazyCompoundVal LCV) {
2580   FieldVector Fields;
2581 
2582   if (const CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(RD))
2583     if (Class->getNumBases() != 0 || Class->getNumVBases() != 0)
2584       return std::nullopt;
2585 
2586   for (const auto *FD : RD->fields()) {
2587     if (FD->isUnnamedBitfield())
2588       continue;
2589 
2590     // If there are too many fields, or if any of the fields are aggregates,
2591     // just use the LCV as a default binding.
2592     if (Fields.size() == SmallStructLimit)
2593       return std::nullopt;
2594 
2595     QualType Ty = FD->getType();
2596 
2597     // Zero length arrays are basically no-ops, so we also ignore them here.
2598     if (Ty->isConstantArrayType() &&
2599         Ctx.getConstantArrayElementCount(Ctx.getAsConstantArrayType(Ty)) == 0)
2600       continue;
2601 
2602     if (!(Ty->isScalarType() || Ty->isReferenceType()))
2603       return std::nullopt;
2604 
2605     Fields.push_back(FD);
2606   }
2607 
2608   RegionBindingsRef NewB = B;
2609 
2610   for (FieldVector::iterator I = Fields.begin(), E = Fields.end(); I != E; ++I){
2611     const FieldRegion *SourceFR = MRMgr.getFieldRegion(*I, LCV.getRegion());
2612     SVal V = getBindingForField(getRegionBindings(LCV.getStore()), SourceFR);
2613 
2614     const FieldRegion *DestFR = MRMgr.getFieldRegion(*I, R);
2615     NewB = bind(NewB, loc::MemRegionVal(DestFR), V);
2616   }
2617 
2618   return NewB;
2619 }
2620 
2621 RegionBindingsRef RegionStoreManager::bindStruct(RegionBindingsConstRef B,
2622                                                  const TypedValueRegion *R,
2623                                                  SVal V) {
2624   QualType T = R->getValueType();
2625   assert(T->isStructureOrClassType());
2626 
2627   const RecordType* RT = T->castAs<RecordType>();
2628   const RecordDecl *RD = RT->getDecl();
2629 
2630   if (!RD->isCompleteDefinition())
2631     return B;
2632 
2633   // Handle lazy compound values and symbolic values.
2634   if (Optional<nonloc::LazyCompoundVal> LCV =
2635         V.getAs<nonloc::LazyCompoundVal>()) {
2636     if (Optional<RegionBindingsRef> NewB = tryBindSmallStruct(B, R, RD, *LCV))
2637       return *NewB;
2638     return bindAggregate(B, R, V);
2639   }
2640   if (isa<nonloc::SymbolVal>(V))
2641     return bindAggregate(B, R, V);
2642 
2643   // We may get non-CompoundVal accidentally due to imprecise cast logic or
2644   // that we are binding symbolic struct value. Kill the field values, and if
2645   // the value is symbolic go and bind it as a "default" binding.
2646   if (V.isUnknown() || !isa<nonloc::CompoundVal>(V))
2647     return bindAggregate(B, R, UnknownVal());
2648 
2649   // The raw CompoundVal is essentially a symbolic InitListExpr: an (immutable)
2650   // list of other values. It appears pretty much only when there's an actual
2651   // initializer list expression in the program, and the analyzer tries to
2652   // unwrap it as soon as possible.
2653   // This code is where such unwrap happens: when the compound value is put into
2654   // the object that it was supposed to initialize (it's an *initializer* list,
2655   // after all), instead of binding the whole value to the whole object, we bind
2656   // sub-values to sub-objects. Sub-values may themselves be compound values,
2657   // and in this case the procedure becomes recursive.
2658   // FIXME: The annoying part about compound values is that they don't carry
2659   // any sort of information about which value corresponds to which sub-object.
2660   // It's simply a list of values in the middle of nowhere; we expect to match
2661   // them to sub-objects, essentially, "by index": first value binds to
2662   // the first field, second value binds to the second field, etc.
2663   // It would have been much safer to organize non-lazy compound values as
2664   // a mapping from fields/bases to values.
2665   const nonloc::CompoundVal& CV = V.castAs<nonloc::CompoundVal>();
2666   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
2667 
2668   RegionBindingsRef NewB(B);
2669 
2670   // In C++17 aggregates may have base classes, handle those as well.
2671   // They appear before fields in the initializer list / compound value.
2672   if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
2673     // If the object was constructed with a constructor, its value is a
2674     // LazyCompoundVal. If it's a raw CompoundVal, it means that we're
2675     // performing aggregate initialization. The only exception from this
2676     // rule is sending an Objective-C++ message that returns a C++ object
2677     // to a nil receiver; in this case the semantics is to return a
2678     // zero-initialized object even if it's a C++ object that doesn't have
2679     // this sort of constructor; the CompoundVal is empty in this case.
2680     assert((CRD->isAggregate() || (Ctx.getLangOpts().ObjC && VI == VE)) &&
2681            "Non-aggregates are constructed with a constructor!");
2682 
2683     for (const auto &B : CRD->bases()) {
2684       // (Multiple inheritance is fine though.)
2685       assert(!B.isVirtual() && "Aggregates cannot have virtual base classes!");
2686 
2687       if (VI == VE)
2688         break;
2689 
2690       QualType BTy = B.getType();
2691       assert(BTy->isStructureOrClassType() && "Base classes must be classes!");
2692 
2693       const CXXRecordDecl *BRD = BTy->getAsCXXRecordDecl();
2694       assert(BRD && "Base classes must be C++ classes!");
2695 
2696       const CXXBaseObjectRegion *BR =
2697           MRMgr.getCXXBaseObjectRegion(BRD, R, /*IsVirtual=*/false);
2698 
2699       NewB = bindStruct(NewB, BR, *VI);
2700 
2701       ++VI;
2702     }
2703   }
2704 
2705   RecordDecl::field_iterator FI, FE;
2706 
2707   for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; ++FI) {
2708 
2709     if (VI == VE)
2710       break;
2711 
2712     // Skip any unnamed bitfields to stay in sync with the initializers.
2713     if (FI->isUnnamedBitfield())
2714       continue;
2715 
2716     QualType FTy = FI->getType();
2717     const FieldRegion* FR = MRMgr.getFieldRegion(*FI, R);
2718 
2719     if (FTy->isArrayType())
2720       NewB = bindArray(NewB, FR, *VI);
2721     else if (FTy->isStructureOrClassType())
2722       NewB = bindStruct(NewB, FR, *VI);
2723     else
2724       NewB = bind(NewB, loc::MemRegionVal(FR), *VI);
2725     ++VI;
2726   }
2727 
2728   // There may be fewer values in the initialize list than the fields of struct.
2729   if (FI != FE) {
2730     NewB = NewB.addBinding(R, BindingKey::Default,
2731                            svalBuilder.makeIntVal(0, false));
2732   }
2733 
2734   return NewB;
2735 }
2736 
2737 RegionBindingsRef
2738 RegionStoreManager::bindAggregate(RegionBindingsConstRef B,
2739                                   const TypedRegion *R,
2740                                   SVal Val) {
2741   // Remove the old bindings, using 'R' as the root of all regions
2742   // we will invalidate. Then add the new binding.
2743   return removeSubRegionBindings(B, R).addBinding(R, BindingKey::Default, Val);
2744 }
2745 
2746 //===----------------------------------------------------------------------===//
2747 // State pruning.
2748 //===----------------------------------------------------------------------===//
2749 
2750 namespace {
2751 class RemoveDeadBindingsWorker
2752     : public ClusterAnalysis<RemoveDeadBindingsWorker> {
2753   SmallVector<const SymbolicRegion *, 12> Postponed;
2754   SymbolReaper &SymReaper;
2755   const StackFrameContext *CurrentLCtx;
2756 
2757 public:
2758   RemoveDeadBindingsWorker(RegionStoreManager &rm,
2759                            ProgramStateManager &stateMgr,
2760                            RegionBindingsRef b, SymbolReaper &symReaper,
2761                            const StackFrameContext *LCtx)
2762     : ClusterAnalysis<RemoveDeadBindingsWorker>(rm, stateMgr, b),
2763       SymReaper(symReaper), CurrentLCtx(LCtx) {}
2764 
2765   // Called by ClusterAnalysis.
2766   void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C);
2767   void VisitCluster(const MemRegion *baseR, const ClusterBindings *C);
2768   using ClusterAnalysis<RemoveDeadBindingsWorker>::VisitCluster;
2769 
2770   using ClusterAnalysis::AddToWorkList;
2771 
2772   bool AddToWorkList(const MemRegion *R);
2773 
2774   bool UpdatePostponed();
2775   void VisitBinding(SVal V);
2776 };
2777 }
2778 
2779 bool RemoveDeadBindingsWorker::AddToWorkList(const MemRegion *R) {
2780   const MemRegion *BaseR = R->getBaseRegion();
2781   return AddToWorkList(WorkListElement(BaseR), getCluster(BaseR));
2782 }
2783 
2784 void RemoveDeadBindingsWorker::VisitAddedToCluster(const MemRegion *baseR,
2785                                                    const ClusterBindings &C) {
2786 
2787   if (const VarRegion *VR = dyn_cast<VarRegion>(baseR)) {
2788     if (SymReaper.isLive(VR))
2789       AddToWorkList(baseR, &C);
2790 
2791     return;
2792   }
2793 
2794   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) {
2795     if (SymReaper.isLive(SR->getSymbol()))
2796       AddToWorkList(SR, &C);
2797     else
2798       Postponed.push_back(SR);
2799 
2800     return;
2801   }
2802 
2803   if (isa<NonStaticGlobalSpaceRegion>(baseR)) {
2804     AddToWorkList(baseR, &C);
2805     return;
2806   }
2807 
2808   // CXXThisRegion in the current or parent location context is live.
2809   if (const CXXThisRegion *TR = dyn_cast<CXXThisRegion>(baseR)) {
2810     const auto *StackReg =
2811         cast<StackArgumentsSpaceRegion>(TR->getSuperRegion());
2812     const StackFrameContext *RegCtx = StackReg->getStackFrame();
2813     if (CurrentLCtx &&
2814         (RegCtx == CurrentLCtx || RegCtx->isParentOf(CurrentLCtx)))
2815       AddToWorkList(TR, &C);
2816   }
2817 }
2818 
2819 void RemoveDeadBindingsWorker::VisitCluster(const MemRegion *baseR,
2820                                             const ClusterBindings *C) {
2821   if (!C)
2822     return;
2823 
2824   // Mark the symbol for any SymbolicRegion with live bindings as live itself.
2825   // This means we should continue to track that symbol.
2826   if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(baseR))
2827     SymReaper.markLive(SymR->getSymbol());
2828 
2829   for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I) {
2830     // Element index of a binding key is live.
2831     SymReaper.markElementIndicesLive(I.getKey().getRegion());
2832 
2833     VisitBinding(I.getData());
2834   }
2835 }
2836 
2837 void RemoveDeadBindingsWorker::VisitBinding(SVal V) {
2838   // Is it a LazyCompoundVal? All referenced regions are live as well.
2839   // The LazyCompoundVal itself is not live but should be readable.
2840   if (auto LCS = V.getAs<nonloc::LazyCompoundVal>()) {
2841     SymReaper.markLazilyCopied(LCS->getRegion());
2842 
2843     for (SVal V : RM.getInterestingValues(*LCS)) {
2844       if (auto DepLCS = V.getAs<nonloc::LazyCompoundVal>())
2845         SymReaper.markLazilyCopied(DepLCS->getRegion());
2846       else
2847         VisitBinding(V);
2848     }
2849 
2850     return;
2851   }
2852 
2853   // If V is a region, then add it to the worklist.
2854   if (const MemRegion *R = V.getAsRegion()) {
2855     AddToWorkList(R);
2856     SymReaper.markLive(R);
2857 
2858     // All regions captured by a block are also live.
2859     if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(R)) {
2860       BlockDataRegion::referenced_vars_iterator I = BR->referenced_vars_begin(),
2861                                                 E = BR->referenced_vars_end();
2862       for ( ; I != E; ++I)
2863         AddToWorkList(I.getCapturedRegion());
2864     }
2865   }
2866 
2867 
2868   // Update the set of live symbols.
2869   for (auto SI = V.symbol_begin(), SE = V.symbol_end(); SI!=SE; ++SI)
2870     SymReaper.markLive(*SI);
2871 }
2872 
2873 bool RemoveDeadBindingsWorker::UpdatePostponed() {
2874   // See if any postponed SymbolicRegions are actually live now, after
2875   // having done a scan.
2876   bool Changed = false;
2877 
2878   for (auto I = Postponed.begin(), E = Postponed.end(); I != E; ++I) {
2879     if (const SymbolicRegion *SR = *I) {
2880       if (SymReaper.isLive(SR->getSymbol())) {
2881         Changed |= AddToWorkList(SR);
2882         *I = nullptr;
2883       }
2884     }
2885   }
2886 
2887   return Changed;
2888 }
2889 
2890 StoreRef RegionStoreManager::removeDeadBindings(Store store,
2891                                                 const StackFrameContext *LCtx,
2892                                                 SymbolReaper& SymReaper) {
2893   RegionBindingsRef B = getRegionBindings(store);
2894   RemoveDeadBindingsWorker W(*this, StateMgr, B, SymReaper, LCtx);
2895   W.GenerateClusters();
2896 
2897   // Enqueue the region roots onto the worklist.
2898   for (SymbolReaper::region_iterator I = SymReaper.region_begin(),
2899        E = SymReaper.region_end(); I != E; ++I) {
2900     W.AddToWorkList(*I);
2901   }
2902 
2903   do W.RunWorkList(); while (W.UpdatePostponed());
2904 
2905   // We have now scanned the store, marking reachable regions and symbols
2906   // as live.  We now remove all the regions that are dead from the store
2907   // as well as update DSymbols with the set symbols that are now dead.
2908   for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; ++I) {
2909     const MemRegion *Base = I.getKey();
2910 
2911     // If the cluster has been visited, we know the region has been marked.
2912     // Otherwise, remove the dead entry.
2913     if (!W.isVisited(Base))
2914       B = B.remove(Base);
2915   }
2916 
2917   return StoreRef(B.asStore(), *this);
2918 }
2919 
2920 //===----------------------------------------------------------------------===//
2921 // Utility methods.
2922 //===----------------------------------------------------------------------===//
2923 
2924 void RegionStoreManager::printJson(raw_ostream &Out, Store S, const char *NL,
2925                                    unsigned int Space, bool IsDot) const {
2926   RegionBindingsRef Bindings = getRegionBindings(S);
2927 
2928   Indent(Out, Space, IsDot) << "\"store\": ";
2929 
2930   if (Bindings.isEmpty()) {
2931     Out << "null," << NL;
2932     return;
2933   }
2934 
2935   Out << "{ \"pointer\": \"" << Bindings.asStore() << "\", \"items\": [" << NL;
2936   Bindings.printJson(Out, NL, Space + 1, IsDot);
2937   Indent(Out, Space, IsDot) << "]}," << NL;
2938 }
2939