1 //== Store.cpp - Interface for maps from Locations to Values ----*- C++ -*--==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defined the types Store and StoreManager.
12 //===----------------------------------------------------------------------===//
14 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/CharUnits.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
21 using namespace clang;
24 StoreManager::StoreManager(ProgramStateManager &stateMgr)
25 : svalBuilder(stateMgr.getSValBuilder()), StateMgr(stateMgr),
26 MRMgr(svalBuilder.getRegionManager()), Ctx(stateMgr.getContext()) {}
28 StoreRef StoreManager::enterStackFrame(Store OldStore,
29 const CallEvent &Call,
30 const StackFrameContext *LCtx) {
31 StoreRef Store = StoreRef(OldStore, *this);
33 SmallVector<CallEvent::FrameBindingTy, 16> InitialBindings;
34 Call.getInitialStackFrameContents(LCtx, InitialBindings);
36 for (CallEvent::BindingsTy::iterator I = InitialBindings.begin(),
37 E = InitialBindings.end();
39 Store = Bind(Store.getStore(), I->first, I->second);
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());
51 StoreRef StoreManager::BindDefault(Store store, const MemRegion *R, SVal V) {
52 return StoreRef(store, *this);
55 const ElementRegion *StoreManager::GetElementZeroRegion(const MemRegion *R,
57 NonLoc idx = svalBuilder.makeZeroArrayIndex();
59 return MRMgr.getElementRegion(T, idx, R, Ctx);
62 const MemRegion *StoreManager::castRegion(const MemRegion *R, QualType CastToTy) {
64 ASTContext &Ctx = StateMgr.getContext();
66 // Handle casts to Objective-C objects.
67 if (CastToTy->isObjCObjectPointerType())
68 return R->StripCasts();
70 if (CastToTy->isBlockPointerType()) {
71 // FIXME: We may need different solutions, depending on the symbol
72 // involved. Blocks can be casted to/from 'id', as they can be treated
73 // as Objective-C objects. This could possibly be handled by enhancing
74 // our reasoning of downcasts of symbolic objects.
75 if (isa<CodeTextRegion>(R) || isa<SymbolicRegion>(R))
78 // We don't know what to make of it. Return a NULL region, which
79 // will be interpretted as UnknownVal.
83 // Now assume we are casting from pointer to pointer. Other cases should
84 // already be handled.
85 QualType PointeeTy = CastToTy->getPointeeType();
86 QualType CanonPointeeTy = Ctx.getCanonicalType(PointeeTy);
88 // Handle casts to void*. We just pass the region through.
89 if (CanonPointeeTy.getLocalUnqualifiedType() == Ctx.VoidTy)
92 // Handle casts from compatible types.
94 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
95 QualType ObjTy = Ctx.getCanonicalType(TR->getValueType());
96 if (CanonPointeeTy == ObjTy)
100 // Process region cast according to the kind of the region being cast.
101 switch (R->getKind()) {
102 case MemRegion::CXXThisRegionKind:
103 case MemRegion::CodeSpaceRegionKind:
104 case MemRegion::StackLocalsSpaceRegionKind:
105 case MemRegion::StackArgumentsSpaceRegionKind:
106 case MemRegion::HeapSpaceRegionKind:
107 case MemRegion::UnknownSpaceRegionKind:
108 case MemRegion::StaticGlobalSpaceRegionKind:
109 case MemRegion::GlobalInternalSpaceRegionKind:
110 case MemRegion::GlobalSystemSpaceRegionKind:
111 case MemRegion::GlobalImmutableSpaceRegionKind: {
112 llvm_unreachable("Invalid region cast");
115 case MemRegion::FunctionCodeRegionKind:
116 case MemRegion::BlockCodeRegionKind:
117 case MemRegion::BlockDataRegionKind:
118 case MemRegion::StringRegionKind:
119 // FIXME: Need to handle arbitrary downcasts.
120 case MemRegion::SymbolicRegionKind:
121 case MemRegion::AllocaRegionKind:
122 case MemRegion::CompoundLiteralRegionKind:
123 case MemRegion::FieldRegionKind:
124 case MemRegion::ObjCIvarRegionKind:
125 case MemRegion::ObjCStringRegionKind:
126 case MemRegion::VarRegionKind:
127 case MemRegion::CXXTempObjectRegionKind:
128 case MemRegion::CXXBaseObjectRegionKind:
129 return MakeElementRegion(R, PointeeTy);
131 case MemRegion::ElementRegionKind: {
132 // If we are casting from an ElementRegion to another type, the
133 // algorithm is as follows:
135 // (1) Compute the "raw offset" of the ElementRegion from the
136 // base region. This is done by calling 'getAsRawOffset()'.
138 // (2a) If we get a 'RegionRawOffset' after calling
139 // 'getAsRawOffset()', determine if the absolute offset
140 // can be exactly divided into chunks of the size of the
141 // casted-pointee type. If so, create a new ElementRegion with
142 // the pointee-cast type as the new ElementType and the index
143 // being the offset divded by the chunk size. If not, create
144 // a new ElementRegion at offset 0 off the raw offset region.
146 // (2b) If we don't a get a 'RegionRawOffset' after calling
147 // 'getAsRawOffset()', it means that we are at offset 0.
149 // FIXME: Handle symbolic raw offsets.
151 const ElementRegion *elementR = cast<ElementRegion>(R);
152 const RegionRawOffset &rawOff = elementR->getAsArrayOffset();
153 const MemRegion *baseR = rawOff.getRegion();
155 // If we cannot compute a raw offset, throw up our hands and return
156 // a NULL MemRegion*.
160 CharUnits off = rawOff.getOffset();
163 // Edge case: we are at 0 bytes off the beginning of baseR. We
164 // check to see if type we are casting to is the same as the base
165 // region. If so, just return the base region.
166 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(baseR)) {
167 QualType ObjTy = Ctx.getCanonicalType(TR->getValueType());
168 QualType CanonPointeeTy = Ctx.getCanonicalType(PointeeTy);
169 if (CanonPointeeTy == ObjTy)
173 // Otherwise, create a new ElementRegion at offset 0.
174 return MakeElementRegion(baseR, PointeeTy);
177 // We have a non-zero offset from the base region. We want to determine
178 // if the offset can be evenly divided by sizeof(PointeeTy). If so,
179 // we create an ElementRegion whose index is that value. Otherwise, we
180 // create two ElementRegions, one that reflects a raw offset and the other
181 // that reflects the cast.
183 // Compute the index for the new ElementRegion.
184 int64_t newIndex = 0;
185 const MemRegion *newSuperR = nullptr;
187 // We can only compute sizeof(PointeeTy) if it is a complete type.
188 if (!PointeeTy->isIncompleteType()) {
189 // Compute the size in **bytes**.
190 CharUnits pointeeTySize = Ctx.getTypeSizeInChars(PointeeTy);
191 if (!pointeeTySize.isZero()) {
192 // Is the offset a multiple of the size? If so, we can layer the
193 // ElementRegion (with elementType == PointeeTy) directly on top of
195 if (off % pointeeTySize == 0) {
196 newIndex = off / pointeeTySize;
203 // Create an intermediate ElementRegion to represent the raw byte.
204 // This will be the super region of the final ElementRegion.
205 newSuperR = MakeElementRegion(baseR, Ctx.CharTy, off.getQuantity());
208 return MakeElementRegion(newSuperR, PointeeTy, newIndex);
212 llvm_unreachable("unreachable");
215 static bool regionMatchesCXXRecordType(SVal V, QualType Ty) {
216 const MemRegion *MR = V.getAsRegion();
220 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
224 const CXXRecordDecl *RD = TVR->getValueType()->getAsCXXRecordDecl();
228 const CXXRecordDecl *Expected = Ty->getPointeeCXXRecordDecl();
230 Expected = Ty->getAsCXXRecordDecl();
232 return Expected->getCanonicalDecl() == RD->getCanonicalDecl();
235 SVal StoreManager::evalDerivedToBase(SVal Derived, const CastExpr *Cast) {
236 // Sanity check to avoid doing the wrong thing in the face of
238 if (!regionMatchesCXXRecordType(Derived, Cast->getSubExpr()->getType()))
241 // Walk through the cast path to create nested CXXBaseRegions.
242 SVal Result = Derived;
243 for (CastExpr::path_const_iterator I = Cast->path_begin(),
244 E = Cast->path_end();
246 Result = evalDerivedToBase(Result, (*I)->getType(), (*I)->isVirtual());
251 SVal StoreManager::evalDerivedToBase(SVal Derived, const CXXBasePath &Path) {
252 // Walk through the path to create nested CXXBaseRegions.
253 SVal Result = Derived;
254 for (CXXBasePath::const_iterator I = Path.begin(), E = Path.end();
256 Result = evalDerivedToBase(Result, I->Base->getType(),
257 I->Base->isVirtual());
262 SVal StoreManager::evalDerivedToBase(SVal Derived, QualType BaseType,
264 Optional<loc::MemRegionVal> DerivedRegVal =
265 Derived.getAs<loc::MemRegionVal>();
269 const CXXRecordDecl *BaseDecl = BaseType->getPointeeCXXRecordDecl();
271 BaseDecl = BaseType->getAsCXXRecordDecl();
272 assert(BaseDecl && "not a C++ object?");
274 const MemRegion *BaseReg =
275 MRMgr.getCXXBaseObjectRegion(BaseDecl, DerivedRegVal->getRegion(),
278 return loc::MemRegionVal(BaseReg);
281 /// Returns the static type of the given region, if it represents a C++ class
284 /// This handles both fully-typed regions, where the dynamic type is known, and
285 /// symbolic regions, where the dynamic type is merely bounded (and even then,
286 /// only ostensibly!), but does not take advantage of any dynamic type info.
287 static const CXXRecordDecl *getCXXRecordType(const MemRegion *MR) {
288 if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR))
289 return TVR->getValueType()->getAsCXXRecordDecl();
290 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(MR))
291 return SR->getSymbol()->getType()->getPointeeCXXRecordDecl();
295 SVal StoreManager::attemptDownCast(SVal Base, QualType TargetType,
299 const MemRegion *MR = Base.getAsRegion();
303 // Assume the derived class is a pointer or a reference to a CXX record.
304 TargetType = TargetType->getPointeeType();
305 assert(!TargetType.isNull());
306 const CXXRecordDecl *TargetClass = TargetType->getAsCXXRecordDecl();
307 if (!TargetClass && !TargetType->isVoidType())
310 // Drill down the CXXBaseObject chains, which represent upcasts (casts from
312 while (const CXXRecordDecl *MRClass = getCXXRecordType(MR)) {
313 // If found the derived class, the cast succeeds.
314 if (MRClass == TargetClass)
315 return loc::MemRegionVal(MR);
317 // We skip over incomplete types. They must be the result of an earlier
318 // reinterpret_cast, as one can only dynamic_cast between types in the same
320 if (!TargetType->isVoidType() && MRClass->hasDefinition()) {
321 // Static upcasts are marked as DerivedToBase casts by Sema, so this will
322 // only happen when multiple or virtual inheritance is involved.
323 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/true,
324 /*DetectVirtual=*/false);
325 if (MRClass->isDerivedFrom(TargetClass, Paths))
326 return evalDerivedToBase(loc::MemRegionVal(MR), Paths.front());
329 if (const CXXBaseObjectRegion *BaseR = dyn_cast<CXXBaseObjectRegion>(MR)) {
330 // Drill down the chain to get the derived classes.
331 MR = BaseR->getSuperRegion();
335 // If this is a cast to void*, return the region.
336 if (TargetType->isVoidType())
337 return loc::MemRegionVal(MR);
339 // Strange use of reinterpret_cast can give us paths we don't reason
340 // about well, by putting in ElementRegions where we'd expect
341 // CXXBaseObjectRegions. If it's a valid reinterpret_cast (i.e. if the
342 // derived class has a zero offset from the base class), then it's safe
343 // to strip the cast; if it's invalid, -Wreinterpret-base-class should
344 // catch it. In the interest of performance, the analyzer will silently
345 // do the wrong thing in the invalid case (because offsets for subregions
347 const MemRegion *Uncasted = MR->StripCasts(/*IncludeBaseCasts=*/false);
348 if (Uncasted == MR) {
349 // We reached the bottom of the hierarchy and did not find the derived
350 // class. We we must be casting the base to derived, so the cast should
358 // We failed if the region we ended up with has perfect type info.
359 Failed = isa<TypedValueRegion>(MR);
364 /// CastRetrievedVal - Used by subclasses of StoreManager to implement
365 /// implicit casts that arise from loads from regions that are reinterpreted
366 /// as another region.
367 SVal StoreManager::CastRetrievedVal(SVal V, const TypedValueRegion *R,
368 QualType castTy, bool performTestOnly) {
370 if (castTy.isNull() || V.isUnknownOrUndef())
373 ASTContext &Ctx = svalBuilder.getContext();
375 if (performTestOnly) {
376 // Automatically translate references to pointers.
377 QualType T = R->getValueType();
378 if (const ReferenceType *RT = T->getAs<ReferenceType>())
379 T = Ctx.getPointerType(RT->getPointeeType());
381 assert(svalBuilder.getContext().hasSameUnqualifiedType(castTy, T));
385 return svalBuilder.dispatchCast(V, castTy);
388 SVal StoreManager::getLValueFieldOrIvar(const Decl *D, SVal Base) {
389 if (Base.isUnknownOrUndef())
392 Loc BaseL = Base.castAs<Loc>();
393 const MemRegion* BaseR = nullptr;
395 switch (BaseL.getSubKind()) {
396 case loc::MemRegionValKind:
397 BaseR = BaseL.castAs<loc::MemRegionVal>().getRegion();
400 case loc::GotoLabelKind:
401 // These are anormal cases. Flag an undefined value.
402 return UndefinedVal();
404 case loc::ConcreteIntKind:
405 // While these seem funny, this can happen through casts.
406 // FIXME: What we should return is the field offset. For example,
407 // add the field offset to the integer value. That way funny things
408 // like this work properly: &(((struct foo *) 0xa)->f)
412 llvm_unreachable("Unhandled Base.");
415 // NOTE: We must have this check first because ObjCIvarDecl is a subclass
417 if (const ObjCIvarDecl *ID = dyn_cast<ObjCIvarDecl>(D))
418 return loc::MemRegionVal(MRMgr.getObjCIvarRegion(ID, BaseR));
420 return loc::MemRegionVal(MRMgr.getFieldRegion(cast<FieldDecl>(D), BaseR));
423 SVal StoreManager::getLValueIvar(const ObjCIvarDecl *decl, SVal base) {
424 return getLValueFieldOrIvar(decl, base);
427 SVal StoreManager::getLValueElement(QualType elementType, NonLoc Offset,
430 // If the base is an unknown or undefined value, just return it back.
431 // FIXME: For absolute pointer addresses, we just return that value back as
432 // well, although in reality we should return the offset added to that
434 if (Base.isUnknownOrUndef() || Base.getAs<loc::ConcreteInt>())
437 const MemRegion* BaseRegion = Base.castAs<loc::MemRegionVal>().getRegion();
439 // Pointer of any type can be cast and used as array base.
440 const ElementRegion *ElemR = dyn_cast<ElementRegion>(BaseRegion);
442 // Convert the offset to the appropriate size and signedness.
443 Offset = svalBuilder.convertToArrayIndex(Offset).castAs<NonLoc>();
447 // If the base region is not an ElementRegion, create one.
448 // This can happen in the following example:
450 // char *p = __builtin_alloc(10);
453 // Observe that 'p' binds to an AllocaRegion.
455 return loc::MemRegionVal(MRMgr.getElementRegion(elementType, Offset,
459 SVal BaseIdx = ElemR->getIndex();
461 if (!BaseIdx.getAs<nonloc::ConcreteInt>())
464 const llvm::APSInt &BaseIdxI =
465 BaseIdx.castAs<nonloc::ConcreteInt>().getValue();
467 // Only allow non-integer offsets if the base region has no offset itself.
468 // FIXME: This is a somewhat arbitrary restriction. We should be using
469 // SValBuilder here to add the two offsets without checking their types.
470 if (!Offset.getAs<nonloc::ConcreteInt>()) {
471 if (isa<ElementRegion>(BaseRegion->StripCasts()))
474 return loc::MemRegionVal(MRMgr.getElementRegion(elementType, Offset,
475 ElemR->getSuperRegion(),
479 const llvm::APSInt& OffI = Offset.castAs<nonloc::ConcreteInt>().getValue();
480 assert(BaseIdxI.isSigned());
482 // Compute the new index.
483 nonloc::ConcreteInt NewIdx(svalBuilder.getBasicValueFactory().getValue(BaseIdxI +
486 // Construct the new ElementRegion.
487 const MemRegion *ArrayR = ElemR->getSuperRegion();
488 return loc::MemRegionVal(MRMgr.getElementRegion(elementType, NewIdx, ArrayR,
492 StoreManager::BindingsHandler::~BindingsHandler() {}
494 bool StoreManager::FindUniqueBinding::HandleBinding(StoreManager& SMgr,
498 SymbolRef SymV = val.getAsLocSymbol();
499 if (!SymV || SymV != Sym)