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