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