RegionStore.cpp 85 KB

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