]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/Store.cpp
Merge clang trunk r300422 and resolve conflicts.
[FreeBSD/FreeBSD.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/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"
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 ElementRegion *StoreManager::MakeElementRegion(const SubRegion *Base,
46                                                      QualType EleTy,
47                                                      uint64_t index) {
48   NonLoc idx = svalBuilder.makeArrayIndex(index);
49   return MRMgr.getElementRegion(EleTy, idx, Base, svalBuilder.getContext());
50 }
51
52 StoreRef StoreManager::BindDefault(Store store, const MemRegion *R, SVal V) {
53   return StoreRef(store, *this);
54 }
55
56 const ElementRegion *StoreManager::GetElementZeroRegion(const SubRegion *R,
57                                                         QualType T) {
58   NonLoc idx = svalBuilder.makeZeroArrayIndex();
59   assert(!T.isNull());
60   return MRMgr.getElementRegion(T, idx, R, Ctx);
61 }
62
63 const MemRegion *StoreManager::castRegion(const MemRegion *R, QualType CastToTy) {
64
65   ASTContext &Ctx = StateMgr.getContext();
66
67   // Handle casts to Objective-C objects.
68   if (CastToTy->isObjCObjectPointerType())
69     return R->StripCasts();
70
71   if (CastToTy->isBlockPointerType()) {
72     // FIXME: We may need different solutions, depending on the symbol
73     // involved.  Blocks can be casted to/from 'id', as they can be treated
74     // as Objective-C objects.  This could possibly be handled by enhancing
75     // our reasoning of downcasts of symbolic objects.
76     if (isa<CodeTextRegion>(R) || isa<SymbolicRegion>(R))
77       return R;
78
79     // We don't know what to make of it.  Return a NULL region, which
80     // will be interpretted as UnknownVal.
81     return nullptr;
82   }
83
84   // Now assume we are casting from pointer to pointer. Other cases should
85   // already be handled.
86   QualType PointeeTy = CastToTy->getPointeeType();
87   QualType CanonPointeeTy = Ctx.getCanonicalType(PointeeTy);
88
89   // Handle casts to void*.  We just pass the region through.
90   if (CanonPointeeTy.getLocalUnqualifiedType() == Ctx.VoidTy)
91     return R;
92
93   // Handle casts from compatible types.
94   if (R->isBoundable())
95     if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
96       QualType ObjTy = Ctx.getCanonicalType(TR->getValueType());
97       if (CanonPointeeTy == ObjTy)
98         return R;
99     }
100
101   // Process region cast according to the kind of the region being cast.
102   switch (R->getKind()) {
103     case MemRegion::CXXThisRegionKind:
104     case MemRegion::CodeSpaceRegionKind:
105     case MemRegion::StackLocalsSpaceRegionKind:
106     case MemRegion::StackArgumentsSpaceRegionKind:
107     case MemRegion::HeapSpaceRegionKind:
108     case MemRegion::UnknownSpaceRegionKind:
109     case MemRegion::StaticGlobalSpaceRegionKind:
110     case MemRegion::GlobalInternalSpaceRegionKind:
111     case MemRegion::GlobalSystemSpaceRegionKind:
112     case MemRegion::GlobalImmutableSpaceRegionKind: {
113       llvm_unreachable("Invalid region cast");
114     }
115
116     case MemRegion::FunctionCodeRegionKind:
117     case MemRegion::BlockCodeRegionKind:
118     case MemRegion::BlockDataRegionKind:
119     case MemRegion::StringRegionKind:
120       // FIXME: Need to handle arbitrary downcasts.
121     case MemRegion::SymbolicRegionKind:
122     case MemRegion::AllocaRegionKind:
123     case MemRegion::CompoundLiteralRegionKind:
124     case MemRegion::FieldRegionKind:
125     case MemRegion::ObjCIvarRegionKind:
126     case MemRegion::ObjCStringRegionKind:
127     case MemRegion::VarRegionKind:
128     case MemRegion::CXXTempObjectRegionKind:
129     case MemRegion::CXXBaseObjectRegionKind:
130       return MakeElementRegion(cast<SubRegion>(R), PointeeTy);
131
132     case MemRegion::ElementRegionKind: {
133       // If we are casting from an ElementRegion to another type, the
134       // algorithm is as follows:
135       //
136       // (1) Compute the "raw offset" of the ElementRegion from the
137       //     base region.  This is done by calling 'getAsRawOffset()'.
138       //
139       // (2a) If we get a 'RegionRawOffset' after calling
140       //      'getAsRawOffset()', determine if the absolute offset
141       //      can be exactly divided into chunks of the size of the
142       //      casted-pointee type.  If so, create a new ElementRegion with
143       //      the pointee-cast type as the new ElementType and the index
144       //      being the offset divded by the chunk size.  If not, create
145       //      a new ElementRegion at offset 0 off the raw offset region.
146       //
147       // (2b) If we don't a get a 'RegionRawOffset' after calling
148       //      'getAsRawOffset()', it means that we are at offset 0.
149       //
150       // FIXME: Handle symbolic raw offsets.
151
152       const ElementRegion *elementR = cast<ElementRegion>(R);
153       const RegionRawOffset &rawOff = elementR->getAsArrayOffset();
154       const MemRegion *baseR = rawOff.getRegion();
155
156       // If we cannot compute a raw offset, throw up our hands and return
157       // a NULL MemRegion*.
158       if (!baseR)
159         return nullptr;
160
161       CharUnits off = rawOff.getOffset();
162
163       if (off.isZero()) {
164         // Edge case: we are at 0 bytes off the beginning of baseR.  We
165         // check to see if type we are casting to is the same as the base
166         // region.  If so, just return the base region.
167         if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(baseR)) {
168           QualType ObjTy = Ctx.getCanonicalType(TR->getValueType());
169           QualType CanonPointeeTy = Ctx.getCanonicalType(PointeeTy);
170           if (CanonPointeeTy == ObjTy)
171             return baseR;
172         }
173
174         // Otherwise, create a new ElementRegion at offset 0.
175         return MakeElementRegion(cast<SubRegion>(baseR), PointeeTy);
176       }
177
178       // We have a non-zero offset from the base region.  We want to determine
179       // if the offset can be evenly divided by sizeof(PointeeTy).  If so,
180       // we create an ElementRegion whose index is that value.  Otherwise, we
181       // create two ElementRegions, one that reflects a raw offset and the other
182       // that reflects the cast.
183
184       // Compute the index for the new ElementRegion.
185       int64_t newIndex = 0;
186       const MemRegion *newSuperR = nullptr;
187
188       // We can only compute sizeof(PointeeTy) if it is a complete type.
189       if (!PointeeTy->isIncompleteType()) {
190         // Compute the size in **bytes**.
191         CharUnits pointeeTySize = Ctx.getTypeSizeInChars(PointeeTy);
192         if (!pointeeTySize.isZero()) {
193           // Is the offset a multiple of the size?  If so, we can layer the
194           // ElementRegion (with elementType == PointeeTy) directly on top of
195           // the base region.
196           if (off % pointeeTySize == 0) {
197             newIndex = off / pointeeTySize;
198             newSuperR = baseR;
199           }
200         }
201       }
202
203       if (!newSuperR) {
204         // Create an intermediate ElementRegion to represent the raw byte.
205         // This will be the super region of the final ElementRegion.
206         newSuperR = MakeElementRegion(cast<SubRegion>(baseR), Ctx.CharTy,
207                                       off.getQuantity());
208       }
209
210       return MakeElementRegion(cast<SubRegion>(newSuperR), PointeeTy, newIndex);
211     }
212   }
213
214   llvm_unreachable("unreachable");
215 }
216
217 static bool regionMatchesCXXRecordType(SVal V, QualType Ty) {
218   const MemRegion *MR = V.getAsRegion();
219   if (!MR)
220     return true;
221
222   const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
223   if (!TVR)
224     return true;
225
226   const CXXRecordDecl *RD = TVR->getValueType()->getAsCXXRecordDecl();
227   if (!RD)
228     return true;
229
230   const CXXRecordDecl *Expected = Ty->getPointeeCXXRecordDecl();
231   if (!Expected)
232     Expected = Ty->getAsCXXRecordDecl();
233
234   return Expected->getCanonicalDecl() == RD->getCanonicalDecl();
235 }
236
237 SVal StoreManager::evalDerivedToBase(SVal Derived, const CastExpr *Cast) {
238   // Sanity check to avoid doing the wrong thing in the face of
239   // reinterpret_cast.
240   if (!regionMatchesCXXRecordType(Derived, Cast->getSubExpr()->getType()))
241     return UnknownVal();
242
243   // Walk through the cast path to create nested CXXBaseRegions.
244   SVal Result = Derived;
245   for (CastExpr::path_const_iterator I = Cast->path_begin(),
246                                      E = Cast->path_end();
247        I != E; ++I) {
248     Result = evalDerivedToBase(Result, (*I)->getType(), (*I)->isVirtual());
249   }
250   return Result;
251 }
252
253 SVal StoreManager::evalDerivedToBase(SVal Derived, const CXXBasePath &Path) {
254   // Walk through the path to create nested CXXBaseRegions.
255   SVal Result = Derived;
256   for (CXXBasePath::const_iterator I = Path.begin(), E = Path.end();
257        I != E; ++I) {
258     Result = evalDerivedToBase(Result, I->Base->getType(),
259                                I->Base->isVirtual());
260   }
261   return Result;
262 }
263
264 SVal StoreManager::evalDerivedToBase(SVal Derived, QualType BaseType,
265                                      bool IsVirtual) {
266   Optional<loc::MemRegionVal> DerivedRegVal =
267       Derived.getAs<loc::MemRegionVal>();
268   if (!DerivedRegVal)
269     return Derived;
270
271   const CXXRecordDecl *BaseDecl = BaseType->getPointeeCXXRecordDecl();
272   if (!BaseDecl)
273     BaseDecl = BaseType->getAsCXXRecordDecl();
274   assert(BaseDecl && "not a C++ object?");
275
276   const MemRegion *BaseReg = MRMgr.getCXXBaseObjectRegion(
277       BaseDecl, cast<SubRegion>(DerivedRegVal->getRegion()), IsVirtual);
278
279   return loc::MemRegionVal(BaseReg);
280 }
281
282 /// Returns the static type of the given region, if it represents a C++ class
283 /// object.
284 ///
285 /// This handles both fully-typed regions, where the dynamic type is known, and
286 /// symbolic regions, where the dynamic type is merely bounded (and even then,
287 /// only ostensibly!), but does not take advantage of any dynamic type info.
288 static const CXXRecordDecl *getCXXRecordType(const MemRegion *MR) {
289   if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR))
290     return TVR->getValueType()->getAsCXXRecordDecl();
291   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(MR))
292     return SR->getSymbol()->getType()->getPointeeCXXRecordDecl();
293   return nullptr;
294 }
295
296 SVal StoreManager::attemptDownCast(SVal Base, QualType TargetType,
297                                    bool &Failed) {
298   Failed = false;
299
300   const MemRegion *MR = Base.getAsRegion();
301   if (!MR)
302     return UnknownVal();
303
304   // Assume the derived class is a pointer or a reference to a CXX record.
305   TargetType = TargetType->getPointeeType();
306   assert(!TargetType.isNull());
307   const CXXRecordDecl *TargetClass = TargetType->getAsCXXRecordDecl();
308   if (!TargetClass && !TargetType->isVoidType())
309     return UnknownVal();
310
311   // Drill down the CXXBaseObject chains, which represent upcasts (casts from
312   // derived to base).
313   while (const CXXRecordDecl *MRClass = getCXXRecordType(MR)) {
314     // If found the derived class, the cast succeeds.
315     if (MRClass == TargetClass)
316       return loc::MemRegionVal(MR);
317
318     // We skip over incomplete types. They must be the result of an earlier
319     // reinterpret_cast, as one can only dynamic_cast between types in the same
320     // class hierarchy.
321     if (!TargetType->isVoidType() && MRClass->hasDefinition()) {
322       // Static upcasts are marked as DerivedToBase casts by Sema, so this will
323       // only happen when multiple or virtual inheritance is involved.
324       CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/true,
325                          /*DetectVirtual=*/false);
326       if (MRClass->isDerivedFrom(TargetClass, Paths))
327         return evalDerivedToBase(loc::MemRegionVal(MR), Paths.front());
328     }
329
330     if (const CXXBaseObjectRegion *BaseR = dyn_cast<CXXBaseObjectRegion>(MR)) {
331       // Drill down the chain to get the derived classes.
332       MR = BaseR->getSuperRegion();
333       continue;
334     }
335
336     // If this is a cast to void*, return the region.
337     if (TargetType->isVoidType())
338       return loc::MemRegionVal(MR);
339
340     // Strange use of reinterpret_cast can give us paths we don't reason
341     // about well, by putting in ElementRegions where we'd expect
342     // CXXBaseObjectRegions. If it's a valid reinterpret_cast (i.e. if the
343     // derived class has a zero offset from the base class), then it's safe
344     // to strip the cast; if it's invalid, -Wreinterpret-base-class should
345     // catch it. In the interest of performance, the analyzer will silently
346     // do the wrong thing in the invalid case (because offsets for subregions
347     // will be wrong).
348     const MemRegion *Uncasted = MR->StripCasts(/*IncludeBaseCasts=*/false);
349     if (Uncasted == MR) {
350       // We reached the bottom of the hierarchy and did not find the derived
351       // class. We we must be casting the base to derived, so the cast should
352       // fail.
353       break;
354     }
355
356     MR = Uncasted;
357   }
358
359   // We failed if the region we ended up with has perfect type info.
360   Failed = isa<TypedValueRegion>(MR);
361   return UnknownVal();
362 }
363
364
365 /// CastRetrievedVal - Used by subclasses of StoreManager to implement
366 ///  implicit casts that arise from loads from regions that are reinterpreted
367 ///  as another region.
368 SVal StoreManager::CastRetrievedVal(SVal V, const TypedValueRegion *R,
369                                     QualType castTy, bool performTestOnly) {
370
371   if (castTy.isNull() || V.isUnknownOrUndef())
372     return V;
373
374   ASTContext &Ctx = svalBuilder.getContext();
375
376   if (performTestOnly) {
377     // Automatically translate references to pointers.
378     QualType T = R->getValueType();
379     if (const ReferenceType *RT = T->getAs<ReferenceType>())
380       T = Ctx.getPointerType(RT->getPointeeType());
381
382     assert(svalBuilder.getContext().hasSameUnqualifiedType(castTy, T));
383     return V;
384   }
385
386   return svalBuilder.dispatchCast(V, castTy);
387 }
388
389 SVal StoreManager::getLValueFieldOrIvar(const Decl *D, SVal Base) {
390   if (Base.isUnknownOrUndef())
391     return Base;
392
393   Loc BaseL = Base.castAs<Loc>();
394   const SubRegion* BaseR = nullptr;
395
396   switch (BaseL.getSubKind()) {
397   case loc::MemRegionValKind:
398     BaseR = cast<SubRegion>(BaseL.castAs<loc::MemRegionVal>().getRegion());
399     break;
400
401   case loc::GotoLabelKind:
402     // These are anormal cases. Flag an undefined value.
403     return UndefinedVal();
404
405   case loc::ConcreteIntKind:
406     // While these seem funny, this can happen through casts.
407     // FIXME: What we should return is the field offset.  For example,
408     //  add the field offset to the integer value.  That way funny things
409     //  like this work properly:  &(((struct foo *) 0xa)->f)
410     return Base;
411
412   default:
413     llvm_unreachable("Unhandled Base.");
414   }
415
416   // NOTE: We must have this check first because ObjCIvarDecl is a subclass
417   // of FieldDecl.
418   if (const ObjCIvarDecl *ID = dyn_cast<ObjCIvarDecl>(D))
419     return loc::MemRegionVal(MRMgr.getObjCIvarRegion(ID, BaseR));
420
421   return loc::MemRegionVal(MRMgr.getFieldRegion(cast<FieldDecl>(D), BaseR));
422 }
423
424 SVal StoreManager::getLValueIvar(const ObjCIvarDecl *decl, SVal base) {
425   return getLValueFieldOrIvar(decl, base);
426 }
427
428 SVal StoreManager::getLValueElement(QualType elementType, NonLoc Offset,
429                                     SVal Base) {
430
431   // If the base is an unknown or undefined value, just return it back.
432   // FIXME: For absolute pointer addresses, we just return that value back as
433   //  well, although in reality we should return the offset added to that
434   //  value.
435   if (Base.isUnknownOrUndef() || Base.getAs<loc::ConcreteInt>())
436     return Base;
437
438   const SubRegion *BaseRegion =
439       Base.castAs<loc::MemRegionVal>().getRegionAs<SubRegion>();
440
441   // Pointer of any type can be cast and used as array base.
442   const ElementRegion *ElemR = dyn_cast<ElementRegion>(BaseRegion);
443
444   // Convert the offset to the appropriate size and signedness.
445   Offset = svalBuilder.convertToArrayIndex(Offset).castAs<NonLoc>();
446
447   if (!ElemR) {
448     //
449     // If the base region is not an ElementRegion, create one.
450     // This can happen in the following example:
451     //
452     //   char *p = __builtin_alloc(10);
453     //   p[1] = 8;
454     //
455     //  Observe that 'p' binds to an AllocaRegion.
456     //
457     return loc::MemRegionVal(MRMgr.getElementRegion(elementType, Offset,
458                                                     BaseRegion, Ctx));
459   }
460
461   SVal BaseIdx = ElemR->getIndex();
462
463   if (!BaseIdx.getAs<nonloc::ConcreteInt>())
464     return UnknownVal();
465
466   const llvm::APSInt &BaseIdxI =
467       BaseIdx.castAs<nonloc::ConcreteInt>().getValue();
468
469   // Only allow non-integer offsets if the base region has no offset itself.
470   // FIXME: This is a somewhat arbitrary restriction. We should be using
471   // SValBuilder here to add the two offsets without checking their types.
472   if (!Offset.getAs<nonloc::ConcreteInt>()) {
473     if (isa<ElementRegion>(BaseRegion->StripCasts()))
474       return UnknownVal();
475
476     return loc::MemRegionVal(MRMgr.getElementRegion(
477         elementType, Offset, cast<SubRegion>(ElemR->getSuperRegion()), Ctx));
478   }
479
480   const llvm::APSInt& OffI = Offset.castAs<nonloc::ConcreteInt>().getValue();
481   assert(BaseIdxI.isSigned());
482
483   // Compute the new index.
484   nonloc::ConcreteInt NewIdx(svalBuilder.getBasicValueFactory().getValue(BaseIdxI +
485                                                                     OffI));
486
487   // Construct the new ElementRegion.
488   const SubRegion *ArrayR = cast<SubRegion>(ElemR->getSuperRegion());
489   return loc::MemRegionVal(MRMgr.getElementRegion(elementType, NewIdx, ArrayR,
490                                                   Ctx));
491 }
492
493 StoreManager::BindingsHandler::~BindingsHandler() {}
494
495 bool StoreManager::FindUniqueBinding::HandleBinding(StoreManager& SMgr,
496                                                     Store store,
497                                                     const MemRegion* R,
498                                                     SVal val) {
499   SymbolRef SymV = val.getAsLocSymbol();
500   if (!SymV || SymV != Sym)
501     return true;
502
503   if (Binding) {
504     First = false;
505     return false;
506   }
507   else
508     Binding = R;
509
510   return true;
511 }