RegionStore.cpp 85 KB

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