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