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