RegionStore.cpp 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868
  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/CharUnits.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/Analysis/Analyses/LiveVariables.h"
  21. #include "clang/Analysis/AnalysisContext.h"
  22. #include "clang/Basic/TargetInfo.h"
  23. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  24. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  25. #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
  26. #include "llvm/ADT/ImmutableList.h"
  27. #include "llvm/ADT/ImmutableMap.h"
  28. #include "llvm/ADT/Optional.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. using namespace clang;
  31. using namespace ento;
  32. using llvm::Optional;
  33. //===----------------------------------------------------------------------===//
  34. // Representation of binding keys.
  35. //===----------------------------------------------------------------------===//
  36. namespace {
  37. class BindingKey {
  38. public:
  39. enum Kind { Direct = 0x0, Default = 0x1 };
  40. private:
  41. llvm ::PointerIntPair<const MemRegion*, 1> P;
  42. uint64_t Offset;
  43. explicit BindingKey(const MemRegion *r, uint64_t offset, Kind k)
  44. : P(r, (unsigned) k), Offset(offset) {}
  45. public:
  46. bool isDirect() const { return P.getInt() == Direct; }
  47. const MemRegion *getRegion() const { return P.getPointer(); }
  48. uint64_t getOffset() const { return Offset; }
  49. void Profile(llvm::FoldingSetNodeID& ID) const {
  50. ID.AddPointer(P.getOpaqueValue());
  51. ID.AddInteger(Offset);
  52. }
  53. static BindingKey Make(const MemRegion *R, Kind k);
  54. bool operator<(const BindingKey &X) const {
  55. if (P.getOpaqueValue() < X.P.getOpaqueValue())
  56. return true;
  57. if (P.getOpaqueValue() > X.P.getOpaqueValue())
  58. return false;
  59. return Offset < X.Offset;
  60. }
  61. bool operator==(const BindingKey &X) const {
  62. return P.getOpaqueValue() == X.P.getOpaqueValue() &&
  63. Offset == X.Offset;
  64. }
  65. bool isValid() const {
  66. return getRegion() != NULL;
  67. }
  68. };
  69. } // end anonymous namespace
  70. BindingKey BindingKey::Make(const MemRegion *R, Kind k) {
  71. if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
  72. const RegionRawOffset &O = ER->getAsArrayOffset();
  73. // FIXME: There are some ElementRegions for which we cannot compute
  74. // raw offsets yet, including regions with symbolic offsets. These will be
  75. // ignored by the store.
  76. return BindingKey(O.getRegion(), O.getOffset().getQuantity(), k);
  77. }
  78. return BindingKey(R, 0, k);
  79. }
  80. namespace llvm {
  81. static inline
  82. raw_ostream &operator<<(raw_ostream &os, BindingKey K) {
  83. os << '(' << K.getRegion() << ',' << K.getOffset()
  84. << ',' << (K.isDirect() ? "direct" : "default")
  85. << ')';
  86. return os;
  87. }
  88. } // end llvm namespace
  89. //===----------------------------------------------------------------------===//
  90. // Actual Store type.
  91. //===----------------------------------------------------------------------===//
  92. typedef llvm::ImmutableMap<BindingKey, SVal> RegionBindings;
  93. //===----------------------------------------------------------------------===//
  94. // Fine-grained control of RegionStoreManager.
  95. //===----------------------------------------------------------------------===//
  96. namespace {
  97. struct minimal_features_tag {};
  98. struct maximal_features_tag {};
  99. class RegionStoreFeatures {
  100. bool SupportsFields;
  101. public:
  102. RegionStoreFeatures(minimal_features_tag) :
  103. SupportsFields(false) {}
  104. RegionStoreFeatures(maximal_features_tag) :
  105. SupportsFields(true) {}
  106. void enableFields(bool t) { SupportsFields = t; }
  107. bool supportsFields() const { return SupportsFields; }
  108. };
  109. }
  110. //===----------------------------------------------------------------------===//
  111. // Main RegionStore logic.
  112. //===----------------------------------------------------------------------===//
  113. namespace {
  114. class RegionStoreSubRegionMap : public SubRegionMap {
  115. public:
  116. typedef llvm::ImmutableSet<const MemRegion*> Set;
  117. typedef llvm::DenseMap<const MemRegion*, Set> Map;
  118. private:
  119. Set::Factory F;
  120. Map M;
  121. public:
  122. bool add(const MemRegion* Parent, const MemRegion* SubRegion) {
  123. Map::iterator I = M.find(Parent);
  124. if (I == M.end()) {
  125. M.insert(std::make_pair(Parent, F.add(F.getEmptySet(), SubRegion)));
  126. return true;
  127. }
  128. I->second = F.add(I->second, SubRegion);
  129. return false;
  130. }
  131. void process(SmallVectorImpl<const SubRegion*> &WL, const SubRegion *R);
  132. ~RegionStoreSubRegionMap() {}
  133. const Set *getSubRegions(const MemRegion *Parent) const {
  134. Map::const_iterator I = M.find(Parent);
  135. return I == M.end() ? NULL : &I->second;
  136. }
  137. bool iterSubRegions(const MemRegion* Parent, Visitor& V) const {
  138. Map::const_iterator I = M.find(Parent);
  139. if (I == M.end())
  140. return true;
  141. Set S = I->second;
  142. for (Set::iterator SI=S.begin(),SE=S.end(); SI != SE; ++SI) {
  143. if (!V.Visit(Parent, *SI))
  144. return false;
  145. }
  146. return true;
  147. }
  148. };
  149. void
  150. RegionStoreSubRegionMap::process(SmallVectorImpl<const SubRegion*> &WL,
  151. const SubRegion *R) {
  152. const MemRegion *superR = R->getSuperRegion();
  153. if (add(superR, R))
  154. if (const SubRegion *sr = dyn_cast<SubRegion>(superR))
  155. WL.push_back(sr);
  156. }
  157. class RegionStoreManager : public StoreManager {
  158. const RegionStoreFeatures Features;
  159. RegionBindings::Factory RBFactory;
  160. public:
  161. RegionStoreManager(ProgramStateManager& mgr, const RegionStoreFeatures &f)
  162. : StoreManager(mgr),
  163. Features(f),
  164. RBFactory(mgr.getAllocator()) {}
  165. SubRegionMap *getSubRegionMap(Store store) {
  166. return getRegionStoreSubRegionMap(store);
  167. }
  168. RegionStoreSubRegionMap *getRegionStoreSubRegionMap(Store store);
  169. Optional<SVal> getDirectBinding(RegionBindings B, const MemRegion *R);
  170. /// getDefaultBinding - Returns an SVal* representing an optional default
  171. /// binding associated with a region and its subregions.
  172. Optional<SVal> getDefaultBinding(RegionBindings B, const MemRegion *R);
  173. /// setImplicitDefaultValue - Set the default binding for the provided
  174. /// MemRegion to the value implicitly defined for compound literals when
  175. /// the value is not specified.
  176. StoreRef setImplicitDefaultValue(Store store, const MemRegion *R, QualType T);
  177. /// ArrayToPointer - Emulates the "decay" of an array to a pointer
  178. /// type. 'Array' represents the lvalue of the array being decayed
  179. /// to a pointer, and the returned SVal represents the decayed
  180. /// version of that lvalue (i.e., a pointer to the first element of
  181. /// the array). This is called by ExprEngine when evaluating
  182. /// casts from arrays to pointers.
  183. SVal ArrayToPointer(Loc Array);
  184. /// For DerivedToBase casts, create a CXXBaseObjectRegion and return it.
  185. virtual SVal evalDerivedToBase(SVal derived, QualType basePtrType);
  186. StoreRef getInitialStore(const LocationContext *InitLoc) {
  187. return StoreRef(RBFactory.getEmptyMap().getRootWithoutRetain(), *this);
  188. }
  189. //===-------------------------------------------------------------------===//
  190. // Binding values to regions.
  191. //===-------------------------------------------------------------------===//
  192. StoreRef invalidateRegions(Store store, ArrayRef<const MemRegion *> Regions,
  193. const Expr *E, unsigned Count,
  194. InvalidatedSymbols &IS,
  195. bool invalidateGlobals,
  196. InvalidatedRegions *Invalidated);
  197. public: // Made public for helper classes.
  198. void RemoveSubRegionBindings(RegionBindings &B, const MemRegion *R,
  199. RegionStoreSubRegionMap &M);
  200. RegionBindings addBinding(RegionBindings B, BindingKey K, SVal V);
  201. RegionBindings addBinding(RegionBindings B, const MemRegion *R,
  202. BindingKey::Kind k, SVal V);
  203. const SVal *lookup(RegionBindings B, BindingKey K);
  204. const SVal *lookup(RegionBindings B, const MemRegion *R, BindingKey::Kind k);
  205. RegionBindings removeBinding(RegionBindings B, BindingKey K);
  206. RegionBindings removeBinding(RegionBindings B, const MemRegion *R,
  207. BindingKey::Kind k);
  208. RegionBindings removeBinding(RegionBindings B, const MemRegion *R) {
  209. return removeBinding(removeBinding(B, R, BindingKey::Direct), R,
  210. BindingKey::Default);
  211. }
  212. public: // Part of public interface to class.
  213. StoreRef Bind(Store store, Loc LV, SVal V);
  214. // BindDefault is only used to initialize a region with a default value.
  215. StoreRef BindDefault(Store store, const MemRegion *R, SVal V) {
  216. RegionBindings B = GetRegionBindings(store);
  217. assert(!lookup(B, R, BindingKey::Default));
  218. assert(!lookup(B, R, BindingKey::Direct));
  219. return StoreRef(addBinding(B, R, BindingKey::Default, V).getRootWithoutRetain(), *this);
  220. }
  221. StoreRef BindCompoundLiteral(Store store, const CompoundLiteralExpr *CL,
  222. const LocationContext *LC, SVal V);
  223. StoreRef BindDecl(Store store, const VarRegion *VR, SVal InitVal);
  224. StoreRef BindDeclWithNoInit(Store store, const VarRegion *) {
  225. return StoreRef(store, *this);
  226. }
  227. /// BindStruct - Bind a compound value to a structure.
  228. StoreRef BindStruct(Store store, const TypedValueRegion* R, SVal V);
  229. StoreRef BindArray(Store store, const TypedValueRegion* R, SVal V);
  230. /// KillStruct - Set the entire struct to unknown.
  231. StoreRef KillStruct(Store store, const TypedRegion* R, SVal DefaultVal);
  232. StoreRef Remove(Store store, Loc LV);
  233. void incrementReferenceCount(Store store) {
  234. GetRegionBindings(store).manualRetain();
  235. }
  236. /// If the StoreManager supports it, decrement the reference count of
  237. /// the specified Store object. If the reference count hits 0, the memory
  238. /// associated with the object is recycled.
  239. void decrementReferenceCount(Store store) {
  240. GetRegionBindings(store).manualRelease();
  241. }
  242. bool includedInBindings(Store store, const MemRegion *region) const;
  243. //===------------------------------------------------------------------===//
  244. // Loading values from regions.
  245. //===------------------------------------------------------------------===//
  246. /// The high level logic for this method is this:
  247. /// Retrieve (L)
  248. /// if L has binding
  249. /// return L's binding
  250. /// else if L is in killset
  251. /// return unknown
  252. /// else
  253. /// if L is on stack or heap
  254. /// return undefined
  255. /// else
  256. /// return symbolic
  257. SVal Retrieve(Store store, Loc L, QualType T = QualType());
  258. SVal RetrieveElement(Store store, const ElementRegion *R);
  259. SVal RetrieveField(Store store, const FieldRegion *R);
  260. SVal RetrieveObjCIvar(Store store, const ObjCIvarRegion *R);
  261. SVal RetrieveVar(Store store, const VarRegion *R);
  262. SVal RetrieveLazySymbol(const TypedValueRegion *R);
  263. SVal RetrieveFieldOrElementCommon(Store store, const TypedValueRegion *R,
  264. QualType Ty, const MemRegion *superR);
  265. SVal RetrieveLazyBinding(const MemRegion *lazyBindingRegion,
  266. Store lazyBindingStore);
  267. /// Retrieve the values in a struct and return a CompoundVal, used when doing
  268. /// struct copy:
  269. /// struct s x, y;
  270. /// x = y;
  271. /// y's value is retrieved by this method.
  272. SVal RetrieveStruct(Store store, const TypedValueRegion* R);
  273. SVal RetrieveArray(Store store, const TypedValueRegion* R);
  274. /// Used to lazily generate derived symbols for bindings that are defined
  275. /// implicitly by default bindings in a super region.
  276. Optional<SVal> RetrieveDerivedDefaultValue(RegionBindings B,
  277. const MemRegion *superR,
  278. const TypedValueRegion *R,
  279. QualType Ty);
  280. /// Get the state and region whose binding this region R corresponds to.
  281. std::pair<Store, const MemRegion*>
  282. GetLazyBinding(RegionBindings B, const MemRegion *R,
  283. const MemRegion *originalRegion);
  284. StoreRef CopyLazyBindings(nonloc::LazyCompoundVal V, Store store,
  285. const TypedRegion *R);
  286. //===------------------------------------------------------------------===//
  287. // State pruning.
  288. //===------------------------------------------------------------------===//
  289. /// removeDeadBindings - Scans the RegionStore of 'state' for dead values.
  290. /// It returns a new Store with these values removed.
  291. StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx,
  292. SymbolReaper& SymReaper);
  293. StoreRef enterStackFrame(const ProgramState *state,
  294. const StackFrameContext *frame);
  295. //===------------------------------------------------------------------===//
  296. // Region "extents".
  297. //===------------------------------------------------------------------===//
  298. // FIXME: This method will soon be eliminated; see the note in Store.h.
  299. DefinedOrUnknownSVal getSizeInElements(const ProgramState *state,
  300. const MemRegion* R, QualType EleTy);
  301. //===------------------------------------------------------------------===//
  302. // Utility methods.
  303. //===------------------------------------------------------------------===//
  304. static inline RegionBindings GetRegionBindings(Store store) {
  305. return RegionBindings(static_cast<const RegionBindings::TreeTy*>(store));
  306. }
  307. void print(Store store, raw_ostream &Out, const char* nl,
  308. const char *sep);
  309. void iterBindings(Store store, BindingsHandler& f) {
  310. RegionBindings B = GetRegionBindings(store);
  311. for (RegionBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
  312. const BindingKey &K = I.getKey();
  313. if (!K.isDirect())
  314. continue;
  315. if (const SubRegion *R = dyn_cast<SubRegion>(I.getKey().getRegion())) {
  316. // FIXME: Possibly incorporate the offset?
  317. if (!f.HandleBinding(*this, store, R, I.getData()))
  318. return;
  319. }
  320. }
  321. }
  322. };
  323. } // end anonymous namespace
  324. //===----------------------------------------------------------------------===//
  325. // RegionStore creation.
  326. //===----------------------------------------------------------------------===//
  327. StoreManager *ento::CreateRegionStoreManager(ProgramStateManager& StMgr) {
  328. RegionStoreFeatures F = maximal_features_tag();
  329. return new RegionStoreManager(StMgr, F);
  330. }
  331. StoreManager *ento::CreateFieldsOnlyRegionStoreManager(ProgramStateManager &StMgr) {
  332. RegionStoreFeatures F = minimal_features_tag();
  333. F.enableFields(true);
  334. return new RegionStoreManager(StMgr, F);
  335. }
  336. RegionStoreSubRegionMap*
  337. RegionStoreManager::getRegionStoreSubRegionMap(Store store) {
  338. RegionBindings B = GetRegionBindings(store);
  339. RegionStoreSubRegionMap *M = new RegionStoreSubRegionMap();
  340. SmallVector<const SubRegion*, 10> WL;
  341. for (RegionBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I)
  342. if (const SubRegion *R = dyn_cast<SubRegion>(I.getKey().getRegion()))
  343. M->process(WL, R);
  344. // We also need to record in the subregion map "intermediate" regions that
  345. // don't have direct bindings but are super regions of those that do.
  346. while (!WL.empty()) {
  347. const SubRegion *R = WL.back();
  348. WL.pop_back();
  349. M->process(WL, R);
  350. }
  351. return M;
  352. }
  353. //===----------------------------------------------------------------------===//
  354. // Region Cluster analysis.
  355. //===----------------------------------------------------------------------===//
  356. namespace {
  357. template <typename DERIVED>
  358. class ClusterAnalysis {
  359. protected:
  360. typedef BumpVector<BindingKey> RegionCluster;
  361. typedef llvm::DenseMap<const MemRegion *, RegionCluster *> ClusterMap;
  362. llvm::DenseMap<const RegionCluster*, unsigned> Visited;
  363. typedef SmallVector<std::pair<const MemRegion *, RegionCluster*>, 10>
  364. WorkList;
  365. BumpVectorContext BVC;
  366. ClusterMap ClusterM;
  367. WorkList WL;
  368. RegionStoreManager &RM;
  369. ASTContext &Ctx;
  370. SValBuilder &svalBuilder;
  371. RegionBindings B;
  372. const bool includeGlobals;
  373. public:
  374. ClusterAnalysis(RegionStoreManager &rm, ProgramStateManager &StateMgr,
  375. RegionBindings b, const bool includeGlobals)
  376. : RM(rm), Ctx(StateMgr.getContext()),
  377. svalBuilder(StateMgr.getSValBuilder()),
  378. B(b), includeGlobals(includeGlobals) {}
  379. RegionBindings getRegionBindings() const { return B; }
  380. RegionCluster &AddToCluster(BindingKey K) {
  381. const MemRegion *R = K.getRegion();
  382. const MemRegion *baseR = R->getBaseRegion();
  383. RegionCluster &C = getCluster(baseR);
  384. C.push_back(K, BVC);
  385. static_cast<DERIVED*>(this)->VisitAddedToCluster(baseR, C);
  386. return C;
  387. }
  388. bool isVisited(const MemRegion *R) {
  389. return (bool) Visited[&getCluster(R->getBaseRegion())];
  390. }
  391. RegionCluster& getCluster(const MemRegion *R) {
  392. RegionCluster *&CRef = ClusterM[R];
  393. if (!CRef) {
  394. void *Mem = BVC.getAllocator().template Allocate<RegionCluster>();
  395. CRef = new (Mem) RegionCluster(BVC, 10);
  396. }
  397. return *CRef;
  398. }
  399. void GenerateClusters() {
  400. // Scan the entire set of bindings and make the region clusters.
  401. for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){
  402. RegionCluster &C = AddToCluster(RI.getKey());
  403. if (const MemRegion *R = RI.getData().getAsRegion()) {
  404. // Generate a cluster, but don't add the region to the cluster
  405. // if there aren't any bindings.
  406. getCluster(R->getBaseRegion());
  407. }
  408. if (includeGlobals) {
  409. const MemRegion *R = RI.getKey().getRegion();
  410. if (isa<NonStaticGlobalSpaceRegion>(R->getMemorySpace()))
  411. AddToWorkList(R, C);
  412. }
  413. }
  414. }
  415. bool AddToWorkList(const MemRegion *R, RegionCluster &C) {
  416. if (unsigned &visited = Visited[&C])
  417. return false;
  418. else
  419. visited = 1;
  420. WL.push_back(std::make_pair(R, &C));
  421. return true;
  422. }
  423. bool AddToWorkList(BindingKey K) {
  424. return AddToWorkList(K.getRegion());
  425. }
  426. bool AddToWorkList(const MemRegion *R) {
  427. const MemRegion *baseR = R->getBaseRegion();
  428. return AddToWorkList(baseR, getCluster(baseR));
  429. }
  430. void RunWorkList() {
  431. while (!WL.empty()) {
  432. const MemRegion *baseR;
  433. RegionCluster *C;
  434. llvm::tie(baseR, C) = WL.back();
  435. WL.pop_back();
  436. // First visit the cluster.
  437. static_cast<DERIVED*>(this)->VisitCluster(baseR, C->begin(), C->end());
  438. // Next, visit the base region.
  439. static_cast<DERIVED*>(this)->VisitBaseRegion(baseR);
  440. }
  441. }
  442. public:
  443. void VisitAddedToCluster(const MemRegion *baseR, RegionCluster &C) {}
  444. void VisitCluster(const MemRegion *baseR, BindingKey *I, BindingKey *E) {}
  445. void VisitBaseRegion(const MemRegion *baseR) {}
  446. };
  447. }
  448. //===----------------------------------------------------------------------===//
  449. // Binding invalidation.
  450. //===----------------------------------------------------------------------===//
  451. void RegionStoreManager::RemoveSubRegionBindings(RegionBindings &B,
  452. const MemRegion *R,
  453. RegionStoreSubRegionMap &M) {
  454. if (const RegionStoreSubRegionMap::Set *S = M.getSubRegions(R))
  455. for (RegionStoreSubRegionMap::Set::iterator I = S->begin(), E = S->end();
  456. I != E; ++I)
  457. RemoveSubRegionBindings(B, *I, M);
  458. B = removeBinding(B, R);
  459. }
  460. namespace {
  461. class invalidateRegionsWorker : public ClusterAnalysis<invalidateRegionsWorker>
  462. {
  463. const Expr *Ex;
  464. unsigned Count;
  465. StoreManager::InvalidatedSymbols &IS;
  466. StoreManager::InvalidatedRegions *Regions;
  467. public:
  468. invalidateRegionsWorker(RegionStoreManager &rm,
  469. ProgramStateManager &stateMgr,
  470. RegionBindings b,
  471. const Expr *ex, unsigned count,
  472. StoreManager::InvalidatedSymbols &is,
  473. StoreManager::InvalidatedRegions *r,
  474. bool includeGlobals)
  475. : ClusterAnalysis<invalidateRegionsWorker>(rm, stateMgr, b, includeGlobals),
  476. Ex(ex), Count(count), IS(is), Regions(r) {}
  477. void VisitCluster(const MemRegion *baseR, BindingKey *I, BindingKey *E);
  478. void VisitBaseRegion(const MemRegion *baseR);
  479. private:
  480. void VisitBinding(SVal V);
  481. };
  482. }
  483. void invalidateRegionsWorker::VisitBinding(SVal V) {
  484. // A symbol? Mark it touched by the invalidation.
  485. if (SymbolRef Sym = V.getAsSymbol())
  486. IS.insert(Sym);
  487. if (const MemRegion *R = V.getAsRegion()) {
  488. AddToWorkList(R);
  489. return;
  490. }
  491. // Is it a LazyCompoundVal? All references get invalidated as well.
  492. if (const nonloc::LazyCompoundVal *LCS =
  493. dyn_cast<nonloc::LazyCompoundVal>(&V)) {
  494. const MemRegion *LazyR = LCS->getRegion();
  495. RegionBindings B = RegionStoreManager::GetRegionBindings(LCS->getStore());
  496. for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){
  497. const SubRegion *baseR = dyn_cast<SubRegion>(RI.getKey().getRegion());
  498. if (baseR && baseR->isSubRegionOf(LazyR))
  499. VisitBinding(RI.getData());
  500. }
  501. return;
  502. }
  503. }
  504. void invalidateRegionsWorker::VisitCluster(const MemRegion *baseR,
  505. BindingKey *I, BindingKey *E) {
  506. for ( ; I != E; ++I) {
  507. // Get the old binding. Is it a region? If so, add it to the worklist.
  508. const BindingKey &K = *I;
  509. if (const SVal *V = RM.lookup(B, K))
  510. VisitBinding(*V);
  511. B = RM.removeBinding(B, K);
  512. }
  513. }
  514. void invalidateRegionsWorker::VisitBaseRegion(const MemRegion *baseR) {
  515. // Symbolic region? Mark that symbol touched by the invalidation.
  516. if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR))
  517. IS.insert(SR->getSymbol());
  518. // BlockDataRegion? If so, invalidate captured variables that are passed
  519. // by reference.
  520. if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) {
  521. for (BlockDataRegion::referenced_vars_iterator
  522. BI = BR->referenced_vars_begin(), BE = BR->referenced_vars_end() ;
  523. BI != BE; ++BI) {
  524. const VarRegion *VR = *BI;
  525. const VarDecl *VD = VR->getDecl();
  526. if (VD->getAttr<BlocksAttr>() || !VD->hasLocalStorage())
  527. AddToWorkList(VR);
  528. }
  529. return;
  530. }
  531. // Otherwise, we have a normal data region. Record that we touched the region.
  532. if (Regions)
  533. Regions->push_back(baseR);
  534. if (isa<AllocaRegion>(baseR) || isa<SymbolicRegion>(baseR)) {
  535. // Invalidate the region by setting its default value to
  536. // conjured symbol. The type of the symbol is irrelavant.
  537. DefinedOrUnknownSVal V =
  538. svalBuilder.getConjuredSymbolVal(baseR, Ex, Ctx.IntTy, Count);
  539. B = RM.addBinding(B, baseR, BindingKey::Default, V);
  540. return;
  541. }
  542. if (!baseR->isBoundable())
  543. return;
  544. const TypedValueRegion *TR = cast<TypedValueRegion>(baseR);
  545. QualType T = TR->getValueType();
  546. // Invalidate the binding.
  547. if (T->isStructureOrClassType()) {
  548. // Invalidate the region by setting its default value to
  549. // conjured symbol. The type of the symbol is irrelavant.
  550. DefinedOrUnknownSVal V =
  551. svalBuilder.getConjuredSymbolVal(baseR, Ex, Ctx.IntTy, Count);
  552. B = RM.addBinding(B, baseR, BindingKey::Default, V);
  553. return;
  554. }
  555. if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
  556. // Set the default value of the array to conjured symbol.
  557. DefinedOrUnknownSVal V =
  558. svalBuilder.getConjuredSymbolVal(baseR, Ex, AT->getElementType(), Count);
  559. B = RM.addBinding(B, baseR, BindingKey::Default, V);
  560. return;
  561. }
  562. if (includeGlobals &&
  563. isa<NonStaticGlobalSpaceRegion>(baseR->getMemorySpace())) {
  564. // If the region is a global and we are invalidating all globals,
  565. // just erase the entry. This causes all globals to be lazily
  566. // symbolicated from the same base symbol.
  567. B = RM.removeBinding(B, baseR);
  568. return;
  569. }
  570. DefinedOrUnknownSVal V = svalBuilder.getConjuredSymbolVal(baseR, Ex, T, Count);
  571. assert(SymbolManager::canSymbolicate(T) || V.isUnknown());
  572. B = RM.addBinding(B, baseR, BindingKey::Direct, V);
  573. }
  574. StoreRef RegionStoreManager::invalidateRegions(Store store,
  575. ArrayRef<const MemRegion *> Regions,
  576. const Expr *Ex, unsigned Count,
  577. InvalidatedSymbols &IS,
  578. bool invalidateGlobals,
  579. InvalidatedRegions *Invalidated) {
  580. invalidateRegionsWorker W(*this, StateMgr,
  581. RegionStoreManager::GetRegionBindings(store),
  582. Ex, Count, IS, Invalidated, invalidateGlobals);
  583. // Scan the bindings and generate the clusters.
  584. W.GenerateClusters();
  585. // Add the regions to the worklist.
  586. for (ArrayRef<const MemRegion *>::iterator
  587. I = Regions.begin(), E = Regions.end(); I != E; ++I)
  588. W.AddToWorkList(*I);
  589. W.RunWorkList();
  590. // Return the new bindings.
  591. RegionBindings B = W.getRegionBindings();
  592. if (invalidateGlobals) {
  593. // Bind the non-static globals memory space to a new symbol that we will
  594. // use to derive the bindings for all non-static globals.
  595. const GlobalsSpaceRegion *GS = MRMgr.getGlobalsRegion();
  596. SVal V =
  597. svalBuilder.getConjuredSymbolVal(/* SymbolTag = */ (void*) GS, Ex,
  598. /* symbol type, doesn't matter */ Ctx.IntTy,
  599. Count);
  600. B = addBinding(B, BindingKey::Make(GS, BindingKey::Default), V);
  601. // Even if there are no bindings in the global scope, we still need to
  602. // record that we touched it.
  603. if (Invalidated)
  604. Invalidated->push_back(GS);
  605. }
  606. return StoreRef(B.getRootWithoutRetain(), *this);
  607. }
  608. //===----------------------------------------------------------------------===//
  609. // Extents for regions.
  610. //===----------------------------------------------------------------------===//
  611. DefinedOrUnknownSVal RegionStoreManager::getSizeInElements(const ProgramState *state,
  612. const MemRegion *R,
  613. QualType EleTy) {
  614. SVal Size = cast<SubRegion>(R)->getExtent(svalBuilder);
  615. const llvm::APSInt *SizeInt = svalBuilder.getKnownValue(state, Size);
  616. if (!SizeInt)
  617. return UnknownVal();
  618. CharUnits RegionSize = CharUnits::fromQuantity(SizeInt->getSExtValue());
  619. if (Ctx.getAsVariableArrayType(EleTy)) {
  620. // FIXME: We need to track extra state to properly record the size
  621. // of VLAs. Returning UnknownVal here, however, is a stop-gap so that
  622. // we don't have a divide-by-zero below.
  623. return UnknownVal();
  624. }
  625. CharUnits EleSize = Ctx.getTypeSizeInChars(EleTy);
  626. // If a variable is reinterpreted as a type that doesn't fit into a larger
  627. // type evenly, round it down.
  628. // This is a signed value, since it's used in arithmetic with signed indices.
  629. return svalBuilder.makeIntVal(RegionSize / EleSize, false);
  630. }
  631. //===----------------------------------------------------------------------===//
  632. // Location and region casting.
  633. //===----------------------------------------------------------------------===//
  634. /// ArrayToPointer - Emulates the "decay" of an array to a pointer
  635. /// type. 'Array' represents the lvalue of the array being decayed
  636. /// to a pointer, and the returned SVal represents the decayed
  637. /// version of that lvalue (i.e., a pointer to the first element of
  638. /// the array). This is called by ExprEngine when evaluating casts
  639. /// from arrays to pointers.
  640. SVal RegionStoreManager::ArrayToPointer(Loc Array) {
  641. if (!isa<loc::MemRegionVal>(Array))
  642. return UnknownVal();
  643. const MemRegion* R = cast<loc::MemRegionVal>(&Array)->getRegion();
  644. const TypedValueRegion* ArrayR = dyn_cast<TypedValueRegion>(R);
  645. if (!ArrayR)
  646. return UnknownVal();
  647. // Strip off typedefs from the ArrayRegion's ValueType.
  648. QualType T = ArrayR->getValueType().getDesugaredType(Ctx);
  649. const ArrayType *AT = cast<ArrayType>(T);
  650. T = AT->getElementType();
  651. NonLoc ZeroIdx = svalBuilder.makeZeroArrayIndex();
  652. return loc::MemRegionVal(MRMgr.getElementRegion(T, ZeroIdx, ArrayR, Ctx));
  653. }
  654. SVal RegionStoreManager::evalDerivedToBase(SVal derived, QualType baseType) {
  655. const CXXRecordDecl *baseDecl;
  656. if (baseType->isPointerType())
  657. baseDecl = baseType->getCXXRecordDeclForPointerType();
  658. else
  659. baseDecl = baseType->getAsCXXRecordDecl();
  660. assert(baseDecl && "not a CXXRecordDecl?");
  661. loc::MemRegionVal *derivedRegVal = dyn_cast<loc::MemRegionVal>(&derived);
  662. if (!derivedRegVal)
  663. return derived;
  664. const MemRegion *baseReg =
  665. MRMgr.getCXXBaseObjectRegion(baseDecl, derivedRegVal->getRegion());
  666. return loc::MemRegionVal(baseReg);
  667. }
  668. //===----------------------------------------------------------------------===//
  669. // Loading values from regions.
  670. //===----------------------------------------------------------------------===//
  671. Optional<SVal> RegionStoreManager::getDirectBinding(RegionBindings B,
  672. const MemRegion *R) {
  673. if (const SVal *V = lookup(B, R, BindingKey::Direct))
  674. return *V;
  675. return Optional<SVal>();
  676. }
  677. Optional<SVal> RegionStoreManager::getDefaultBinding(RegionBindings B,
  678. const MemRegion *R) {
  679. if (R->isBoundable())
  680. if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R))
  681. if (TR->getValueType()->isUnionType())
  682. return UnknownVal();
  683. if (const SVal *V = lookup(B, R, BindingKey::Default))
  684. return *V;
  685. return Optional<SVal>();
  686. }
  687. SVal RegionStoreManager::Retrieve(Store store, Loc L, QualType T) {
  688. assert(!isa<UnknownVal>(L) && "location unknown");
  689. assert(!isa<UndefinedVal>(L) && "location undefined");
  690. // For access to concrete addresses, return UnknownVal. Checks
  691. // for null dereferences (and similar errors) are done by checkers, not
  692. // the Store.
  693. // FIXME: We can consider lazily symbolicating such memory, but we really
  694. // should defer this when we can reason easily about symbolicating arrays
  695. // of bytes.
  696. if (isa<loc::ConcreteInt>(L)) {
  697. return UnknownVal();
  698. }
  699. if (!isa<loc::MemRegionVal>(L)) {
  700. return UnknownVal();
  701. }
  702. const MemRegion *MR = cast<loc::MemRegionVal>(L).getRegion();
  703. if (isa<AllocaRegion>(MR) ||
  704. isa<SymbolicRegion>(MR) ||
  705. isa<CodeTextRegion>(MR)) {
  706. if (T.isNull()) {
  707. const SymbolicRegion *SR = cast<SymbolicRegion>(MR);
  708. T = SR->getSymbol()->getType(Ctx);
  709. }
  710. MR = GetElementZeroRegion(MR, T);
  711. }
  712. // FIXME: Perhaps this method should just take a 'const MemRegion*' argument
  713. // instead of 'Loc', and have the other Loc cases handled at a higher level.
  714. const TypedValueRegion *R = cast<TypedValueRegion>(MR);
  715. QualType RTy = R->getValueType();
  716. // FIXME: We should eventually handle funny addressing. e.g.:
  717. //
  718. // int x = ...;
  719. // int *p = &x;
  720. // char *q = (char*) p;
  721. // char c = *q; // returns the first byte of 'x'.
  722. //
  723. // Such funny addressing will occur due to layering of regions.
  724. if (RTy->isStructureOrClassType())
  725. return RetrieveStruct(store, R);
  726. // FIXME: Handle unions.
  727. if (RTy->isUnionType())
  728. return UnknownVal();
  729. if (RTy->isArrayType())
  730. return RetrieveArray(store, R);
  731. // FIXME: handle Vector types.
  732. if (RTy->isVectorType())
  733. return UnknownVal();
  734. if (const FieldRegion* FR = dyn_cast<FieldRegion>(R))
  735. return CastRetrievedVal(RetrieveField(store, FR), FR, T, false);
  736. if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) {
  737. // FIXME: Here we actually perform an implicit conversion from the loaded
  738. // value to the element type. Eventually we want to compose these values
  739. // more intelligently. For example, an 'element' can encompass multiple
  740. // bound regions (e.g., several bound bytes), or could be a subset of
  741. // a larger value.
  742. return CastRetrievedVal(RetrieveElement(store, ER), ER, T, false);
  743. }
  744. if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) {
  745. // FIXME: Here we actually perform an implicit conversion from the loaded
  746. // value to the ivar type. What we should model is stores to ivars
  747. // that blow past the extent of the ivar. If the address of the ivar is
  748. // reinterpretted, it is possible we stored a different value that could
  749. // fit within the ivar. Either we need to cast these when storing them
  750. // or reinterpret them lazily (as we do here).
  751. return CastRetrievedVal(RetrieveObjCIvar(store, IVR), IVR, T, false);
  752. }
  753. if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
  754. // FIXME: Here we actually perform an implicit conversion from the loaded
  755. // value to the variable type. What we should model is stores to variables
  756. // that blow past the extent of the variable. If the address of the
  757. // variable is reinterpretted, it is possible we stored a different value
  758. // that could fit within the variable. Either we need to cast these when
  759. // storing them or reinterpret them lazily (as we do here).
  760. return CastRetrievedVal(RetrieveVar(store, VR), VR, T, false);
  761. }
  762. RegionBindings B = GetRegionBindings(store);
  763. const SVal *V = lookup(B, R, BindingKey::Direct);
  764. // Check if the region has a binding.
  765. if (V)
  766. return *V;
  767. // The location does not have a bound value. This means that it has
  768. // the value it had upon its creation and/or entry to the analyzed
  769. // function/method. These are either symbolic values or 'undefined'.
  770. if (R->hasStackNonParametersStorage()) {
  771. // All stack variables are considered to have undefined values
  772. // upon creation. All heap allocated blocks are considered to
  773. // have undefined values as well unless they are explicitly bound
  774. // to specific values.
  775. return UndefinedVal();
  776. }
  777. // All other values are symbolic.
  778. return svalBuilder.getRegionValueSymbolVal(R);
  779. }
  780. std::pair<Store, const MemRegion *>
  781. RegionStoreManager::GetLazyBinding(RegionBindings B, const MemRegion *R,
  782. const MemRegion *originalRegion) {
  783. if (originalRegion != R) {
  784. if (Optional<SVal> OV = getDefaultBinding(B, R)) {
  785. if (const nonloc::LazyCompoundVal *V =
  786. dyn_cast<nonloc::LazyCompoundVal>(OV.getPointer()))
  787. return std::make_pair(V->getStore(), V->getRegion());
  788. }
  789. }
  790. if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
  791. const std::pair<Store, const MemRegion *> &X =
  792. GetLazyBinding(B, ER->getSuperRegion(), originalRegion);
  793. if (X.second)
  794. return std::make_pair(X.first,
  795. MRMgr.getElementRegionWithSuper(ER, X.second));
  796. }
  797. else if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) {
  798. const std::pair<Store, const MemRegion *> &X =
  799. GetLazyBinding(B, FR->getSuperRegion(), originalRegion);
  800. if (X.second)
  801. return std::make_pair(X.first,
  802. MRMgr.getFieldRegionWithSuper(FR, X.second));
  803. }
  804. // C++ base object region is another kind of region that we should blast
  805. // through to look for lazy compound value. It is like a field region.
  806. else if (const CXXBaseObjectRegion *baseReg =
  807. dyn_cast<CXXBaseObjectRegion>(R)) {
  808. const std::pair<Store, const MemRegion *> &X =
  809. GetLazyBinding(B, baseReg->getSuperRegion(), originalRegion);
  810. if (X.second)
  811. return std::make_pair(X.first,
  812. MRMgr.getCXXBaseObjectRegionWithSuper(baseReg, X.second));
  813. }
  814. // The NULL MemRegion indicates an non-existent lazy binding. A NULL Store is
  815. // possible for a valid lazy binding.
  816. return std::make_pair((Store) 0, (const MemRegion *) 0);
  817. }
  818. SVal RegionStoreManager::RetrieveElement(Store store,
  819. const ElementRegion* R) {
  820. // Check if the region has a binding.
  821. RegionBindings B = GetRegionBindings(store);
  822. if (const Optional<SVal> &V = getDirectBinding(B, R))
  823. return *V;
  824. const MemRegion* superR = R->getSuperRegion();
  825. // Check if the region is an element region of a string literal.
  826. if (const StringRegion *StrR=dyn_cast<StringRegion>(superR)) {
  827. // FIXME: Handle loads from strings where the literal is treated as
  828. // an integer, e.g., *((unsigned int*)"hello")
  829. QualType T = Ctx.getAsArrayType(StrR->getValueType())->getElementType();
  830. if (T != Ctx.getCanonicalType(R->getElementType()))
  831. return UnknownVal();
  832. const StringLiteral *Str = StrR->getStringLiteral();
  833. SVal Idx = R->getIndex();
  834. if (nonloc::ConcreteInt *CI = dyn_cast<nonloc::ConcreteInt>(&Idx)) {
  835. int64_t i = CI->getValue().getSExtValue();
  836. // Abort on string underrun. This can be possible by arbitrary
  837. // clients of RetrieveElement().
  838. if (i < 0)
  839. return UndefinedVal();
  840. int64_t length = Str->getLength();
  841. // Technically, only i == length is guaranteed to be null.
  842. // However, such overflows should be caught before reaching this point;
  843. // the only time such an access would be made is if a string literal was
  844. // used to initialize a larger array.
  845. char c = (i >= length) ? '\0' : Str->getCodeUnit(i);
  846. return svalBuilder.makeIntVal(c, T);
  847. }
  848. }
  849. // Check for loads from a code text region. For such loads, just give up.
  850. if (isa<CodeTextRegion>(superR))
  851. return UnknownVal();
  852. // Handle the case where we are indexing into a larger scalar object.
  853. // For example, this handles:
  854. // int x = ...
  855. // char *y = &x;
  856. // return *y;
  857. // FIXME: This is a hack, and doesn't do anything really intelligent yet.
  858. const RegionRawOffset &O = R->getAsArrayOffset();
  859. // If we cannot reason about the offset, return an unknown value.
  860. if (!O.getRegion())
  861. return UnknownVal();
  862. if (const TypedValueRegion *baseR =
  863. dyn_cast_or_null<TypedValueRegion>(O.getRegion())) {
  864. QualType baseT = baseR->getValueType();
  865. if (baseT->isScalarType()) {
  866. QualType elemT = R->getElementType();
  867. if (elemT->isScalarType()) {
  868. if (Ctx.getTypeSizeInChars(baseT) >= Ctx.getTypeSizeInChars(elemT)) {
  869. if (const Optional<SVal> &V = getDirectBinding(B, superR)) {
  870. if (SymbolRef parentSym = V->getAsSymbol())
  871. return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
  872. if (V->isUnknownOrUndef())
  873. return *V;
  874. // Other cases: give up. We are indexing into a larger object
  875. // that has some value, but we don't know how to handle that yet.
  876. return UnknownVal();
  877. }
  878. }
  879. }
  880. }
  881. }
  882. return RetrieveFieldOrElementCommon(store, R, R->getElementType(), superR);
  883. }
  884. SVal RegionStoreManager::RetrieveField(Store store,
  885. const FieldRegion* R) {
  886. // Check if the region has a binding.
  887. RegionBindings B = GetRegionBindings(store);
  888. if (const Optional<SVal> &V = getDirectBinding(B, R))
  889. return *V;
  890. QualType Ty = R->getValueType();
  891. return RetrieveFieldOrElementCommon(store, R, Ty, R->getSuperRegion());
  892. }
  893. Optional<SVal>
  894. RegionStoreManager::RetrieveDerivedDefaultValue(RegionBindings B,
  895. const MemRegion *superR,
  896. const TypedValueRegion *R,
  897. QualType Ty) {
  898. if (const Optional<SVal> &D = getDefaultBinding(B, superR)) {
  899. const SVal &val = D.getValue();
  900. if (SymbolRef parentSym = val.getAsSymbol())
  901. return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
  902. if (val.isZeroConstant())
  903. return svalBuilder.makeZeroVal(Ty);
  904. if (val.isUnknownOrUndef())
  905. return val;
  906. // Lazy bindings are handled later.
  907. if (isa<nonloc::LazyCompoundVal>(val))
  908. return Optional<SVal>();
  909. llvm_unreachable("Unknown default value");
  910. }
  911. return Optional<SVal>();
  912. }
  913. SVal RegionStoreManager::RetrieveLazyBinding(const MemRegion *lazyBindingRegion,
  914. Store lazyBindingStore) {
  915. if (const ElementRegion *ER = dyn_cast<ElementRegion>(lazyBindingRegion))
  916. return RetrieveElement(lazyBindingStore, ER);
  917. return RetrieveField(lazyBindingStore,
  918. cast<FieldRegion>(lazyBindingRegion));
  919. }
  920. SVal RegionStoreManager::RetrieveFieldOrElementCommon(Store store,
  921. const TypedValueRegion *R,
  922. QualType Ty,
  923. const MemRegion *superR) {
  924. // At this point we have already checked in either RetrieveElement or
  925. // RetrieveField if 'R' has a direct binding.
  926. RegionBindings B = GetRegionBindings(store);
  927. while (superR) {
  928. if (const Optional<SVal> &D =
  929. RetrieveDerivedDefaultValue(B, superR, R, Ty))
  930. return *D;
  931. // If our super region is a field or element itself, walk up the region
  932. // hierarchy to see if there is a default value installed in an ancestor.
  933. if (const SubRegion *SR = dyn_cast<SubRegion>(superR)) {
  934. superR = SR->getSuperRegion();
  935. continue;
  936. }
  937. break;
  938. }
  939. // Lazy binding?
  940. Store lazyBindingStore = NULL;
  941. const MemRegion *lazyBindingRegion = NULL;
  942. llvm::tie(lazyBindingStore, lazyBindingRegion) = GetLazyBinding(B, R, R);
  943. if (lazyBindingRegion)
  944. return RetrieveLazyBinding(lazyBindingRegion, lazyBindingStore);
  945. if (R->hasStackNonParametersStorage()) {
  946. if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
  947. // Currently we don't reason specially about Clang-style vectors. Check
  948. // if superR is a vector and if so return Unknown.
  949. if (const TypedValueRegion *typedSuperR =
  950. dyn_cast<TypedValueRegion>(superR)) {
  951. if (typedSuperR->getValueType()->isVectorType())
  952. return UnknownVal();
  953. }
  954. // FIXME: We also need to take ElementRegions with symbolic indexes into
  955. // account.
  956. if (!ER->getIndex().isConstant())
  957. return UnknownVal();
  958. }
  959. return UndefinedVal();
  960. }
  961. // All other values are symbolic.
  962. return svalBuilder.getRegionValueSymbolVal(R);
  963. }
  964. SVal RegionStoreManager::RetrieveObjCIvar(Store store, const ObjCIvarRegion* R){
  965. // Check if the region has a binding.
  966. RegionBindings B = GetRegionBindings(store);
  967. if (const Optional<SVal> &V = getDirectBinding(B, R))
  968. return *V;
  969. const MemRegion *superR = R->getSuperRegion();
  970. // Check if the super region has a default binding.
  971. if (const Optional<SVal> &V = getDefaultBinding(B, superR)) {
  972. if (SymbolRef parentSym = V->getAsSymbol())
  973. return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
  974. // Other cases: give up.
  975. return UnknownVal();
  976. }
  977. return RetrieveLazySymbol(R);
  978. }
  979. SVal RegionStoreManager::RetrieveVar(Store store, const VarRegion *R) {
  980. // Check if the region has a binding.
  981. RegionBindings B = GetRegionBindings(store);
  982. if (const Optional<SVal> &V = getDirectBinding(B, R))
  983. return *V;
  984. // Lazily derive a value for the VarRegion.
  985. const VarDecl *VD = R->getDecl();
  986. QualType T = VD->getType();
  987. const MemSpaceRegion *MS = R->getMemorySpace();
  988. if (isa<UnknownSpaceRegion>(MS) ||
  989. isa<StackArgumentsSpaceRegion>(MS))
  990. return svalBuilder.getRegionValueSymbolVal(R);
  991. if (isa<GlobalsSpaceRegion>(MS)) {
  992. if (isa<NonStaticGlobalSpaceRegion>(MS)) {
  993. // Is 'VD' declared constant? If so, retrieve the constant value.
  994. QualType CT = Ctx.getCanonicalType(T);
  995. if (CT.isConstQualified()) {
  996. const Expr *Init = VD->getInit();
  997. // Do the null check first, as we want to call 'IgnoreParenCasts'.
  998. if (Init)
  999. if (const IntegerLiteral *IL =
  1000. dyn_cast<IntegerLiteral>(Init->IgnoreParenCasts())) {
  1001. const nonloc::ConcreteInt &V = svalBuilder.makeIntVal(IL);
  1002. return svalBuilder.evalCast(V, Init->getType(), IL->getType());
  1003. }
  1004. }
  1005. if (const Optional<SVal> &V = RetrieveDerivedDefaultValue(B, MS, R, CT))
  1006. return V.getValue();
  1007. return svalBuilder.getRegionValueSymbolVal(R);
  1008. }
  1009. if (T->isIntegerType())
  1010. return svalBuilder.makeIntVal(0, T);
  1011. if (T->isPointerType())
  1012. return svalBuilder.makeNull();
  1013. return UnknownVal();
  1014. }
  1015. return UndefinedVal();
  1016. }
  1017. SVal RegionStoreManager::RetrieveLazySymbol(const TypedValueRegion *R) {
  1018. // All other values are symbolic.
  1019. return svalBuilder.getRegionValueSymbolVal(R);
  1020. }
  1021. SVal RegionStoreManager::RetrieveStruct(Store store,
  1022. const TypedValueRegion* R) {
  1023. QualType T = R->getValueType();
  1024. assert(T->isStructureOrClassType());
  1025. return svalBuilder.makeLazyCompoundVal(StoreRef(store, *this), R);
  1026. }
  1027. SVal RegionStoreManager::RetrieveArray(Store store,
  1028. const TypedValueRegion * R) {
  1029. assert(Ctx.getAsConstantArrayType(R->getValueType()));
  1030. return svalBuilder.makeLazyCompoundVal(StoreRef(store, *this), R);
  1031. }
  1032. bool RegionStoreManager::includedInBindings(Store store,
  1033. const MemRegion *region) const {
  1034. RegionBindings B = GetRegionBindings(store);
  1035. region = region->getBaseRegion();
  1036. for (RegionBindings::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
  1037. const BindingKey &K = it.getKey();
  1038. if (region == K.getRegion())
  1039. return true;
  1040. const SVal &D = it.getData();
  1041. if (const MemRegion *r = D.getAsRegion())
  1042. if (r == region)
  1043. return true;
  1044. }
  1045. return false;
  1046. }
  1047. //===----------------------------------------------------------------------===//
  1048. // Binding values to regions.
  1049. //===----------------------------------------------------------------------===//
  1050. StoreRef RegionStoreManager::Remove(Store store, Loc L) {
  1051. if (isa<loc::MemRegionVal>(L))
  1052. if (const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion())
  1053. return StoreRef(removeBinding(GetRegionBindings(store),
  1054. R).getRootWithoutRetain(),
  1055. *this);
  1056. return StoreRef(store, *this);
  1057. }
  1058. StoreRef RegionStoreManager::Bind(Store store, Loc L, SVal V) {
  1059. if (isa<loc::ConcreteInt>(L))
  1060. return StoreRef(store, *this);
  1061. // If we get here, the location should be a region.
  1062. const MemRegion *R = cast<loc::MemRegionVal>(L).getRegion();
  1063. // Check if the region is a struct region.
  1064. if (const TypedValueRegion* TR = dyn_cast<TypedValueRegion>(R))
  1065. if (TR->getValueType()->isStructureOrClassType())
  1066. return BindStruct(store, TR, V);
  1067. if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
  1068. if (ER->getIndex().isZeroConstant()) {
  1069. if (const TypedValueRegion *superR =
  1070. dyn_cast<TypedValueRegion>(ER->getSuperRegion())) {
  1071. QualType superTy = superR->getValueType();
  1072. // For now, just invalidate the fields of the struct/union/class.
  1073. // This is for test rdar_test_7185607 in misc-ps-region-store.m.
  1074. // FIXME: Precisely handle the fields of the record.
  1075. if (superTy->isStructureOrClassType())
  1076. return KillStruct(store, superR, UnknownVal());
  1077. }
  1078. }
  1079. }
  1080. else if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) {
  1081. // Binding directly to a symbolic region should be treated as binding
  1082. // to element 0.
  1083. QualType T = SR->getSymbol()->getType(Ctx);
  1084. // FIXME: Is this the right way to handle symbols that are references?
  1085. if (const PointerType *PT = T->getAs<PointerType>())
  1086. T = PT->getPointeeType();
  1087. else
  1088. T = T->getAs<ReferenceType>()->getPointeeType();
  1089. R = GetElementZeroRegion(SR, T);
  1090. }
  1091. // Perform the binding.
  1092. RegionBindings B = GetRegionBindings(store);
  1093. return StoreRef(addBinding(B, R, BindingKey::Direct,
  1094. V).getRootWithoutRetain(), *this);
  1095. }
  1096. StoreRef RegionStoreManager::BindDecl(Store store, const VarRegion *VR,
  1097. SVal InitVal) {
  1098. QualType T = VR->getDecl()->getType();
  1099. if (T->isArrayType())
  1100. return BindArray(store, VR, InitVal);
  1101. if (T->isStructureOrClassType())
  1102. return BindStruct(store, VR, InitVal);
  1103. return Bind(store, svalBuilder.makeLoc(VR), InitVal);
  1104. }
  1105. // FIXME: this method should be merged into Bind().
  1106. StoreRef RegionStoreManager::BindCompoundLiteral(Store store,
  1107. const CompoundLiteralExpr *CL,
  1108. const LocationContext *LC,
  1109. SVal V) {
  1110. return Bind(store, loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CL, LC)),
  1111. V);
  1112. }
  1113. StoreRef RegionStoreManager::setImplicitDefaultValue(Store store,
  1114. const MemRegion *R,
  1115. QualType T) {
  1116. RegionBindings B = GetRegionBindings(store);
  1117. SVal V;
  1118. if (Loc::isLocType(T))
  1119. V = svalBuilder.makeNull();
  1120. else if (T->isIntegerType())
  1121. V = svalBuilder.makeZeroVal(T);
  1122. else if (T->isStructureOrClassType() || T->isArrayType()) {
  1123. // Set the default value to a zero constant when it is a structure
  1124. // or array. The type doesn't really matter.
  1125. V = svalBuilder.makeZeroVal(Ctx.IntTy);
  1126. }
  1127. else {
  1128. // We can't represent values of this type, but we still need to set a value
  1129. // to record that the region has been initialized.
  1130. // If this assertion ever fires, a new case should be added above -- we
  1131. // should know how to default-initialize any value we can symbolicate.
  1132. assert(!SymbolManager::canSymbolicate(T) && "This type is representable");
  1133. V = UnknownVal();
  1134. }
  1135. return StoreRef(addBinding(B, R, BindingKey::Default,
  1136. V).getRootWithoutRetain(), *this);
  1137. }
  1138. StoreRef RegionStoreManager::BindArray(Store store, const TypedValueRegion* R,
  1139. SVal Init) {
  1140. const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType()));
  1141. QualType ElementTy = AT->getElementType();
  1142. Optional<uint64_t> Size;
  1143. if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT))
  1144. Size = CAT->getSize().getZExtValue();
  1145. // Check if the init expr is a string literal.
  1146. if (loc::MemRegionVal *MRV = dyn_cast<loc::MemRegionVal>(&Init)) {
  1147. const StringRegion *S = cast<StringRegion>(MRV->getRegion());
  1148. // Treat the string as a lazy compound value.
  1149. nonloc::LazyCompoundVal LCV =
  1150. cast<nonloc::LazyCompoundVal>(svalBuilder.
  1151. makeLazyCompoundVal(StoreRef(store, *this), S));
  1152. return CopyLazyBindings(LCV, store, R);
  1153. }
  1154. // Handle lazy compound values.
  1155. if (nonloc::LazyCompoundVal *LCV = dyn_cast<nonloc::LazyCompoundVal>(&Init))
  1156. return CopyLazyBindings(*LCV, store, R);
  1157. // Remaining case: explicit compound values.
  1158. if (Init.isUnknown())
  1159. return setImplicitDefaultValue(store, R, ElementTy);
  1160. nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(Init);
  1161. nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
  1162. uint64_t i = 0;
  1163. StoreRef newStore(store, *this);
  1164. for (; Size.hasValue() ? i < Size.getValue() : true ; ++i, ++VI) {
  1165. // The init list might be shorter than the array length.
  1166. if (VI == VE)
  1167. break;
  1168. const NonLoc &Idx = svalBuilder.makeArrayIndex(i);
  1169. const ElementRegion *ER = MRMgr.getElementRegion(ElementTy, Idx, R, Ctx);
  1170. if (ElementTy->isStructureOrClassType())
  1171. newStore = BindStruct(newStore.getStore(), ER, *VI);
  1172. else if (ElementTy->isArrayType())
  1173. newStore = BindArray(newStore.getStore(), ER, *VI);
  1174. else
  1175. newStore = Bind(newStore.getStore(), svalBuilder.makeLoc(ER), *VI);
  1176. }
  1177. // If the init list is shorter than the array length, set the
  1178. // array default value.
  1179. if (Size.hasValue() && i < Size.getValue())
  1180. newStore = setImplicitDefaultValue(newStore.getStore(), R, ElementTy);
  1181. return newStore;
  1182. }
  1183. StoreRef RegionStoreManager::BindStruct(Store store, const TypedValueRegion* R,
  1184. SVal V) {
  1185. if (!Features.supportsFields())
  1186. return StoreRef(store, *this);
  1187. QualType T = R->getValueType();
  1188. assert(T->isStructureOrClassType());
  1189. const RecordType* RT = T->getAs<RecordType>();
  1190. RecordDecl *RD = RT->getDecl();
  1191. if (!RD->isCompleteDefinition())
  1192. return StoreRef(store, *this);
  1193. // Handle lazy compound values.
  1194. if (const nonloc::LazyCompoundVal *LCV=dyn_cast<nonloc::LazyCompoundVal>(&V))
  1195. return CopyLazyBindings(*LCV, store, R);
  1196. // We may get non-CompoundVal accidentally due to imprecise cast logic or
  1197. // that we are binding symbolic struct value. Kill the field values, and if
  1198. // the value is symbolic go and bind it as a "default" binding.
  1199. if (V.isUnknown() || !isa<nonloc::CompoundVal>(V)) {
  1200. SVal SV = isa<nonloc::SymbolVal>(V) ? V : UnknownVal();
  1201. return KillStruct(store, R, SV);
  1202. }
  1203. nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(V);
  1204. nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
  1205. RecordDecl::field_iterator FI, FE;
  1206. StoreRef newStore(store, *this);
  1207. for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; ++FI) {
  1208. if (VI == VE)
  1209. break;
  1210. // Skip any unnamed bitfields to stay in sync with the initializers.
  1211. if ((*FI)->isUnnamedBitfield())
  1212. continue;
  1213. QualType FTy = (*FI)->getType();
  1214. const FieldRegion* FR = MRMgr.getFieldRegion(*FI, R);
  1215. if (FTy->isArrayType())
  1216. newStore = BindArray(newStore.getStore(), FR, *VI);
  1217. else if (FTy->isStructureOrClassType())
  1218. newStore = BindStruct(newStore.getStore(), FR, *VI);
  1219. else
  1220. newStore = Bind(newStore.getStore(), svalBuilder.makeLoc(FR), *VI);
  1221. ++VI;
  1222. }
  1223. // There may be fewer values in the initialize list than the fields of struct.
  1224. if (FI != FE) {
  1225. RegionBindings B = GetRegionBindings(newStore.getStore());
  1226. B = addBinding(B, R, BindingKey::Default, svalBuilder.makeIntVal(0, false));
  1227. newStore = StoreRef(B.getRootWithoutRetain(), *this);
  1228. }
  1229. return newStore;
  1230. }
  1231. StoreRef RegionStoreManager::KillStruct(Store store, const TypedRegion* R,
  1232. SVal DefaultVal) {
  1233. BindingKey key = BindingKey::Make(R, BindingKey::Default);
  1234. // The BindingKey may be "invalid" if we cannot handle the region binding
  1235. // explicitly. One example is something like array[index], where index
  1236. // is a symbolic value. In such cases, we want to invalidate the entire
  1237. // array, as the index assignment could have been to any element. In
  1238. // the case of nested symbolic indices, we need to march up the region
  1239. // hierarchy untile we reach a region whose binding we can reason about.
  1240. const SubRegion *subReg = R;
  1241. while (!key.isValid()) {
  1242. if (const SubRegion *tmp = dyn_cast<SubRegion>(subReg->getSuperRegion())) {
  1243. subReg = tmp;
  1244. key = BindingKey::Make(tmp, BindingKey::Default);
  1245. }
  1246. else
  1247. break;
  1248. }
  1249. // Remove the old bindings, using 'subReg' as the root of all regions
  1250. // we will invalidate.
  1251. RegionBindings B = GetRegionBindings(store);
  1252. llvm::OwningPtr<RegionStoreSubRegionMap>
  1253. SubRegions(getRegionStoreSubRegionMap(store));
  1254. RemoveSubRegionBindings(B, subReg, *SubRegions);
  1255. // Set the default value of the struct region to "unknown".
  1256. if (!key.isValid())
  1257. return StoreRef(B.getRootWithoutRetain(), *this);
  1258. return StoreRef(addBinding(B, key, DefaultVal).getRootWithoutRetain(), *this);
  1259. }
  1260. StoreRef RegionStoreManager::CopyLazyBindings(nonloc::LazyCompoundVal V,
  1261. Store store,
  1262. const TypedRegion *R) {
  1263. // Nuke the old bindings stemming from R.
  1264. RegionBindings B = GetRegionBindings(store);
  1265. llvm::OwningPtr<RegionStoreSubRegionMap>
  1266. SubRegions(getRegionStoreSubRegionMap(store));
  1267. // B and DVM are updated after the call to RemoveSubRegionBindings.
  1268. RemoveSubRegionBindings(B, R, *SubRegions.get());
  1269. // Now copy the bindings. This amounts to just binding 'V' to 'R'. This
  1270. // results in a zero-copy algorithm.
  1271. return StoreRef(addBinding(B, R, BindingKey::Default,
  1272. V).getRootWithoutRetain(), *this);
  1273. }
  1274. //===----------------------------------------------------------------------===//
  1275. // "Raw" retrievals and bindings.
  1276. //===----------------------------------------------------------------------===//
  1277. RegionBindings RegionStoreManager::addBinding(RegionBindings B, BindingKey K,
  1278. SVal V) {
  1279. if (!K.isValid())
  1280. return B;
  1281. return RBFactory.add(B, K, V);
  1282. }
  1283. RegionBindings RegionStoreManager::addBinding(RegionBindings B,
  1284. const MemRegion *R,
  1285. BindingKey::Kind k, SVal V) {
  1286. return addBinding(B, BindingKey::Make(R, k), V);
  1287. }
  1288. const SVal *RegionStoreManager::lookup(RegionBindings B, BindingKey K) {
  1289. if (!K.isValid())
  1290. return NULL;
  1291. return B.lookup(K);
  1292. }
  1293. const SVal *RegionStoreManager::lookup(RegionBindings B,
  1294. const MemRegion *R,
  1295. BindingKey::Kind k) {
  1296. return lookup(B, BindingKey::Make(R, k));
  1297. }
  1298. RegionBindings RegionStoreManager::removeBinding(RegionBindings B,
  1299. BindingKey K) {
  1300. if (!K.isValid())
  1301. return B;
  1302. return RBFactory.remove(B, K);
  1303. }
  1304. RegionBindings RegionStoreManager::removeBinding(RegionBindings B,
  1305. const MemRegion *R,
  1306. BindingKey::Kind k){
  1307. return removeBinding(B, BindingKey::Make(R, k));
  1308. }
  1309. //===----------------------------------------------------------------------===//
  1310. // State pruning.
  1311. //===----------------------------------------------------------------------===//
  1312. namespace {
  1313. class removeDeadBindingsWorker :
  1314. public ClusterAnalysis<removeDeadBindingsWorker> {
  1315. SmallVector<const SymbolicRegion*, 12> Postponed;
  1316. SymbolReaper &SymReaper;
  1317. const StackFrameContext *CurrentLCtx;
  1318. public:
  1319. removeDeadBindingsWorker(RegionStoreManager &rm, ProgramStateManager &stateMgr,
  1320. RegionBindings b, SymbolReaper &symReaper,
  1321. const StackFrameContext *LCtx)
  1322. : ClusterAnalysis<removeDeadBindingsWorker>(rm, stateMgr, b,
  1323. /* includeGlobals = */ false),
  1324. SymReaper(symReaper), CurrentLCtx(LCtx) {}
  1325. // Called by ClusterAnalysis.
  1326. void VisitAddedToCluster(const MemRegion *baseR, RegionCluster &C);
  1327. void VisitCluster(const MemRegion *baseR, BindingKey *I, BindingKey *E);
  1328. void VisitBindingKey(BindingKey K);
  1329. bool UpdatePostponed();
  1330. void VisitBinding(SVal V);
  1331. };
  1332. }
  1333. void removeDeadBindingsWorker::VisitAddedToCluster(const MemRegion *baseR,
  1334. RegionCluster &C) {
  1335. if (const VarRegion *VR = dyn_cast<VarRegion>(baseR)) {
  1336. if (SymReaper.isLive(VR))
  1337. AddToWorkList(baseR, C);
  1338. return;
  1339. }
  1340. if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) {
  1341. if (SymReaper.isLive(SR->getSymbol()))
  1342. AddToWorkList(SR, C);
  1343. else
  1344. Postponed.push_back(SR);
  1345. return;
  1346. }
  1347. if (isa<NonStaticGlobalSpaceRegion>(baseR)) {
  1348. AddToWorkList(baseR, C);
  1349. return;
  1350. }
  1351. // CXXThisRegion in the current or parent location context is live.
  1352. if (const CXXThisRegion *TR = dyn_cast<CXXThisRegion>(baseR)) {
  1353. const StackArgumentsSpaceRegion *StackReg =
  1354. cast<StackArgumentsSpaceRegion>(TR->getSuperRegion());
  1355. const StackFrameContext *RegCtx = StackReg->getStackFrame();
  1356. if (RegCtx == CurrentLCtx || RegCtx->isParentOf(CurrentLCtx))
  1357. AddToWorkList(TR, C);
  1358. }
  1359. }
  1360. void removeDeadBindingsWorker::VisitCluster(const MemRegion *baseR,
  1361. BindingKey *I, BindingKey *E) {
  1362. for ( ; I != E; ++I)
  1363. VisitBindingKey(*I);
  1364. }
  1365. void removeDeadBindingsWorker::VisitBinding(SVal V) {
  1366. // Is it a LazyCompoundVal? All referenced regions are live as well.
  1367. if (const nonloc::LazyCompoundVal *LCS =
  1368. dyn_cast<nonloc::LazyCompoundVal>(&V)) {
  1369. const MemRegion *LazyR = LCS->getRegion();
  1370. RegionBindings B = RegionStoreManager::GetRegionBindings(LCS->getStore());
  1371. for (RegionBindings::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){
  1372. const SubRegion *baseR = dyn_cast<SubRegion>(RI.getKey().getRegion());
  1373. if (baseR && baseR->isSubRegionOf(LazyR))
  1374. VisitBinding(RI.getData());
  1375. }
  1376. return;
  1377. }
  1378. // If V is a region, then add it to the worklist.
  1379. if (const MemRegion *R = V.getAsRegion())
  1380. AddToWorkList(R);
  1381. // Update the set of live symbols.
  1382. for (SymExpr::symbol_iterator SI = V.symbol_begin(), SE = V.symbol_end();
  1383. SI!=SE; ++SI)
  1384. SymReaper.markLive(*SI);
  1385. }
  1386. void removeDeadBindingsWorker::VisitBindingKey(BindingKey K) {
  1387. const MemRegion *R = K.getRegion();
  1388. // Mark this region "live" by adding it to the worklist. This will cause
  1389. // use to visit all regions in the cluster (if we haven't visited them
  1390. // already).
  1391. if (AddToWorkList(R)) {
  1392. // Mark the symbol for any live SymbolicRegion as "live". This means we
  1393. // should continue to track that symbol.
  1394. if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(R))
  1395. SymReaper.markLive(SymR->getSymbol());
  1396. // For BlockDataRegions, enqueue the VarRegions for variables marked
  1397. // with __block (passed-by-reference).
  1398. // via BlockDeclRefExprs.
  1399. if (const BlockDataRegion *BD = dyn_cast<BlockDataRegion>(R)) {
  1400. for (BlockDataRegion::referenced_vars_iterator
  1401. RI = BD->referenced_vars_begin(), RE = BD->referenced_vars_end();
  1402. RI != RE; ++RI) {
  1403. if ((*RI)->getDecl()->getAttr<BlocksAttr>())
  1404. AddToWorkList(*RI);
  1405. }
  1406. // No possible data bindings on a BlockDataRegion.
  1407. return;
  1408. }
  1409. }
  1410. // Visit the data binding for K.
  1411. if (const SVal *V = RM.lookup(B, K))
  1412. VisitBinding(*V);
  1413. }
  1414. bool removeDeadBindingsWorker::UpdatePostponed() {
  1415. // See if any postponed SymbolicRegions are actually live now, after
  1416. // having done a scan.
  1417. bool changed = false;
  1418. for (SmallVectorImpl<const SymbolicRegion*>::iterator
  1419. I = Postponed.begin(), E = Postponed.end() ; I != E ; ++I) {
  1420. if (const SymbolicRegion *SR = cast_or_null<SymbolicRegion>(*I)) {
  1421. if (SymReaper.isLive(SR->getSymbol())) {
  1422. changed |= AddToWorkList(SR);
  1423. *I = NULL;
  1424. }
  1425. }
  1426. }
  1427. return changed;
  1428. }
  1429. StoreRef RegionStoreManager::removeDeadBindings(Store store,
  1430. const StackFrameContext *LCtx,
  1431. SymbolReaper& SymReaper) {
  1432. RegionBindings B = GetRegionBindings(store);
  1433. removeDeadBindingsWorker W(*this, StateMgr, B, SymReaper, LCtx);
  1434. W.GenerateClusters();
  1435. // Enqueue the region roots onto the worklist.
  1436. for (SymbolReaper::region_iterator I = SymReaper.region_begin(),
  1437. E = SymReaper.region_end(); I != E; ++I) {
  1438. W.AddToWorkList(*I);
  1439. }
  1440. do W.RunWorkList(); while (W.UpdatePostponed());
  1441. // We have now scanned the store, marking reachable regions and symbols
  1442. // as live. We now remove all the regions that are dead from the store
  1443. // as well as update DSymbols with the set symbols that are now dead.
  1444. for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
  1445. const BindingKey &K = I.getKey();
  1446. // If the cluster has been visited, we know the region has been marked.
  1447. if (W.isVisited(K.getRegion()))
  1448. continue;
  1449. // Remove the dead entry.
  1450. B = removeBinding(B, K);
  1451. // Mark all non-live symbols that this binding references as dead.
  1452. if (const SymbolicRegion* SymR = dyn_cast<SymbolicRegion>(K.getRegion()))
  1453. SymReaper.maybeDead(SymR->getSymbol());
  1454. SVal X = I.getData();
  1455. SymExpr::symbol_iterator SI = X.symbol_begin(), SE = X.symbol_end();
  1456. for (; SI != SE; ++SI)
  1457. SymReaper.maybeDead(*SI);
  1458. }
  1459. return StoreRef(B.getRootWithoutRetain(), *this);
  1460. }
  1461. StoreRef RegionStoreManager::enterStackFrame(const ProgramState *state,
  1462. const StackFrameContext *frame) {
  1463. FunctionDecl const *FD = cast<FunctionDecl>(frame->getDecl());
  1464. FunctionDecl::param_const_iterator PI = FD->param_begin(),
  1465. PE = FD->param_end();
  1466. StoreRef store = StoreRef(state->getStore(), *this);
  1467. if (CallExpr const *CE = dyn_cast<CallExpr>(frame->getCallSite())) {
  1468. CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end();
  1469. // Copy the arg expression value to the arg variables. We check that
  1470. // PI != PE because the actual number of arguments may be different than
  1471. // the function declaration.
  1472. for (; AI != AE && PI != PE; ++AI, ++PI) {
  1473. SVal ArgVal = state->getSVal(*AI);
  1474. store = Bind(store.getStore(),
  1475. svalBuilder.makeLoc(MRMgr.getVarRegion(*PI, frame)), ArgVal);
  1476. }
  1477. } else if (const CXXConstructExpr *CE =
  1478. dyn_cast<CXXConstructExpr>(frame->getCallSite())) {
  1479. CXXConstructExpr::const_arg_iterator AI = CE->arg_begin(),
  1480. AE = CE->arg_end();
  1481. // Copy the arg expression value to the arg variables.
  1482. for (; AI != AE; ++AI, ++PI) {
  1483. SVal ArgVal = state->getSVal(*AI);
  1484. store = Bind(store.getStore(),
  1485. svalBuilder.makeLoc(MRMgr.getVarRegion(*PI,frame)), ArgVal);
  1486. }
  1487. } else
  1488. assert(isa<CXXDestructorDecl>(frame->getDecl()));
  1489. return store;
  1490. }
  1491. //===----------------------------------------------------------------------===//
  1492. // Utility methods.
  1493. //===----------------------------------------------------------------------===//
  1494. void RegionStoreManager::print(Store store, raw_ostream &OS,
  1495. const char* nl, const char *sep) {
  1496. RegionBindings B = GetRegionBindings(store);
  1497. OS << "Store (direct and default bindings):" << nl;
  1498. for (RegionBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
  1499. OS << ' ' << I.getKey() << " : " << I.getData() << nl;
  1500. }