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 return static_cast<DERIVED*>(this)->AddToWorkList(R); 714 } 715 716 void RunWorkList() { 717 while (!WL.empty()) { 718 WorkListElement E = WL.pop_back_val(); 719 const MemRegion *BaseR = E; 720 721 static_cast<DERIVED*>(this)->VisitCluster(BaseR, getCluster(BaseR)); 722 } 723 } 724 725 void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C) {} 726 void VisitCluster(const MemRegion *baseR, const ClusterBindings *C) {} 727 728 void VisitCluster(const MemRegion *BaseR, const ClusterBindings *C, 729 bool Flag) { 730 static_cast<DERIVED*>(this)->VisitCluster(BaseR, C); 731 } 732 }; 733 } 734 735 //===----------------------------------------------------------------------===// 736 // Binding invalidation. 737 //===----------------------------------------------------------------------===// 738 739 bool RegionStoreManager::scanReachableSymbols(Store S, const MemRegion *R, 740 ScanReachableSymbols &Callbacks) { 741 assert(R == R->getBaseRegion() && "Should only be called for base regions"); 742 RegionBindingsRef B = getRegionBindings(S); 743 const ClusterBindings *Cluster = B.lookup(R); 744 745 if (!Cluster) 746 return true; 747 748 for (ClusterBindings::iterator RI = Cluster->begin(), RE = Cluster->end(); 749 RI != RE; ++RI) { 750 if (!Callbacks.scan(RI.getData())) 751 return false; 752 } 753 754 return true; 755 } 756 757 static inline bool isUnionField(const FieldRegion *FR) { 758 return FR->getDecl()->getParent()->isUnion(); 759 } 760 761 typedef SmallVector<const FieldDecl *, 8> FieldVector; 762 763 static void getSymbolicOffsetFields(BindingKey K, FieldVector &Fields) { 764 assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys"); 765 766 const MemRegion *Base = K.getConcreteOffsetRegion(); 767 const MemRegion *R = K.getRegion(); 768 769 while (R != Base) { 770 if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) 771 if (!isUnionField(FR)) 772 Fields.push_back(FR->getDecl()); 773 774 R = cast<SubRegion>(R)->getSuperRegion(); 775 } 776 } 777 778 static bool isCompatibleWithFields(BindingKey K, const FieldVector &Fields) { 779 assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys"); 780 781 if (Fields.empty()) 782 return true; 783 784 FieldVector FieldsInBindingKey; 785 getSymbolicOffsetFields(K, FieldsInBindingKey); 786 787 ptrdiff_t Delta = FieldsInBindingKey.size() - Fields.size(); 788 if (Delta >= 0) 789 return std::equal(FieldsInBindingKey.begin() + Delta, 790 FieldsInBindingKey.end(), 791 Fields.begin()); 792 else 793 return std::equal(FieldsInBindingKey.begin(), FieldsInBindingKey.end(), 794 Fields.begin() - Delta); 795 } 796 797 /// Collects all bindings in \p Cluster that may refer to bindings within 798 /// \p Top. 799 /// 800 /// Each binding is a pair whose \c first is the key (a BindingKey) and whose 801 /// \c second is the value (an SVal). 802 /// 803 /// The \p IncludeAllDefaultBindings parameter specifies whether to include 804 /// default bindings that may extend beyond \p Top itself, e.g. if \p Top is 805 /// an aggregate within a larger aggregate with a default binding. 806 static void 807 collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings, 808 SValBuilder &SVB, const ClusterBindings &Cluster, 809 const SubRegion *Top, BindingKey TopKey, 810 bool IncludeAllDefaultBindings) { 811 FieldVector FieldsInSymbolicSubregions; 812 if (TopKey.hasSymbolicOffset()) { 813 getSymbolicOffsetFields(TopKey, FieldsInSymbolicSubregions); 814 Top = cast<SubRegion>(TopKey.getConcreteOffsetRegion()); 815 TopKey = BindingKey::Make(Top, BindingKey::Default); 816 } 817 818 // Find the length (in bits) of the region being invalidated. 819 uint64_t Length = UINT64_MAX; 820 SVal Extent = Top->getExtent(SVB); 821 if (Optional<nonloc::ConcreteInt> ExtentCI = 822 Extent.getAs<nonloc::ConcreteInt>()) { 823 const llvm::APSInt &ExtentInt = ExtentCI->getValue(); 824 assert(ExtentInt.isNonNegative() || ExtentInt.isUnsigned()); 825 // Extents are in bytes but region offsets are in bits. Be careful! 826 Length = ExtentInt.getLimitedValue() * SVB.getContext().getCharWidth(); 827 } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(Top)) { 828 if (FR->getDecl()->isBitField()) 829 Length = FR->getDecl()->getBitWidthValue(SVB.getContext()); 830 } 831 832 for (ClusterBindings::iterator I = Cluster.begin(), E = Cluster.end(); 833 I != E; ++I) { 834 BindingKey NextKey = I.getKey(); 835 if (NextKey.getRegion() == TopKey.getRegion()) { 836 // FIXME: This doesn't catch the case where we're really invalidating a 837 // region with a symbolic offset. Example: 838 // R: points[i].y 839 // Next: points[0].x 840 841 if (NextKey.getOffset() > TopKey.getOffset() && 842 NextKey.getOffset() - TopKey.getOffset() < Length) { 843 // Case 1: The next binding is inside the region we're invalidating. 844 // Include it. 845 Bindings.push_back(*I); 846 847 } else if (NextKey.getOffset() == TopKey.getOffset()) { 848 // Case 2: The next binding is at the same offset as the region we're 849 // invalidating. In this case, we need to leave default bindings alone, 850 // since they may be providing a default value for a regions beyond what 851 // we're invalidating. 852 // FIXME: This is probably incorrect; consider invalidating an outer 853 // struct whose first field is bound to a LazyCompoundVal. 854 if (IncludeAllDefaultBindings || NextKey.isDirect()) 855 Bindings.push_back(*I); 856 } 857 858 } else if (NextKey.hasSymbolicOffset()) { 859 const MemRegion *Base = NextKey.getConcreteOffsetRegion(); 860 if (Top->isSubRegionOf(Base)) { 861 // Case 3: The next key is symbolic and we just changed something within 862 // its concrete region. We don't know if the binding is still valid, so 863 // we'll be conservative and include it. 864 if (IncludeAllDefaultBindings || NextKey.isDirect()) 865 if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions)) 866 Bindings.push_back(*I); 867 } else if (const SubRegion *BaseSR = dyn_cast<SubRegion>(Base)) { 868 // Case 4: The next key is symbolic, but we changed a known 869 // super-region. In this case the binding is certainly included. 870 if (Top == Base || BaseSR->isSubRegionOf(Top)) 871 if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions)) 872 Bindings.push_back(*I); 873 } 874 } 875 } 876 } 877 878 static void 879 collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings, 880 SValBuilder &SVB, const ClusterBindings &Cluster, 881 const SubRegion *Top, bool IncludeAllDefaultBindings) { 882 collectSubRegionBindings(Bindings, SVB, Cluster, Top, 883 BindingKey::Make(Top, BindingKey::Default), 884 IncludeAllDefaultBindings); 885 } 886 887 RegionBindingsRef 888 RegionStoreManager::removeSubRegionBindings(RegionBindingsConstRef B, 889 const SubRegion *Top) { 890 BindingKey TopKey = BindingKey::Make(Top, BindingKey::Default); 891 const MemRegion *ClusterHead = TopKey.getBaseRegion(); 892 893 if (Top == ClusterHead) { 894 // We can remove an entire cluster's bindings all in one go. 895 return B.remove(Top); 896 } 897 898 const ClusterBindings *Cluster = B.lookup(ClusterHead); 899 if (!Cluster) { 900 // If we're invalidating a region with a symbolic offset, we need to make 901 // sure we don't treat the base region as uninitialized anymore. 902 if (TopKey.hasSymbolicOffset()) { 903 const SubRegion *Concrete = TopKey.getConcreteOffsetRegion(); 904 return B.addBinding(Concrete, BindingKey::Default, UnknownVal()); 905 } 906 return B; 907 } 908 909 SmallVector<BindingPair, 32> Bindings; 910 collectSubRegionBindings(Bindings, svalBuilder, *Cluster, Top, TopKey, 911 /*IncludeAllDefaultBindings=*/false); 912 913 ClusterBindingsRef Result(*Cluster, CBFactory); 914 for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(), 915 E = Bindings.end(); 916 I != E; ++I) 917 Result = Result.remove(I->first); 918 919 // If we're invalidating a region with a symbolic offset, we need to make sure 920 // we don't treat the base region as uninitialized anymore. 921 // FIXME: This isn't very precise; see the example in 922 // collectSubRegionBindings. 923 if (TopKey.hasSymbolicOffset()) { 924 const SubRegion *Concrete = TopKey.getConcreteOffsetRegion(); 925 Result = Result.add(BindingKey::Make(Concrete, BindingKey::Default), 926 UnknownVal()); 927 } 928 929 if (Result.isEmpty()) 930 return B.remove(ClusterHead); 931 return B.add(ClusterHead, Result.asImmutableMap()); 932 } 933 934 namespace { 935 class invalidateRegionsWorker : public ClusterAnalysis<invalidateRegionsWorker> 936 { 937 const Expr *Ex; 938 unsigned Count; 939 const LocationContext *LCtx; 940 InvalidatedSymbols &IS; 941 RegionAndSymbolInvalidationTraits &ITraits; 942 StoreManager::InvalidatedRegions *Regions; 943 public: 944 invalidateRegionsWorker(RegionStoreManager &rm, 945 ProgramStateManager &stateMgr, 946 RegionBindingsRef b, 947 const Expr *ex, unsigned count, 948 const LocationContext *lctx, 949 InvalidatedSymbols &is, 950 RegionAndSymbolInvalidationTraits &ITraitsIn, 951 StoreManager::InvalidatedRegions *r, 952 GlobalsFilterKind GFK) 953 : ClusterAnalysis<invalidateRegionsWorker>(rm, stateMgr, b, GFK), 954 Ex(ex), Count(count), LCtx(lctx), IS(is), ITraits(ITraitsIn), Regions(r){} 955 956 void VisitCluster(const MemRegion *baseR, const ClusterBindings *C); 957 void VisitBinding(SVal V); 958 959 using ClusterAnalysis::AddToWorkList; 960 961 bool AddToWorkList(const MemRegion *R); 962 }; 963 } 964 965 bool invalidateRegionsWorker::AddToWorkList(const MemRegion *R) { 966 bool doNotInvalidateSuperRegion = ITraits.hasTrait( 967 R, RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion); 968 const MemRegion *BaseR = doNotInvalidateSuperRegion ? R : R->getBaseRegion(); 969 return AddToWorkList(WorkListElement(BaseR), getCluster(BaseR)); 970 } 971 972 void invalidateRegionsWorker::VisitBinding(SVal V) { 973 // A symbol? Mark it touched by the invalidation. 974 if (SymbolRef Sym = V.getAsSymbol()) 975 IS.insert(Sym); 976 977 if (const MemRegion *R = V.getAsRegion()) { 978 AddToWorkList(R); 979 return; 980 } 981 982 // Is it a LazyCompoundVal? All references get invalidated as well. 983 if (Optional<nonloc::LazyCompoundVal> LCS = 984 V.getAs<nonloc::LazyCompoundVal>()) { 985 986 const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS); 987 988 for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(), 989 E = Vals.end(); 990 I != E; ++I) 991 VisitBinding(*I); 992 993 return; 994 } 995 } 996 997 void invalidateRegionsWorker::VisitCluster(const MemRegion *baseR, 998 const ClusterBindings *C) { 999 1000 bool PreserveRegionsContents = 1001 ITraits.hasTrait(baseR, 1002 RegionAndSymbolInvalidationTraits::TK_PreserveContents); 1003 1004 if (C) { 1005 for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I) 1006 VisitBinding(I.getData()); 1007 1008 // Invalidate regions contents. 1009 if (!PreserveRegionsContents) 1010 B = B.remove(baseR); 1011 } 1012 1013 // BlockDataRegion? If so, invalidate captured variables that are passed 1014 // by reference. 1015 if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) { 1016 for (BlockDataRegion::referenced_vars_iterator 1017 BI = BR->referenced_vars_begin(), BE = BR->referenced_vars_end() ; 1018 BI != BE; ++BI) { 1019 const VarRegion *VR = BI.getCapturedRegion(); 1020 const VarDecl *VD = VR->getDecl(); 1021 if (VD->hasAttr<BlocksAttr>() || !VD->hasLocalStorage()) { 1022 AddToWorkList(VR); 1023 } 1024 else if (Loc::isLocType(VR->getValueType())) { 1025 // Map the current bindings to a Store to retrieve the value 1026 // of the binding. If that binding itself is a region, we should 1027 // invalidate that region. This is because a block may capture 1028 // a pointer value, but the thing pointed by that pointer may 1029 // get invalidated. 1030 SVal V = RM.getBinding(B, loc::MemRegionVal(VR)); 1031 if (Optional<Loc> L = V.getAs<Loc>()) { 1032 if (const MemRegion *LR = L->getAsRegion()) 1033 AddToWorkList(LR); 1034 } 1035 } 1036 } 1037 return; 1038 } 1039 1040 // Symbolic region? 1041 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) 1042 IS.insert(SR->getSymbol()); 1043 1044 // Nothing else should be done in the case when we preserve regions context. 1045 if (PreserveRegionsContents) 1046 return; 1047 1048 // Otherwise, we have a normal data region. Record that we touched the region. 1049 if (Regions) 1050 Regions->push_back(baseR); 1051 1052 if (isa<AllocaRegion>(baseR) || isa<SymbolicRegion>(baseR)) { 1053 // Invalidate the region by setting its default value to 1054 // conjured symbol. The type of the symbol is irrelevant. 1055 DefinedOrUnknownSVal V = 1056 svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count); 1057 B = B.addBinding(baseR, BindingKey::Default, V); 1058 return; 1059 } 1060 1061 if (!baseR->isBoundable()) 1062 return; 1063 1064 const TypedValueRegion *TR = cast<TypedValueRegion>(baseR); 1065 QualType T = TR->getValueType(); 1066 1067 if (isInitiallyIncludedGlobalRegion(baseR)) { 1068 // If the region is a global and we are invalidating all globals, 1069 // erasing the entry is good enough. This causes all globals to be lazily 1070 // symbolicated from the same base symbol. 1071 return; 1072 } 1073 1074 if (T->isStructureOrClassType()) { 1075 // Invalidate the region by setting its default value to 1076 // conjured symbol. The type of the symbol is irrelevant. 1077 DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, 1078 Ctx.IntTy, Count); 1079 B = B.addBinding(baseR, BindingKey::Default, V); 1080 return; 1081 } 1082 1083 if (const ArrayType *AT = Ctx.getAsArrayType(T)) { 1084 bool doNotInvalidateSuperRegion = ITraits.hasTrait( 1085 baseR, 1086 RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion); 1087 1088 if (doNotInvalidateSuperRegion) { 1089 // We are not doing blank invalidation of the whole array region so we 1090 // have to manually invalidate each elements. 1091 Optional<uint64_t> NumElements; 1092 1093 // Compute lower and upper offsets for region within array. 1094 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 1095 NumElements = CAT->getSize().getZExtValue(); 1096 if (!NumElements) // We are not dealing with a constant size array 1097 goto conjure_default; 1098 QualType ElementTy = AT->getElementType(); 1099 uint64_t ElemSize = Ctx.getTypeSize(ElementTy); 1100 const RegionOffset &RO = baseR->getAsOffset(); 1101 const MemRegion *SuperR = baseR->getBaseRegion(); 1102 if (RO.hasSymbolicOffset()) { 1103 // If base region has a symbolic offset, 1104 // we revert to invalidating the super region. 1105 if (SuperR) 1106 AddToWorkList(SuperR); 1107 goto conjure_default; 1108 } 1109 1110 uint64_t LowerOffset = RO.getOffset(); 1111 uint64_t UpperOffset = LowerOffset + *NumElements * ElemSize; 1112 bool UpperOverflow = UpperOffset < LowerOffset; 1113 1114 // Invalidate regions which are within array boundaries, 1115 // or have a symbolic offset. 1116 if (!SuperR) 1117 goto conjure_default; 1118 1119 const ClusterBindings *C = B.lookup(SuperR); 1120 if (!C) 1121 goto conjure_default; 1122 1123 for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; 1124 ++I) { 1125 const BindingKey &BK = I.getKey(); 1126 Optional<uint64_t> ROffset = 1127 BK.hasSymbolicOffset() ? Optional<uint64_t>() : BK.getOffset(); 1128 1129 // Check offset is not symbolic and within array's boundaries. 1130 // Handles arrays of 0 elements and of 0-sized elements as well. 1131 if (!ROffset || 1132 (ROffset && 1133 ((*ROffset >= LowerOffset && *ROffset < UpperOffset) || 1134 (UpperOverflow && 1135 (*ROffset >= LowerOffset || *ROffset < UpperOffset)) || 1136 (LowerOffset == UpperOffset && *ROffset == LowerOffset)))) { 1137 B = B.removeBinding(I.getKey()); 1138 // Bound symbolic regions need to be invalidated for dead symbol 1139 // detection. 1140 SVal V = I.getData(); 1141 const MemRegion *R = V.getAsRegion(); 1142 if (R && isa<SymbolicRegion>(R)) 1143 VisitBinding(V); 1144 } 1145 } 1146 } 1147 conjure_default: 1148 // Set the default value of the array to conjured symbol. 1149 DefinedOrUnknownSVal V = 1150 svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, 1151 AT->getElementType(), Count); 1152 B = B.addBinding(baseR, BindingKey::Default, V); 1153 return; 1154 } 1155 1156 DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, 1157 T,Count); 1158 assert(SymbolManager::canSymbolicate(T) || V.isUnknown()); 1159 B = B.addBinding(baseR, BindingKey::Direct, V); 1160 } 1161 1162 RegionBindingsRef 1163 RegionStoreManager::invalidateGlobalRegion(MemRegion::Kind K, 1164 const Expr *Ex, 1165 unsigned Count, 1166 const LocationContext *LCtx, 1167 RegionBindingsRef B, 1168 InvalidatedRegions *Invalidated) { 1169 // Bind the globals memory space to a new symbol that we will use to derive 1170 // the bindings for all globals. 1171 const GlobalsSpaceRegion *GS = MRMgr.getGlobalsRegion(K); 1172 SVal V = svalBuilder.conjureSymbolVal(/* SymbolTag = */ (const void*) GS, Ex, LCtx, 1173 /* type does not matter */ Ctx.IntTy, 1174 Count); 1175 1176 B = B.removeBinding(GS) 1177 .addBinding(BindingKey::Make(GS, BindingKey::Default), V); 1178 1179 // Even if there are no bindings in the global scope, we still need to 1180 // record that we touched it. 1181 if (Invalidated) 1182 Invalidated->push_back(GS); 1183 1184 return B; 1185 } 1186 1187 void RegionStoreManager::populateWorkList(invalidateRegionsWorker &W, 1188 ArrayRef<SVal> Values, 1189 InvalidatedRegions *TopLevelRegions) { 1190 for (ArrayRef<SVal>::iterator I = Values.begin(), 1191 E = Values.end(); I != E; ++I) { 1192 SVal V = *I; 1193 if (Optional<nonloc::LazyCompoundVal> LCS = 1194 V.getAs<nonloc::LazyCompoundVal>()) { 1195 1196 const SValListTy &Vals = getInterestingValues(*LCS); 1197 1198 for (SValListTy::const_iterator I = Vals.begin(), 1199 E = Vals.end(); I != E; ++I) { 1200 // Note: the last argument is false here because these are 1201 // non-top-level regions. 1202 if (const MemRegion *R = (*I).getAsRegion()) 1203 W.AddToWorkList(R); 1204 } 1205 continue; 1206 } 1207 1208 if (const MemRegion *R = V.getAsRegion()) { 1209 if (TopLevelRegions) 1210 TopLevelRegions->push_back(R); 1211 W.AddToWorkList(R); 1212 continue; 1213 } 1214 } 1215 } 1216 1217 StoreRef 1218 RegionStoreManager::invalidateRegions(Store store, 1219 ArrayRef<SVal> Values, 1220 const Expr *Ex, unsigned Count, 1221 const LocationContext *LCtx, 1222 const CallEvent *Call, 1223 InvalidatedSymbols &IS, 1224 RegionAndSymbolInvalidationTraits &ITraits, 1225 InvalidatedRegions *TopLevelRegions, 1226 InvalidatedRegions *Invalidated) { 1227 GlobalsFilterKind GlobalsFilter; 1228 if (Call) { 1229 if (Call->isInSystemHeader()) 1230 GlobalsFilter = GFK_SystemOnly; 1231 else 1232 GlobalsFilter = GFK_All; 1233 } else { 1234 GlobalsFilter = GFK_None; 1235 } 1236 1237 RegionBindingsRef B = getRegionBindings(store); 1238 invalidateRegionsWorker W(*this, StateMgr, B, Ex, Count, LCtx, IS, ITraits, 1239 Invalidated, GlobalsFilter); 1240 1241 // Scan the bindings and generate the clusters. 1242 W.GenerateClusters(); 1243 1244 // Add the regions to the worklist. 1245 populateWorkList(W, Values, TopLevelRegions); 1246 1247 W.RunWorkList(); 1248 1249 // Return the new bindings. 1250 B = W.getRegionBindings(); 1251 1252 // For calls, determine which global regions should be invalidated and 1253 // invalidate them. (Note that function-static and immutable globals are never 1254 // invalidated by this.) 1255 // TODO: This could possibly be more precise with modules. 1256 switch (GlobalsFilter) { 1257 case GFK_All: 1258 B = invalidateGlobalRegion(MemRegion::GlobalInternalSpaceRegionKind, 1259 Ex, Count, LCtx, B, Invalidated); 1260 // FALLTHROUGH 1261 case GFK_SystemOnly: 1262 B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind, 1263 Ex, Count, LCtx, B, Invalidated); 1264 // FALLTHROUGH 1265 case GFK_None: 1266 break; 1267 } 1268 1269 return StoreRef(B.asStore(), *this); 1270 } 1271 1272 //===----------------------------------------------------------------------===// 1273 // Extents for regions. 1274 //===----------------------------------------------------------------------===// 1275 1276 DefinedOrUnknownSVal 1277 RegionStoreManager::getSizeInElements(ProgramStateRef state, 1278 const MemRegion *R, 1279 QualType EleTy) { 1280 SVal Size = cast<SubRegion>(R)->getExtent(svalBuilder); 1281 const llvm::APSInt *SizeInt = svalBuilder.getKnownValue(state, Size); 1282 if (!SizeInt) 1283 return UnknownVal(); 1284 1285 CharUnits RegionSize = CharUnits::fromQuantity(SizeInt->getSExtValue()); 1286 1287 if (Ctx.getAsVariableArrayType(EleTy)) { 1288 // FIXME: We need to track extra state to properly record the size 1289 // of VLAs. Returning UnknownVal here, however, is a stop-gap so that 1290 // we don't have a divide-by-zero below. 1291 return UnknownVal(); 1292 } 1293 1294 CharUnits EleSize = Ctx.getTypeSizeInChars(EleTy); 1295 1296 // If a variable is reinterpreted as a type that doesn't fit into a larger 1297 // type evenly, round it down. 1298 // This is a signed value, since it's used in arithmetic with signed indices. 1299 return svalBuilder.makeIntVal(RegionSize / EleSize, false); 1300 } 1301 1302 //===----------------------------------------------------------------------===// 1303 // Location and region casting. 1304 //===----------------------------------------------------------------------===// 1305 1306 /// ArrayToPointer - Emulates the "decay" of an array to a pointer 1307 /// type. 'Array' represents the lvalue of the array being decayed 1308 /// to a pointer, and the returned SVal represents the decayed 1309 /// version of that lvalue (i.e., a pointer to the first element of 1310 /// the array). This is called by ExprEngine when evaluating casts 1311 /// from arrays to pointers. 1312 SVal RegionStoreManager::ArrayToPointer(Loc Array, QualType T) { 1313 if (!Array.getAs<loc::MemRegionVal>()) 1314 return UnknownVal(); 1315 1316 const MemRegion* R = Array.castAs<loc::MemRegionVal>().getRegion(); 1317 NonLoc ZeroIdx = svalBuilder.makeZeroArrayIndex(); 1318 return loc::MemRegionVal(MRMgr.getElementRegion(T, ZeroIdx, R, Ctx)); 1319 } 1320 1321 //===----------------------------------------------------------------------===// 1322 // Loading values from regions. 1323 //===----------------------------------------------------------------------===// 1324 1325 SVal RegionStoreManager::getBinding(RegionBindingsConstRef B, Loc L, QualType T) { 1326 assert(!L.getAs<UnknownVal>() && "location unknown"); 1327 assert(!L.getAs<UndefinedVal>() && "location undefined"); 1328 1329 // For access to concrete addresses, return UnknownVal. Checks 1330 // for null dereferences (and similar errors) are done by checkers, not 1331 // the Store. 1332 // FIXME: We can consider lazily symbolicating such memory, but we really 1333 // should defer this when we can reason easily about symbolicating arrays 1334 // of bytes. 1335 if (L.getAs<loc::ConcreteInt>()) { 1336 return UnknownVal(); 1337 } 1338 if (!L.getAs<loc::MemRegionVal>()) { 1339 return UnknownVal(); 1340 } 1341 1342 const MemRegion *MR = L.castAs<loc::MemRegionVal>().getRegion(); 1343 1344 if (isa<AllocaRegion>(MR) || 1345 isa<SymbolicRegion>(MR) || 1346 isa<CodeTextRegion>(MR)) { 1347 if (T.isNull()) { 1348 if (const TypedRegion *TR = dyn_cast<TypedRegion>(MR)) 1349 T = TR->getLocationType(); 1350 else { 1351 const SymbolicRegion *SR = cast<SymbolicRegion>(MR); 1352 T = SR->getSymbol()->getType(); 1353 } 1354 } 1355 MR = GetElementZeroRegion(MR, T); 1356 } 1357 1358 // FIXME: Perhaps this method should just take a 'const MemRegion*' argument 1359 // instead of 'Loc', and have the other Loc cases handled at a higher level. 1360 const TypedValueRegion *R = cast<TypedValueRegion>(MR); 1361 QualType RTy = R->getValueType(); 1362 1363 // FIXME: we do not yet model the parts of a complex type, so treat the 1364 // whole thing as "unknown". 1365 if (RTy->isAnyComplexType()) 1366 return UnknownVal(); 1367 1368 // FIXME: We should eventually handle funny addressing. e.g.: 1369 // 1370 // int x = ...; 1371 // int *p = &x; 1372 // char *q = (char*) p; 1373 // char c = *q; // returns the first byte of 'x'. 1374 // 1375 // Such funny addressing will occur due to layering of regions. 1376 if (RTy->isStructureOrClassType()) 1377 return getBindingForStruct(B, R); 1378 1379 // FIXME: Handle unions. 1380 if (RTy->isUnionType()) 1381 return createLazyBinding(B, R); 1382 1383 if (RTy->isArrayType()) { 1384 if (RTy->isConstantArrayType()) 1385 return getBindingForArray(B, R); 1386 else 1387 return UnknownVal(); 1388 } 1389 1390 // FIXME: handle Vector types. 1391 if (RTy->isVectorType()) 1392 return UnknownVal(); 1393 1394 if (const FieldRegion* FR = dyn_cast<FieldRegion>(R)) 1395 return CastRetrievedVal(getBindingForField(B, FR), FR, T, false); 1396 1397 if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) { 1398 // FIXME: Here we actually perform an implicit conversion from the loaded 1399 // value to the element type. Eventually we want to compose these values 1400 // more intelligently. For example, an 'element' can encompass multiple 1401 // bound regions (e.g., several bound bytes), or could be a subset of 1402 // a larger value. 1403 return CastRetrievedVal(getBindingForElement(B, ER), ER, T, false); 1404 } 1405 1406 if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) { 1407 // FIXME: Here we actually perform an implicit conversion from the loaded 1408 // value to the ivar type. What we should model is stores to ivars 1409 // that blow past the extent of the ivar. If the address of the ivar is 1410 // reinterpretted, it is possible we stored a different value that could 1411 // fit within the ivar. Either we need to cast these when storing them 1412 // or reinterpret them lazily (as we do here). 1413 return CastRetrievedVal(getBindingForObjCIvar(B, IVR), IVR, T, false); 1414 } 1415 1416 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) { 1417 // FIXME: Here we actually perform an implicit conversion from the loaded 1418 // value to the variable type. What we should model is stores to variables 1419 // that blow past the extent of the variable. If the address of the 1420 // variable is reinterpretted, it is possible we stored a different value 1421 // that could fit within the variable. Either we need to cast these when 1422 // storing them or reinterpret them lazily (as we do here). 1423 return CastRetrievedVal(getBindingForVar(B, VR), VR, T, false); 1424 } 1425 1426 const SVal *V = B.lookup(R, BindingKey::Direct); 1427 1428 // Check if the region has a binding. 1429 if (V) 1430 return *V; 1431 1432 // The location does not have a bound value. This means that it has 1433 // the value it had upon its creation and/or entry to the analyzed 1434 // function/method. These are either symbolic values or 'undefined'. 1435 if (R->hasStackNonParametersStorage()) { 1436 // All stack variables are considered to have undefined values 1437 // upon creation. All heap allocated blocks are considered to 1438 // have undefined values as well unless they are explicitly bound 1439 // to specific values. 1440 return UndefinedVal(); 1441 } 1442 1443 // All other values are symbolic. 1444 return svalBuilder.getRegionValueSymbolVal(R); 1445 } 1446 1447 static QualType getUnderlyingType(const SubRegion *R) { 1448 QualType RegionTy; 1449 if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(R)) 1450 RegionTy = TVR->getValueType(); 1451 1452 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) 1453 RegionTy = SR->getSymbol()->getType(); 1454 1455 return RegionTy; 1456 } 1457 1458 /// Checks to see if store \p B has a lazy binding for region \p R. 1459 /// 1460 /// If \p AllowSubregionBindings is \c false, a lazy binding will be rejected 1461 /// if there are additional bindings within \p R. 1462 /// 1463 /// Note that unlike RegionStoreManager::findLazyBinding, this will not search 1464 /// for lazy bindings for super-regions of \p R. 1465 static Optional<nonloc::LazyCompoundVal> 1466 getExistingLazyBinding(SValBuilder &SVB, RegionBindingsConstRef B, 1467 const SubRegion *R, bool AllowSubregionBindings) { 1468 Optional<SVal> V = B.getDefaultBinding(R); 1469 if (!V) 1470 return None; 1471 1472 Optional<nonloc::LazyCompoundVal> LCV = V->getAs<nonloc::LazyCompoundVal>(); 1473 if (!LCV) 1474 return None; 1475 1476 // If the LCV is for a subregion, the types might not match, and we shouldn't 1477 // reuse the binding. 1478 QualType RegionTy = getUnderlyingType(R); 1479 if (!RegionTy.isNull() && 1480 !RegionTy->isVoidPointerType()) { 1481 QualType SourceRegionTy = LCV->getRegion()->getValueType(); 1482 if (!SVB.getContext().hasSameUnqualifiedType(RegionTy, SourceRegionTy)) 1483 return None; 1484 } 1485 1486 if (!AllowSubregionBindings) { 1487 // If there are any other bindings within this region, we shouldn't reuse 1488 // the top-level binding. 1489 SmallVector<BindingPair, 16> Bindings; 1490 collectSubRegionBindings(Bindings, SVB, *B.lookup(R->getBaseRegion()), R, 1491 /*IncludeAllDefaultBindings=*/true); 1492 if (Bindings.size() > 1) 1493 return None; 1494 } 1495 1496 return *LCV; 1497 } 1498 1499 1500 std::pair<Store, const SubRegion *> 1501 RegionStoreManager::findLazyBinding(RegionBindingsConstRef B, 1502 const SubRegion *R, 1503 const SubRegion *originalRegion) { 1504 if (originalRegion != R) { 1505 if (Optional<nonloc::LazyCompoundVal> V = 1506 getExistingLazyBinding(svalBuilder, B, R, true)) 1507 return std::make_pair(V->getStore(), V->getRegion()); 1508 } 1509 1510 typedef std::pair<Store, const SubRegion *> StoreRegionPair; 1511 StoreRegionPair Result = StoreRegionPair(); 1512 1513 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) { 1514 Result = findLazyBinding(B, cast<SubRegion>(ER->getSuperRegion()), 1515 originalRegion); 1516 1517 if (Result.second) 1518 Result.second = MRMgr.getElementRegionWithSuper(ER, Result.second); 1519 1520 } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) { 1521 Result = findLazyBinding(B, cast<SubRegion>(FR->getSuperRegion()), 1522 originalRegion); 1523 1524 if (Result.second) 1525 Result.second = MRMgr.getFieldRegionWithSuper(FR, Result.second); 1526 1527 } else if (const CXXBaseObjectRegion *BaseReg = 1528 dyn_cast<CXXBaseObjectRegion>(R)) { 1529 // C++ base object region is another kind of region that we should blast 1530 // through to look for lazy compound value. It is like a field region. 1531 Result = findLazyBinding(B, cast<SubRegion>(BaseReg->getSuperRegion()), 1532 originalRegion); 1533 1534 if (Result.second) 1535 Result.second = MRMgr.getCXXBaseObjectRegionWithSuper(BaseReg, 1536 Result.second); 1537 } 1538 1539 return Result; 1540 } 1541 1542 SVal RegionStoreManager::getBindingForElement(RegionBindingsConstRef B, 1543 const ElementRegion* R) { 1544 // We do not currently model bindings of the CompoundLiteralregion. 1545 if (isa<CompoundLiteralRegion>(R->getBaseRegion())) 1546 return UnknownVal(); 1547 1548 // Check if the region has a binding. 1549 if (const Optional<SVal> &V = B.getDirectBinding(R)) 1550 return *V; 1551 1552 const MemRegion* superR = R->getSuperRegion(); 1553 1554 // Check if the region is an element region of a string literal. 1555 if (const StringRegion *StrR=dyn_cast<StringRegion>(superR)) { 1556 // FIXME: Handle loads from strings where the literal is treated as 1557 // an integer, e.g., *((unsigned int*)"hello") 1558 QualType T = Ctx.getAsArrayType(StrR->getValueType())->getElementType(); 1559 if (!Ctx.hasSameUnqualifiedType(T, R->getElementType())) 1560 return UnknownVal(); 1561 1562 const StringLiteral *Str = StrR->getStringLiteral(); 1563 SVal Idx = R->getIndex(); 1564 if (Optional<nonloc::ConcreteInt> CI = Idx.getAs<nonloc::ConcreteInt>()) { 1565 int64_t i = CI->getValue().getSExtValue(); 1566 // Abort on string underrun. This can be possible by arbitrary 1567 // clients of getBindingForElement(). 1568 if (i < 0) 1569 return UndefinedVal(); 1570 int64_t length = Str->getLength(); 1571 // Technically, only i == length is guaranteed to be null. 1572 // However, such overflows should be caught before reaching this point; 1573 // the only time such an access would be made is if a string literal was 1574 // used to initialize a larger array. 1575 char c = (i >= length) ? '\0' : Str->getCodeUnit(i); 1576 return svalBuilder.makeIntVal(c, T); 1577 } 1578 } 1579 1580 // Check for loads from a code text region. For such loads, just give up. 1581 if (isa<CodeTextRegion>(superR)) 1582 return UnknownVal(); 1583 1584 // Handle the case where we are indexing into a larger scalar object. 1585 // For example, this handles: 1586 // int x = ... 1587 // char *y = &x; 1588 // return *y; 1589 // FIXME: This is a hack, and doesn't do anything really intelligent yet. 1590 const RegionRawOffset &O = R->getAsArrayOffset(); 1591 1592 // If we cannot reason about the offset, return an unknown value. 1593 if (!O.getRegion()) 1594 return UnknownVal(); 1595 1596 if (const TypedValueRegion *baseR = 1597 dyn_cast_or_null<TypedValueRegion>(O.getRegion())) { 1598 QualType baseT = baseR->getValueType(); 1599 if (baseT->isScalarType()) { 1600 QualType elemT = R->getElementType(); 1601 if (elemT->isScalarType()) { 1602 if (Ctx.getTypeSizeInChars(baseT) >= Ctx.getTypeSizeInChars(elemT)) { 1603 if (const Optional<SVal> &V = B.getDirectBinding(superR)) { 1604 if (SymbolRef parentSym = V->getAsSymbol()) 1605 return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R); 1606 1607 if (V->isUnknownOrUndef()) 1608 return *V; 1609 // Other cases: give up. We are indexing into a larger object 1610 // that has some value, but we don't know how to handle that yet. 1611 return UnknownVal(); 1612 } 1613 } 1614 } 1615 } 1616 } 1617 return getBindingForFieldOrElementCommon(B, R, R->getElementType()); 1618 } 1619 1620 SVal RegionStoreManager::getBindingForField(RegionBindingsConstRef B, 1621 const FieldRegion* R) { 1622 1623 // Check if the region has a binding. 1624 if (const Optional<SVal> &V = B.getDirectBinding(R)) 1625 return *V; 1626 1627 QualType Ty = R->getValueType(); 1628 return getBindingForFieldOrElementCommon(B, R, Ty); 1629 } 1630 1631 Optional<SVal> 1632 RegionStoreManager::getBindingForDerivedDefaultValue(RegionBindingsConstRef B, 1633 const MemRegion *superR, 1634 const TypedValueRegion *R, 1635 QualType Ty) { 1636 1637 if (const Optional<SVal> &D = B.getDefaultBinding(superR)) { 1638 const SVal &val = D.getValue(); 1639 if (SymbolRef parentSym = val.getAsSymbol()) 1640 return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R); 1641 1642 if (val.isZeroConstant()) 1643 return svalBuilder.makeZeroVal(Ty); 1644 1645 if (val.isUnknownOrUndef()) 1646 return val; 1647 1648 // Lazy bindings are usually handled through getExistingLazyBinding(). 1649 // We should unify these two code paths at some point. 1650 if (val.getAs<nonloc::LazyCompoundVal>()) 1651 return val; 1652 1653 llvm_unreachable("Unknown default value"); 1654 } 1655 1656 return None; 1657 } 1658 1659 SVal RegionStoreManager::getLazyBinding(const SubRegion *LazyBindingRegion, 1660 RegionBindingsRef LazyBinding) { 1661 SVal Result; 1662 if (const ElementRegion *ER = dyn_cast<ElementRegion>(LazyBindingRegion)) 1663 Result = getBindingForElement(LazyBinding, ER); 1664 else 1665 Result = getBindingForField(LazyBinding, 1666 cast<FieldRegion>(LazyBindingRegion)); 1667 1668 // FIXME: This is a hack to deal with RegionStore's inability to distinguish a 1669 // default value for /part/ of an aggregate from a default value for the 1670 // /entire/ aggregate. The most common case of this is when struct Outer 1671 // has as its first member a struct Inner, which is copied in from a stack 1672 // variable. In this case, even if the Outer's default value is symbolic, 0, 1673 // or unknown, it gets overridden by the Inner's default value of undefined. 1674 // 1675 // This is a general problem -- if the Inner is zero-initialized, the Outer 1676 // will now look zero-initialized. The proper way to solve this is with a 1677 // new version of RegionStore that tracks the extent of a binding as well 1678 // as the offset. 1679 // 1680 // This hack only takes care of the undefined case because that can very 1681 // quickly result in a warning. 1682 if (Result.isUndef()) 1683 Result = UnknownVal(); 1684 1685 return Result; 1686 } 1687 1688 SVal 1689 RegionStoreManager::getBindingForFieldOrElementCommon(RegionBindingsConstRef B, 1690 const TypedValueRegion *R, 1691 QualType Ty) { 1692 1693 // At this point we have already checked in either getBindingForElement or 1694 // getBindingForField if 'R' has a direct binding. 1695 1696 // Lazy binding? 1697 Store lazyBindingStore = nullptr; 1698 const SubRegion *lazyBindingRegion = nullptr; 1699 std::tie(lazyBindingStore, lazyBindingRegion) = findLazyBinding(B, R, R); 1700 if (lazyBindingRegion) 1701 return getLazyBinding(lazyBindingRegion, 1702 getRegionBindings(lazyBindingStore)); 1703 1704 // Record whether or not we see a symbolic index. That can completely 1705 // be out of scope of our lookup. 1706 bool hasSymbolicIndex = false; 1707 1708 // FIXME: This is a hack to deal with RegionStore's inability to distinguish a 1709 // default value for /part/ of an aggregate from a default value for the 1710 // /entire/ aggregate. The most common case of this is when struct Outer 1711 // has as its first member a struct Inner, which is copied in from a stack 1712 // variable. In this case, even if the Outer's default value is symbolic, 0, 1713 // or unknown, it gets overridden by the Inner's default value of undefined. 1714 // 1715 // This is a general problem -- if the Inner is zero-initialized, the Outer 1716 // will now look zero-initialized. The proper way to solve this is with a 1717 // new version of RegionStore that tracks the extent of a binding as well 1718 // as the offset. 1719 // 1720 // This hack only takes care of the undefined case because that can very 1721 // quickly result in a warning. 1722 bool hasPartialLazyBinding = false; 1723 1724 const SubRegion *SR = dyn_cast<SubRegion>(R); 1725 while (SR) { 1726 const MemRegion *Base = SR->getSuperRegion(); 1727 if (Optional<SVal> D = getBindingForDerivedDefaultValue(B, Base, R, Ty)) { 1728 if (D->getAs<nonloc::LazyCompoundVal>()) { 1729 hasPartialLazyBinding = true; 1730 break; 1731 } 1732 1733 return *D; 1734 } 1735 1736 if (const ElementRegion *ER = dyn_cast<ElementRegion>(Base)) { 1737 NonLoc index = ER->getIndex(); 1738 if (!index.isConstant()) 1739 hasSymbolicIndex = true; 1740 } 1741 1742 // If our super region is a field or element itself, walk up the region 1743 // hierarchy to see if there is a default value installed in an ancestor. 1744 SR = dyn_cast<SubRegion>(Base); 1745 } 1746 1747 if (R->hasStackNonParametersStorage()) { 1748 if (isa<ElementRegion>(R)) { 1749 // Currently we don't reason specially about Clang-style vectors. Check 1750 // if superR is a vector and if so return Unknown. 1751 if (const TypedValueRegion *typedSuperR = 1752 dyn_cast<TypedValueRegion>(R->getSuperRegion())) { 1753 if (typedSuperR->getValueType()->isVectorType()) 1754 return UnknownVal(); 1755 } 1756 } 1757 1758 // FIXME: We also need to take ElementRegions with symbolic indexes into 1759 // account. This case handles both directly accessing an ElementRegion 1760 // with a symbolic offset, but also fields within an element with 1761 // a symbolic offset. 1762 if (hasSymbolicIndex) 1763 return UnknownVal(); 1764 1765 if (!hasPartialLazyBinding) 1766 return UndefinedVal(); 1767 } 1768 1769 // All other values are symbolic. 1770 return svalBuilder.getRegionValueSymbolVal(R); 1771 } 1772 1773 SVal RegionStoreManager::getBindingForObjCIvar(RegionBindingsConstRef B, 1774 const ObjCIvarRegion* R) { 1775 // Check if the region has a binding. 1776 if (const Optional<SVal> &V = B.getDirectBinding(R)) 1777 return *V; 1778 1779 const MemRegion *superR = R->getSuperRegion(); 1780 1781 // Check if the super region has a default binding. 1782 if (const Optional<SVal> &V = B.getDefaultBinding(superR)) { 1783 if (SymbolRef parentSym = V->getAsSymbol()) 1784 return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R); 1785 1786 // Other cases: give up. 1787 return UnknownVal(); 1788 } 1789 1790 return getBindingForLazySymbol(R); 1791 } 1792 1793 SVal RegionStoreManager::getBindingForVar(RegionBindingsConstRef B, 1794 const VarRegion *R) { 1795 1796 // Check if the region has a binding. 1797 if (const Optional<SVal> &V = B.getDirectBinding(R)) 1798 return *V; 1799 1800 // Lazily derive a value for the VarRegion. 1801 const VarDecl *VD = R->getDecl(); 1802 const MemSpaceRegion *MS = R->getMemorySpace(); 1803 1804 // Arguments are always symbolic. 1805 if (isa<StackArgumentsSpaceRegion>(MS)) 1806 return svalBuilder.getRegionValueSymbolVal(R); 1807 1808 // Is 'VD' declared constant? If so, retrieve the constant value. 1809 if (VD->getType().isConstQualified()) 1810 if (const Expr *Init = VD->getInit()) 1811 if (Optional<SVal> V = svalBuilder.getConstantVal(Init)) 1812 return *V; 1813 1814 // This must come after the check for constants because closure-captured 1815 // constant variables may appear in UnknownSpaceRegion. 1816 if (isa<UnknownSpaceRegion>(MS)) 1817 return svalBuilder.getRegionValueSymbolVal(R); 1818 1819 if (isa<GlobalsSpaceRegion>(MS)) { 1820 QualType T = VD->getType(); 1821 1822 // Function-scoped static variables are default-initialized to 0; if they 1823 // have an initializer, it would have been processed by now. 1824 if (isa<StaticGlobalSpaceRegion>(MS)) 1825 return svalBuilder.makeZeroVal(T); 1826 1827 if (Optional<SVal> V = getBindingForDerivedDefaultValue(B, MS, R, T)) { 1828 assert(!V->getAs<nonloc::LazyCompoundVal>()); 1829 return V.getValue(); 1830 } 1831 1832 return svalBuilder.getRegionValueSymbolVal(R); 1833 } 1834 1835 return UndefinedVal(); 1836 } 1837 1838 SVal RegionStoreManager::getBindingForLazySymbol(const TypedValueRegion *R) { 1839 // All other values are symbolic. 1840 return svalBuilder.getRegionValueSymbolVal(R); 1841 } 1842 1843 const RegionStoreManager::SValListTy & 1844 RegionStoreManager::getInterestingValues(nonloc::LazyCompoundVal LCV) { 1845 // First, check the cache. 1846 LazyBindingsMapTy::iterator I = LazyBindingsMap.find(LCV.getCVData()); 1847 if (I != LazyBindingsMap.end()) 1848 return I->second; 1849 1850 // If we don't have a list of values cached, start constructing it. 1851 SValListTy List; 1852 1853 const SubRegion *LazyR = LCV.getRegion(); 1854 RegionBindingsRef B = getRegionBindings(LCV.getStore()); 1855 1856 // If this region had /no/ bindings at the time, there are no interesting 1857 // values to return. 1858 const ClusterBindings *Cluster = B.lookup(LazyR->getBaseRegion()); 1859 if (!Cluster) 1860 return (LazyBindingsMap[LCV.getCVData()] = std::move(List)); 1861 1862 SmallVector<BindingPair, 32> Bindings; 1863 collectSubRegionBindings(Bindings, svalBuilder, *Cluster, LazyR, 1864 /*IncludeAllDefaultBindings=*/true); 1865 for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(), 1866 E = Bindings.end(); 1867 I != E; ++I) { 1868 SVal V = I->second; 1869 if (V.isUnknownOrUndef() || V.isConstant()) 1870 continue; 1871 1872 if (Optional<nonloc::LazyCompoundVal> InnerLCV = 1873 V.getAs<nonloc::LazyCompoundVal>()) { 1874 const SValListTy &InnerList = getInterestingValues(*InnerLCV); 1875 List.insert(List.end(), InnerList.begin(), InnerList.end()); 1876 continue; 1877 } 1878 1879 List.push_back(V); 1880 } 1881 1882 return (LazyBindingsMap[LCV.getCVData()] = std::move(List)); 1883 } 1884 1885 NonLoc RegionStoreManager::createLazyBinding(RegionBindingsConstRef B, 1886 const TypedValueRegion *R) { 1887 if (Optional<nonloc::LazyCompoundVal> V = 1888 getExistingLazyBinding(svalBuilder, B, R, false)) 1889 return *V; 1890 1891 return svalBuilder.makeLazyCompoundVal(StoreRef(B.asStore(), *this), R); 1892 } 1893 1894 static bool isRecordEmpty(const RecordDecl *RD) { 1895 if (!RD->field_empty()) 1896 return false; 1897 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) 1898 return CRD->getNumBases() == 0; 1899 return true; 1900 } 1901 1902 SVal RegionStoreManager::getBindingForStruct(RegionBindingsConstRef B, 1903 const TypedValueRegion *R) { 1904 const RecordDecl *RD = R->getValueType()->castAs<RecordType>()->getDecl(); 1905 if (!RD->getDefinition() || isRecordEmpty(RD)) 1906 return UnknownVal(); 1907 1908 return createLazyBinding(B, R); 1909 } 1910 1911 SVal RegionStoreManager::getBindingForArray(RegionBindingsConstRef B, 1912 const TypedValueRegion *R) { 1913 assert(Ctx.getAsConstantArrayType(R->getValueType()) && 1914 "Only constant array types can have compound bindings."); 1915 1916 return createLazyBinding(B, R); 1917 } 1918 1919 bool RegionStoreManager::includedInBindings(Store store, 1920 const MemRegion *region) const { 1921 RegionBindingsRef B = getRegionBindings(store); 1922 region = region->getBaseRegion(); 1923 1924 // Quick path: if the base is the head of a cluster, the region is live. 1925 if (B.lookup(region)) 1926 return true; 1927 1928 // Slow path: if the region is the VALUE of any binding, it is live. 1929 for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI) { 1930 const ClusterBindings &Cluster = RI.getData(); 1931 for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end(); 1932 CI != CE; ++CI) { 1933 const SVal &D = CI.getData(); 1934 if (const MemRegion *R = D.getAsRegion()) 1935 if (R->getBaseRegion() == region) 1936 return true; 1937 } 1938 } 1939 1940 return false; 1941 } 1942 1943 //===----------------------------------------------------------------------===// 1944 // Binding values to regions. 1945 //===----------------------------------------------------------------------===// 1946 1947 StoreRef RegionStoreManager::killBinding(Store ST, Loc L) { 1948 if (Optional<loc::MemRegionVal> LV = L.getAs<loc::MemRegionVal>()) 1949 if (const MemRegion* R = LV->getRegion()) 1950 return StoreRef(getRegionBindings(ST).removeBinding(R) 1951 .asImmutableMap() 1952 .getRootWithoutRetain(), 1953 *this); 1954 1955 return StoreRef(ST, *this); 1956 } 1957 1958 RegionBindingsRef 1959 RegionStoreManager::bind(RegionBindingsConstRef B, Loc L, SVal V) { 1960 if (L.getAs<loc::ConcreteInt>()) 1961 return B; 1962 1963 // If we get here, the location should be a region. 1964 const MemRegion *R = L.castAs<loc::MemRegionVal>().getRegion(); 1965 1966 // Check if the region is a struct region. 1967 if (const TypedValueRegion* TR = dyn_cast<TypedValueRegion>(R)) { 1968 QualType Ty = TR->getValueType(); 1969 if (Ty->isArrayType()) 1970 return bindArray(B, TR, V); 1971 if (Ty->isStructureOrClassType()) 1972 return bindStruct(B, TR, V); 1973 if (Ty->isVectorType()) 1974 return bindVector(B, TR, V); 1975 if (Ty->isUnionType()) 1976 return bindAggregate(B, TR, V); 1977 } 1978 1979 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) { 1980 // Binding directly to a symbolic region should be treated as binding 1981 // to element 0. 1982 QualType T = SR->getSymbol()->getType(); 1983 if (T->isAnyPointerType() || T->isReferenceType()) 1984 T = T->getPointeeType(); 1985 1986 R = GetElementZeroRegion(SR, T); 1987 } 1988 1989 // Clear out bindings that may overlap with this binding. 1990 RegionBindingsRef NewB = removeSubRegionBindings(B, cast<SubRegion>(R)); 1991 return NewB.addBinding(BindingKey::Make(R, BindingKey::Direct), V); 1992 } 1993 1994 RegionBindingsRef 1995 RegionStoreManager::setImplicitDefaultValue(RegionBindingsConstRef B, 1996 const MemRegion *R, 1997 QualType T) { 1998 SVal V; 1999 2000 if (Loc::isLocType(T)) 2001 V = svalBuilder.makeNull(); 2002 else if (T->isIntegralOrEnumerationType()) 2003 V = svalBuilder.makeZeroVal(T); 2004 else if (T->isStructureOrClassType() || T->isArrayType()) { 2005 // Set the default value to a zero constant when it is a structure 2006 // or array. The type doesn't really matter. 2007 V = svalBuilder.makeZeroVal(Ctx.IntTy); 2008 } 2009 else { 2010 // We can't represent values of this type, but we still need to set a value 2011 // to record that the region has been initialized. 2012 // If this assertion ever fires, a new case should be added above -- we 2013 // should know how to default-initialize any value we can symbolicate. 2014 assert(!SymbolManager::canSymbolicate(T) && "This type is representable"); 2015 V = UnknownVal(); 2016 } 2017 2018 return B.addBinding(R, BindingKey::Default, V); 2019 } 2020 2021 RegionBindingsRef 2022 RegionStoreManager::bindArray(RegionBindingsConstRef B, 2023 const TypedValueRegion* R, 2024 SVal Init) { 2025 2026 const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType())); 2027 QualType ElementTy = AT->getElementType(); 2028 Optional<uint64_t> Size; 2029 2030 if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT)) 2031 Size = CAT->getSize().getZExtValue(); 2032 2033 // Check if the init expr is a string literal. 2034 if (Optional<loc::MemRegionVal> MRV = Init.getAs<loc::MemRegionVal>()) { 2035 const StringRegion *S = cast<StringRegion>(MRV->getRegion()); 2036 2037 // Treat the string as a lazy compound value. 2038 StoreRef store(B.asStore(), *this); 2039 nonloc::LazyCompoundVal LCV = svalBuilder.makeLazyCompoundVal(store, S) 2040 .castAs<nonloc::LazyCompoundVal>(); 2041 return bindAggregate(B, R, LCV); 2042 } 2043 2044 // Handle lazy compound values. 2045 if (Init.getAs<nonloc::LazyCompoundVal>()) 2046 return bindAggregate(B, R, Init); 2047 2048 // Remaining case: explicit compound values. 2049 2050 if (Init.isUnknown()) 2051 return setImplicitDefaultValue(B, R, ElementTy); 2052 2053 const nonloc::CompoundVal& CV = Init.castAs<nonloc::CompoundVal>(); 2054 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end(); 2055 uint64_t i = 0; 2056 2057 RegionBindingsRef NewB(B); 2058 2059 for (; Size.hasValue() ? i < Size.getValue() : true ; ++i, ++VI) { 2060 // The init list might be shorter than the array length. 2061 if (VI == VE) 2062 break; 2063 2064 const NonLoc &Idx = svalBuilder.makeArrayIndex(i); 2065 const ElementRegion *ER = MRMgr.getElementRegion(ElementTy, Idx, R, Ctx); 2066 2067 if (ElementTy->isStructureOrClassType()) 2068 NewB = bindStruct(NewB, ER, *VI); 2069 else if (ElementTy->isArrayType()) 2070 NewB = bindArray(NewB, ER, *VI); 2071 else 2072 NewB = bind(NewB, loc::MemRegionVal(ER), *VI); 2073 } 2074 2075 // If the init list is shorter than the array length, set the 2076 // array default value. 2077 if (Size.hasValue() && i < Size.getValue()) 2078 NewB = setImplicitDefaultValue(NewB, R, ElementTy); 2079 2080 return NewB; 2081 } 2082 2083 RegionBindingsRef RegionStoreManager::bindVector(RegionBindingsConstRef B, 2084 const TypedValueRegion* R, 2085 SVal V) { 2086 QualType T = R->getValueType(); 2087 assert(T->isVectorType()); 2088 const VectorType *VT = T->getAs<VectorType>(); // Use getAs for typedefs. 2089 2090 // Handle lazy compound values and symbolic values. 2091 if (V.getAs<nonloc::LazyCompoundVal>() || V.getAs<nonloc::SymbolVal>()) 2092 return bindAggregate(B, R, V); 2093 2094 // We may get non-CompoundVal accidentally due to imprecise cast logic or 2095 // that we are binding symbolic struct value. Kill the field values, and if 2096 // the value is symbolic go and bind it as a "default" binding. 2097 if (!V.getAs<nonloc::CompoundVal>()) { 2098 return bindAggregate(B, R, UnknownVal()); 2099 } 2100 2101 QualType ElemType = VT->getElementType(); 2102 nonloc::CompoundVal CV = V.castAs<nonloc::CompoundVal>(); 2103 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end(); 2104 unsigned index = 0, numElements = VT->getNumElements(); 2105 RegionBindingsRef NewB(B); 2106 2107 for ( ; index != numElements ; ++index) { 2108 if (VI == VE) 2109 break; 2110 2111 NonLoc Idx = svalBuilder.makeArrayIndex(index); 2112 const ElementRegion *ER = MRMgr.getElementRegion(ElemType, Idx, R, Ctx); 2113 2114 if (ElemType->isArrayType()) 2115 NewB = bindArray(NewB, ER, *VI); 2116 else if (ElemType->isStructureOrClassType()) 2117 NewB = bindStruct(NewB, ER, *VI); 2118 else 2119 NewB = bind(NewB, loc::MemRegionVal(ER), *VI); 2120 } 2121 return NewB; 2122 } 2123 2124 Optional<RegionBindingsRef> 2125 RegionStoreManager::tryBindSmallStruct(RegionBindingsConstRef B, 2126 const TypedValueRegion *R, 2127 const RecordDecl *RD, 2128 nonloc::LazyCompoundVal LCV) { 2129 FieldVector Fields; 2130 2131 if (const CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(RD)) 2132 if (Class->getNumBases() != 0 || Class->getNumVBases() != 0) 2133 return None; 2134 2135 for (const auto *FD : RD->fields()) { 2136 if (FD->isUnnamedBitfield()) 2137 continue; 2138 2139 // If there are too many fields, or if any of the fields are aggregates, 2140 // just use the LCV as a default binding. 2141 if (Fields.size() == SmallStructLimit) 2142 return None; 2143 2144 QualType Ty = FD->getType(); 2145 if (!(Ty->isScalarType() || Ty->isReferenceType())) 2146 return None; 2147 2148 Fields.push_back(FD); 2149 } 2150 2151 RegionBindingsRef NewB = B; 2152 2153 for (FieldVector::iterator I = Fields.begin(), E = Fields.end(); I != E; ++I){ 2154 const FieldRegion *SourceFR = MRMgr.getFieldRegion(*I, LCV.getRegion()); 2155 SVal V = getBindingForField(getRegionBindings(LCV.getStore()), SourceFR); 2156 2157 const FieldRegion *DestFR = MRMgr.getFieldRegion(*I, R); 2158 NewB = bind(NewB, loc::MemRegionVal(DestFR), V); 2159 } 2160 2161 return NewB; 2162 } 2163 2164 RegionBindingsRef RegionStoreManager::bindStruct(RegionBindingsConstRef B, 2165 const TypedValueRegion* R, 2166 SVal V) { 2167 if (!Features.supportsFields()) 2168 return B; 2169 2170 QualType T = R->getValueType(); 2171 assert(T->isStructureOrClassType()); 2172 2173 const RecordType* RT = T->getAs<RecordType>(); 2174 const RecordDecl *RD = RT->getDecl(); 2175 2176 if (!RD->isCompleteDefinition()) 2177 return B; 2178 2179 // Handle lazy compound values and symbolic values. 2180 if (Optional<nonloc::LazyCompoundVal> LCV = 2181 V.getAs<nonloc::LazyCompoundVal>()) { 2182 if (Optional<RegionBindingsRef> NewB = tryBindSmallStruct(B, R, RD, *LCV)) 2183 return *NewB; 2184 return bindAggregate(B, R, V); 2185 } 2186 if (V.getAs<nonloc::SymbolVal>()) 2187 return bindAggregate(B, R, V); 2188 2189 // We may get non-CompoundVal accidentally due to imprecise cast logic or 2190 // that we are binding symbolic struct value. Kill the field values, and if 2191 // the value is symbolic go and bind it as a "default" binding. 2192 if (V.isUnknown() || !V.getAs<nonloc::CompoundVal>()) 2193 return bindAggregate(B, R, UnknownVal()); 2194 2195 const nonloc::CompoundVal& CV = V.castAs<nonloc::CompoundVal>(); 2196 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end(); 2197 2198 RecordDecl::field_iterator FI, FE; 2199 RegionBindingsRef NewB(B); 2200 2201 for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; ++FI) { 2202 2203 if (VI == VE) 2204 break; 2205 2206 // Skip any unnamed bitfields to stay in sync with the initializers. 2207 if (FI->isUnnamedBitfield()) 2208 continue; 2209 2210 QualType FTy = FI->getType(); 2211 const FieldRegion* FR = MRMgr.getFieldRegion(*FI, R); 2212 2213 if (FTy->isArrayType()) 2214 NewB = bindArray(NewB, FR, *VI); 2215 else if (FTy->isStructureOrClassType()) 2216 NewB = bindStruct(NewB, FR, *VI); 2217 else 2218 NewB = bind(NewB, loc::MemRegionVal(FR), *VI); 2219 ++VI; 2220 } 2221 2222 // There may be fewer values in the initialize list than the fields of struct. 2223 if (FI != FE) { 2224 NewB = NewB.addBinding(R, BindingKey::Default, 2225 svalBuilder.makeIntVal(0, false)); 2226 } 2227 2228 return NewB; 2229 } 2230 2231 RegionBindingsRef 2232 RegionStoreManager::bindAggregate(RegionBindingsConstRef B, 2233 const TypedRegion *R, 2234 SVal Val) { 2235 // Remove the old bindings, using 'R' as the root of all regions 2236 // we will invalidate. Then add the new binding. 2237 return removeSubRegionBindings(B, R).addBinding(R, BindingKey::Default, Val); 2238 } 2239 2240 //===----------------------------------------------------------------------===// 2241 // State pruning. 2242 //===----------------------------------------------------------------------===// 2243 2244 namespace { 2245 class removeDeadBindingsWorker : 2246 public ClusterAnalysis<removeDeadBindingsWorker> { 2247 SmallVector<const SymbolicRegion*, 12> Postponed; 2248 SymbolReaper &SymReaper; 2249 const StackFrameContext *CurrentLCtx; 2250 2251 public: 2252 removeDeadBindingsWorker(RegionStoreManager &rm, 2253 ProgramStateManager &stateMgr, 2254 RegionBindingsRef b, SymbolReaper &symReaper, 2255 const StackFrameContext *LCtx) 2256 : ClusterAnalysis<removeDeadBindingsWorker>(rm, stateMgr, b, GFK_None), 2257 SymReaper(symReaper), CurrentLCtx(LCtx) {} 2258 2259 // Called by ClusterAnalysis. 2260 void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C); 2261 void VisitCluster(const MemRegion *baseR, const ClusterBindings *C); 2262 using ClusterAnalysis<removeDeadBindingsWorker>::VisitCluster; 2263 2264 using ClusterAnalysis::AddToWorkList; 2265 2266 bool AddToWorkList(const MemRegion *R); 2267 2268 bool UpdatePostponed(); 2269 void VisitBinding(SVal V); 2270 }; 2271 } 2272 2273 bool removeDeadBindingsWorker::AddToWorkList(const MemRegion *R) { 2274 const MemRegion *BaseR = R->getBaseRegion(); 2275 return AddToWorkList(WorkListElement(BaseR), getCluster(BaseR)); 2276 } 2277 2278 void removeDeadBindingsWorker::VisitAddedToCluster(const MemRegion *baseR, 2279 const ClusterBindings &C) { 2280 2281 if (const VarRegion *VR = dyn_cast<VarRegion>(baseR)) { 2282 if (SymReaper.isLive(VR)) 2283 AddToWorkList(baseR, &C); 2284 2285 return; 2286 } 2287 2288 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) { 2289 if (SymReaper.isLive(SR->getSymbol())) 2290 AddToWorkList(SR, &C); 2291 else 2292 Postponed.push_back(SR); 2293 2294 return; 2295 } 2296 2297 if (isa<NonStaticGlobalSpaceRegion>(baseR)) { 2298 AddToWorkList(baseR, &C); 2299 return; 2300 } 2301 2302 // CXXThisRegion in the current or parent location context is live. 2303 if (const CXXThisRegion *TR = dyn_cast<CXXThisRegion>(baseR)) { 2304 const StackArgumentsSpaceRegion *StackReg = 2305 cast<StackArgumentsSpaceRegion>(TR->getSuperRegion()); 2306 const StackFrameContext *RegCtx = StackReg->getStackFrame(); 2307 if (CurrentLCtx && 2308 (RegCtx == CurrentLCtx || RegCtx->isParentOf(CurrentLCtx))) 2309 AddToWorkList(TR, &C); 2310 } 2311 } 2312 2313 void removeDeadBindingsWorker::VisitCluster(const MemRegion *baseR, 2314 const ClusterBindings *C) { 2315 if (!C) 2316 return; 2317 2318 // Mark the symbol for any SymbolicRegion with live bindings as live itself. 2319 // This means we should continue to track that symbol. 2320 if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(baseR)) 2321 SymReaper.markLive(SymR->getSymbol()); 2322 2323 for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I) 2324 VisitBinding(I.getData()); 2325 } 2326 2327 void removeDeadBindingsWorker::VisitBinding(SVal V) { 2328 // Is it a LazyCompoundVal? All referenced regions are live as well. 2329 if (Optional<nonloc::LazyCompoundVal> LCS = 2330 V.getAs<nonloc::LazyCompoundVal>()) { 2331 2332 const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS); 2333 2334 for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(), 2335 E = Vals.end(); 2336 I != E; ++I) 2337 VisitBinding(*I); 2338 2339 return; 2340 } 2341 2342 // If V is a region, then add it to the worklist. 2343 if (const MemRegion *R = V.getAsRegion()) { 2344 AddToWorkList(R); 2345 2346 // All regions captured by a block are also live. 2347 if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(R)) { 2348 BlockDataRegion::referenced_vars_iterator I = BR->referenced_vars_begin(), 2349 E = BR->referenced_vars_end(); 2350 for ( ; I != E; ++I) 2351 AddToWorkList(I.getCapturedRegion()); 2352 } 2353 } 2354 2355 2356 // Update the set of live symbols. 2357 for (SymExpr::symbol_iterator SI = V.symbol_begin(), SE = V.symbol_end(); 2358 SI!=SE; ++SI) 2359 SymReaper.markLive(*SI); 2360 } 2361 2362 bool removeDeadBindingsWorker::UpdatePostponed() { 2363 // See if any postponed SymbolicRegions are actually live now, after 2364 // having done a scan. 2365 bool changed = false; 2366 2367 for (SmallVectorImpl<const SymbolicRegion*>::iterator 2368 I = Postponed.begin(), E = Postponed.end() ; I != E ; ++I) { 2369 if (const SymbolicRegion *SR = *I) { 2370 if (SymReaper.isLive(SR->getSymbol())) { 2371 changed |= AddToWorkList(SR); 2372 *I = nullptr; 2373 } 2374 } 2375 } 2376 2377 return changed; 2378 } 2379 2380 StoreRef RegionStoreManager::removeDeadBindings(Store store, 2381 const StackFrameContext *LCtx, 2382 SymbolReaper& SymReaper) { 2383 RegionBindingsRef B = getRegionBindings(store); 2384 removeDeadBindingsWorker W(*this, StateMgr, B, SymReaper, LCtx); 2385 W.GenerateClusters(); 2386 2387 // Enqueue the region roots onto the worklist. 2388 for (SymbolReaper::region_iterator I = SymReaper.region_begin(), 2389 E = SymReaper.region_end(); I != E; ++I) { 2390 W.AddToWorkList(*I); 2391 } 2392 2393 do W.RunWorkList(); while (W.UpdatePostponed()); 2394 2395 // We have now scanned the store, marking reachable regions and symbols 2396 // as live. We now remove all the regions that are dead from the store 2397 // as well as update DSymbols with the set symbols that are now dead. 2398 for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; ++I) { 2399 const MemRegion *Base = I.getKey(); 2400 2401 // If the cluster has been visited, we know the region has been marked. 2402 if (W.isVisited(Base)) 2403 continue; 2404 2405 // Remove the dead entry. 2406 B = B.remove(Base); 2407 2408 if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(Base)) 2409 SymReaper.maybeDead(SymR->getSymbol()); 2410 2411 // Mark all non-live symbols that this binding references as dead. 2412 const ClusterBindings &Cluster = I.getData(); 2413 for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end(); 2414 CI != CE; ++CI) { 2415 SVal X = CI.getData(); 2416 SymExpr::symbol_iterator SI = X.symbol_begin(), SE = X.symbol_end(); 2417 for (; SI != SE; ++SI) 2418 SymReaper.maybeDead(*SI); 2419 } 2420 } 2421 2422 return StoreRef(B.asStore(), *this); 2423 } 2424 2425 //===----------------------------------------------------------------------===// 2426 // Utility methods. 2427 //===----------------------------------------------------------------------===// 2428 2429 void RegionStoreManager::print(Store store, raw_ostream &OS, 2430 const char* nl, const char *sep) { 2431 RegionBindingsRef B = getRegionBindings(store); 2432 OS << "Store (direct and default bindings), " 2433 << B.asStore() 2434 << " :" << nl; 2435 B.dump(OS, nl); 2436 } 2437