blob: 0671a806d2200d2a6a33fd16e528f7d90db97b67 [file] [log] [blame]
Zhongxing Xu17892752008-10-08 02:50:44 +00001//== 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/Analysis/PathSensitive/MemRegion.h"
18#include "clang/Analysis/PathSensitive/GRState.h"
Zhongxing Xudc0a25d2008-11-16 04:07:26 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Zhongxing Xu17892752008-10-08 02:50:44 +000020#include "clang/Analysis/Analyses/LiveVariables.h"
21
22#include "llvm/ADT/ImmutableMap.h"
Zhongxing Xudc0a25d2008-11-16 04:07:26 +000023#include "llvm/ADT/ImmutableList.h"
Zhongxing Xua071eb02008-10-24 06:01:33 +000024#include "llvm/Support/raw_ostream.h"
Zhongxing Xu17892752008-10-08 02:50:44 +000025#include "llvm/Support/Compiler.h"
26
27using namespace clang;
28
Zhongxing Xubaf03a72008-11-24 09:44:56 +000029// Actual Store type.
Zhongxing Xu1c96b242008-10-17 05:57:07 +000030typedef llvm::ImmutableMap<const MemRegion*, SVal> RegionBindingsTy;
Zhongxing Xubaf03a72008-11-24 09:44:56 +000031
Ted Kremenek50dc1b32008-12-24 01:05:03 +000032//===----------------------------------------------------------------------===//
33// Region "Views"
34//===----------------------------------------------------------------------===//
35//
36// MemRegions can be layered on top of each other. This GDM entry tracks
37// what are the MemRegions that layer a given MemRegion.
38//
Zhongxing Xu5834ed62009-01-13 01:49:57 +000039typedef llvm::ImmutableSet<const MemRegion*> RegionViews;
Ted Kremenek50dc1b32008-12-24 01:05:03 +000040namespace { class VISIBILITY_HIDDEN RegionViewMap {}; }
41static int RegionViewMapIndex = 0;
Zhongxing Xudc0a25d2008-11-16 04:07:26 +000042namespace clang {
Ted Kremenek50dc1b32008-12-24 01:05:03 +000043 template<> struct GRStateTrait<RegionViewMap>
44 : public GRStatePartialTrait<llvm::ImmutableMap<const MemRegion*,
45 RegionViews> > {
46
47 static void* GDMIndex() { return &RegionViewMapIndex; }
48 };
Zhongxing Xudc0a25d2008-11-16 04:07:26 +000049}
Zhongxing Xu17892752008-10-08 02:50:44 +000050
Ted Kremenek50dc1b32008-12-24 01:05:03 +000051//===----------------------------------------------------------------------===//
52// Region "Extents"
53//===----------------------------------------------------------------------===//
54//
55// MemRegions represent chunks of memory with a size (their "extent"). This
56// GDM entry tracks the extents for regions. Extents are in bytes.
Ted Kremenekd6cfbe42009-01-07 22:18:50 +000057//
Ted Kremenek50dc1b32008-12-24 01:05:03 +000058namespace { class VISIBILITY_HIDDEN RegionExtents {}; }
59static int RegionExtentsIndex = 0;
Zhongxing Xubaf03a72008-11-24 09:44:56 +000060namespace clang {
Ted Kremenek50dc1b32008-12-24 01:05:03 +000061 template<> struct GRStateTrait<RegionExtents>
62 : public GRStatePartialTrait<llvm::ImmutableMap<const MemRegion*, SVal> > {
63 static void* GDMIndex() { return &RegionExtentsIndex; }
64 };
Zhongxing Xubaf03a72008-11-24 09:44:56 +000065}
66
Ted Kremenek50dc1b32008-12-24 01:05:03 +000067//===----------------------------------------------------------------------===//
68// Region "killsets".
69//===----------------------------------------------------------------------===//
70//
Zhongxing Xu5834ed62009-01-13 01:49:57 +000071// RegionStore lazily adds value bindings to regions when the analyzer handles
72// assignment statements. Killsets track which default values have been
73// killed, thus distinguishing between "unknown" values and default
74// values. Regions are added to killset only when they are assigned "unknown"
75// directly, otherwise we should have their value in the region bindings.
Ted Kremenek50dc1b32008-12-24 01:05:03 +000076//
77namespace { class VISIBILITY_HIDDEN RegionKills {}; }
Ted Kremenek2ed14be2008-12-05 00:47:52 +000078static int RegionKillsIndex = 0;
Ted Kremenekc48ea6e2008-12-04 02:08:27 +000079namespace clang {
Ted Kremenek2ed14be2008-12-05 00:47:52 +000080 template<> struct GRStateTrait<RegionKills>
Ted Kremenek50dc1b32008-12-24 01:05:03 +000081 : public GRStatePartialTrait< llvm::ImmutableSet<const MemRegion*> > {
Ted Kremenek2ed14be2008-12-05 00:47:52 +000082 static void* GDMIndex() { return &RegionKillsIndex; }
Ted Kremenekc48ea6e2008-12-04 02:08:27 +000083 };
84}
85
Ted Kremenek50dc1b32008-12-24 01:05:03 +000086//===----------------------------------------------------------------------===//
Zhongxing Xu5834ed62009-01-13 01:49:57 +000087// Regions with default values.
Ted Kremenek50dc1b32008-12-24 01:05:03 +000088//===----------------------------------------------------------------------===//
89//
Zhongxing Xu5834ed62009-01-13 01:49:57 +000090// This GDM entry tracks what regions have a default value if they have no bound
91// value and have not been killed.
Ted Kremenek50dc1b32008-12-24 01:05:03 +000092//
93namespace { class VISIBILITY_HIDDEN RegionDefaultValue {}; }
94static int RegionDefaultValueIndex = 0;
95namespace clang {
96 template<> struct GRStateTrait<RegionDefaultValue>
97 : public GRStatePartialTrait<llvm::ImmutableMap<const MemRegion*, SVal> > {
98 static void* GDMIndex() { return &RegionDefaultValueIndex; }
99 };
100}
101
102//===----------------------------------------------------------------------===//
103// Main RegionStore logic.
104//===----------------------------------------------------------------------===//
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000105
Zhongxing Xu17892752008-10-08 02:50:44 +0000106namespace {
107
Ted Kremenek59e8f112009-03-03 01:35:36 +0000108class VISIBILITY_HIDDEN RegionStoreSubRegionMap : public SubRegionMap {
109 typedef llvm::DenseMap<const MemRegion*,
110 llvm::ImmutableSet<const MemRegion*> > Map;
111
112 llvm::ImmutableSet<const MemRegion*>::Factory F;
113 Map M;
114
115public:
116 void add(const MemRegion* Parent, const MemRegion* SubRegion) {
117 Map::iterator I = M.find(Parent);
118 M.insert(std::make_pair(Parent,
119 F.Add(I == M.end() ? F.GetEmptySet() : I->second, SubRegion)));
120 }
121
122 ~RegionStoreSubRegionMap() {}
123
124 void iterSubRegions(const MemRegion* Parent, Visitor& V) const {
125 Map::iterator I = M.find(Parent);
126
127 if (I == M.end())
128 return;
129
130 llvm::ImmutableSet<const MemRegion*> S = I->second;
131 for (llvm::ImmutableSet<const MemRegion*>::iterator SI=S.begin(),SE=S.end();
132 SI != SE; ++SI) {
133 if (!V.Visit(Parent, *SI))
134 return;
135 }
136 }
137};
138
Zhongxing Xu17892752008-10-08 02:50:44 +0000139class VISIBILITY_HIDDEN RegionStoreManager : public StoreManager {
140 RegionBindingsTy::Factory RBFactory;
Ted Kremenek50dc1b32008-12-24 01:05:03 +0000141 RegionViews::Factory RVFactory;
Zhongxing Xudc0a25d2008-11-16 04:07:26 +0000142
Zhongxing Xu17892752008-10-08 02:50:44 +0000143 GRStateManager& StateMgr;
Ted Kremenek6fd8f912009-01-22 23:43:57 +0000144 const MemRegion* SelfRegion;
145 const ImplicitParamDecl *SelfDecl;
Zhongxing Xu17892752008-10-08 02:50:44 +0000146
147public:
148 RegionStoreManager(GRStateManager& mgr)
Ted Kremenekd6cfbe42009-01-07 22:18:50 +0000149 : StoreManager(mgr.getAllocator()),
150 RBFactory(mgr.getAllocator()),
Zhongxing Xudc0a25d2008-11-16 04:07:26 +0000151 RVFactory(mgr.getAllocator()),
Ted Kremenek6fd8f912009-01-22 23:43:57 +0000152 StateMgr(mgr), SelfRegion(0), SelfDecl(0) {
153 if (const ObjCMethodDecl* MD =
154 dyn_cast<ObjCMethodDecl>(&StateMgr.getCodeDecl()))
155 SelfDecl = MD->getSelfDecl();
156 }
Zhongxing Xu17892752008-10-08 02:50:44 +0000157
158 virtual ~RegionStoreManager() {}
159
Zhongxing Xu24194ef2008-10-24 01:38:55 +0000160 MemRegionManager& getRegionManager() { return MRMgr; }
Ted Kremenek4f090272008-10-27 21:54:31 +0000161
Ted Kremenek59e8f112009-03-03 01:35:36 +0000162 std::auto_ptr<SubRegionMap> getSubRegionMap(const GRState *state);
163
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000164 const GRState* BindCompoundLiteral(const GRState* St,
165 const CompoundLiteralExpr* CL, SVal V);
Zhongxing Xu24194ef2008-10-24 01:38:55 +0000166
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000167 /// getLValueString - Returns an SVal representing the lvalue of a
168 /// StringLiteral. Within RegionStore a StringLiteral has an
169 /// associated StringRegion, and the lvalue of a StringLiteral is
170 /// the lvalue of that region.
Zhongxing Xu143bf822008-10-25 14:18:57 +0000171 SVal getLValueString(const GRState* St, const StringLiteral* S);
172
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000173 /// getLValueCompoundLiteral - Returns an SVal representing the
174 /// lvalue of a compound literal. Within RegionStore a compound
175 /// literal has an associated region, and the lvalue of the
176 /// compound literal is the lvalue of that region.
Zhongxing Xuf22679e2008-11-07 10:38:33 +0000177 SVal getLValueCompoundLiteral(const GRState* St, const CompoundLiteralExpr*);
178
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000179 /// getLValueVar - Returns an SVal that represents the lvalue of a
180 /// variable. Within RegionStore a variable has an associated
181 /// VarRegion, and the lvalue of the variable is the lvalue of that region.
Zhongxing Xuc4bf72c2008-10-22 13:44:38 +0000182 SVal getLValueVar(const GRState* St, const VarDecl* VD);
183
184 SVal getLValueIvar(const GRState* St, const ObjCIvarDecl* D, SVal Base);
185
186 SVal getLValueField(const GRState* St, SVal Base, const FieldDecl* D);
187
Zhongxing Xub1d542a2008-10-24 01:09:32 +0000188 SVal getLValueElement(const GRState* St, SVal Base, SVal Offset);
189
Zhongxing Xue8a964b2008-11-22 13:21:46 +0000190 SVal getSizeInElements(const GRState* St, const MemRegion* R);
191
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000192 /// ArrayToPointer - Emulates the "decay" of an array to a pointer
193 /// type. 'Array' represents the lvalue of the array being decayed
194 /// to a pointer, and the returned SVal represents the decayed
195 /// version of that lvalue (i.e., a pointer to the first element of
196 /// the array). This is called by GRExprEngine when evaluating
197 /// casts from arrays to pointers.
Zhongxing Xub1d542a2008-10-24 01:09:32 +0000198 SVal ArrayToPointer(SVal Array);
199
Ted Kremenek6eddeb12008-12-13 21:49:13 +0000200 /// CastRegion - Used by GRExprEngine::VisitCast to handle casts from
201 /// a MemRegion* to a specific location type. 'R' is the region being
202 /// casted and 'CastToTy' the result type of the cast.
203 CastResult CastRegion(const GRState* state, const MemRegion* R,
204 QualType CastToTy);
Zhongxing Xudc0a25d2008-11-16 04:07:26 +0000205
Zhongxing Xu94aa6c12009-03-02 07:52:23 +0000206 SVal EvalBinOp(BinaryOperator::Opcode Op, Loc L, NonLoc R);
207
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000208 /// The high level logic for this method is this:
209 /// Retrieve (L)
210 /// if L has binding
211 /// return L's binding
212 /// else if L is in killset
213 /// return unknown
214 /// else
215 /// if L is on stack or heap
216 /// return undefined
217 /// else
218 /// return symbolic
Ted Kremenek2ed14be2008-12-05 00:47:52 +0000219 SVal Retrieve(const GRState* state, Loc L, QualType T = QualType());
Zhongxing Xuc4bf72c2008-10-22 13:44:38 +0000220
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000221 const GRState* Bind(const GRState* St, Loc LV, SVal V);
Zhongxing Xu17892752008-10-08 02:50:44 +0000222
Zhongxing Xu9c9ca082008-12-16 02:36:30 +0000223 Store Remove(Store store, Loc LV);
Zhongxing Xu24194ef2008-10-24 01:38:55 +0000224
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000225 Store getInitialStore() { return RBFactory.GetEmptyMap().getRoot(); }
Ted Kremenek9deb0e32008-10-24 20:32:16 +0000226
227 /// getSelfRegion - Returns the region for the 'self' (Objective-C) or
228 /// 'this' object (C++). When used when analyzing a normal function this
229 /// method returns NULL.
230 const MemRegion* getSelfRegion(Store) {
Ted Kremenek6fd8f912009-01-22 23:43:57 +0000231 if (!SelfDecl)
232 return 0;
233
234 if (!SelfRegion) {
235 const ObjCMethodDecl *MD = cast<ObjCMethodDecl>(&StateMgr.getCodeDecl());
236 SelfRegion = MRMgr.getObjCObjectRegion(MD->getClassInterface(),
237 MRMgr.getHeapRegion());
238 }
239
240 return SelfRegion;
Ted Kremenek9deb0e32008-10-24 20:32:16 +0000241 }
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000242
Ted Kremenek2ed14be2008-12-05 00:47:52 +0000243 /// RemoveDeadBindings - Scans the RegionStore of 'state' for dead values.
244 /// It returns a new Store with these values removed, and populates LSymbols
245 // and DSymbols with the known set of live and dead symbols respectively.
246 Store RemoveDeadBindings(const GRState* state, Stmt* Loc,
Ted Kremenek241677a2009-01-21 22:26:05 +0000247 SymbolReaper& SymReaper,
248 llvm::SmallVectorImpl<const MemRegion*>& RegionRoots);
Zhongxing Xu24194ef2008-10-24 01:38:55 +0000249
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000250 const GRState* BindDecl(const GRState* St, const VarDecl* VD, SVal InitVal);
251
252 const GRState* BindDeclWithNoInit(const GRState* St, const VarDecl* VD) {
253 return St;
254 }
Zhongxing Xu53bcdd42008-10-21 05:29:26 +0000255
Zhongxing Xubaf03a72008-11-24 09:44:56 +0000256 const GRState* setExtent(const GRState* St, const MemRegion* R, SVal Extent);
257
Zhongxing Xu17892752008-10-08 02:50:44 +0000258 static inline RegionBindingsTy GetRegionBindings(Store store) {
Zhongxing Xu9c9ca082008-12-16 02:36:30 +0000259 return RegionBindingsTy(static_cast<const RegionBindingsTy::TreeTy*>(store));
Zhongxing Xu17892752008-10-08 02:50:44 +0000260 }
Zhongxing Xu24194ef2008-10-24 01:38:55 +0000261
Zhongxing Xu5b8b6f22008-10-24 04:33:15 +0000262 void print(Store store, std::ostream& Out, const char* nl, const char *sep);
Zhongxing Xu24194ef2008-10-24 01:38:55 +0000263
264 void iterBindings(Store store, BindingsHandler& f) {
265 // FIXME: Implement.
266 }
Zhongxing Xua82512a2008-10-24 08:42:28 +0000267
268private:
269 Loc getVarLoc(const VarDecl* VD) {
270 return loc::MemRegionVal(MRMgr.getVarRegion(VD));
271 }
272
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000273 const GRState* BindArray(const GRState* St, const TypedRegion* R, SVal V);
Zhongxing Xu6e3f01c2008-10-31 07:16:08 +0000274
Zhongxing Xu0b242ec2008-12-04 01:12:41 +0000275 /// Retrieve the values in a struct and return a CompoundVal, used when doing
276 /// struct copy:
277 /// struct s x, y;
278 /// x = y;
279 /// y's value is retrieved by this method.
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000280 SVal RetrieveStruct(const GRState* St, const TypedRegion* R);
Zhongxing Xu0b242ec2008-12-04 01:12:41 +0000281
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000282 const GRState* BindStruct(const GRState* St, const TypedRegion* R, SVal V);
Zhongxing Xu63123d82008-11-23 04:30:35 +0000283
Zhongxing Xu5834ed62009-01-13 01:49:57 +0000284 /// KillStruct - Set the entire struct to unknown.
285 const GRState* KillStruct(const GRState* St, const TypedRegion* R);
286
Zhongxing Xu6e3f01c2008-10-31 07:16:08 +0000287 // Utility methods.
288 BasicValueFactory& getBasicVals() { return StateMgr.getBasicVals(); }
289 ASTContext& getContext() { return StateMgr.getContext(); }
Zhongxing Xu63123d82008-11-23 04:30:35 +0000290 SymbolManager& getSymbolManager() { return StateMgr.getSymbolManager(); }
Zhongxing Xudc0a25d2008-11-16 04:07:26 +0000291
292 const GRState* AddRegionView(const GRState* St,
293 const MemRegion* View, const MemRegion* Base);
Zhongxing Xu5834ed62009-01-13 01:49:57 +0000294 const GRState* RemoveRegionView(const GRState* St,
295 const MemRegion* View, const MemRegion* Base);
Zhongxing Xu17892752008-10-08 02:50:44 +0000296};
297
298} // end anonymous namespace
299
Ted Kremenek95c7b002008-10-24 01:04:59 +0000300StoreManager* clang::CreateRegionStoreManager(GRStateManager& StMgr) {
Zhongxing Xu24194ef2008-10-24 01:38:55 +0000301 return new RegionStoreManager(StMgr);
Ted Kremenek95c7b002008-10-24 01:04:59 +0000302}
303
Ted Kremenek59e8f112009-03-03 01:35:36 +0000304std::auto_ptr<SubRegionMap>
305RegionStoreManager::getSubRegionMap(const GRState *state) {
306 RegionBindingsTy B = GetRegionBindings(state->getStore());
307 RegionStoreSubRegionMap *M = new RegionStoreSubRegionMap();
308
309 for (RegionBindingsTy::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
310 if (const SubRegion* R = dyn_cast<SubRegion>(I.getKey()))
311 M->add(R->getSuperRegion(), R);
312 }
313
314 return std::auto_ptr<SubRegionMap>(M);
315}
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000316
317/// getLValueString - Returns an SVal representing the lvalue of a
318/// StringLiteral. Within RegionStore a StringLiteral has an
319/// associated StringRegion, and the lvalue of a StringLiteral is the
320/// lvalue of that region.
Zhongxing Xu143bf822008-10-25 14:18:57 +0000321SVal RegionStoreManager::getLValueString(const GRState* St,
322 const StringLiteral* S) {
323 return loc::MemRegionVal(MRMgr.getStringRegion(S));
324}
325
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000326/// getLValueVar - Returns an SVal that represents the lvalue of a
327/// variable. Within RegionStore a variable has an associated
328/// VarRegion, and the lvalue of the variable is the lvalue of that region.
Zhongxing Xuc4bf72c2008-10-22 13:44:38 +0000329SVal RegionStoreManager::getLValueVar(const GRState* St, const VarDecl* VD) {
330 return loc::MemRegionVal(MRMgr.getVarRegion(VD));
331}
Zhongxing Xuf22679e2008-11-07 10:38:33 +0000332
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000333/// getLValueCompoundLiteral - Returns an SVal representing the lvalue
334/// of a compound literal. Within RegionStore a compound literal
335/// has an associated region, and the lvalue of the compound literal
336/// is the lvalue of that region.
337SVal
338RegionStoreManager::getLValueCompoundLiteral(const GRState* St,
339 const CompoundLiteralExpr* CL) {
Zhongxing Xuf22679e2008-11-07 10:38:33 +0000340 return loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CL));
341}
342
Zhongxing Xuc4bf72c2008-10-22 13:44:38 +0000343SVal RegionStoreManager::getLValueIvar(const GRState* St, const ObjCIvarDecl* D,
344 SVal Base) {
345 return UnknownVal();
346}
347
348SVal RegionStoreManager::getLValueField(const GRState* St, SVal Base,
349 const FieldDecl* D) {
350 if (Base.isUnknownOrUndef())
351 return Base;
352
353 Loc BaseL = cast<Loc>(Base);
354 const MemRegion* BaseR = 0;
355
356 switch (BaseL.getSubKind()) {
357 case loc::MemRegionKind:
358 BaseR = cast<loc::MemRegionVal>(BaseL).getRegion();
359 break;
360
361 case loc::SymbolValKind:
Zhongxing Xu026c6632009-02-05 06:57:29 +0000362 BaseR = MRMgr.getSymbolicRegion(cast<loc::SymbolVal>(&BaseL)->getSymbol(),
363 StateMgr.getSymbolManager());
Zhongxing Xuc4bf72c2008-10-22 13:44:38 +0000364 break;
365
366 case loc::GotoLabelKind:
367 case loc::FuncValKind:
368 // These are anormal cases. Flag an undefined value.
369 return UndefinedVal();
370
371 case loc::ConcreteIntKind:
Zhongxing Xuc4bf72c2008-10-22 13:44:38 +0000372 // While these seem funny, this can happen through casts.
373 // FIXME: What we should return is the field offset. For example,
374 // add the field offset to the integer value. That way funny things
375 // like this work properly: &(((struct foo *) 0xa)->f)
376 return Base;
377
378 default:
Zhongxing Xu13d1ee22008-11-07 08:57:30 +0000379 assert(0 && "Unhandled Base.");
Zhongxing Xuc4bf72c2008-10-22 13:44:38 +0000380 return Base;
381 }
382
383 return loc::MemRegionVal(MRMgr.getFieldRegion(D, BaseR));
384}
385
Zhongxing Xub1d542a2008-10-24 01:09:32 +0000386SVal RegionStoreManager::getLValueElement(const GRState* St,
387 SVal Base, SVal Offset) {
Zhongxing Xub1d542a2008-10-24 01:09:32 +0000388
Zhongxing Xua48f7372009-02-06 08:44:27 +0000389 if (Base.isUnknownOrUndef())
Zhongxing Xu4a1513e2008-10-27 12:23:17 +0000390 return Base;
391
Ted Kremeneka7ac9442009-01-22 20:27:48 +0000392 // Only handle integer offsets... for now.
393 if (!isa<nonloc::ConcreteInt>(Offset))
Zhongxing Xue4d13932008-11-13 09:48:44 +0000394 return UnknownVal();
Ted Kremeneka7ac9442009-01-22 20:27:48 +0000395
Zhongxing Xua48f7372009-02-06 08:44:27 +0000396 const TypedRegion* BaseRegion = 0;
397
398 if (isa<loc::SymbolVal>(Base))
399 BaseRegion = MRMgr.getSymbolicRegion(cast<loc::SymbolVal>(Base).getSymbol(),
400 StateMgr.getSymbolManager());
401 else
402 BaseRegion = cast<TypedRegion>(cast<loc::MemRegionVal>(Base).getRegion());
Ted Kremeneka7ac9442009-01-22 20:27:48 +0000403
404 // Pointer of any type can be cast and used as array base.
405 const ElementRegion *ElemR = dyn_cast<ElementRegion>(BaseRegion);
406
407 if (!ElemR) {
408 //
409 // If the base region is not an ElementRegion, create one.
410 // This can happen in the following example:
411 //
412 // char *p = __builtin_alloc(10);
413 // p[1] = 8;
414 //
Ted Kremenek0312c0e2009-03-01 05:44:08 +0000415 // Observe that 'p' binds to an TypedViewRegion<AllocaRegion>.
Ted Kremeneka7ac9442009-01-22 20:27:48 +0000416 //
Zhongxing Xu5ea2ffc2009-02-19 08:37:16 +0000417
418 // Offset might be unsigned. We have to convert it to signed ConcreteInt.
419 if (nonloc::ConcreteInt* CI = dyn_cast<nonloc::ConcreteInt>(&Offset)) {
420 const llvm::APSInt& OffI = CI->getValue();
421 if (OffI.isUnsigned()) {
422 llvm::APSInt Tmp = OffI;
423 Tmp.setIsSigned(true);
424 Offset = NonLoc::MakeVal(getBasicVals(), Tmp);
425 }
426 }
Ted Kremeneka7ac9442009-01-22 20:27:48 +0000427 return loc::MemRegionVal(MRMgr.getElementRegion(Offset, BaseRegion));
Zhongxing Xue4d13932008-11-13 09:48:44 +0000428 }
Ted Kremeneka7ac9442009-01-22 20:27:48 +0000429
430 SVal BaseIdx = ElemR->getIndex();
431
432 if (!isa<nonloc::ConcreteInt>(BaseIdx))
433 return UnknownVal();
434
435 const llvm::APSInt& BaseIdxI = cast<nonloc::ConcreteInt>(BaseIdx).getValue();
436 const llvm::APSInt& OffI = cast<nonloc::ConcreteInt>(Offset).getValue();
437 assert(BaseIdxI.isSigned());
438
439 // FIXME: This appears to be the assumption of this code. We should review
440 // whether or not BaseIdxI.getBitWidth() < OffI.getBitWidth(). If it
441 // can't we need to put a comment here. If it can, we should handle it.
442 assert(BaseIdxI.getBitWidth() >= OffI.getBitWidth());
Zhongxing Xue4d13932008-11-13 09:48:44 +0000443
Ted Kremeneka7ac9442009-01-22 20:27:48 +0000444 const TypedRegion *ArrayR = ElemR->getArrayRegion();
445 SVal NewIdx;
446
447 if (OffI.isUnsigned() || OffI.getBitWidth() < BaseIdxI.getBitWidth()) {
448 // 'Offset' might be unsigned. We have to convert it to signed and
449 // possibly extend it.
450 llvm::APSInt Tmp = OffI;
451
452 if (OffI.getBitWidth() < BaseIdxI.getBitWidth())
453 Tmp.extend(BaseIdxI.getBitWidth());
454
455 Tmp.setIsSigned(true);
456 Tmp += BaseIdxI; // Compute the new offset.
Zhongxing Xu5ea2ffc2009-02-19 08:37:16 +0000457 NewIdx = NonLoc::MakeVal(getBasicVals(), Tmp);
Zhongxing Xub1d542a2008-10-24 01:09:32 +0000458 }
Ted Kremeneka7ac9442009-01-22 20:27:48 +0000459 else
460 NewIdx = nonloc::ConcreteInt(getBasicVals().getValue(BaseIdxI + OffI));
Zhongxing Xub1d542a2008-10-24 01:09:32 +0000461
Ted Kremeneka7ac9442009-01-22 20:27:48 +0000462 return loc::MemRegionVal(MRMgr.getElementRegion(NewIdx, ArrayR));
Zhongxing Xub1d542a2008-10-24 01:09:32 +0000463}
464
Zhongxing Xue8a964b2008-11-22 13:21:46 +0000465SVal RegionStoreManager::getSizeInElements(const GRState* St,
466 const MemRegion* R) {
467 if (const VarRegion* VR = dyn_cast<VarRegion>(R)) {
468 // Get the type of the variable.
Ted Kremenek14553ab2009-01-30 00:08:43 +0000469 QualType T = VR->getDesugaredRValueType(getContext());
Zhongxing Xue8a964b2008-11-22 13:21:46 +0000470
Ted Kremenek14553ab2009-01-30 00:08:43 +0000471 // FIXME: Handle variable-length arrays.
472 if (isa<VariableArrayType>(T))
473 return UnknownVal();
474
475 if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(T)) {
476 // return the size as signed integer.
477 return NonLoc::MakeVal(getBasicVals(), CAT->getSize(), false);
478 }
479
480 // Clients can use ordinary variables as if they were arrays. These
481 // essentially are arrays of size 1.
482 return NonLoc::MakeIntVal(getBasicVals(), 1, false);
Zhongxing Xue8a964b2008-11-22 13:21:46 +0000483 }
484
485 if (const StringRegion* SR = dyn_cast<StringRegion>(R)) {
Zhongxing Xu6613d082008-11-24 02:18:56 +0000486 const StringLiteral* Str = SR->getStringLiteral();
Zhongxing Xud0fd3b72008-11-24 02:30:48 +0000487 // We intentionally made the size value signed because it participates in
488 // operations with signed indices.
Ted Kremenek14553ab2009-01-30 00:08:43 +0000489 return NonLoc::MakeIntVal(getBasicVals(), Str->getByteLength()+1, false);
Zhongxing Xue8a964b2008-11-22 13:21:46 +0000490 }
491
Ted Kremenek0312c0e2009-03-01 05:44:08 +0000492 if (const TypedViewRegion* ATR = dyn_cast<TypedViewRegion>(R)) {
Ted Kremenek2e842572009-01-22 23:56:56 +0000493#if 0
494 // FIXME: This logic doesn't really work, as we can have all sorts of
495 // weird cases. For example, this crashes on test case 'rdar-6442306-1.m'.
496 // The weird cases come in when arbitrary casting comes into play, violating
497 // any type-safe programming.
498
Zhongxing Xubaf03a72008-11-24 09:44:56 +0000499 GRStateRef state(St, StateMgr);
500
501 // Get the size of the super region in bytes.
Ted Kremenek50dc1b32008-12-24 01:05:03 +0000502 const SVal* Extent = state.get<RegionExtents>(ATR->getSuperRegion());
503 assert(Extent && "region extent not exist");
Zhongxing Xubaf03a72008-11-24 09:44:56 +0000504
505 // Assume it's ConcreteInt for now.
Ted Kremenek50dc1b32008-12-24 01:05:03 +0000506 llvm::APSInt SSize = cast<nonloc::ConcreteInt>(*Extent).getValue();
Zhongxing Xubaf03a72008-11-24 09:44:56 +0000507
508 // Get the size of the element in bits.
Ted Kremenek6eddeb12008-12-13 21:49:13 +0000509 QualType LvT = ATR->getLValueType(getContext());
510 QualType ElemTy = cast<PointerType>(LvT.getTypePtr())->getPointeeType();
Zhongxing Xubaf03a72008-11-24 09:44:56 +0000511
512 uint64_t X = getContext().getTypeSize(ElemTy);
513
514 const llvm::APSInt& ESize = getBasicVals().getValue(X, SSize.getBitWidth(),
515 false);
516
517 // Calculate the number of elements.
518
519 // FIXME: What do we do with signed-ness problem? Shall we make all APSInts
520 // signed?
521 if (SSize.isUnsigned())
522 SSize.setIsSigned(true);
523
524 // FIXME: move this operation into BasicVals.
525 const llvm::APSInt S =
526 (SSize * getBasicVals().getValue(8, SSize.getBitWidth(), false)) / ESize;
527
528 return NonLoc::MakeVal(getBasicVals(), S);
Ted Kremenek2e842572009-01-22 23:56:56 +0000529#else
530 ATR = ATR;
531 return UnknownVal();
532#endif
Zhongxing Xue8a964b2008-11-22 13:21:46 +0000533 }
534
535 if (const FieldRegion* FR = dyn_cast<FieldRegion>(R)) {
536 // FIXME: Unsupported yet.
537 FR = 0;
538 return UnknownVal();
539 }
Zhongxing Xu369f4292008-11-22 13:23:00 +0000540
Zhongxing Xu02ebefb2009-02-06 08:51:30 +0000541 if (isa<SymbolicRegion>(R)) {
Zhongxing Xua48f7372009-02-06 08:44:27 +0000542 return UnknownVal();
543 }
544
Zhongxing Xue8a964b2008-11-22 13:21:46 +0000545 assert(0 && "Other regions are not supported yet.");
Ted Kremeneka21362d2009-01-06 19:12:06 +0000546 return UnknownVal();
Zhongxing Xue8a964b2008-11-22 13:21:46 +0000547}
548
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000549/// ArrayToPointer - Emulates the "decay" of an array to a pointer
550/// type. 'Array' represents the lvalue of the array being decayed
551/// to a pointer, and the returned SVal represents the decayed
552/// version of that lvalue (i.e., a pointer to the first element of
553/// the array). This is called by GRExprEngine when evaluating casts
554/// from arrays to pointers.
Zhongxing Xub1d542a2008-10-24 01:09:32 +0000555SVal RegionStoreManager::ArrayToPointer(SVal Array) {
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000556 // FIXME: This should be factored into GRExprEngine. This allows
557 // us to pass a "loc" instead of an "SVal" for "Array".
Ted Kremenekabb042f2008-12-13 19:24:37 +0000558 if (Array.isUnknownOrUndef())
559 return Array;
560
561 if (!isa<loc::MemRegionVal>(Array))
562 return UnknownVal();
563
564 const MemRegion* R = cast<loc::MemRegionVal>(&Array)->getRegion();
565 const TypedRegion* ArrayR = dyn_cast<TypedRegion>(R);
566
Ted Kremenekbbee1a72009-01-13 01:03:27 +0000567 if (!ArrayR)
Ted Kremenekabb042f2008-12-13 19:24:37 +0000568 return UnknownVal();
569
Zhongxing Xu63123d82008-11-23 04:30:35 +0000570 nonloc::ConcreteInt Idx(getBasicVals().getZeroWithPtrWidth(false));
Zhongxing Xu0b7e6422008-10-26 02:23:57 +0000571 ElementRegion* ER = MRMgr.getElementRegion(Idx, ArrayR);
572
573 return loc::MemRegionVal(ER);
Zhongxing Xub1d542a2008-10-24 01:09:32 +0000574}
575
Ted Kremenek6eddeb12008-12-13 21:49:13 +0000576StoreManager::CastResult
577RegionStoreManager::CastRegion(const GRState* state, const MemRegion* R,
578 QualType CastToTy) {
579
580 // Return the same region if the region types are compatible.
581 if (const TypedRegion* TR = dyn_cast<TypedRegion>(R)) {
582 ASTContext& Ctx = StateMgr.getContext();
583 QualType Ta = Ctx.getCanonicalType(TR->getLValueType(Ctx));
584 QualType Tb = Ctx.getCanonicalType(CastToTy);
585
586 if (Ta == Tb)
587 return CastResult(state, R);
Zhongxing Xudc0a25d2008-11-16 04:07:26 +0000588 }
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000589
590 // FIXME: We should handle the case when we are casting *back* to a
591 // previous type. For example:
592 //
593 // void* x = ...;
594 // char* y = (char*) x;
595 // void* z = (void*) y; // <-- we should get the same region that is
596 // bound to 'x'
Ted Kremenek0312c0e2009-03-01 05:44:08 +0000597 const MemRegion* ViewR = MRMgr.getTypedViewRegion(CastToTy, R);
Ted Kremenek6eddeb12008-12-13 21:49:13 +0000598 return CastResult(AddRegionView(state, ViewR, R), ViewR);
Zhongxing Xudc0a25d2008-11-16 04:07:26 +0000599}
600
Zhongxing Xu94aa6c12009-03-02 07:52:23 +0000601SVal RegionStoreManager::EvalBinOp(BinaryOperator::Opcode Op, Loc L, NonLoc R) {
602 // Assume the base location is MemRegionVal(ElementRegion).
603
604 if (!isa<loc::MemRegionVal>(L)) {
605 return UnknownVal();
606 }
607
608 const MemRegion* MR = cast<loc::MemRegionVal>(L).getRegion();
609
610 const ElementRegion* ER = cast<ElementRegion>(MR);
611 SVal Idx = ER->getIndex();
612
613 nonloc::ConcreteInt* Base = dyn_cast<nonloc::ConcreteInt>(&Idx);
614 nonloc::ConcreteInt* Offset = dyn_cast<nonloc::ConcreteInt>(&R);
615
616 // Only support concrete integer indexes for now.
617 if (Base && Offset) {
618 SVal NewIdx = Base->EvalBinOp(getBasicVals(), Op, *Offset);
619
620 const MemRegion* NewER = MRMgr.getElementRegion(NewIdx,
621 ER->getArrayRegion());
622 return Loc::MakeVal(NewER);
623
624 } else
625 return UnknownVal();
626}
627
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000628SVal RegionStoreManager::Retrieve(const GRState* St, Loc L, QualType T) {
Zhongxing Xu53bcdd42008-10-21 05:29:26 +0000629 assert(!isa<UnknownVal>(L) && "location unknown");
630 assert(!isa<UndefinedVal>(L) && "location undefined");
631
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000632 // FIXME: What does loc::SymbolVal represent? It represents the value
633 // of a location but that value is not known. In the future we should
634 // handle potential aliasing relationships; e.g. a loc::SymbolVal could
635 // be an alias for a particular region.
Zhongxing Xu779747c2009-02-20 05:19:30 +0000636 // Example:
637 // void foo(char* buf) {
638 // char c = *buf;
639 // }
640 if (isa<loc::SymbolVal>(L)) {
Zhongxing Xu53bcdd42008-10-21 05:29:26 +0000641 return UnknownVal();
Zhongxing Xu779747c2009-02-20 05:19:30 +0000642 }
Zhongxing Xu53bcdd42008-10-21 05:29:26 +0000643
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000644 // FIXME: Is this even possible? Shouldn't this be treated as a null
645 // dereference at a higher level?
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000646 if (isa<loc::ConcreteInt>(L))
647 return UndefinedVal();
Zhongxing Xu53bcdd42008-10-21 05:29:26 +0000648
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000649 // FIXME: Should this be refactored into GRExprEngine or GRStateManager?
650 // It seems that all StoreManagers would do the same thing here.
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000651 if (isa<loc::FuncVal>(L))
Zhongxing Xu53bcdd42008-10-21 05:29:26 +0000652 return L;
653
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000654 // FIXME: Perhaps this method should just take a 'const MemRegion*' argument
655 // instead of 'Loc', and have the other Loc cases handled at a higher level.
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000656 const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion();
657 assert(R && "bad region");
658
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000659 // FIXME: We should eventually handle funny addressing. e.g.:
660 //
661 // int x = ...;
662 // int *p = &x;
663 // char *q = (char*) p;
664 // char c = *q; // returns the first byte of 'x'.
665 //
666 // Such funny addressing will occur due to layering of regions.
667
Ted Kremenek265a3052009-02-24 02:23:11 +0000668 if (const TypedRegion* TR = dyn_cast<TypedRegion>(R)) {
669 QualType T =TR->getRValueType(getContext());
670 if (T->isStructureType())
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000671 return RetrieveStruct(St, TR);
Ted Kremenek265a3052009-02-24 02:23:11 +0000672 // FIXME: handle Vector types.
673 if (T->isVectorType())
674 return UnknownVal();
675 }
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000676
677 RegionBindingsTy B = GetRegionBindings(St->getStore());
678 RegionBindingsTy::data_type* V = B.lookup(R);
679
680 // Check if the region has a binding.
681 if (V)
682 return *V;
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000683
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000684 GRStateRef state(St, StateMgr);
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000685
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000686 // Check if the region is in killset.
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000687 if (state.contains<RegionKills>(R))
688 return UnknownVal();
689
Zhongxing Xu562c4d92009-01-23 11:22:12 +0000690 // If the region is an element of field, it may have a default value.
691 if (isa<ElementRegion>(R) || isa<FieldRegion>(R)) {
692 const MemRegion* SuperR = cast<SubRegion>(R)->getSuperRegion();
693 GRStateTrait<RegionDefaultValue>::lookup_type D =
694 state.get<RegionDefaultValue>(SuperR);
695 if (D)
696 return *D;
697 }
698
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000699 // The location does not have a bound value. This means that it has
700 // the value it had upon its creation and/or entry to the analyzed
701 // function/method. These are either symbolic values or 'undefined'.
702
703 // We treat function parameters as symbolic values.
Ted Kremenek6fd8f912009-01-22 23:43:57 +0000704 if (const VarRegion* VR = dyn_cast<VarRegion>(R)) {
705 const VarDecl *VD = VR->getDecl();
706
Zhongxing Xud8895f62009-02-19 09:56:08 +0000707 if (isa<ParmVarDecl>(VD) || VD->hasGlobalStorage()) {
708 QualType VTy = VD->getType();
709 if (Loc::IsLocType(VTy) || VTy->isIntegerType())
710 return SVal::GetRValueSymbolVal(getSymbolManager(), VR);
711 else
712 return UnknownVal();
713 }
Ted Kremenek6fd8f912009-01-22 23:43:57 +0000714 else if (VD == SelfDecl)
715 return loc::MemRegionVal(getSelfRegion(0));
716 }
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000717
Ted Kremenek265a3052009-02-24 02:23:11 +0000718
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000719 if (MRMgr.onStack(R) || MRMgr.onHeap(R)) {
720 // All stack variables are considered to have undefined values
721 // upon creation. All heap allocated blocks are considered to
722 // have undefined values as well unless they are explicitly bound
723 // to specific values.
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000724 return UndefinedVal();
Ted Kremenek869fb4a2008-12-24 07:46:32 +0000725 }
726
727 // All other values are symbolic.
Ted Kremenek9ab6b9c2009-01-22 18:23:34 +0000728 return SVal::GetRValueSymbolVal(getSymbolManager(), R);
Zhongxing Xu53bcdd42008-10-21 05:29:26 +0000729}
730
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000731SVal RegionStoreManager::RetrieveStruct(const GRState* St,const TypedRegion* R){
732
733 Store store = St->getStore();
734 GRStateRef state(St, StateMgr);
735
Ted Kremenek6eddeb12008-12-13 21:49:13 +0000736 // FIXME: Verify we want getRValueType instead of getLValueType.
737 QualType T = R->getRValueType(getContext());
Zhongxing Xu6e3f01c2008-10-31 07:16:08 +0000738 assert(T->isStructureType());
739
740 const RecordType* RT = cast<RecordType>(T.getTypePtr());
741 RecordDecl* RD = RT->getDecl();
742 assert(RD->isDefinition());
743
744 llvm::ImmutableList<SVal> StructVal = getBasicVals().getEmptySValList();
745
Douglas Gregore267ff32008-12-11 20:41:00 +0000746 std::vector<FieldDecl *> Fields(RD->field_begin(), RD->field_end());
Douglas Gregor44b43212008-12-11 16:49:14 +0000747
Douglas Gregore267ff32008-12-11 20:41:00 +0000748 for (std::vector<FieldDecl *>::reverse_iterator Field = Fields.rbegin(),
749 FieldEnd = Fields.rend();
750 Field != FieldEnd; ++Field) {
751 FieldRegion* FR = MRMgr.getFieldRegion(*Field, R);
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000752 RegionBindingsTy B = GetRegionBindings(store);
Zhongxing Xuf0dfa8d2008-10-31 08:10:01 +0000753 RegionBindingsTy::data_type* data = B.lookup(FR);
Zhongxing Xu6e3f01c2008-10-31 07:16:08 +0000754
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000755 SVal FieldValue;
756 if (data)
757 FieldValue = *data;
758 else if (state.contains<RegionKills>(FR))
759 FieldValue = UnknownVal();
760 else {
761 if (MRMgr.onStack(FR) || MRMgr.onHeap(FR))
762 FieldValue = UndefinedVal();
763 else
Ted Kremenek9ab6b9c2009-01-22 18:23:34 +0000764 FieldValue = SVal::GetRValueSymbolVal(getSymbolManager(), FR);
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000765 }
Zhongxing Xu6e3f01c2008-10-31 07:16:08 +0000766
767 StructVal = getBasicVals().consVals(FieldValue, StructVal);
768 }
769
770 return NonLoc::MakeCompoundVal(T, StructVal, getBasicVals());
771}
772
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000773const GRState* RegionStoreManager::Bind(const GRState* St, Loc L, SVal V) {
774 // Currently we don't bind value to symbolic location. But if the logic is
775 // made clear, we might change this decision.
776 if (isa<loc::SymbolVal>(L))
777 return St;
Zhongxing Xu8fe63af2008-10-27 09:24:07 +0000778
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000779 // If we get here, the location should be a region.
780 const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion();
Zhongxing Xuf0dfa8d2008-10-31 08:10:01 +0000781 assert(R);
782
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000783 // Check if the region is a struct region.
Zhongxing Xuf0dfa8d2008-10-31 08:10:01 +0000784 if (const TypedRegion* TR = dyn_cast<TypedRegion>(R))
Ted Kremenek6eddeb12008-12-13 21:49:13 +0000785 // FIXME: Verify we want getRValueType().
786 if (TR->getRValueType(getContext())->isStructureType())
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000787 return BindStruct(St, TR, V);
Zhongxing Xu17892752008-10-08 02:50:44 +0000788
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000789 Store store = St->getStore();
Zhongxing Xu17892752008-10-08 02:50:44 +0000790 RegionBindingsTy B = GetRegionBindings(store);
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000791
792 if (V.isUnknown()) {
793 // Remove the binding.
794 store = RBFactory.Remove(B, R).getRoot();
795
796 // Add the region to the killset.
797 GRStateRef state(St, StateMgr);
798 St = state.add<RegionKills>(R);
799 }
800 else
801 store = RBFactory.Add(B, R, V).getRoot();
802
803 return StateMgr.MakeStateWithStore(St, store);
Zhongxing Xu17892752008-10-08 02:50:44 +0000804}
805
Zhongxing Xu9c9ca082008-12-16 02:36:30 +0000806Store RegionStoreManager::Remove(Store store, Loc L) {
Ted Kremenek0964a062009-01-21 06:57:53 +0000807 const MemRegion* R = 0;
808
809 if (isa<loc::MemRegionVal>(L))
810 R = cast<loc::MemRegionVal>(L).getRegion();
811 else if (isa<loc::SymbolVal>(L))
Zhongxing Xu026c6632009-02-05 06:57:29 +0000812 R = MRMgr.getSymbolicRegion(cast<loc::SymbolVal>(L).getSymbol(),
813 StateMgr.getSymbolManager());
Ted Kremenek0964a062009-01-21 06:57:53 +0000814
815 if (R) {
816 RegionBindingsTy B = GetRegionBindings(store);
817 return RBFactory.Remove(B, R).getRoot();
818 }
819
820 return store;
Zhongxing Xu9c9ca082008-12-16 02:36:30 +0000821}
822
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000823const GRState* RegionStoreManager::BindDecl(const GRState* St,
824 const VarDecl* VD, SVal InitVal) {
Zhongxing Xua4f28ff2008-11-13 08:41:36 +0000825
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000826 QualType T = VD->getType();
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000827 VarRegion* VR = MRMgr.getVarRegion(VD);
Zhongxing Xuf0dfa8d2008-10-31 08:10:01 +0000828
Ted Kremenek0964a062009-01-21 06:57:53 +0000829 if (T->isArrayType())
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000830 return BindArray(St, VR, InitVal);
Ted Kremenek0964a062009-01-21 06:57:53 +0000831 if (T->isStructureType())
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000832 return BindStruct(St, VR, InitVal);
Zhongxing Xud463d442008-11-02 12:13:30 +0000833
Ted Kremenek0964a062009-01-21 06:57:53 +0000834 return Bind(St, Loc::MakeVal(VR), InitVal);
Zhongxing Xu17892752008-10-08 02:50:44 +0000835}
Zhongxing Xu53bcdd42008-10-21 05:29:26 +0000836
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000837// FIXME: this method should be merged into Bind().
838const GRState*
839RegionStoreManager::BindCompoundLiteral(const GRState* St,
840 const CompoundLiteralExpr* CL, SVal V) {
Zhongxing Xuf22679e2008-11-07 10:38:33 +0000841 CompoundLiteralRegion* R = MRMgr.getCompoundLiteralRegion(CL);
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000842 return Bind(St, loc::MemRegionVal(R), V);
Zhongxing Xuf22679e2008-11-07 10:38:33 +0000843}
844
Zhongxing Xubaf03a72008-11-24 09:44:56 +0000845const GRState* RegionStoreManager::setExtent(const GRState* St,
846 const MemRegion* R, SVal Extent) {
847 GRStateRef state(St, StateMgr);
Ted Kremenek50dc1b32008-12-24 01:05:03 +0000848 return state.set<RegionExtents>(R, Extent);
Zhongxing Xubaf03a72008-11-24 09:44:56 +0000849}
850
851
Ted Kremenek241677a2009-01-21 22:26:05 +0000852static void UpdateLiveSymbols(SVal X, SymbolReaper& SymReaper) {
853 for (SVal::symbol_iterator SI=X.symbol_begin(), SE=X.symbol_end();SI!=SE;++SI)
854 SymReaper.markLive(*SI);
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000855}
856
Ted Kremenek2ed14be2008-12-05 00:47:52 +0000857Store RegionStoreManager::RemoveDeadBindings(const GRState* state, Stmt* Loc,
Ted Kremenek241677a2009-01-21 22:26:05 +0000858 SymbolReaper& SymReaper,
859 llvm::SmallVectorImpl<const MemRegion*>& RegionRoots)
860{
Zhongxing Xu8916d5b2008-11-10 09:39:04 +0000861
Ted Kremenek2ed14be2008-12-05 00:47:52 +0000862 Store store = state->getStore();
Zhongxing Xu8916d5b2008-11-10 09:39:04 +0000863 RegionBindingsTy B = GetRegionBindings(store);
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000864
865 // Lazily constructed backmap from MemRegions to SubRegions.
866 typedef llvm::ImmutableSet<const MemRegion*> SubRegionsTy;
867 typedef llvm::ImmutableMap<const MemRegion*, SubRegionsTy> SubRegionsMapTy;
868
869 // FIXME: As a future optimization we can modifiy BumpPtrAllocator to have
870 // the ability to reuse memory. This way we can keep TmpAlloc around as
871 // an instance variable of RegionStoreManager (avoiding repeated malloc
872 // overhead).
873 llvm::BumpPtrAllocator TmpAlloc;
874
875 // Factory objects.
876 SubRegionsMapTy::Factory SubRegMapF(TmpAlloc);
877 SubRegionsTy::Factory SubRegF(TmpAlloc);
878
879 // The backmap from regions to subregions.
880 SubRegionsMapTy SubRegMap = SubRegMapF.GetEmptyMap();
881
882 // Do a pass over the regions in the store. For VarRegions we check if
883 // the variable is still live and if so add it to the list of live roots.
884 // For other regions we populate our region backmap.
Zhongxing Xu8916d5b2008-11-10 09:39:04 +0000885 for (RegionBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000886 const MemRegion* R = I.getKey();
887 if (const VarRegion* VR = dyn_cast<VarRegion>(R)) {
Ted Kremenek241677a2009-01-21 22:26:05 +0000888 if (SymReaper.isLive(Loc, VR->getDecl()))
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000889 RegionRoots.push_back(VR); // This is a live "root".
890 }
891 else {
892 // Get the super region for R.
893 const MemRegion* SuperR = cast<SubRegion>(R)->getSuperRegion();
894 // Get the current set of subregions for SuperR.
895 const SubRegionsTy* SRptr = SubRegMap.lookup(SuperR);
896 SubRegionsTy SR = SRptr ? *SRptr : SubRegF.GetEmptySet();
897 // Add R to the subregions of SuperR.
898 SubRegMap = SubRegMapF.Add(SubRegMap, SuperR, SubRegF.Add(SR, R));
899
900 // Finally, check if SuperR is a VarRegion. We need to do this
901 // to also mark SuperR as a root (as it may not have a value directly
902 // bound to it in the store).
903 if (const VarRegion* VR = dyn_cast<VarRegion>(SuperR)) {
Ted Kremenek241677a2009-01-21 22:26:05 +0000904 if (SymReaper.isLive(Loc, VR->getDecl()))
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000905 RegionRoots.push_back(VR); // This is a live "root".
906 }
907 }
Zhongxing Xu8916d5b2008-11-10 09:39:04 +0000908 }
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000909
910 // Process the worklist of RegionRoots. This performs a "mark-and-sweep"
911 // of the store. We want to find all live symbols and dead regions.
912 llvm::SmallPtrSet<const MemRegion*, 10> Marked;
913
914 while (!RegionRoots.empty()) {
915 // Dequeue the next region on the worklist.
916 const MemRegion* R = RegionRoots.back();
917 RegionRoots.pop_back();
Zhongxing Xu8916d5b2008-11-10 09:39:04 +0000918
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000919 // Check if we have already processed this region.
920 if (Marked.count(R)) continue;
921
922 // Mark this region as processed. This is needed for termination in case
923 // a region is referenced more than once.
924 Marked.insert(R);
925
926 // Mark the symbol for any live SymbolicRegion as "live". This means we
927 // should continue to track that symbol.
928 if (const SymbolicRegion* SymR = dyn_cast<SymbolicRegion>(R))
Ted Kremenek241677a2009-01-21 22:26:05 +0000929 SymReaper.markLive(SymR->getSymbol());
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000930
931 // Get the data binding for R (if any).
932 RegionBindingsTy::data_type* Xptr = B.lookup(R);
933 if (Xptr) {
934 SVal X = *Xptr;
Ted Kremenek241677a2009-01-21 22:26:05 +0000935 UpdateLiveSymbols(X, SymReaper); // Update the set of live symbols.
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000936
937 // If X is a region, then add it the RegionRoots.
938 if (loc::MemRegionVal* RegionX = dyn_cast<loc::MemRegionVal>(&X))
939 RegionRoots.push_back(RegionX->getRegion());
940 }
941
942 // Get the subregions of R. These are RegionRoots as well since they
943 // represent values that are also bound to R.
944 const SubRegionsTy* SRptr = SubRegMap.lookup(R);
945 if (!SRptr) continue;
946 SubRegionsTy SR = *SRptr;
947
948 for (SubRegionsTy::iterator I=SR.begin(), E=SR.end(); I!=E; ++I)
949 RegionRoots.push_back(*I);
950 }
951
952 // We have now scanned the store, marking reachable regions and symbols
953 // as live. We now remove all the regions that are dead from the store
954 // as well as update DSymbols with the set symbols that are now dead.
955
956 for (RegionBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
957 const MemRegion* R = I.getKey();
958
959 // If this region live? Is so, none of its symbols are dead.
960 if (Marked.count(R))
961 continue;
962
963 // Remove this dead region from the store.
Zhongxing Xu9c9ca082008-12-16 02:36:30 +0000964 store = Remove(store, Loc::MakeVal(R));
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000965
966 // Mark all non-live symbols that this region references as dead.
Ted Kremenek241677a2009-01-21 22:26:05 +0000967 if (const SymbolicRegion* SymR = dyn_cast<SymbolicRegion>(R))
968 SymReaper.maybeDead(SymR->getSymbol());
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000969
970 SVal X = I.getData();
971 SVal::symbol_iterator SI = X.symbol_begin(), SE = X.symbol_end();
Ted Kremenek241677a2009-01-21 22:26:05 +0000972 for (; SI != SE; ++SI) SymReaper.maybeDead(*SI);
Ted Kremenekc48ea6e2008-12-04 02:08:27 +0000973 }
974
Zhongxing Xu8916d5b2008-11-10 09:39:04 +0000975 return store;
976}
977
Zhongxing Xua071eb02008-10-24 06:01:33 +0000978void RegionStoreManager::print(Store store, std::ostream& Out,
979 const char* nl, const char *sep) {
980 llvm::raw_os_ostream OS(Out);
981 RegionBindingsTy B = GetRegionBindings(store);
982 OS << "Store:" << nl;
983
984 for (RegionBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
985 OS << ' '; I.getKey()->print(OS); OS << " : ";
986 I.getData().print(OS); OS << nl;
987 }
Zhongxing Xu5b8b6f22008-10-24 04:33:15 +0000988}
Zhongxing Xua82512a2008-10-24 08:42:28 +0000989
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000990const GRState* RegionStoreManager::BindArray(const GRState* St,
991 const TypedRegion* R, SVal Init) {
Ted Kremenek6eddeb12008-12-13 21:49:13 +0000992
993 // FIXME: Verify we should use getLValueType or getRValueType.
Zhongxing Xu2ef93722008-12-14 03:14:52 +0000994 QualType T = R->getRValueType(getContext());
Zhongxing Xu1a12a0e2008-10-31 10:24:47 +0000995 assert(T->isArrayType());
996
Zhongxing Xu4193eca2008-12-20 06:32:12 +0000997 // When we are binding the whole array, it always has default value 0.
998 GRStateRef state(St, StateMgr);
Ted Kremenek14553ab2009-01-30 00:08:43 +0000999 St = state.set<RegionDefaultValue>(R, NonLoc::MakeIntVal(getBasicVals(), 0,
1000 false));
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001001
1002 Store store = St->getStore();
1003
Zhongxing Xu1a12a0e2008-10-31 10:24:47 +00001004 ConstantArrayType* CAT = cast<ConstantArrayType>(T.getTypePtr());
1005
Zhongxing Xu6987c7b2008-11-30 05:49:49 +00001006 llvm::APSInt Size(CAT->getSize(), false);
Sebastian Redl1be3da52009-01-26 19:54:12 +00001007 llvm::APSInt i = getBasicVals().getValue(0, Size.getBitWidth(),
1008 Size.isUnsigned());
Zhongxing Xu6987c7b2008-11-30 05:49:49 +00001009
1010 // Check if the init expr is a StringLiteral.
1011 if (isa<loc::MemRegionVal>(Init)) {
1012 const MemRegion* InitR = cast<loc::MemRegionVal>(Init).getRegion();
1013 const StringLiteral* S = cast<StringRegion>(InitR)->getStringLiteral();
1014 const char* str = S->getStrData();
1015 unsigned len = S->getByteLength();
1016 unsigned j = 0;
1017
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001018 // Copy bytes from the string literal into the target array. Trailing bytes
1019 // in the array that are not covered by the string literal are initialized
1020 // to zero.
Zhongxing Xu6987c7b2008-11-30 05:49:49 +00001021 for (; i < Size; ++i, ++j) {
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001022 if (j >= len)
1023 break;
1024
Zhongxing Xu6987c7b2008-11-30 05:49:49 +00001025 SVal Idx = NonLoc::MakeVal(getBasicVals(), i);
1026 ElementRegion* ER = MRMgr.getElementRegion(Idx, R);
1027
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001028 SVal V = NonLoc::MakeVal(getBasicVals(), str[j], sizeof(char)*8, true);
1029 St = Bind(St, loc::MemRegionVal(ER), V);
Zhongxing Xu6987c7b2008-11-30 05:49:49 +00001030 }
1031
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001032 return StateMgr.MakeStateWithStore(St, store);
Zhongxing Xu6987c7b2008-11-30 05:49:49 +00001033 }
1034
Zhongxing Xu1a12a0e2008-10-31 10:24:47 +00001035
1036 nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(Init);
1037
1038 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
1039
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001040 for (; i < Size; ++i, ++VI) {
1041 // The init list might be shorter than the array decl.
1042 if (VI == VE)
1043 break;
1044
Zhongxing Xu6987c7b2008-11-30 05:49:49 +00001045 SVal Idx = NonLoc::MakeVal(getBasicVals(), i);
Zhongxing Xu1a12a0e2008-10-31 10:24:47 +00001046 ElementRegion* ER = MRMgr.getElementRegion(Idx, R);
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001047
1048 if (CAT->getElementType()->isStructureType())
1049 St = BindStruct(St, ER, *VI);
1050 else
1051 St = Bind(St, Loc::MakeVal(ER), *VI);
Zhongxing Xu1a12a0e2008-10-31 10:24:47 +00001052 }
1053
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001054 return StateMgr.MakeStateWithStore(St, store);
Zhongxing Xu1a12a0e2008-10-31 10:24:47 +00001055}
1056
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001057const GRState*
1058RegionStoreManager::BindStruct(const GRState* St, const TypedRegion* R, SVal V){
Ted Kremenek6eddeb12008-12-13 21:49:13 +00001059 // FIXME: Verify that we should use getRValueType or getLValueType.
1060 QualType T = R->getRValueType(getContext());
Zhongxing Xuaf0a8442008-10-31 10:53:01 +00001061 assert(T->isStructureType());
1062
1063 RecordType* RT = cast<RecordType>(T.getTypePtr());
1064 RecordDecl* RD = RT->getDecl();
1065 assert(RD->isDefinition());
1066
Zhongxing Xu5834ed62009-01-13 01:49:57 +00001067 if (V.isUnknown())
1068 return KillStruct(St, R);
1069
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001070 nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(V);
Zhongxing Xuaf0a8442008-10-31 10:53:01 +00001071 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
1072 RecordDecl::field_iterator FI = RD->field_begin(), FE = RD->field_end();
1073
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001074 for (; FI != FE; ++FI, ++VI) {
1075
1076 // There may be fewer values than fields only when we are initializing a
1077 // struct decl. In this case, mark the region as having default value.
1078 if (VI == VE) {
Zhongxing Xu13020162008-12-24 07:29:24 +00001079 GRStateRef state(St, StateMgr);
Ted Kremenek14553ab2009-01-30 00:08:43 +00001080 const NonLoc& Idx = NonLoc::MakeIntVal(getBasicVals(), 0, false);
1081 St = state.set<RegionDefaultValue>(R, Idx);
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001082 break;
1083 }
1084
Zhongxing Xuaf0a8442008-10-31 10:53:01 +00001085 QualType FTy = (*FI)->getType();
1086 FieldRegion* FR = MRMgr.getFieldRegion(*FI, R);
1087
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001088 if (Loc::IsLocType(FTy) || FTy->isIntegerType())
1089 St = Bind(St, Loc::MakeVal(FR), *VI);
Zhongxing Xua82512a2008-10-24 08:42:28 +00001090
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001091 else if (FTy->isArrayType())
1092 St = BindArray(St, FR, *VI);
Zhongxing Xua82512a2008-10-24 08:42:28 +00001093
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001094 else if (FTy->isStructureType())
1095 St = BindStruct(St, FR, *VI);
Zhongxing Xua82512a2008-10-24 08:42:28 +00001096 }
1097
Zhongxing Xu4193eca2008-12-20 06:32:12 +00001098 return St;
Zhongxing Xuc3a05992008-11-19 11:06:24 +00001099}
1100
Zhongxing Xu5834ed62009-01-13 01:49:57 +00001101const GRState* RegionStoreManager::KillStruct(const GRState* St,
1102 const TypedRegion* R){
1103 GRStateRef state(St, StateMgr);
1104
1105 // Kill the struct region because it is assigned "unknown".
1106 St = state.add<RegionKills>(R);
1107
1108 // Set the default value of the struct region to "unknown".
1109 St = state.set<RegionDefaultValue>(R, UnknownVal());
1110
1111 Store store = St->getStore();
1112 RegionBindingsTy B = GetRegionBindings(store);
1113
1114 // Remove all bindings for the subregions of the struct.
1115 for (RegionBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1116 const MemRegion* r = I.getKey();
1117 if (const SubRegion* sr = dyn_cast<SubRegion>(r))
1118 if (sr->isSubRegionOf(R))
1119 store = Remove(store, Loc::MakeVal(sr));
Zhongxing Xu9c2a3db2009-01-13 03:07:41 +00001120 // FIXME: Maybe we should also remove the bindings for the "views" of the
1121 // subregions.
Zhongxing Xu5834ed62009-01-13 01:49:57 +00001122 }
1123
1124 return StateMgr.MakeStateWithStore(St, store);
1125}
1126
Zhongxing Xudc0a25d2008-11-16 04:07:26 +00001127const GRState* RegionStoreManager::AddRegionView(const GRState* St,
1128 const MemRegion* View,
1129 const MemRegion* Base) {
1130 GRStateRef state(St, StateMgr);
1131
1132 // First, retrieve the region view of the base region.
Ted Kremenek50dc1b32008-12-24 01:05:03 +00001133 const RegionViews* d = state.get<RegionViewMap>(Base);
Zhongxing Xu5834ed62009-01-13 01:49:57 +00001134 RegionViews L = d ? *d : RVFactory.GetEmptySet();
Zhongxing Xudc0a25d2008-11-16 04:07:26 +00001135
1136 // Now add View to the region view.
Zhongxing Xu5834ed62009-01-13 01:49:57 +00001137 L = RVFactory.Add(L, View);
Zhongxing Xudc0a25d2008-11-16 04:07:26 +00001138
1139 // Create a new state with the new region view.
Ted Kremenek50dc1b32008-12-24 01:05:03 +00001140 return state.set<RegionViewMap>(Base, L);
Zhongxing Xudc0a25d2008-11-16 04:07:26 +00001141}
Zhongxing Xu5834ed62009-01-13 01:49:57 +00001142
1143const GRState* RegionStoreManager::RemoveRegionView(const GRState* St,
1144 const MemRegion* View,
1145 const MemRegion* Base) {
1146 GRStateRef state(St, StateMgr);
1147
1148 // Retrieve the region view of the base region.
1149 const RegionViews* d = state.get<RegionViewMap>(Base);
1150
1151 // If the base region has no view, return.
1152 if (!d)
1153 return St;
1154
1155 // Remove the view.
1156 RegionViews V = *d;
1157 V = RVFactory.Remove(V, View);
1158
1159 return state.set<RegionViewMap>(Base, V);
1160}