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