]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/Store.cpp
MFC r244628:
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / lib / StaticAnalyzer / Core / Store.cpp
1 //== Store.cpp - Interface for maps from Locations to Values ----*- 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 defined the types Store and StoreManager.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
15 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
16 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/DeclObjC.h"
20
21 using namespace clang;
22 using namespace ento;
23
24 StoreManager::StoreManager(ProgramStateManager &stateMgr)
25   : svalBuilder(stateMgr.getSValBuilder()), StateMgr(stateMgr),
26     MRMgr(svalBuilder.getRegionManager()), Ctx(stateMgr.getContext()) {}
27
28 StoreRef StoreManager::enterStackFrame(Store OldStore,
29                                        const CallEvent &Call,
30                                        const StackFrameContext *LCtx) {
31   StoreRef Store = StoreRef(OldStore, *this);
32
33   SmallVector<CallEvent::FrameBindingTy, 16> InitialBindings;
34   Call.getInitialStackFrameContents(LCtx, InitialBindings);
35
36   for (CallEvent::BindingsTy::iterator I = InitialBindings.begin(),
37                                        E = InitialBindings.end();
38        I != E; ++I) {
39     Store = Bind(Store.getStore(), I->first, I->second);
40   }
41
42   return Store;
43 }
44
45 const MemRegion *StoreManager::MakeElementRegion(const MemRegion *Base,
46                                               QualType EleTy, uint64_t index) {
47   NonLoc idx = svalBuilder.makeArrayIndex(index);
48   return MRMgr.getElementRegion(EleTy, idx, Base, svalBuilder.getContext());
49 }
50
51 // FIXME: Merge with the implementation of the same method in MemRegion.cpp
52 static bool IsCompleteType(ASTContext &Ctx, QualType Ty) {
53   if (const RecordType *RT = Ty->getAs<RecordType>()) {
54     const RecordDecl *D = RT->getDecl();
55     if (!D->getDefinition())
56       return false;
57   }
58
59   return true;
60 }
61
62 StoreRef StoreManager::BindDefault(Store store, const MemRegion *R, SVal V) {
63   return StoreRef(store, *this);
64 }
65
66 const ElementRegion *StoreManager::GetElementZeroRegion(const MemRegion *R, 
67                                                         QualType T) {
68   NonLoc idx = svalBuilder.makeZeroArrayIndex();
69   assert(!T.isNull());
70   return MRMgr.getElementRegion(T, idx, R, Ctx);
71 }
72
73 const MemRegion *StoreManager::castRegion(const MemRegion *R, QualType CastToTy) {
74
75   ASTContext &Ctx = StateMgr.getContext();
76
77   // Handle casts to Objective-C objects.
78   if (CastToTy->isObjCObjectPointerType())
79     return R->StripCasts();
80
81   if (CastToTy->isBlockPointerType()) {
82     // FIXME: We may need different solutions, depending on the symbol
83     // involved.  Blocks can be casted to/from 'id', as they can be treated
84     // as Objective-C objects.  This could possibly be handled by enhancing
85     // our reasoning of downcasts of symbolic objects.
86     if (isa<CodeTextRegion>(R) || isa<SymbolicRegion>(R))
87       return R;
88
89     // We don't know what to make of it.  Return a NULL region, which
90     // will be interpretted as UnknownVal.
91     return NULL;
92   }
93
94   // Now assume we are casting from pointer to pointer. Other cases should
95   // already be handled.
96   QualType PointeeTy = CastToTy->getPointeeType();
97   QualType CanonPointeeTy = Ctx.getCanonicalType(PointeeTy);
98
99   // Handle casts to void*.  We just pass the region through.
100   if (CanonPointeeTy.getLocalUnqualifiedType() == Ctx.VoidTy)
101     return R;
102
103   // Handle casts from compatible types.
104   if (R->isBoundable())
105     if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
106       QualType ObjTy = Ctx.getCanonicalType(TR->getValueType());
107       if (CanonPointeeTy == ObjTy)
108         return R;
109     }
110
111   // Process region cast according to the kind of the region being cast.
112   switch (R->getKind()) {
113     case MemRegion::CXXThisRegionKind:
114     case MemRegion::GenericMemSpaceRegionKind:
115     case MemRegion::StackLocalsSpaceRegionKind:
116     case MemRegion::StackArgumentsSpaceRegionKind:
117     case MemRegion::HeapSpaceRegionKind:
118     case MemRegion::UnknownSpaceRegionKind:
119     case MemRegion::StaticGlobalSpaceRegionKind:
120     case MemRegion::GlobalInternalSpaceRegionKind:
121     case MemRegion::GlobalSystemSpaceRegionKind:
122     case MemRegion::GlobalImmutableSpaceRegionKind: {
123       llvm_unreachable("Invalid region cast");
124     }
125
126     case MemRegion::FunctionTextRegionKind:
127     case MemRegion::BlockTextRegionKind:
128     case MemRegion::BlockDataRegionKind:
129     case MemRegion::StringRegionKind:
130       // FIXME: Need to handle arbitrary downcasts.
131     case MemRegion::SymbolicRegionKind:
132     case MemRegion::AllocaRegionKind:
133     case MemRegion::CompoundLiteralRegionKind:
134     case MemRegion::FieldRegionKind:
135     case MemRegion::ObjCIvarRegionKind:
136     case MemRegion::ObjCStringRegionKind:
137     case MemRegion::VarRegionKind:
138     case MemRegion::CXXTempObjectRegionKind:
139     case MemRegion::CXXBaseObjectRegionKind:
140       return MakeElementRegion(R, PointeeTy);
141
142     case MemRegion::ElementRegionKind: {
143       // If we are casting from an ElementRegion to another type, the
144       // algorithm is as follows:
145       //
146       // (1) Compute the "raw offset" of the ElementRegion from the
147       //     base region.  This is done by calling 'getAsRawOffset()'.
148       //
149       // (2a) If we get a 'RegionRawOffset' after calling
150       //      'getAsRawOffset()', determine if the absolute offset
151       //      can be exactly divided into chunks of the size of the
152       //      casted-pointee type.  If so, create a new ElementRegion with
153       //      the pointee-cast type as the new ElementType and the index
154       //      being the offset divded by the chunk size.  If not, create
155       //      a new ElementRegion at offset 0 off the raw offset region.
156       //
157       // (2b) If we don't a get a 'RegionRawOffset' after calling
158       //      'getAsRawOffset()', it means that we are at offset 0.
159       //
160       // FIXME: Handle symbolic raw offsets.
161
162       const ElementRegion *elementR = cast<ElementRegion>(R);
163       const RegionRawOffset &rawOff = elementR->getAsArrayOffset();
164       const MemRegion *baseR = rawOff.getRegion();
165
166       // If we cannot compute a raw offset, throw up our hands and return
167       // a NULL MemRegion*.
168       if (!baseR)
169         return NULL;
170
171       CharUnits off = rawOff.getOffset();
172
173       if (off.isZero()) {
174         // Edge case: we are at 0 bytes off the beginning of baseR.  We
175         // check to see if type we are casting to is the same as the base
176         // region.  If so, just return the base region.
177         if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(baseR)) {
178           QualType ObjTy = Ctx.getCanonicalType(TR->getValueType());
179           QualType CanonPointeeTy = Ctx.getCanonicalType(PointeeTy);
180           if (CanonPointeeTy == ObjTy)
181             return baseR;
182         }
183
184         // Otherwise, create a new ElementRegion at offset 0.
185         return MakeElementRegion(baseR, PointeeTy);
186       }
187
188       // We have a non-zero offset from the base region.  We want to determine
189       // if the offset can be evenly divided by sizeof(PointeeTy).  If so,
190       // we create an ElementRegion whose index is that value.  Otherwise, we
191       // create two ElementRegions, one that reflects a raw offset and the other
192       // that reflects the cast.
193
194       // Compute the index for the new ElementRegion.
195       int64_t newIndex = 0;
196       const MemRegion *newSuperR = 0;
197
198       // We can only compute sizeof(PointeeTy) if it is a complete type.
199       if (IsCompleteType(Ctx, PointeeTy)) {
200         // Compute the size in **bytes**.
201         CharUnits pointeeTySize = Ctx.getTypeSizeInChars(PointeeTy);
202         if (!pointeeTySize.isZero()) {
203           // Is the offset a multiple of the size?  If so, we can layer the
204           // ElementRegion (with elementType == PointeeTy) directly on top of
205           // the base region.
206           if (off % pointeeTySize == 0) {
207             newIndex = off / pointeeTySize;
208             newSuperR = baseR;
209           }
210         }
211       }
212
213       if (!newSuperR) {
214         // Create an intermediate ElementRegion to represent the raw byte.
215         // This will be the super region of the final ElementRegion.
216         newSuperR = MakeElementRegion(baseR, Ctx.CharTy, off.getQuantity());
217       }
218
219       return MakeElementRegion(newSuperR, PointeeTy, newIndex);
220     }
221   }
222
223   llvm_unreachable("unreachable");
224 }
225
226 SVal StoreManager::evalDerivedToBase(SVal Derived, const CastExpr *Cast) {
227   // Walk through the cast path to create nested CXXBaseRegions.
228   SVal Result = Derived;
229   for (CastExpr::path_const_iterator I = Cast->path_begin(),
230                                      E = Cast->path_end();
231        I != E; ++I) {
232     Result = evalDerivedToBase(Result, (*I)->getType());
233   }
234   return Result;
235 }
236
237 SVal StoreManager::evalDerivedToBase(SVal Derived, const CXXBasePath &Path) {
238   // Walk through the path to create nested CXXBaseRegions.
239   SVal Result = Derived;
240   for (CXXBasePath::const_iterator I = Path.begin(), E = Path.end();
241        I != E; ++I) {
242     Result = evalDerivedToBase(Result, I->Base->getType());
243   }
244   return Result;
245 }
246
247 SVal StoreManager::evalDerivedToBase(SVal Derived, QualType BaseType) {
248   loc::MemRegionVal *DerivedRegVal = dyn_cast<loc::MemRegionVal>(&Derived);
249   if (!DerivedRegVal)
250     return Derived;
251
252   const CXXRecordDecl *BaseDecl = BaseType->getPointeeCXXRecordDecl();
253   if (!BaseDecl)
254     BaseDecl = BaseType->getAsCXXRecordDecl();
255   assert(BaseDecl && "not a C++ object?");
256
257   const MemRegion *BaseReg =
258     MRMgr.getCXXBaseObjectRegion(BaseDecl, DerivedRegVal->getRegion());
259
260   return loc::MemRegionVal(BaseReg);
261 }
262
263 SVal StoreManager::evalDynamicCast(SVal Base, QualType DerivedType,
264                                    bool &Failed) {
265   Failed = false;
266
267   loc::MemRegionVal *BaseRegVal = dyn_cast<loc::MemRegionVal>(&Base);
268   if (!BaseRegVal)
269     return UnknownVal();
270   const MemRegion *BaseRegion = BaseRegVal->stripCasts(/*StripBases=*/false);
271
272   // Assume the derived class is a pointer or a reference to a CXX record.
273   DerivedType = DerivedType->getPointeeType();
274   assert(!DerivedType.isNull());
275   const CXXRecordDecl *DerivedDecl = DerivedType->getAsCXXRecordDecl();
276   if (!DerivedDecl && !DerivedType->isVoidType())
277     return UnknownVal();
278
279   // Drill down the CXXBaseObject chains, which represent upcasts (casts from
280   // derived to base).
281   const MemRegion *SR = BaseRegion;
282   while (const TypedRegion *TSR = dyn_cast_or_null<TypedRegion>(SR)) {
283     QualType BaseType = TSR->getLocationType()->getPointeeType();
284     assert(!BaseType.isNull());
285     const CXXRecordDecl *SRDecl = BaseType->getAsCXXRecordDecl();
286     if (!SRDecl)
287       return UnknownVal();
288
289     // If found the derived class, the cast succeeds.
290     if (SRDecl == DerivedDecl)
291       return loc::MemRegionVal(TSR);
292
293     if (!DerivedType->isVoidType()) {
294       // Static upcasts are marked as DerivedToBase casts by Sema, so this will
295       // only happen when multiple or virtual inheritance is involved.
296       CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/true,
297                          /*DetectVirtual=*/false);
298       if (SRDecl->isDerivedFrom(DerivedDecl, Paths))
299         return evalDerivedToBase(loc::MemRegionVal(TSR), Paths.front());
300     }
301
302     if (const CXXBaseObjectRegion *R = dyn_cast<CXXBaseObjectRegion>(TSR))
303       // Drill down the chain to get the derived classes.
304       SR = R->getSuperRegion();
305     else {
306       // We reached the bottom of the hierarchy.
307
308       // If this is a cast to void*, return the region.
309       if (DerivedType->isVoidType())
310         return loc::MemRegionVal(TSR);
311
312       // We did not find the derived class. We we must be casting the base to
313       // derived, so the cast should fail.
314       Failed = true;
315       return UnknownVal();
316     }
317   }
318   
319   return UnknownVal();
320 }
321
322
323 /// CastRetrievedVal - Used by subclasses of StoreManager to implement
324 ///  implicit casts that arise from loads from regions that are reinterpreted
325 ///  as another region.
326 SVal StoreManager::CastRetrievedVal(SVal V, const TypedValueRegion *R,
327                                     QualType castTy, bool performTestOnly) {
328   
329   if (castTy.isNull() || V.isUnknownOrUndef())
330     return V;
331   
332   ASTContext &Ctx = svalBuilder.getContext();
333
334   if (performTestOnly) {  
335     // Automatically translate references to pointers.
336     QualType T = R->getValueType();
337     if (const ReferenceType *RT = T->getAs<ReferenceType>())
338       T = Ctx.getPointerType(RT->getPointeeType());
339     
340     assert(svalBuilder.getContext().hasSameUnqualifiedType(castTy, T));
341     return V;
342   }
343   
344   return svalBuilder.dispatchCast(V, castTy);
345 }
346
347 SVal StoreManager::getLValueFieldOrIvar(const Decl *D, SVal Base) {
348   if (Base.isUnknownOrUndef())
349     return Base;
350
351   Loc BaseL = cast<Loc>(Base);
352   const MemRegion* BaseR = 0;
353
354   switch (BaseL.getSubKind()) {
355   case loc::MemRegionKind:
356     BaseR = cast<loc::MemRegionVal>(BaseL).getRegion();
357     break;
358
359   case loc::GotoLabelKind:
360     // These are anormal cases. Flag an undefined value.
361     return UndefinedVal();
362
363   case loc::ConcreteIntKind:
364     // While these seem funny, this can happen through casts.
365     // FIXME: What we should return is the field offset.  For example,
366     //  add the field offset to the integer value.  That way funny things
367     //  like this work properly:  &(((struct foo *) 0xa)->f)
368     return Base;
369
370   default:
371     llvm_unreachable("Unhandled Base.");
372   }
373
374   // NOTE: We must have this check first because ObjCIvarDecl is a subclass
375   // of FieldDecl.
376   if (const ObjCIvarDecl *ID = dyn_cast<ObjCIvarDecl>(D))
377     return loc::MemRegionVal(MRMgr.getObjCIvarRegion(ID, BaseR));
378
379   return loc::MemRegionVal(MRMgr.getFieldRegion(cast<FieldDecl>(D), BaseR));
380 }
381
382 SVal StoreManager::getLValueIvar(const ObjCIvarDecl *decl, SVal base) {
383   return getLValueFieldOrIvar(decl, base);
384 }
385
386 SVal StoreManager::getLValueElement(QualType elementType, NonLoc Offset, 
387                                     SVal Base) {
388
389   // If the base is an unknown or undefined value, just return it back.
390   // FIXME: For absolute pointer addresses, we just return that value back as
391   //  well, although in reality we should return the offset added to that
392   //  value.
393   if (Base.isUnknownOrUndef() || isa<loc::ConcreteInt>(Base))
394     return Base;
395
396   const MemRegion* BaseRegion = cast<loc::MemRegionVal>(Base).getRegion();
397
398   // Pointer of any type can be cast and used as array base.
399   const ElementRegion *ElemR = dyn_cast<ElementRegion>(BaseRegion);
400
401   // Convert the offset to the appropriate size and signedness.
402   Offset = cast<NonLoc>(svalBuilder.convertToArrayIndex(Offset));
403
404   if (!ElemR) {
405     //
406     // If the base region is not an ElementRegion, create one.
407     // This can happen in the following example:
408     //
409     //   char *p = __builtin_alloc(10);
410     //   p[1] = 8;
411     //
412     //  Observe that 'p' binds to an AllocaRegion.
413     //
414     return loc::MemRegionVal(MRMgr.getElementRegion(elementType, Offset,
415                                                     BaseRegion, Ctx));
416   }
417
418   SVal BaseIdx = ElemR->getIndex();
419
420   if (!isa<nonloc::ConcreteInt>(BaseIdx))
421     return UnknownVal();
422
423   const llvm::APSInt& BaseIdxI = cast<nonloc::ConcreteInt>(BaseIdx).getValue();
424
425   // Only allow non-integer offsets if the base region has no offset itself.
426   // FIXME: This is a somewhat arbitrary restriction. We should be using
427   // SValBuilder here to add the two offsets without checking their types.
428   if (!isa<nonloc::ConcreteInt>(Offset)) {
429     if (isa<ElementRegion>(BaseRegion->StripCasts()))
430       return UnknownVal();
431
432     return loc::MemRegionVal(MRMgr.getElementRegion(elementType, Offset,
433                                                     ElemR->getSuperRegion(),
434                                                     Ctx));
435   }
436
437   const llvm::APSInt& OffI = cast<nonloc::ConcreteInt>(Offset).getValue();
438   assert(BaseIdxI.isSigned());
439
440   // Compute the new index.
441   nonloc::ConcreteInt NewIdx(svalBuilder.getBasicValueFactory().getValue(BaseIdxI +
442                                                                     OffI));
443
444   // Construct the new ElementRegion.
445   const MemRegion *ArrayR = ElemR->getSuperRegion();
446   return loc::MemRegionVal(MRMgr.getElementRegion(elementType, NewIdx, ArrayR,
447                                                   Ctx));
448 }
449
450 StoreManager::BindingsHandler::~BindingsHandler() {}
451
452 bool StoreManager::FindUniqueBinding::HandleBinding(StoreManager& SMgr,
453                                                     Store store,
454                                                     const MemRegion* R,
455                                                     SVal val) {
456   SymbolRef SymV = val.getAsLocSymbol();
457   if (!SymV || SymV != Sym)
458     return true;
459
460   if (Binding) {
461     First = false;
462     return false;
463   }
464   else
465     Binding = R;
466
467   return true;
468 }