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