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