RegionStore.cpp revision e0d24eb1060a213ec9820dc02c45f26b2d5b348b
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/CharUnits.h" 18#include "clang/AST/DeclCXX.h" 19#include "clang/AST/ExprCXX.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/CallEvent.h" 24#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 25#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" 26#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h" 27#include "llvm/ADT/ImmutableList.h" 28#include "llvm/ADT/ImmutableMap.h" 29#include "llvm/ADT/Optional.h" 30#include "llvm/Support/raw_ostream.h" 31 32using namespace clang; 33using namespace ento; 34using llvm::Optional; 35 36//===----------------------------------------------------------------------===// 37// Representation of binding keys. 38//===----------------------------------------------------------------------===// 39 40namespace { 41class BindingKey { 42public: 43 enum Kind { Direct = 0x0, Default = 0x1 }; 44private: 45 enum { SYMBOLIC = UINT64_MAX }; 46 47 llvm::PointerIntPair<const MemRegion *, 1, Kind> P; 48 uint64_t Offset; 49 50 explicit BindingKey(const MemRegion *r, Kind k) 51 : P(r, k), Offset(SYMBOLIC) {} 52 explicit BindingKey(const MemRegion *r, uint64_t offset, Kind k) 53 : P(r, k), Offset(offset) {} 54public: 55 56 bool isDirect() const { return P.getInt() == Direct; } 57 bool hasSymbolicOffset() const { return Offset == SYMBOLIC; } 58 59 const MemRegion *getRegion() const { return P.getPointer(); } 60 uint64_t getOffset() const { 61 assert(!hasSymbolicOffset()); 62 return Offset; 63 } 64 65 const MemRegion *getConcreteOffsetRegion() const; 66 67 void Profile(llvm::FoldingSetNodeID& ID) const { 68 ID.AddPointer(P.getOpaqueValue()); 69 ID.AddInteger(Offset); 70 } 71 72 static BindingKey Make(const MemRegion *R, Kind k); 73 74 bool operator<(const BindingKey &X) const { 75 if (P.getOpaqueValue() < X.P.getOpaqueValue()) 76 return true; 77 if (P.getOpaqueValue() > X.P.getOpaqueValue()) 78 return false; 79 return Offset < X.Offset; 80 } 81 82 bool operator==(const BindingKey &X) const { 83 return P.getOpaqueValue() == X.P.getOpaqueValue() && 84 Offset == X.Offset; 85 } 86 87 bool isValid() const { 88 return getRegion() != NULL; 89 } 90}; 91} // end anonymous namespace 92 93BindingKey BindingKey::Make(const MemRegion *R, Kind k) { 94 const RegionOffset &RO = R->getAsOffset(); 95 if (RO.isValid()) 96 return BindingKey(RO.getRegion(), RO.getOffset(), k); 97 98 return BindingKey(R, k); 99} 100 101const MemRegion *BindingKey::getConcreteOffsetRegion() const { 102 const MemRegion *R = getRegion(); 103 if (!hasSymbolicOffset()) 104 return R; 105 106 RegionOffset RO; 107 do { 108 const SubRegion *SR = dyn_cast<SubRegion>(R); 109 if (!SR) 110 break; 111 R = SR->getSuperRegion(); 112 RO = R->getAsOffset(); 113 } while (!RO.isValid()); 114 115 return R; 116} 117 118namespace llvm { 119 static inline 120 raw_ostream &operator<<(raw_ostream &os, BindingKey K) { 121 os << '(' << K.getRegion(); 122 if (!K.hasSymbolicOffset()) 123 os << ',' << K.getOffset(); 124 os << ',' << (K.isDirect() ? "direct" : "default") 125 << ')'; 126 return os; 127 } 128} // end llvm namespace 129 130//===----------------------------------------------------------------------===// 131// Actual Store type. 132//===----------------------------------------------------------------------===// 133 134typedef llvm::ImmutableMap<BindingKey, SVal> RegionBindings; 135 136//===----------------------------------------------------------------------===// 137// Fine-grained control of RegionStoreManager. 138//===----------------------------------------------------------------------===// 139 140namespace { 141struct minimal_features_tag {}; 142struct maximal_features_tag {}; 143 144class RegionStoreFeatures { 145 bool SupportsFields; 146public: 147 RegionStoreFeatures(minimal_features_tag) : 148 SupportsFields(false) {} 149 150 RegionStoreFeatures(maximal_features_tag) : 151 SupportsFields(true) {} 152 153 void enableFields(bool t) { SupportsFields = t; } 154 155 bool supportsFields() const { return SupportsFields; } 156}; 157} 158 159//===----------------------------------------------------------------------===// 160// Main RegionStore logic. 161//===----------------------------------------------------------------------===// 162 163namespace { 164 165class RegionStoreManager : public StoreManager { 166 const RegionStoreFeatures Features; 167 RegionBindings::Factory RBFactory; 168 169public: 170 RegionStoreManager(ProgramStateManager& mgr, const RegionStoreFeatures &f) 171 : StoreManager(mgr), 172 Features(f), 173 RBFactory(mgr.getAllocator()) {} 174 175 Optional<SVal> getDirectBinding(RegionBindings B, const MemRegion *R); 176 /// getDefaultBinding - Returns an SVal* representing an optional default 177 /// binding associated with a region and its subregions. 178 Optional<SVal> getDefaultBinding(RegionBindings B, const MemRegion *R); 179 180 /// setImplicitDefaultValue - Set the default binding for the provided 181 /// MemRegion to the value implicitly defined for compound literals when 182 /// the value is not specified. 183 StoreRef setImplicitDefaultValue(Store store, const MemRegion *R, QualType T); 184 185 /// ArrayToPointer - Emulates the "decay" of an array to a pointer 186 /// type. 'Array' represents the lvalue of the array being decayed 187 /// to a pointer, and the returned SVal represents the decayed 188 /// version of that lvalue (i.e., a pointer to the first element of 189 /// the array). This is called by ExprEngine when evaluating 190 /// casts from arrays to pointers. 191 SVal ArrayToPointer(Loc Array); 192 193 /// For DerivedToBase casts, create a CXXBaseObjectRegion and return it. 194 virtual SVal evalDerivedToBase(SVal derived, QualType basePtrType); 195 196 /// \brief Evaluates C++ dynamic_cast cast. 197 /// The callback may result in the following 3 scenarios: 198 /// - Successful cast (ex: derived is subclass of base). 199 /// - Failed cast (ex: derived is definitely not a subclass of base). 200 /// - We don't know (base is a symbolic region and we don't have 201 /// enough info to determine if the cast will succeed at run time). 202 /// The function returns an SVal representing the derived class; it's 203 /// valid only if Failed flag is set to false. 204 virtual SVal evalDynamicCast(SVal base, QualType derivedPtrType,bool &Failed); 205 206 StoreRef getInitialStore(const LocationContext *InitLoc) { 207 return StoreRef(RBFactory.getEmptyMap().getRootWithoutRetain(), *this); 208 } 209 210 //===-------------------------------------------------------------------===// 211 // Binding values to regions. 212 //===-------------------------------------------------------------------===// 213 RegionBindings invalidateGlobalRegion(MemRegion::Kind K, 214 const Expr *Ex, 215 unsigned Count, 216 const LocationContext *LCtx, 217 RegionBindings B, 218 InvalidatedRegions *Invalidated); 219 220 StoreRef invalidateRegions(Store store, ArrayRef<const MemRegion *> Regions, 221 const Expr *E, unsigned Count, 222 const LocationContext *LCtx, 223 InvalidatedSymbols &IS, 224 const CallEvent *Call, 225 InvalidatedRegions *Invalidated); 226 227 bool scanReachableSymbols(Store S, const MemRegion *R, 228 ScanReachableSymbols &Callbacks); 229 230public: // Made public for helper classes. 231 232 RegionBindings removeSubRegionBindings(RegionBindings B, const SubRegion *R); 233 234 RegionBindings addBinding(RegionBindings B, BindingKey K, SVal V); 235 236 RegionBindings addBinding(RegionBindings B, const MemRegion *R, 237 BindingKey::Kind k, SVal V); 238 239 const SVal *lookup(RegionBindings B, BindingKey K); 240 const SVal *lookup(RegionBindings B, const MemRegion *R, BindingKey::Kind k); 241 242 RegionBindings removeBinding(RegionBindings B, BindingKey K); 243 RegionBindings removeBinding(RegionBindings B, const MemRegion *R, 244 BindingKey::Kind k); 245 246 RegionBindings removeBinding(RegionBindings B, const MemRegion *R) { 247 return removeBinding(removeBinding(B, R, BindingKey::Direct), R, 248 BindingKey::Default); 249 } 250 251public: // Part of public interface to class. 252 253 StoreRef Bind(Store store, Loc LV, SVal V); 254 255 // BindDefault is only used to initialize a region with a default value. 256 StoreRef BindDefault(Store store, const MemRegion *R, SVal V) { 257 RegionBindings B = GetRegionBindings(store); 258 assert(!lookup(B, R, BindingKey::Default)); 259 assert(!lookup(B, R, BindingKey::Direct)); 260 return StoreRef(addBinding(B, R, BindingKey::Default, V) 261 .getRootWithoutRetain(), *this); 262 } 263 264 StoreRef BindCompoundLiteral(Store store, const CompoundLiteralExpr *CL, 265 const LocationContext *LC, SVal V); 266 267 StoreRef BindDecl(Store store, const VarRegion *VR, SVal InitVal); 268 269 StoreRef BindDeclWithNoInit(Store store, const VarRegion *) { 270 return StoreRef(store, *this); 271 } 272 273 /// BindStruct - Bind a compound value to a structure. 274 StoreRef BindStruct(Store store, const TypedValueRegion* R, SVal V); 275 276 /// BindVector - Bind a compound value to a vector. 277 StoreRef BindVector(Store store, const TypedValueRegion* R, SVal V); 278 279 StoreRef BindArray(Store store, const TypedValueRegion* R, SVal V); 280 281 /// KillStruct - Set the entire struct to unknown. 282 StoreRef KillStruct(Store store, const TypedRegion* R, SVal DefaultVal); 283 284 StoreRef Remove(Store store, Loc LV); 285 286 void incrementReferenceCount(Store store) { 287 GetRegionBindings(store).manualRetain(); 288 } 289 290 /// If the StoreManager supports it, decrement the reference count of 291 /// the specified Store object. If the reference count hits 0, the memory 292 /// associated with the object is recycled. 293 void decrementReferenceCount(Store store) { 294 GetRegionBindings(store).manualRelease(); 295 } 296 297 bool includedInBindings(Store store, const MemRegion *region) const; 298 299 /// \brief Return the value bound to specified location in a given state. 300 /// 301 /// The high level logic for this method is this: 302 /// getBinding (L) 303 /// if L has binding 304 /// return L's binding 305 /// else if L is in killset 306 /// return unknown 307 /// else 308 /// if L is on stack or heap 309 /// return undefined 310 /// else 311 /// return symbolic 312 SVal getBinding(Store store, Loc L, QualType T = QualType()); 313 314 SVal getBindingForElement(Store store, const ElementRegion *R); 315 316 SVal getBindingForField(Store store, const FieldRegion *R); 317 318 SVal getBindingForObjCIvar(Store store, const ObjCIvarRegion *R); 319 320 SVal getBindingForVar(Store store, const VarRegion *R); 321 322 SVal getBindingForLazySymbol(const TypedValueRegion *R); 323 324 SVal getBindingForFieldOrElementCommon(Store store, const TypedValueRegion *R, 325 QualType Ty, const MemRegion *superR); 326 327 SVal getLazyBinding(const MemRegion *lazyBindingRegion, 328 Store lazyBindingStore); 329 330 /// Get bindings for the values in a struct and return a CompoundVal, used 331 /// when doing struct copy: 332 /// struct s x, y; 333 /// x = y; 334 /// y's value is retrieved by this method. 335 SVal getBindingForStruct(Store store, const TypedValueRegion* R); 336 337 SVal getBindingForArray(Store store, const TypedValueRegion* R); 338 339 /// Used to lazily generate derived symbols for bindings that are defined 340 /// implicitly by default bindings in a super region. 341 Optional<SVal> getBindingForDerivedDefaultValue(RegionBindings B, 342 const MemRegion *superR, 343 const TypedValueRegion *R, 344 QualType Ty); 345 346 /// Get the state and region whose binding this region R corresponds to. 347 std::pair<Store, const MemRegion*> 348 GetLazyBinding(RegionBindings B, const MemRegion *R, 349 const MemRegion *originalRegion, 350 bool includeSuffix = false); 351 352 StoreRef CopyLazyBindings(nonloc::LazyCompoundVal V, Store store, 353 const TypedRegion *R); 354 355 //===------------------------------------------------------------------===// 356 // State pruning. 357 //===------------------------------------------------------------------===// 358 359 /// removeDeadBindings - Scans the RegionStore of 'state' for dead values. 360 /// It returns a new Store with these values removed. 361 StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx, 362 SymbolReaper& SymReaper); 363 364 //===------------------------------------------------------------------===// 365 // Region "extents". 366 //===------------------------------------------------------------------===// 367 368 // FIXME: This method will soon be eliminated; see the note in Store.h. 369 DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state, 370 const MemRegion* R, QualType EleTy); 371 372 //===------------------------------------------------------------------===// 373 // Utility methods. 374 //===------------------------------------------------------------------===// 375 376 static inline RegionBindings GetRegionBindings(Store store) { 377 return RegionBindings(static_cast<const RegionBindings::TreeTy*>(store)); 378 } 379 380 void print(Store store, raw_ostream &Out, const char* nl, 381 const char *sep); 382 383 void iterBindings(Store store, BindingsHandler& f) { 384 RegionBindings B = GetRegionBindings(store); 385 for (RegionBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) { 386 const BindingKey &K = I.getKey(); 387 if (!K.isDirect()) 388 continue; 389 if (const SubRegion *R = dyn_cast<SubRegion>(I.getKey().getRegion())) { 390 // FIXME: Possibly incorporate the offset? 391 if (!f.HandleBinding(*this, store, R, I.getData())) 392 return; 393 } 394 } 395 } 396}; 397 398} // end anonymous namespace 399 400//===----------------------------------------------------------------------===// 401// RegionStore creation. 402//===----------------------------------------------------------------------===// 403 404StoreManager *ento::CreateRegionStoreManager(ProgramStateManager& StMgr) { 405 RegionStoreFeatures F = maximal_features_tag(); 406 return new RegionStoreManager(StMgr, F); 407} 408 409StoreManager * 410ento::CreateFieldsOnlyRegionStoreManager(ProgramStateManager &StMgr) { 411 RegionStoreFeatures F = minimal_features_tag(); 412 F.enableFields(true); 413 return new RegionStoreManager(StMgr, F); 414} 415 416 417//===----------------------------------------------------------------------===// 418// Region Cluster analysis. 419//===----------------------------------------------------------------------===// 420 421namespace { 422template <typename DERIVED> 423class ClusterAnalysis { 424protected: 425 typedef BumpVector<BindingKey> RegionCluster; 426 typedef llvm::DenseMap<const MemRegion *, RegionCluster *> ClusterMap; 427 llvm::DenseMap<const RegionCluster*, unsigned> Visited; 428 typedef SmallVector<std::pair<const MemRegion *, RegionCluster*>, 10> 429 WorkList; 430 431 BumpVectorContext BVC; 432 ClusterMap ClusterM; 433 WorkList WL; 434 435 RegionStoreManager &RM; 436 ASTContext &Ctx; 437 SValBuilder &svalBuilder; 438 439 RegionBindings B; 440 441 const bool includeGlobals; 442 443public: 444 ClusterAnalysis(RegionStoreManager &rm, ProgramStateManager &StateMgr, 445 RegionBindings b, const bool includeGlobals) 446 : RM(rm), Ctx(StateMgr.getContext()), 447 svalBuilder(StateMgr.getSValBuilder()), 448 B(b), includeGlobals(includeGlobals) {} 449 450 RegionBindings getRegionBindings() const { return B; } 451 452 RegionCluster &AddToCluster(BindingKey K) { 453 const MemRegion *R = K.getRegion(); 454 const MemRegion *baseR = R->getBaseRegion(); 455 RegionCluster &C = getCluster(baseR); 456 C.push_back(K, BVC); 457 static_cast<DERIVED*>(this)->VisitAddedToCluster(baseR, C); 458 return C; 459 } 460 461 bool isVisited(const MemRegion *R) { 462 return (bool) Visited[&getCluster(R->getBaseRegion())]; 463 } 464 465 RegionCluster& getCluster(const MemRegion *R) { 466 RegionCluster *&CRef = ClusterM[R]; 467 if (!CRef) { 468 void *Mem = BVC.getAllocator().template Allocate<RegionCluster>(); 469 CRef = new (Mem) RegionCluster(BVC, 10); 470 } 471 return *CRef; 472 } 473 474 void GenerateClusters() { 475 // Scan the entire set of bindings and make the region clusters. 476 for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){ 477 RegionCluster &C = AddToCluster(RI.getKey()); 478 if (const MemRegion *R = RI.getData().getAsRegion()) { 479 // Generate a cluster, but don't add the region to the cluster 480 // if there aren't any bindings. 481 getCluster(R->getBaseRegion()); 482 } 483 if (includeGlobals) { 484 const MemRegion *R = RI.getKey().getRegion(); 485 if (isa<NonStaticGlobalSpaceRegion>(R->getMemorySpace())) 486 AddToWorkList(R, C); 487 } 488 } 489 } 490 491 bool AddToWorkList(const MemRegion *R, RegionCluster &C) { 492 if (unsigned &visited = Visited[&C]) 493 return false; 494 else 495 visited = 1; 496 497 WL.push_back(std::make_pair(R, &C)); 498 return true; 499 } 500 501 bool AddToWorkList(BindingKey K) { 502 return AddToWorkList(K.getRegion()); 503 } 504 505 bool AddToWorkList(const MemRegion *R) { 506 const MemRegion *baseR = R->getBaseRegion(); 507 return AddToWorkList(baseR, getCluster(baseR)); 508 } 509 510 void RunWorkList() { 511 while (!WL.empty()) { 512 const MemRegion *baseR; 513 RegionCluster *C; 514 llvm::tie(baseR, C) = WL.back(); 515 WL.pop_back(); 516 517 // First visit the cluster. 518 static_cast<DERIVED*>(this)->VisitCluster(baseR, C->begin(), C->end()); 519 520 // Next, visit the base region. 521 static_cast<DERIVED*>(this)->VisitBaseRegion(baseR); 522 } 523 } 524 525public: 526 void VisitAddedToCluster(const MemRegion *baseR, RegionCluster &C) {} 527 void VisitCluster(const MemRegion *baseR, BindingKey *I, BindingKey *E) {} 528 void VisitBaseRegion(const MemRegion *baseR) {} 529}; 530} 531 532//===----------------------------------------------------------------------===// 533// Binding invalidation. 534//===----------------------------------------------------------------------===// 535 536bool RegionStoreManager::scanReachableSymbols(Store S, const MemRegion *R, 537 ScanReachableSymbols &Callbacks) { 538 // FIXME: This linear scan through all bindings could possibly be optimized 539 // by changing the data structure used for RegionBindings. 540 541 RegionBindings B = GetRegionBindings(S); 542 for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI) { 543 BindingKey Key = RI.getKey(); 544 if (Key.getRegion() == R) { 545 if (!Callbacks.scan(RI.getData())) 546 return false; 547 } else if (Key.hasSymbolicOffset()) { 548 if (const SubRegion *BaseSR = dyn_cast<SubRegion>(Key.getRegion())) 549 if (BaseSR->isSubRegionOf(R)) 550 if (!Callbacks.scan(RI.getData())) 551 return false; 552 } 553 } 554 555 return true; 556} 557 558RegionBindings RegionStoreManager::removeSubRegionBindings(RegionBindings B, 559 const SubRegion *R) { 560 // FIXME: This linear scan through all bindings could possibly be optimized 561 // by changing the data structure used for RegionBindings. 562 563 BindingKey SRKey = BindingKey::Make(R, BindingKey::Default); 564 assert(SRKey.isValid()); 565 if (SRKey.hasSymbolicOffset()) { 566 const SubRegion *Base = cast<SubRegion>(SRKey.getConcreteOffsetRegion()); 567 B = removeSubRegionBindings(B, Base); 568 return addBinding(B, Base, BindingKey::Default, UnknownVal()); 569 } 570 571 // FIXME: This does the wrong thing for bitfields. 572 uint64_t Length = UINT64_MAX; 573 574 SVal Extent = R->getExtent(svalBuilder); 575 if (nonloc::ConcreteInt *ExtentCI = dyn_cast<nonloc::ConcreteInt>(&Extent)) { 576 const llvm::APSInt &ExtentInt = ExtentCI->getValue(); 577 assert(ExtentInt.isNonNegative() || ExtentInt.isUnsigned()); 578 // Extents are in bytes but region offsets are in bits. Be careful! 579 Length = ExtentInt.getLimitedValue() * Ctx.getCharWidth(); 580 } 581 582 // It is safe to iterate over the bindings as they are being changed 583 // because they are in an ImmutableMap. 584 for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI) { 585 BindingKey NextKey = RI.getKey(); 586 if (NextKey.getRegion() == SRKey.getRegion()) { 587 // Case 1: The next binding is inside the region we're invalidating. 588 // Remove it. 589 if (NextKey.getOffset() > SRKey.getOffset() && 590 NextKey.getOffset() - SRKey.getOffset() < Length) 591 B = removeBinding(B, NextKey); 592 // Case 2: The next binding is at the same offset as the region we're 593 // invalidating. In this case, we need to leave default bindings alone, 594 // since they may be providing a default value for a regions beyond what 595 // we're invalidating. 596 // FIXME: This is probably incorrect; consider invalidating an outer 597 // struct whose first field is bound to a LazyCompoundVal. 598 else if (NextKey.getOffset() == SRKey.getOffset()) 599 if (NextKey.isDirect()) 600 B = removeBinding(B, NextKey); 601 602 } else if (NextKey.hasSymbolicOffset()) { 603 const MemRegion *Base = NextKey.getConcreteOffsetRegion(); 604 // Case 3: The next key is symbolic and we just changed something within 605 // its concrete region. We don't know if the binding is still valid, so 606 // we'll be conservative and remove it. 607 if (R->isSubRegionOf(Base)) 608 B = removeBinding(B, NextKey); 609 // Case 4: The next key is symbolic, but we changed a known super-region. 610 // In this case the binding is certainly no longer valid. 611 else if (const SubRegion *BaseSR = dyn_cast<SubRegion>(Base)) 612 if (BaseSR->isSubRegionOf(R)) 613 B = removeBinding(B, NextKey); 614 } 615 } 616 617 return B; 618} 619 620namespace { 621class invalidateRegionsWorker : public ClusterAnalysis<invalidateRegionsWorker> 622{ 623 const Expr *Ex; 624 unsigned Count; 625 const LocationContext *LCtx; 626 StoreManager::InvalidatedSymbols &IS; 627 StoreManager::InvalidatedRegions *Regions; 628public: 629 invalidateRegionsWorker(RegionStoreManager &rm, 630 ProgramStateManager &stateMgr, 631 RegionBindings b, 632 const Expr *ex, unsigned count, 633 const LocationContext *lctx, 634 StoreManager::InvalidatedSymbols &is, 635 StoreManager::InvalidatedRegions *r, 636 bool includeGlobals) 637 : ClusterAnalysis<invalidateRegionsWorker>(rm, stateMgr, b, includeGlobals), 638 Ex(ex), Count(count), LCtx(lctx), IS(is), Regions(r) {} 639 640 void VisitCluster(const MemRegion *baseR, BindingKey *I, BindingKey *E); 641 void VisitBaseRegion(const MemRegion *baseR); 642 643private: 644 void VisitBinding(SVal V); 645}; 646} 647 648void invalidateRegionsWorker::VisitBinding(SVal V) { 649 // A symbol? Mark it touched by the invalidation. 650 if (SymbolRef Sym = V.getAsSymbol()) 651 IS.insert(Sym); 652 653 if (const MemRegion *R = V.getAsRegion()) { 654 AddToWorkList(R); 655 return; 656 } 657 658 // Is it a LazyCompoundVal? All references get invalidated as well. 659 if (const nonloc::LazyCompoundVal *LCS = 660 dyn_cast<nonloc::LazyCompoundVal>(&V)) { 661 662 const MemRegion *LazyR = LCS->getRegion(); 663 RegionBindings B = RegionStoreManager::GetRegionBindings(LCS->getStore()); 664 665 for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){ 666 const SubRegion *baseR = dyn_cast<SubRegion>(RI.getKey().getRegion()); 667 if (baseR && (baseR == LazyR || baseR->isSubRegionOf(LazyR))) 668 VisitBinding(RI.getData()); 669 } 670 671 return; 672 } 673} 674 675void invalidateRegionsWorker::VisitCluster(const MemRegion *baseR, 676 BindingKey *I, BindingKey *E) { 677 for ( ; I != E; ++I) { 678 // Get the old binding. Is it a region? If so, add it to the worklist. 679 const BindingKey &K = *I; 680 if (const SVal *V = RM.lookup(B, K)) 681 VisitBinding(*V); 682 683 B = RM.removeBinding(B, K); 684 } 685} 686 687void invalidateRegionsWorker::VisitBaseRegion(const MemRegion *baseR) { 688 // Symbolic region? Mark that symbol touched by the invalidation. 689 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) 690 IS.insert(SR->getSymbol()); 691 692 // BlockDataRegion? If so, invalidate captured variables that are passed 693 // by reference. 694 if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) { 695 for (BlockDataRegion::referenced_vars_iterator 696 BI = BR->referenced_vars_begin(), BE = BR->referenced_vars_end() ; 697 BI != BE; ++BI) { 698 const VarRegion *VR = *BI; 699 const VarDecl *VD = VR->getDecl(); 700 if (VD->getAttr<BlocksAttr>() || !VD->hasLocalStorage()) { 701 AddToWorkList(VR); 702 } 703 else if (Loc::isLocType(VR->getValueType())) { 704 // Map the current bindings to a Store to retrieve the value 705 // of the binding. If that binding itself is a region, we should 706 // invalidate that region. This is because a block may capture 707 // a pointer value, but the thing pointed by that pointer may 708 // get invalidated. 709 Store store = B.getRootWithoutRetain(); 710 SVal V = RM.getBinding(store, loc::MemRegionVal(VR)); 711 if (const Loc *L = dyn_cast<Loc>(&V)) { 712 if (const MemRegion *LR = L->getAsRegion()) 713 AddToWorkList(LR); 714 } 715 } 716 } 717 return; 718 } 719 720 // Otherwise, we have a normal data region. Record that we touched the region. 721 if (Regions) 722 Regions->push_back(baseR); 723 724 if (isa<AllocaRegion>(baseR) || isa<SymbolicRegion>(baseR)) { 725 // Invalidate the region by setting its default value to 726 // conjured symbol. The type of the symbol is irrelavant. 727 DefinedOrUnknownSVal V = 728 svalBuilder.getConjuredSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count); 729 B = RM.addBinding(B, baseR, BindingKey::Default, V); 730 return; 731 } 732 733 if (!baseR->isBoundable()) 734 return; 735 736 const TypedValueRegion *TR = cast<TypedValueRegion>(baseR); 737 QualType T = TR->getValueType(); 738 739 // Invalidate the binding. 740 if (T->isStructureOrClassType()) { 741 // Invalidate the region by setting its default value to 742 // conjured symbol. The type of the symbol is irrelavant. 743 DefinedOrUnknownSVal V = 744 svalBuilder.getConjuredSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count); 745 B = RM.addBinding(B, baseR, BindingKey::Default, V); 746 return; 747 } 748 749 if (const ArrayType *AT = Ctx.getAsArrayType(T)) { 750 // Set the default value of the array to conjured symbol. 751 DefinedOrUnknownSVal V = 752 svalBuilder.getConjuredSymbolVal(baseR, Ex, LCtx, 753 AT->getElementType(), Count); 754 B = RM.addBinding(B, baseR, BindingKey::Default, V); 755 return; 756 } 757 758 if (includeGlobals && 759 isa<NonStaticGlobalSpaceRegion>(baseR->getMemorySpace())) { 760 // If the region is a global and we are invalidating all globals, 761 // just erase the entry. This causes all globals to be lazily 762 // symbolicated from the same base symbol. 763 B = RM.removeBinding(B, baseR); 764 return; 765 } 766 767 768 DefinedOrUnknownSVal V = svalBuilder.getConjuredSymbolVal(baseR, Ex, LCtx, 769 T,Count); 770 assert(SymbolManager::canSymbolicate(T) || V.isUnknown()); 771 B = RM.addBinding(B, baseR, BindingKey::Direct, V); 772} 773 774RegionBindings RegionStoreManager::invalidateGlobalRegion(MemRegion::Kind K, 775 const Expr *Ex, 776 unsigned Count, 777 const LocationContext *LCtx, 778 RegionBindings B, 779 InvalidatedRegions *Invalidated) { 780 // Bind the globals memory space to a new symbol that we will use to derive 781 // the bindings for all globals. 782 const GlobalsSpaceRegion *GS = MRMgr.getGlobalsRegion(K); 783 SVal V = 784 svalBuilder.getConjuredSymbolVal(/* SymbolTag = */ (void*) GS, Ex, LCtx, 785 /* symbol type, doesn't matter */ Ctx.IntTy, 786 Count); 787 788 B = removeBinding(B, GS); 789 B = addBinding(B, BindingKey::Make(GS, BindingKey::Default), V); 790 791 // Even if there are no bindings in the global scope, we still need to 792 // record that we touched it. 793 if (Invalidated) 794 Invalidated->push_back(GS); 795 796 return B; 797} 798 799StoreRef RegionStoreManager::invalidateRegions(Store store, 800 ArrayRef<const MemRegion *> Regions, 801 const Expr *Ex, unsigned Count, 802 const LocationContext *LCtx, 803 InvalidatedSymbols &IS, 804 const CallEvent *Call, 805 InvalidatedRegions *Invalidated) { 806 invalidateRegionsWorker W(*this, StateMgr, 807 RegionStoreManager::GetRegionBindings(store), 808 Ex, Count, LCtx, IS, Invalidated, false); 809 810 // Scan the bindings and generate the clusters. 811 W.GenerateClusters(); 812 813 // Add the regions to the worklist. 814 for (ArrayRef<const MemRegion *>::iterator 815 I = Regions.begin(), E = Regions.end(); I != E; ++I) 816 W.AddToWorkList(*I); 817 818 W.RunWorkList(); 819 820 // Return the new bindings. 821 RegionBindings B = W.getRegionBindings(); 822 823 // For all globals which are not static nor immutable: determine which global 824 // regions should be invalidated and invalidate them. 825 // TODO: This could possibly be more precise with modules. 826 // 827 // System calls invalidate only system globals. 828 if (Call && Call->isInSystemHeader()) { 829 B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind, 830 Ex, Count, LCtx, B, Invalidated); 831 // Internal calls might invalidate both system and internal globals. 832 } else { 833 B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind, 834 Ex, Count, LCtx, B, Invalidated); 835 B = invalidateGlobalRegion(MemRegion::GlobalInternalSpaceRegionKind, 836 Ex, Count, LCtx, B, Invalidated); 837 } 838 839 return StoreRef(B.getRootWithoutRetain(), *this); 840} 841 842//===----------------------------------------------------------------------===// 843// Extents for regions. 844//===----------------------------------------------------------------------===// 845 846DefinedOrUnknownSVal 847RegionStoreManager::getSizeInElements(ProgramStateRef state, 848 const MemRegion *R, 849 QualType EleTy) { 850 SVal Size = cast<SubRegion>(R)->getExtent(svalBuilder); 851 const llvm::APSInt *SizeInt = svalBuilder.getKnownValue(state, Size); 852 if (!SizeInt) 853 return UnknownVal(); 854 855 CharUnits RegionSize = CharUnits::fromQuantity(SizeInt->getSExtValue()); 856 857 if (Ctx.getAsVariableArrayType(EleTy)) { 858 // FIXME: We need to track extra state to properly record the size 859 // of VLAs. Returning UnknownVal here, however, is a stop-gap so that 860 // we don't have a divide-by-zero below. 861 return UnknownVal(); 862 } 863 864 CharUnits EleSize = Ctx.getTypeSizeInChars(EleTy); 865 866 // If a variable is reinterpreted as a type that doesn't fit into a larger 867 // type evenly, round it down. 868 // This is a signed value, since it's used in arithmetic with signed indices. 869 return svalBuilder.makeIntVal(RegionSize / EleSize, false); 870} 871 872//===----------------------------------------------------------------------===// 873// Location and region casting. 874//===----------------------------------------------------------------------===// 875 876/// ArrayToPointer - Emulates the "decay" of an array to a pointer 877/// type. 'Array' represents the lvalue of the array being decayed 878/// to a pointer, and the returned SVal represents the decayed 879/// version of that lvalue (i.e., a pointer to the first element of 880/// the array). This is called by ExprEngine when evaluating casts 881/// from arrays to pointers. 882SVal RegionStoreManager::ArrayToPointer(Loc Array) { 883 if (!isa<loc::MemRegionVal>(Array)) 884 return UnknownVal(); 885 886 const MemRegion* R = cast<loc::MemRegionVal>(&Array)->getRegion(); 887 const TypedValueRegion* ArrayR = dyn_cast<TypedValueRegion>(R); 888 889 if (!ArrayR) 890 return UnknownVal(); 891 892 // Strip off typedefs from the ArrayRegion's ValueType. 893 QualType T = ArrayR->getValueType().getDesugaredType(Ctx); 894 const ArrayType *AT = cast<ArrayType>(T); 895 T = AT->getElementType(); 896 897 NonLoc ZeroIdx = svalBuilder.makeZeroArrayIndex(); 898 return loc::MemRegionVal(MRMgr.getElementRegion(T, ZeroIdx, ArrayR, Ctx)); 899} 900 901// This mirrors Type::getCXXRecordDeclForPointerType(), but there doesn't 902// appear to be another need for this in the rest of the codebase. 903static const CXXRecordDecl *GetCXXRecordDeclForReferenceType(QualType Ty) { 904 if (const ReferenceType *RT = Ty->getAs<ReferenceType>()) 905 if (const RecordType *RCT = RT->getPointeeType()->getAs<RecordType>()) 906 return dyn_cast<CXXRecordDecl>(RCT->getDecl()); 907 return 0; 908} 909 910SVal RegionStoreManager::evalDerivedToBase(SVal derived, QualType baseType) { 911 const CXXRecordDecl *baseDecl; 912 913 if (baseType->isPointerType()) 914 baseDecl = baseType->getCXXRecordDeclForPointerType(); 915 else if (baseType->isReferenceType()) 916 baseDecl = GetCXXRecordDeclForReferenceType(baseType); 917 else 918 baseDecl = baseType->getAsCXXRecordDecl(); 919 920 assert(baseDecl && "not a CXXRecordDecl?"); 921 922 loc::MemRegionVal *derivedRegVal = dyn_cast<loc::MemRegionVal>(&derived); 923 if (!derivedRegVal) 924 return derived; 925 926 const MemRegion *baseReg = 927 MRMgr.getCXXBaseObjectRegion(baseDecl, derivedRegVal->getRegion()); 928 929 return loc::MemRegionVal(baseReg); 930} 931 932SVal RegionStoreManager::evalDynamicCast(SVal base, QualType derivedType, 933 bool &Failed) { 934 Failed = false; 935 936 loc::MemRegionVal *baseRegVal = dyn_cast<loc::MemRegionVal>(&base); 937 if (!baseRegVal) 938 return UnknownVal(); 939 const MemRegion *BaseRegion = baseRegVal->stripCasts(); 940 941 // Assume the derived class is a pointer or a reference to a CXX record. 942 derivedType = derivedType->getPointeeType(); 943 assert(!derivedType.isNull()); 944 const CXXRecordDecl *DerivedDecl = derivedType->getAsCXXRecordDecl(); 945 if (!DerivedDecl && !derivedType->isVoidType()) 946 return UnknownVal(); 947 948 // Drill down the CXXBaseObject chains, which represent upcasts (casts from 949 // derived to base). 950 const MemRegion *SR = BaseRegion; 951 while (const TypedRegion *TSR = dyn_cast_or_null<TypedRegion>(SR)) { 952 QualType BaseType = TSR->getLocationType()->getPointeeType(); 953 assert(!BaseType.isNull()); 954 const CXXRecordDecl *SRDecl = BaseType->getAsCXXRecordDecl(); 955 if (!SRDecl) 956 return UnknownVal(); 957 958 // If found the derived class, the cast succeeds. 959 if (SRDecl == DerivedDecl) 960 return loc::MemRegionVal(TSR); 961 962 // If the region type is a subclass of the derived type. 963 if (!derivedType->isVoidType() && SRDecl->isDerivedFrom(DerivedDecl)) { 964 // This occurs in two cases. 965 // 1) We are processing an upcast. 966 // 2) We are processing a downcast but we jumped directly from the 967 // ancestor to a child of the cast value, so conjure the 968 // appropriate region to represent value (the intermediate node). 969 return loc::MemRegionVal(MRMgr.getCXXBaseObjectRegion(DerivedDecl, 970 BaseRegion)); 971 } 972 973 // If super region is not a parent of derived class, the cast definitely 974 // fails. 975 if (!derivedType->isVoidType() && 976 DerivedDecl->isProvablyNotDerivedFrom(SRDecl)) { 977 Failed = true; 978 return UnknownVal(); 979 } 980 981 if (const CXXBaseObjectRegion *R = dyn_cast<CXXBaseObjectRegion>(TSR)) 982 // Drill down the chain to get the derived classes. 983 SR = R->getSuperRegion(); 984 else { 985 // We reached the bottom of the hierarchy. 986 987 // If this is a cast to void*, return the region. 988 if (derivedType->isVoidType()) 989 return loc::MemRegionVal(TSR); 990 991 // We did not find the derived class. We we must be casting the base to 992 // derived, so the cast should fail. 993 Failed = true; 994 return UnknownVal(); 995 } 996 } 997 998 return UnknownVal(); 999} 1000 1001//===----------------------------------------------------------------------===// 1002// Loading values from regions. 1003//===----------------------------------------------------------------------===// 1004 1005Optional<SVal> RegionStoreManager::getDirectBinding(RegionBindings B, 1006 const MemRegion *R) { 1007 1008 if (const SVal *V = lookup(B, R, BindingKey::Direct)) 1009 return *V; 1010 1011 return Optional<SVal>(); 1012} 1013 1014Optional<SVal> RegionStoreManager::getDefaultBinding(RegionBindings B, 1015 const MemRegion *R) { 1016 if (R->isBoundable()) 1017 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) 1018 if (TR->getValueType()->isUnionType()) 1019 return UnknownVal(); 1020 1021 if (const SVal *V = lookup(B, R, BindingKey::Default)) 1022 return *V; 1023 1024 return Optional<SVal>(); 1025} 1026 1027SVal RegionStoreManager::getBinding(Store store, Loc L, QualType T) { 1028 assert(!isa<UnknownVal>(L) && "location unknown"); 1029 assert(!isa<UndefinedVal>(L) && "location undefined"); 1030 1031 // For access to concrete addresses, return UnknownVal. Checks 1032 // for null dereferences (and similar errors) are done by checkers, not 1033 // the Store. 1034 // FIXME: We can consider lazily symbolicating such memory, but we really 1035 // should defer this when we can reason easily about symbolicating arrays 1036 // of bytes. 1037 if (isa<loc::ConcreteInt>(L)) { 1038 return UnknownVal(); 1039 } 1040 if (!isa<loc::MemRegionVal>(L)) { 1041 return UnknownVal(); 1042 } 1043 1044 const MemRegion *MR = cast<loc::MemRegionVal>(L).getRegion(); 1045 1046 if (isa<AllocaRegion>(MR) || 1047 isa<SymbolicRegion>(MR) || 1048 isa<CodeTextRegion>(MR)) { 1049 if (T.isNull()) { 1050 if (const TypedRegion *TR = dyn_cast<TypedRegion>(MR)) 1051 T = TR->getLocationType(); 1052 else { 1053 const SymbolicRegion *SR = cast<SymbolicRegion>(MR); 1054 T = SR->getSymbol()->getType(Ctx); 1055 } 1056 } 1057 MR = GetElementZeroRegion(MR, T); 1058 } 1059 1060 // FIXME: Perhaps this method should just take a 'const MemRegion*' argument 1061 // instead of 'Loc', and have the other Loc cases handled at a higher level. 1062 const TypedValueRegion *R = cast<TypedValueRegion>(MR); 1063 QualType RTy = R->getValueType(); 1064 1065 // FIXME: We should eventually handle funny addressing. e.g.: 1066 // 1067 // int x = ...; 1068 // int *p = &x; 1069 // char *q = (char*) p; 1070 // char c = *q; // returns the first byte of 'x'. 1071 // 1072 // Such funny addressing will occur due to layering of regions. 1073 1074 if (RTy->isStructureOrClassType()) 1075 return getBindingForStruct(store, R); 1076 1077 // FIXME: Handle unions. 1078 if (RTy->isUnionType()) 1079 return UnknownVal(); 1080 1081 if (RTy->isArrayType()) { 1082 if (RTy->isConstantArrayType()) 1083 return getBindingForArray(store, R); 1084 else 1085 return UnknownVal(); 1086 } 1087 1088 // FIXME: handle Vector types. 1089 if (RTy->isVectorType()) 1090 return UnknownVal(); 1091 1092 if (const FieldRegion* FR = dyn_cast<FieldRegion>(R)) 1093 return CastRetrievedVal(getBindingForField(store, FR), FR, T, false); 1094 1095 if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) { 1096 // FIXME: Here we actually perform an implicit conversion from the loaded 1097 // value to the element type. Eventually we want to compose these values 1098 // more intelligently. For example, an 'element' can encompass multiple 1099 // bound regions (e.g., several bound bytes), or could be a subset of 1100 // a larger value. 1101 return CastRetrievedVal(getBindingForElement(store, ER), ER, T, false); 1102 } 1103 1104 if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) { 1105 // FIXME: Here we actually perform an implicit conversion from the loaded 1106 // value to the ivar type. What we should model is stores to ivars 1107 // that blow past the extent of the ivar. If the address of the ivar is 1108 // reinterpretted, it is possible we stored a different value that could 1109 // fit within the ivar. Either we need to cast these when storing them 1110 // or reinterpret them lazily (as we do here). 1111 return CastRetrievedVal(getBindingForObjCIvar(store, IVR), IVR, T, false); 1112 } 1113 1114 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) { 1115 // FIXME: Here we actually perform an implicit conversion from the loaded 1116 // value to the variable type. What we should model is stores to variables 1117 // that blow past the extent of the variable. If the address of the 1118 // variable is reinterpretted, it is possible we stored a different value 1119 // that could fit within the variable. Either we need to cast these when 1120 // storing them or reinterpret them lazily (as we do here). 1121 return CastRetrievedVal(getBindingForVar(store, VR), VR, T, false); 1122 } 1123 1124 RegionBindings B = GetRegionBindings(store); 1125 const SVal *V = lookup(B, R, BindingKey::Direct); 1126 1127 // Check if the region has a binding. 1128 if (V) 1129 return *V; 1130 1131 // The location does not have a bound value. This means that it has 1132 // the value it had upon its creation and/or entry to the analyzed 1133 // function/method. These are either symbolic values or 'undefined'. 1134 if (R->hasStackNonParametersStorage()) { 1135 // All stack variables are considered to have undefined values 1136 // upon creation. All heap allocated blocks are considered to 1137 // have undefined values as well unless they are explicitly bound 1138 // to specific values. 1139 return UndefinedVal(); 1140 } 1141 1142 // All other values are symbolic. 1143 return svalBuilder.getRegionValueSymbolVal(R); 1144} 1145 1146std::pair<Store, const MemRegion *> 1147RegionStoreManager::GetLazyBinding(RegionBindings B, const MemRegion *R, 1148 const MemRegion *originalRegion, 1149 bool includeSuffix) { 1150 1151 if (originalRegion != R) { 1152 if (Optional<SVal> OV = getDefaultBinding(B, R)) { 1153 if (const nonloc::LazyCompoundVal *V = 1154 dyn_cast<nonloc::LazyCompoundVal>(OV.getPointer())) 1155 return std::make_pair(V->getStore(), V->getRegion()); 1156 } 1157 } 1158 1159 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) { 1160 const std::pair<Store, const MemRegion *> &X = 1161 GetLazyBinding(B, ER->getSuperRegion(), originalRegion); 1162 1163 if (X.second) 1164 return std::make_pair(X.first, 1165 MRMgr.getElementRegionWithSuper(ER, X.second)); 1166 } 1167 else if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) { 1168 const std::pair<Store, const MemRegion *> &X = 1169 GetLazyBinding(B, FR->getSuperRegion(), originalRegion); 1170 1171 if (X.second) { 1172 if (includeSuffix) 1173 return std::make_pair(X.first, 1174 MRMgr.getFieldRegionWithSuper(FR, X.second)); 1175 return X; 1176 } 1177 1178 } 1179 // C++ base object region is another kind of region that we should blast 1180 // through to look for lazy compound value. It is like a field region. 1181 else if (const CXXBaseObjectRegion *baseReg = 1182 dyn_cast<CXXBaseObjectRegion>(R)) { 1183 const std::pair<Store, const MemRegion *> &X = 1184 GetLazyBinding(B, baseReg->getSuperRegion(), originalRegion); 1185 1186 if (X.second) { 1187 if (includeSuffix) 1188 return std::make_pair(X.first, 1189 MRMgr.getCXXBaseObjectRegionWithSuper(baseReg, 1190 X.second)); 1191 return X; 1192 } 1193 } 1194 1195 // The NULL MemRegion indicates an non-existent lazy binding. A NULL Store is 1196 // possible for a valid lazy binding. 1197 return std::make_pair((Store) 0, (const MemRegion *) 0); 1198} 1199 1200SVal RegionStoreManager::getBindingForElement(Store store, 1201 const ElementRegion* R) { 1202 // We do not currently model bindings of the CompoundLiteralregion. 1203 if (isa<CompoundLiteralRegion>(R->getBaseRegion())) 1204 return UnknownVal(); 1205 1206 // Check if the region has a binding. 1207 RegionBindings B = GetRegionBindings(store); 1208 if (const Optional<SVal> &V = getDirectBinding(B, R)) 1209 return *V; 1210 1211 const MemRegion* superR = R->getSuperRegion(); 1212 1213 // Check if the region is an element region of a string literal. 1214 if (const StringRegion *StrR=dyn_cast<StringRegion>(superR)) { 1215 // FIXME: Handle loads from strings where the literal is treated as 1216 // an integer, e.g., *((unsigned int*)"hello") 1217 QualType T = Ctx.getAsArrayType(StrR->getValueType())->getElementType(); 1218 if (T != Ctx.getCanonicalType(R->getElementType())) 1219 return UnknownVal(); 1220 1221 const StringLiteral *Str = StrR->getStringLiteral(); 1222 SVal Idx = R->getIndex(); 1223 if (nonloc::ConcreteInt *CI = dyn_cast<nonloc::ConcreteInt>(&Idx)) { 1224 int64_t i = CI->getValue().getSExtValue(); 1225 // Abort on string underrun. This can be possible by arbitrary 1226 // clients of getBindingForElement(). 1227 if (i < 0) 1228 return UndefinedVal(); 1229 int64_t length = Str->getLength(); 1230 // Technically, only i == length is guaranteed to be null. 1231 // However, such overflows should be caught before reaching this point; 1232 // the only time such an access would be made is if a string literal was 1233 // used to initialize a larger array. 1234 char c = (i >= length) ? '\0' : Str->getCodeUnit(i); 1235 return svalBuilder.makeIntVal(c, T); 1236 } 1237 } 1238 1239 // Check for loads from a code text region. For such loads, just give up. 1240 if (isa<CodeTextRegion>(superR)) 1241 return UnknownVal(); 1242 1243 // Handle the case where we are indexing into a larger scalar object. 1244 // For example, this handles: 1245 // int x = ... 1246 // char *y = &x; 1247 // return *y; 1248 // FIXME: This is a hack, and doesn't do anything really intelligent yet. 1249 const RegionRawOffset &O = R->getAsArrayOffset(); 1250 1251 // If we cannot reason about the offset, return an unknown value. 1252 if (!O.getRegion()) 1253 return UnknownVal(); 1254 1255 if (const TypedValueRegion *baseR = 1256 dyn_cast_or_null<TypedValueRegion>(O.getRegion())) { 1257 QualType baseT = baseR->getValueType(); 1258 if (baseT->isScalarType()) { 1259 QualType elemT = R->getElementType(); 1260 if (elemT->isScalarType()) { 1261 if (Ctx.getTypeSizeInChars(baseT) >= Ctx.getTypeSizeInChars(elemT)) { 1262 if (const Optional<SVal> &V = getDirectBinding(B, superR)) { 1263 if (SymbolRef parentSym = V->getAsSymbol()) 1264 return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R); 1265 1266 if (V->isUnknownOrUndef()) 1267 return *V; 1268 // Other cases: give up. We are indexing into a larger object 1269 // that has some value, but we don't know how to handle that yet. 1270 return UnknownVal(); 1271 } 1272 } 1273 } 1274 } 1275 } 1276 return getBindingForFieldOrElementCommon(store, R, R->getElementType(), 1277 superR); 1278} 1279 1280SVal RegionStoreManager::getBindingForField(Store store, 1281 const FieldRegion* R) { 1282 1283 // Check if the region has a binding. 1284 RegionBindings B = GetRegionBindings(store); 1285 if (const Optional<SVal> &V = getDirectBinding(B, R)) 1286 return *V; 1287 1288 QualType Ty = R->getValueType(); 1289 return getBindingForFieldOrElementCommon(store, R, Ty, R->getSuperRegion()); 1290} 1291 1292Optional<SVal> 1293RegionStoreManager::getBindingForDerivedDefaultValue(RegionBindings B, 1294 const MemRegion *superR, 1295 const TypedValueRegion *R, 1296 QualType Ty) { 1297 1298 if (const Optional<SVal> &D = getDefaultBinding(B, superR)) { 1299 const SVal &val = D.getValue(); 1300 if (SymbolRef parentSym = val.getAsSymbol()) 1301 return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R); 1302 1303 if (val.isZeroConstant()) 1304 return svalBuilder.makeZeroVal(Ty); 1305 1306 if (val.isUnknownOrUndef()) 1307 return val; 1308 1309 // Lazy bindings are handled later. 1310 if (isa<nonloc::LazyCompoundVal>(val)) 1311 return Optional<SVal>(); 1312 1313 llvm_unreachable("Unknown default value"); 1314 } 1315 1316 return Optional<SVal>(); 1317} 1318 1319SVal RegionStoreManager::getLazyBinding(const MemRegion *lazyBindingRegion, 1320 Store lazyBindingStore) { 1321 if (const ElementRegion *ER = dyn_cast<ElementRegion>(lazyBindingRegion)) 1322 return getBindingForElement(lazyBindingStore, ER); 1323 1324 return getBindingForField(lazyBindingStore, 1325 cast<FieldRegion>(lazyBindingRegion)); 1326} 1327 1328SVal RegionStoreManager::getBindingForFieldOrElementCommon(Store store, 1329 const TypedValueRegion *R, 1330 QualType Ty, 1331 const MemRegion *superR) { 1332 1333 // At this point we have already checked in either getBindingForElement or 1334 // getBindingForField if 'R' has a direct binding. 1335 RegionBindings B = GetRegionBindings(store); 1336 1337 // Lazy binding? 1338 Store lazyBindingStore = NULL; 1339 const MemRegion *lazyBindingRegion = NULL; 1340 llvm::tie(lazyBindingStore, lazyBindingRegion) = GetLazyBinding(B, R, R, 1341 true); 1342 1343 if (lazyBindingRegion) 1344 return getLazyBinding(lazyBindingRegion, lazyBindingStore); 1345 1346 // Record whether or not we see a symbolic index. That can completely 1347 // be out of scope of our lookup. 1348 bool hasSymbolicIndex = false; 1349 1350 while (superR) { 1351 if (const Optional<SVal> &D = 1352 getBindingForDerivedDefaultValue(B, superR, R, Ty)) 1353 return *D; 1354 1355 if (const ElementRegion *ER = dyn_cast<ElementRegion>(superR)) { 1356 NonLoc index = ER->getIndex(); 1357 if (!index.isConstant()) 1358 hasSymbolicIndex = true; 1359 } 1360 1361 // If our super region is a field or element itself, walk up the region 1362 // hierarchy to see if there is a default value installed in an ancestor. 1363 if (const SubRegion *SR = dyn_cast<SubRegion>(superR)) { 1364 superR = SR->getSuperRegion(); 1365 continue; 1366 } 1367 break; 1368 } 1369 1370 if (R->hasStackNonParametersStorage()) { 1371 if (isa<ElementRegion>(R)) { 1372 // Currently we don't reason specially about Clang-style vectors. Check 1373 // if superR is a vector and if so return Unknown. 1374 if (const TypedValueRegion *typedSuperR = 1375 dyn_cast<TypedValueRegion>(superR)) { 1376 if (typedSuperR->getValueType()->isVectorType()) 1377 return UnknownVal(); 1378 } 1379 } 1380 1381 // FIXME: We also need to take ElementRegions with symbolic indexes into 1382 // account. This case handles both directly accessing an ElementRegion 1383 // with a symbolic offset, but also fields within an element with 1384 // a symbolic offset. 1385 if (hasSymbolicIndex) 1386 return UnknownVal(); 1387 1388 return UndefinedVal(); 1389 } 1390 1391 // All other values are symbolic. 1392 return svalBuilder.getRegionValueSymbolVal(R); 1393} 1394 1395SVal RegionStoreManager::getBindingForObjCIvar(Store store, 1396 const ObjCIvarRegion* R) { 1397 1398 // Check if the region has a binding. 1399 RegionBindings B = GetRegionBindings(store); 1400 1401 if (const Optional<SVal> &V = getDirectBinding(B, R)) 1402 return *V; 1403 1404 const MemRegion *superR = R->getSuperRegion(); 1405 1406 // Check if the super region has a default binding. 1407 if (const Optional<SVal> &V = getDefaultBinding(B, superR)) { 1408 if (SymbolRef parentSym = V->getAsSymbol()) 1409 return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R); 1410 1411 // Other cases: give up. 1412 return UnknownVal(); 1413 } 1414 1415 return getBindingForLazySymbol(R); 1416} 1417 1418SVal RegionStoreManager::getBindingForVar(Store store, const VarRegion *R) { 1419 1420 // Check if the region has a binding. 1421 RegionBindings B = GetRegionBindings(store); 1422 1423 if (const Optional<SVal> &V = getDirectBinding(B, R)) 1424 return *V; 1425 1426 // Lazily derive a value for the VarRegion. 1427 const VarDecl *VD = R->getDecl(); 1428 QualType T = VD->getType(); 1429 const MemSpaceRegion *MS = R->getMemorySpace(); 1430 1431 if (isa<UnknownSpaceRegion>(MS) || 1432 isa<StackArgumentsSpaceRegion>(MS)) 1433 return svalBuilder.getRegionValueSymbolVal(R); 1434 1435 if (isa<GlobalsSpaceRegion>(MS)) { 1436 if (isa<NonStaticGlobalSpaceRegion>(MS)) { 1437 // Is 'VD' declared constant? If so, retrieve the constant value. 1438 QualType CT = Ctx.getCanonicalType(T); 1439 if (CT.isConstQualified()) { 1440 const Expr *Init = VD->getInit(); 1441 // Do the null check first, as we want to call 'IgnoreParenCasts'. 1442 if (Init) 1443 if (const IntegerLiteral *IL = 1444 dyn_cast<IntegerLiteral>(Init->IgnoreParenCasts())) { 1445 const nonloc::ConcreteInt &V = svalBuilder.makeIntVal(IL); 1446 return svalBuilder.evalCast(V, Init->getType(), IL->getType()); 1447 } 1448 } 1449 1450 if (const Optional<SVal> &V 1451 = getBindingForDerivedDefaultValue(B, MS, R, CT)) 1452 return V.getValue(); 1453 1454 return svalBuilder.getRegionValueSymbolVal(R); 1455 } 1456 1457 if (T->isIntegerType()) 1458 return svalBuilder.makeIntVal(0, T); 1459 if (T->isPointerType()) 1460 return svalBuilder.makeNull(); 1461 1462 return UnknownVal(); 1463 } 1464 1465 return UndefinedVal(); 1466} 1467 1468SVal RegionStoreManager::getBindingForLazySymbol(const TypedValueRegion *R) { 1469 // All other values are symbolic. 1470 return svalBuilder.getRegionValueSymbolVal(R); 1471} 1472 1473static bool mayHaveLazyBinding(QualType Ty) { 1474 return Ty->isArrayType() || Ty->isStructureOrClassType(); 1475} 1476 1477SVal RegionStoreManager::getBindingForStruct(Store store, 1478 const TypedValueRegion* R) { 1479 const RecordDecl *RD = R->getValueType()->castAs<RecordType>()->getDecl(); 1480 if (RD->field_empty()) 1481 return UnknownVal(); 1482 1483 // If we already have a lazy binding, don't create a new one, 1484 // unless the first field might have a lazy binding of its own. 1485 // (Right now we can't tell the difference.) 1486 QualType FirstFieldType = RD->field_begin()->getType(); 1487 if (!mayHaveLazyBinding(FirstFieldType)) { 1488 RegionBindings B = GetRegionBindings(store); 1489 BindingKey K = BindingKey::Make(R, BindingKey::Default); 1490 if (const nonloc::LazyCompoundVal *V = 1491 dyn_cast_or_null<nonloc::LazyCompoundVal>(lookup(B, K))) { 1492 return *V; 1493 } 1494 } 1495 1496 return svalBuilder.makeLazyCompoundVal(StoreRef(store, *this), R); 1497} 1498 1499SVal RegionStoreManager::getBindingForArray(Store store, 1500 const TypedValueRegion * R) { 1501 const ConstantArrayType *Ty = Ctx.getAsConstantArrayType(R->getValueType()); 1502 assert(Ty && "Only constant array types can have compound bindings."); 1503 1504 // If we already have a lazy binding, don't create a new one, 1505 // unless the first element might have a lazy binding of its own. 1506 // (Right now we can't tell the difference.) 1507 if (!mayHaveLazyBinding(Ty->getElementType())) { 1508 RegionBindings B = GetRegionBindings(store); 1509 BindingKey K = BindingKey::Make(R, BindingKey::Default); 1510 if (const nonloc::LazyCompoundVal *V = 1511 dyn_cast_or_null<nonloc::LazyCompoundVal>(lookup(B, K))) { 1512 return *V; 1513 } 1514 } 1515 1516 return svalBuilder.makeLazyCompoundVal(StoreRef(store, *this), R); 1517} 1518 1519bool RegionStoreManager::includedInBindings(Store store, 1520 const MemRegion *region) const { 1521 RegionBindings B = GetRegionBindings(store); 1522 region = region->getBaseRegion(); 1523 1524 for (RegionBindings::iterator it = B.begin(), ei = B.end(); it != ei; ++it) { 1525 const BindingKey &K = it.getKey(); 1526 if (region == K.getRegion()) 1527 return true; 1528 const SVal &D = it.getData(); 1529 if (const MemRegion *r = D.getAsRegion()) 1530 if (r == region) 1531 return true; 1532 } 1533 return false; 1534} 1535 1536//===----------------------------------------------------------------------===// 1537// Binding values to regions. 1538//===----------------------------------------------------------------------===// 1539 1540StoreRef RegionStoreManager::Remove(Store store, Loc L) { 1541 if (isa<loc::MemRegionVal>(L)) 1542 if (const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion()) 1543 return StoreRef(removeBinding(GetRegionBindings(store), 1544 R).getRootWithoutRetain(), 1545 *this); 1546 1547 return StoreRef(store, *this); 1548} 1549 1550StoreRef RegionStoreManager::Bind(Store store, Loc L, SVal V) { 1551 if (isa<loc::ConcreteInt>(L)) 1552 return StoreRef(store, *this); 1553 1554 // If we get here, the location should be a region. 1555 const MemRegion *R = cast<loc::MemRegionVal>(L).getRegion(); 1556 1557 // Check if the region is a struct region. 1558 if (const TypedValueRegion* TR = dyn_cast<TypedValueRegion>(R)) { 1559 QualType Ty = TR->getValueType(); 1560 if (Ty->isStructureOrClassType()) 1561 return BindStruct(store, TR, V); 1562 if (Ty->isVectorType()) 1563 return BindVector(store, TR, V); 1564 } 1565 1566 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) { 1567 // Binding directly to a symbolic region should be treated as binding 1568 // to element 0. 1569 QualType T = SR->getSymbol()->getType(Ctx); 1570 1571 // FIXME: Is this the right way to handle symbols that are references? 1572 if (const PointerType *PT = T->getAs<PointerType>()) 1573 T = PT->getPointeeType(); 1574 else 1575 T = T->getAs<ReferenceType>()->getPointeeType(); 1576 1577 R = GetElementZeroRegion(SR, T); 1578 } 1579 1580 // Clear out bindings that may overlap with this binding. 1581 1582 // Perform the binding. 1583 RegionBindings B = GetRegionBindings(store); 1584 B = removeSubRegionBindings(B, cast<SubRegion>(R)); 1585 BindingKey Key = BindingKey::Make(R, BindingKey::Direct); 1586 return StoreRef(addBinding(B, Key, V).getRootWithoutRetain(), *this); 1587} 1588 1589StoreRef RegionStoreManager::BindDecl(Store store, const VarRegion *VR, 1590 SVal InitVal) { 1591 1592 QualType T = VR->getDecl()->getType(); 1593 1594 if (T->isArrayType()) 1595 return BindArray(store, VR, InitVal); 1596 if (T->isStructureOrClassType()) 1597 return BindStruct(store, VR, InitVal); 1598 1599 return Bind(store, svalBuilder.makeLoc(VR), InitVal); 1600} 1601 1602// FIXME: this method should be merged into Bind(). 1603StoreRef RegionStoreManager::BindCompoundLiteral(Store store, 1604 const CompoundLiteralExpr *CL, 1605 const LocationContext *LC, 1606 SVal V) { 1607 return Bind(store, loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CL, LC)), 1608 V); 1609} 1610 1611StoreRef RegionStoreManager::setImplicitDefaultValue(Store store, 1612 const MemRegion *R, 1613 QualType T) { 1614 RegionBindings B = GetRegionBindings(store); 1615 SVal V; 1616 1617 if (Loc::isLocType(T)) 1618 V = svalBuilder.makeNull(); 1619 else if (T->isIntegerType()) 1620 V = svalBuilder.makeZeroVal(T); 1621 else if (T->isStructureOrClassType() || T->isArrayType()) { 1622 // Set the default value to a zero constant when it is a structure 1623 // or array. The type doesn't really matter. 1624 V = svalBuilder.makeZeroVal(Ctx.IntTy); 1625 } 1626 else { 1627 // We can't represent values of this type, but we still need to set a value 1628 // to record that the region has been initialized. 1629 // If this assertion ever fires, a new case should be added above -- we 1630 // should know how to default-initialize any value we can symbolicate. 1631 assert(!SymbolManager::canSymbolicate(T) && "This type is representable"); 1632 V = UnknownVal(); 1633 } 1634 1635 return StoreRef(addBinding(B, R, BindingKey::Default, 1636 V).getRootWithoutRetain(), *this); 1637} 1638 1639StoreRef RegionStoreManager::BindArray(Store store, const TypedValueRegion* R, 1640 SVal Init) { 1641 1642 const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType())); 1643 QualType ElementTy = AT->getElementType(); 1644 Optional<uint64_t> Size; 1645 1646 if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT)) 1647 Size = CAT->getSize().getZExtValue(); 1648 1649 // Check if the init expr is a string literal. 1650 if (loc::MemRegionVal *MRV = dyn_cast<loc::MemRegionVal>(&Init)) { 1651 const StringRegion *S = cast<StringRegion>(MRV->getRegion()); 1652 1653 // Treat the string as a lazy compound value. 1654 nonloc::LazyCompoundVal LCV = 1655 cast<nonloc::LazyCompoundVal>(svalBuilder. 1656 makeLazyCompoundVal(StoreRef(store, *this), S)); 1657 return CopyLazyBindings(LCV, store, R); 1658 } 1659 1660 // Handle lazy compound values. 1661 if (nonloc::LazyCompoundVal *LCV = dyn_cast<nonloc::LazyCompoundVal>(&Init)) 1662 return CopyLazyBindings(*LCV, store, R); 1663 1664 // Remaining case: explicit compound values. 1665 1666 if (Init.isUnknown()) 1667 return setImplicitDefaultValue(store, R, ElementTy); 1668 1669 nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(Init); 1670 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end(); 1671 uint64_t i = 0; 1672 1673 StoreRef newStore(store, *this); 1674 for (; Size.hasValue() ? i < Size.getValue() : true ; ++i, ++VI) { 1675 // The init list might be shorter than the array length. 1676 if (VI == VE) 1677 break; 1678 1679 const NonLoc &Idx = svalBuilder.makeArrayIndex(i); 1680 const ElementRegion *ER = MRMgr.getElementRegion(ElementTy, Idx, R, Ctx); 1681 1682 if (ElementTy->isStructureOrClassType()) 1683 newStore = BindStruct(newStore.getStore(), ER, *VI); 1684 else if (ElementTy->isArrayType()) 1685 newStore = BindArray(newStore.getStore(), ER, *VI); 1686 else 1687 newStore = Bind(newStore.getStore(), svalBuilder.makeLoc(ER), *VI); 1688 } 1689 1690 // If the init list is shorter than the array length, set the 1691 // array default value. 1692 if (Size.hasValue() && i < Size.getValue()) 1693 newStore = setImplicitDefaultValue(newStore.getStore(), R, ElementTy); 1694 1695 return newStore; 1696} 1697 1698StoreRef RegionStoreManager::BindVector(Store store, const TypedValueRegion* R, 1699 SVal V) { 1700 QualType T = R->getValueType(); 1701 assert(T->isVectorType()); 1702 const VectorType *VT = T->getAs<VectorType>(); // Use getAs for typedefs. 1703 1704 // Handle lazy compound values. 1705 if (nonloc::LazyCompoundVal *LCV = dyn_cast<nonloc::LazyCompoundVal>(&V)) 1706 return CopyLazyBindings(*LCV, store, R); 1707 1708 // We may get non-CompoundVal accidentally due to imprecise cast logic or 1709 // that we are binding symbolic struct value. Kill the field values, and if 1710 // the value is symbolic go and bind it as a "default" binding. 1711 if (V.isUnknown() || !isa<nonloc::CompoundVal>(V)) { 1712 SVal SV = isa<nonloc::SymbolVal>(V) ? V : UnknownVal(); 1713 return KillStruct(store, R, SV); 1714 } 1715 1716 QualType ElemType = VT->getElementType(); 1717 nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(V); 1718 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end(); 1719 unsigned index = 0, numElements = VT->getNumElements(); 1720 StoreRef newStore(store, *this); 1721 1722 for ( ; index != numElements ; ++index) { 1723 if (VI == VE) 1724 break; 1725 1726 NonLoc Idx = svalBuilder.makeArrayIndex(index); 1727 const ElementRegion *ER = MRMgr.getElementRegion(ElemType, Idx, R, Ctx); 1728 1729 if (ElemType->isArrayType()) 1730 newStore = BindArray(newStore.getStore(), ER, *VI); 1731 else if (ElemType->isStructureOrClassType()) 1732 newStore = BindStruct(newStore.getStore(), ER, *VI); 1733 else 1734 newStore = Bind(newStore.getStore(), svalBuilder.makeLoc(ER), *VI); 1735 } 1736 return newStore; 1737} 1738 1739StoreRef RegionStoreManager::BindStruct(Store store, const TypedValueRegion* R, 1740 SVal V) { 1741 1742 if (!Features.supportsFields()) 1743 return StoreRef(store, *this); 1744 1745 QualType T = R->getValueType(); 1746 assert(T->isStructureOrClassType()); 1747 1748 const RecordType* RT = T->getAs<RecordType>(); 1749 RecordDecl *RD = RT->getDecl(); 1750 1751 if (!RD->isCompleteDefinition()) 1752 return StoreRef(store, *this); 1753 1754 // Handle lazy compound values. 1755 if (const nonloc::LazyCompoundVal *LCV=dyn_cast<nonloc::LazyCompoundVal>(&V)) 1756 return CopyLazyBindings(*LCV, store, R); 1757 1758 // We may get non-CompoundVal accidentally due to imprecise cast logic or 1759 // that we are binding symbolic struct value. Kill the field values, and if 1760 // the value is symbolic go and bind it as a "default" binding. 1761 if (V.isUnknown() || !isa<nonloc::CompoundVal>(V)) { 1762 SVal SV = isa<nonloc::SymbolVal>(V) ? V : UnknownVal(); 1763 return KillStruct(store, R, SV); 1764 } 1765 1766 nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(V); 1767 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end(); 1768 1769 RecordDecl::field_iterator FI, FE; 1770 StoreRef newStore(store, *this); 1771 1772 for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; ++FI) { 1773 1774 if (VI == VE) 1775 break; 1776 1777 // Skip any unnamed bitfields to stay in sync with the initializers. 1778 if (FI->isUnnamedBitfield()) 1779 continue; 1780 1781 QualType FTy = FI->getType(); 1782 const FieldRegion* FR = MRMgr.getFieldRegion(*FI, R); 1783 1784 if (FTy->isArrayType()) 1785 newStore = BindArray(newStore.getStore(), FR, *VI); 1786 else if (FTy->isStructureOrClassType()) 1787 newStore = BindStruct(newStore.getStore(), FR, *VI); 1788 else 1789 newStore = Bind(newStore.getStore(), svalBuilder.makeLoc(FR), *VI); 1790 ++VI; 1791 } 1792 1793 // There may be fewer values in the initialize list than the fields of struct. 1794 if (FI != FE) { 1795 RegionBindings B = GetRegionBindings(newStore.getStore()); 1796 B = addBinding(B, R, BindingKey::Default, svalBuilder.makeIntVal(0, false)); 1797 newStore = StoreRef(B.getRootWithoutRetain(), *this); 1798 } 1799 1800 return newStore; 1801} 1802 1803StoreRef RegionStoreManager::KillStruct(Store store, const TypedRegion* R, 1804 SVal DefaultVal) { 1805 BindingKey key = BindingKey::Make(R, BindingKey::Default); 1806 1807 // Remove the old bindings, using 'R' as the root of all regions 1808 // we will invalidate. 1809 RegionBindings B = GetRegionBindings(store); 1810 B = removeSubRegionBindings(B, R); 1811 1812 // Set the default value of the struct region to "unknown". 1813 if (!key.isValid()) 1814 return StoreRef(B.getRootWithoutRetain(), *this); 1815 1816 return StoreRef(addBinding(B, key, DefaultVal).getRootWithoutRetain(), *this); 1817} 1818 1819StoreRef RegionStoreManager::CopyLazyBindings(nonloc::LazyCompoundVal V, 1820 Store store, 1821 const TypedRegion *R) { 1822 1823 // Nuke the old bindings stemming from R. 1824 RegionBindings B = GetRegionBindings(store); 1825 B = removeSubRegionBindings(B, R); 1826 1827 // Now copy the bindings. This amounts to just binding 'V' to 'R'. This 1828 // results in a zero-copy algorithm. 1829 return StoreRef(addBinding(B, R, BindingKey::Default, 1830 V).getRootWithoutRetain(), *this); 1831} 1832 1833//===----------------------------------------------------------------------===// 1834// "Raw" retrievals and bindings. 1835//===----------------------------------------------------------------------===// 1836 1837 1838RegionBindings RegionStoreManager::addBinding(RegionBindings B, BindingKey K, 1839 SVal V) { 1840 if (!K.isValid()) 1841 return B; 1842 return RBFactory.add(B, K, V); 1843} 1844 1845RegionBindings RegionStoreManager::addBinding(RegionBindings B, 1846 const MemRegion *R, 1847 BindingKey::Kind k, SVal V) { 1848 return addBinding(B, BindingKey::Make(R, k), V); 1849} 1850 1851const SVal *RegionStoreManager::lookup(RegionBindings B, BindingKey K) { 1852 if (!K.isValid()) 1853 return NULL; 1854 return B.lookup(K); 1855} 1856 1857const SVal *RegionStoreManager::lookup(RegionBindings B, 1858 const MemRegion *R, 1859 BindingKey::Kind k) { 1860 return lookup(B, BindingKey::Make(R, k)); 1861} 1862 1863RegionBindings RegionStoreManager::removeBinding(RegionBindings B, 1864 BindingKey K) { 1865 if (!K.isValid()) 1866 return B; 1867 return RBFactory.remove(B, K); 1868} 1869 1870RegionBindings RegionStoreManager::removeBinding(RegionBindings B, 1871 const MemRegion *R, 1872 BindingKey::Kind k){ 1873 return removeBinding(B, BindingKey::Make(R, k)); 1874} 1875 1876//===----------------------------------------------------------------------===// 1877// State pruning. 1878//===----------------------------------------------------------------------===// 1879 1880namespace { 1881class removeDeadBindingsWorker : 1882 public ClusterAnalysis<removeDeadBindingsWorker> { 1883 SmallVector<const SymbolicRegion*, 12> Postponed; 1884 SymbolReaper &SymReaper; 1885 const StackFrameContext *CurrentLCtx; 1886 1887public: 1888 removeDeadBindingsWorker(RegionStoreManager &rm, 1889 ProgramStateManager &stateMgr, 1890 RegionBindings b, SymbolReaper &symReaper, 1891 const StackFrameContext *LCtx) 1892 : ClusterAnalysis<removeDeadBindingsWorker>(rm, stateMgr, b, 1893 /* includeGlobals = */ false), 1894 SymReaper(symReaper), CurrentLCtx(LCtx) {} 1895 1896 // Called by ClusterAnalysis. 1897 void VisitAddedToCluster(const MemRegion *baseR, RegionCluster &C); 1898 void VisitCluster(const MemRegion *baseR, BindingKey *I, BindingKey *E); 1899 1900 void VisitBindingKey(BindingKey K); 1901 bool UpdatePostponed(); 1902 void VisitBinding(SVal V); 1903}; 1904} 1905 1906void removeDeadBindingsWorker::VisitAddedToCluster(const MemRegion *baseR, 1907 RegionCluster &C) { 1908 1909 if (const VarRegion *VR = dyn_cast<VarRegion>(baseR)) { 1910 if (SymReaper.isLive(VR)) 1911 AddToWorkList(baseR, C); 1912 1913 return; 1914 } 1915 1916 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) { 1917 if (SymReaper.isLive(SR->getSymbol())) 1918 AddToWorkList(SR, C); 1919 else 1920 Postponed.push_back(SR); 1921 1922 return; 1923 } 1924 1925 if (isa<NonStaticGlobalSpaceRegion>(baseR)) { 1926 AddToWorkList(baseR, C); 1927 return; 1928 } 1929 1930 // CXXThisRegion in the current or parent location context is live. 1931 if (const CXXThisRegion *TR = dyn_cast<CXXThisRegion>(baseR)) { 1932 const StackArgumentsSpaceRegion *StackReg = 1933 cast<StackArgumentsSpaceRegion>(TR->getSuperRegion()); 1934 const StackFrameContext *RegCtx = StackReg->getStackFrame(); 1935 if (RegCtx == CurrentLCtx || RegCtx->isParentOf(CurrentLCtx)) 1936 AddToWorkList(TR, C); 1937 } 1938} 1939 1940void removeDeadBindingsWorker::VisitCluster(const MemRegion *baseR, 1941 BindingKey *I, BindingKey *E) { 1942 for ( ; I != E; ++I) 1943 VisitBindingKey(*I); 1944} 1945 1946void removeDeadBindingsWorker::VisitBinding(SVal V) { 1947 // Is it a LazyCompoundVal? All referenced regions are live as well. 1948 if (const nonloc::LazyCompoundVal *LCS = 1949 dyn_cast<nonloc::LazyCompoundVal>(&V)) { 1950 1951 const MemRegion *LazyR = LCS->getRegion(); 1952 RegionBindings B = RegionStoreManager::GetRegionBindings(LCS->getStore()); 1953 for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){ 1954 const SubRegion *baseR = dyn_cast<SubRegion>(RI.getKey().getRegion()); 1955 if (baseR && baseR->isSubRegionOf(LazyR)) 1956 VisitBinding(RI.getData()); 1957 } 1958 return; 1959 } 1960 1961 // If V is a region, then add it to the worklist. 1962 if (const MemRegion *R = V.getAsRegion()) { 1963 AddToWorkList(R); 1964 1965 // All regions captured by a block are also live. 1966 if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(R)) { 1967 BlockDataRegion::referenced_vars_iterator I = BR->referenced_vars_begin(), 1968 E = BR->referenced_vars_end(); 1969 for ( ; I != E; ++I) 1970 AddToWorkList(I.getCapturedRegion()); 1971 } 1972 } 1973 1974 1975 // Update the set of live symbols. 1976 for (SymExpr::symbol_iterator SI = V.symbol_begin(), SE = V.symbol_end(); 1977 SI!=SE; ++SI) 1978 SymReaper.markLive(*SI); 1979} 1980 1981void removeDeadBindingsWorker::VisitBindingKey(BindingKey K) { 1982 const MemRegion *R = K.getRegion(); 1983 1984 // Mark this region "live" by adding it to the worklist. This will cause 1985 // use to visit all regions in the cluster (if we haven't visited them 1986 // already). 1987 if (AddToWorkList(R)) { 1988 // Mark the symbol for any live SymbolicRegion as "live". This means we 1989 // should continue to track that symbol. 1990 if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(R)) 1991 SymReaper.markLive(SymR->getSymbol()); 1992 } 1993 1994 // Visit the data binding for K. 1995 if (const SVal *V = RM.lookup(B, K)) 1996 VisitBinding(*V); 1997} 1998 1999bool removeDeadBindingsWorker::UpdatePostponed() { 2000 // See if any postponed SymbolicRegions are actually live now, after 2001 // having done a scan. 2002 bool changed = false; 2003 2004 for (SmallVectorImpl<const SymbolicRegion*>::iterator 2005 I = Postponed.begin(), E = Postponed.end() ; I != E ; ++I) { 2006 if (const SymbolicRegion *SR = cast_or_null<SymbolicRegion>(*I)) { 2007 if (SymReaper.isLive(SR->getSymbol())) { 2008 changed |= AddToWorkList(SR); 2009 *I = NULL; 2010 } 2011 } 2012 } 2013 2014 return changed; 2015} 2016 2017StoreRef RegionStoreManager::removeDeadBindings(Store store, 2018 const StackFrameContext *LCtx, 2019 SymbolReaper& SymReaper) { 2020 RegionBindings B = GetRegionBindings(store); 2021 removeDeadBindingsWorker W(*this, StateMgr, B, SymReaper, LCtx); 2022 W.GenerateClusters(); 2023 2024 // Enqueue the region roots onto the worklist. 2025 for (SymbolReaper::region_iterator I = SymReaper.region_begin(), 2026 E = SymReaper.region_end(); I != E; ++I) { 2027 W.AddToWorkList(*I); 2028 } 2029 2030 do W.RunWorkList(); while (W.UpdatePostponed()); 2031 2032 // We have now scanned the store, marking reachable regions and symbols 2033 // as live. We now remove all the regions that are dead from the store 2034 // as well as update DSymbols with the set symbols that are now dead. 2035 for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) { 2036 const BindingKey &K = I.getKey(); 2037 2038 // If the cluster has been visited, we know the region has been marked. 2039 if (W.isVisited(K.getRegion())) 2040 continue; 2041 2042 // Remove the dead entry. 2043 B = removeBinding(B, K); 2044 2045 // Mark all non-live symbols that this binding references as dead. 2046 if (const SymbolicRegion* SymR = dyn_cast<SymbolicRegion>(K.getRegion())) 2047 SymReaper.maybeDead(SymR->getSymbol()); 2048 2049 SVal X = I.getData(); 2050 SymExpr::symbol_iterator SI = X.symbol_begin(), SE = X.symbol_end(); 2051 for (; SI != SE; ++SI) 2052 SymReaper.maybeDead(*SI); 2053 } 2054 2055 return StoreRef(B.getRootWithoutRetain(), *this); 2056} 2057 2058//===----------------------------------------------------------------------===// 2059// Utility methods. 2060//===----------------------------------------------------------------------===// 2061 2062void RegionStoreManager::print(Store store, raw_ostream &OS, 2063 const char* nl, const char *sep) { 2064 RegionBindings B = GetRegionBindings(store); 2065 OS << "Store (direct and default bindings), " 2066 << (void*) B.getRootWithoutRetain() 2067 << " :" << nl; 2068 2069 for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) 2070 OS << ' ' << I.getKey() << " : " << I.getData() << nl; 2071} 2072