]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / contrib / llvm / tools / clang / lib / StaticAnalyzer / Core / ExprEngineCXX.cpp
1 //===- ExprEngineCXX.cpp - ExprEngine support for C++ -----------*- 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 the C++ expression evaluation engine.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/StmtCXX.h"
17 #include "clang/Basic/PrettyStackTrace.h"
18 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
21
22 using namespace clang;
23 using namespace ento;
24
25 void ExprEngine::CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
26                                           ExplodedNode *Pred,
27                                           ExplodedNodeSet &Dst) {
28   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
29   const Expr *tempExpr = ME->GetTemporaryExpr()->IgnoreParens();
30   ProgramStateRef state = Pred->getState();
31   const LocationContext *LCtx = Pred->getLocationContext();
32
33   SVal V = state->getSVal(tempExpr, LCtx);
34
35   // If the value is already a CXXTempObjectRegion, it is fine as it is.
36   // Otherwise, create a new CXXTempObjectRegion, and copy the value into it.
37   // This is an optimization for when an rvalue is constructed and then
38   // immediately materialized.
39   const MemRegion *MR = V.getAsRegion();
40   if (const CXXTempObjectRegion *TR =
41         dyn_cast_or_null<CXXTempObjectRegion>(MR)) {
42     if (getContext().hasSameUnqualifiedType(TR->getValueType(), ME->getType()))
43       state = state->BindExpr(ME, LCtx, V);
44   }
45
46   if (state == Pred->getState())
47     state = createTemporaryRegionIfNeeded(state, LCtx, tempExpr, ME);
48   Bldr.generateNode(ME, Pred, state);
49 }
50
51 // FIXME: This is the sort of code that should eventually live in a Core
52 // checker rather than as a special case in ExprEngine.
53 void ExprEngine::performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred,
54                                     const CallEvent &Call) {
55   SVal ThisVal;
56   bool AlwaysReturnsLValue;
57   if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) {
58     assert(Ctor->getDecl()->isTrivial());
59     assert(Ctor->getDecl()->isCopyOrMoveConstructor());
60     ThisVal = Ctor->getCXXThisVal();
61     AlwaysReturnsLValue = false;
62   } else {
63     assert(cast<CXXMethodDecl>(Call.getDecl())->isTrivial());
64     assert(cast<CXXMethodDecl>(Call.getDecl())->getOverloadedOperator() ==
65            OO_Equal);
66     ThisVal = cast<CXXInstanceCall>(Call).getCXXThisVal();
67     AlwaysReturnsLValue = true;
68   }
69
70   const LocationContext *LCtx = Pred->getLocationContext();
71
72   ExplodedNodeSet Dst;
73   Bldr.takeNodes(Pred);
74
75   SVal V = Call.getArgSVal(0);
76
77   // If the value being copied is not unknown, load from its location to get
78   // an aggregate rvalue.
79   if (Optional<Loc> L = V.getAs<Loc>())
80     V = Pred->getState()->getSVal(*L);
81   else
82     assert(V.isUnknown());
83
84   const Expr *CallExpr = Call.getOriginExpr();
85   evalBind(Dst, CallExpr, Pred, ThisVal, V, true);
86
87   PostStmt PS(CallExpr, LCtx);
88   for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end();
89        I != E; ++I) {
90     ProgramStateRef State = (*I)->getState();
91     if (AlwaysReturnsLValue)
92       State = State->BindExpr(CallExpr, LCtx, ThisVal);
93     else
94       State = bindReturnValue(Call, LCtx, State);
95     Bldr.generateNode(PS, State, *I);
96   }
97 }
98
99
100 /// Returns a region representing the first element of a (possibly
101 /// multi-dimensional) array.
102 ///
103 /// On return, \p Ty will be set to the base type of the array.
104 ///
105 /// If the type is not an array type at all, the original value is returned.
106 static SVal makeZeroElementRegion(ProgramStateRef State, SVal LValue,
107                                   QualType &Ty) {
108   SValBuilder &SVB = State->getStateManager().getSValBuilder();
109   ASTContext &Ctx = SVB.getContext();
110
111   while (const ArrayType *AT = Ctx.getAsArrayType(Ty)) {
112     Ty = AT->getElementType();
113     LValue = State->getLValue(Ty, SVB.makeZeroArrayIndex(), LValue);
114   }
115
116   return LValue;
117 }
118
119 void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE,
120                                        ExplodedNode *Pred,
121                                        ExplodedNodeSet &destNodes) {
122   const LocationContext *LCtx = Pred->getLocationContext();
123   ProgramStateRef State = Pred->getState();
124
125   const MemRegion *Target = 0;
126
127   // FIXME: Handle arrays, which run the same constructor for every element.
128   // For now, we just run the first constructor (which should still invalidate
129   // the entire array).
130
131   switch (CE->getConstructionKind()) {
132   case CXXConstructExpr::CK_Complete: {
133     // See if we're constructing an existing region by looking at the next
134     // element in the CFG.
135     const CFGBlock *B = currBldrCtx->getBlock();
136     if (currStmtIdx + 1 < B->size()) {
137       CFGElement Next = (*B)[currStmtIdx+1];
138
139       // Is this a constructor for a local variable?
140       if (Optional<CFGStmt> StmtElem = Next.getAs<CFGStmt>()) {
141         if (const DeclStmt *DS = dyn_cast<DeclStmt>(StmtElem->getStmt())) {
142           if (const VarDecl *Var = dyn_cast<VarDecl>(DS->getSingleDecl())) {
143             if (Var->getInit()->IgnoreImplicit() == CE) {
144               SVal LValue = State->getLValue(Var, LCtx);
145               QualType Ty = Var->getType();
146               LValue = makeZeroElementRegion(State, LValue, Ty);
147               Target = LValue.getAsRegion();
148             }
149           }
150         }
151       }
152       
153       // Is this a constructor for a member?
154       if (Optional<CFGInitializer> InitElem = Next.getAs<CFGInitializer>()) {
155         const CXXCtorInitializer *Init = InitElem->getInitializer();
156         assert(Init->isAnyMemberInitializer());
157
158         const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
159         Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
160                                                   LCtx->getCurrentStackFrame());
161         SVal ThisVal = State->getSVal(ThisPtr);
162
163         const ValueDecl *Field;
164         SVal FieldVal;
165         if (Init->isIndirectMemberInitializer()) {
166           Field = Init->getIndirectMember();
167           FieldVal = State->getLValue(Init->getIndirectMember(), ThisVal);
168         } else {
169           Field = Init->getMember();
170           FieldVal = State->getLValue(Init->getMember(), ThisVal);
171         }
172
173         QualType Ty = Field->getType();
174         FieldVal = makeZeroElementRegion(State, FieldVal, Ty);
175         Target = FieldVal.getAsRegion();
176       }
177
178       // FIXME: This will eventually need to handle new-expressions as well.
179     }
180
181     // If we couldn't find an existing region to construct into, assume we're
182     // constructing a temporary.
183     if (!Target) {
184       MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
185       Target = MRMgr.getCXXTempObjectRegion(CE, LCtx);
186     }
187
188     break;
189   }
190   case CXXConstructExpr::CK_NonVirtualBase:
191   case CXXConstructExpr::CK_VirtualBase:
192   case CXXConstructExpr::CK_Delegating: {
193     const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
194     Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
195                                               LCtx->getCurrentStackFrame());
196     SVal ThisVal = State->getSVal(ThisPtr);
197
198     if (CE->getConstructionKind() == CXXConstructExpr::CK_Delegating) {
199       Target = ThisVal.getAsRegion();
200     } else {
201       // Cast to the base type.
202       bool IsVirtual =
203         (CE->getConstructionKind() == CXXConstructExpr::CK_VirtualBase);
204       SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, CE->getType(),
205                                                          IsVirtual);
206       Target = BaseVal.getAsRegion();
207     }
208     break;
209   }
210   }
211
212   CallEventManager &CEMgr = getStateManager().getCallEventManager();
213   CallEventRef<CXXConstructorCall> Call =
214     CEMgr.getCXXConstructorCall(CE, Target, State, LCtx);
215
216   ExplodedNodeSet DstPreVisit;
217   getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, CE, *this);
218   ExplodedNodeSet DstPreCall;
219   getCheckerManager().runCheckersForPreCall(DstPreCall, DstPreVisit,
220                                             *Call, *this);
221
222   ExplodedNodeSet DstEvaluated;
223   StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx);
224
225   bool IsArray = isa<ElementRegion>(Target);
226   if (CE->getConstructor()->isTrivial() &&
227       CE->getConstructor()->isCopyOrMoveConstructor() &&
228       !IsArray) {
229     // FIXME: Handle other kinds of trivial constructors as well.
230     for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
231          I != E; ++I)
232       performTrivialCopy(Bldr, *I, *Call);
233
234   } else {
235     for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
236          I != E; ++I)
237       defaultEvalCall(Bldr, *I, *Call);
238   }
239
240   ExplodedNodeSet DstPostCall;
241   getCheckerManager().runCheckersForPostCall(DstPostCall, DstEvaluated,
242                                              *Call, *this);
243   getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, CE, *this);
244 }
245
246 void ExprEngine::VisitCXXDestructor(QualType ObjectType,
247                                     const MemRegion *Dest,
248                                     const Stmt *S,
249                                     bool IsBaseDtor,
250                                     ExplodedNode *Pred, 
251                                     ExplodedNodeSet &Dst) {
252   const LocationContext *LCtx = Pred->getLocationContext();
253   ProgramStateRef State = Pred->getState();
254
255   // FIXME: We need to run the same destructor on every element of the array.
256   // This workaround will just run the first destructor (which will still
257   // invalidate the entire array).
258   SVal DestVal = loc::MemRegionVal(Dest);
259   DestVal = makeZeroElementRegion(State, DestVal, ObjectType);
260   Dest = DestVal.getAsRegion();
261
262   const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl();
263   assert(RecordDecl && "Only CXXRecordDecls should have destructors");
264   const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
265
266   CallEventManager &CEMgr = getStateManager().getCallEventManager();
267   CallEventRef<CXXDestructorCall> Call =
268     CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx);
269
270   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
271                                 Call->getSourceRange().getBegin(),
272                                 "Error evaluating destructor");
273
274   ExplodedNodeSet DstPreCall;
275   getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
276                                             *Call, *this);
277
278   ExplodedNodeSet DstInvalidated;
279   StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
280   for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
281        I != E; ++I)
282     defaultEvalCall(Bldr, *I, *Call);
283
284   ExplodedNodeSet DstPostCall;
285   getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
286                                              *Call, *this);
287 }
288
289 void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
290                                    ExplodedNodeSet &Dst) {
291   // FIXME: Much of this should eventually migrate to CXXAllocatorCall.
292   // Also, we need to decide how allocators actually work -- they're not
293   // really part of the CXXNewExpr because they happen BEFORE the
294   // CXXConstructExpr subexpression. See PR12014 for some discussion.
295   
296   unsigned blockCount = currBldrCtx->blockCount();
297   const LocationContext *LCtx = Pred->getLocationContext();
298   DefinedOrUnknownSVal symVal = UnknownVal();
299   FunctionDecl *FD = CNE->getOperatorNew();
300
301   bool IsStandardGlobalOpNewFunction = false;
302   if (FD && !isa<CXXMethodDecl>(FD) && !FD->isVariadic()) {
303     if (FD->getNumParams() == 2) {
304       QualType T = FD->getParamDecl(1)->getType();
305       if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
306         // NoThrow placement new behaves as a standard new.
307         IsStandardGlobalOpNewFunction = II->getName().equals("nothrow_t");
308     }
309     else
310       // Placement forms are considered non-standard.
311       IsStandardGlobalOpNewFunction = (FD->getNumParams() == 1);
312   }
313
314   // We assume all standard global 'operator new' functions allocate memory in 
315   // heap. We realize this is an approximation that might not correctly model 
316   // a custom global allocator.
317   if (IsStandardGlobalOpNewFunction)
318     symVal = svalBuilder.getConjuredHeapSymbolVal(CNE, LCtx, blockCount);
319   else
320     symVal = svalBuilder.conjureSymbolVal(0, CNE, LCtx, CNE->getType(), 
321                                           blockCount);
322
323   ProgramStateRef State = Pred->getState();
324   CallEventManager &CEMgr = getStateManager().getCallEventManager();
325   CallEventRef<CXXAllocatorCall> Call =
326     CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
327
328   // Invalidate placement args.
329   // FIXME: Once we figure out how we want allocators to work,
330   // we should be using the usual pre-/(default-)eval-/post-call checks here.
331   State = Call->invalidateRegions(blockCount);
332   if (!State)
333     return;
334
335   // If we're compiling with exceptions enabled, and this allocation function
336   // is not declared as non-throwing, failures /must/ be signalled by
337   // exceptions, and thus the return value will never be NULL.
338   // C++11 [basic.stc.dynamic.allocation]p3.
339   if (FD && getContext().getLangOpts().CXXExceptions) {
340     QualType Ty = FD->getType();
341     if (const FunctionProtoType *ProtoType = Ty->getAs<FunctionProtoType>())
342       if (!ProtoType->isNothrow(getContext()))
343         State = State->assume(symVal, true);
344   }
345
346   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
347
348   if (CNE->isArray()) {
349     // FIXME: allocating an array requires simulating the constructors.
350     // For now, just return a symbolicated region.
351     const MemRegion *NewReg = symVal.castAs<loc::MemRegionVal>().getRegion();
352     QualType ObjTy = CNE->getType()->getAs<PointerType>()->getPointeeType();
353     const ElementRegion *EleReg =
354       getStoreManager().GetElementZeroRegion(NewReg, ObjTy);
355     State = State->BindExpr(CNE, Pred->getLocationContext(),
356                             loc::MemRegionVal(EleReg));
357     Bldr.generateNode(CNE, Pred, State);
358     return;
359   }
360
361   // FIXME: Once we have proper support for CXXConstructExprs inside
362   // CXXNewExpr, we need to make sure that the constructed object is not
363   // immediately invalidated here. (The placement call should happen before
364   // the constructor call anyway.)
365   SVal Result = symVal;
366   if (FD && FD->isReservedGlobalPlacementOperator()) {
367     // Non-array placement new should always return the placement location.
368     SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx);
369     Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(),
370                                   CNE->getPlacementArg(0)->getType());
371   }
372
373   // Bind the address of the object, then check to see if we cached out.
374   State = State->BindExpr(CNE, LCtx, Result);
375   ExplodedNode *NewN = Bldr.generateNode(CNE, Pred, State);
376   if (!NewN)
377     return;
378
379   // If the type is not a record, we won't have a CXXConstructExpr as an
380   // initializer. Copy the value over.
381   if (const Expr *Init = CNE->getInitializer()) {
382     if (!isa<CXXConstructExpr>(Init)) {
383       assert(Bldr.getResults().size() == 1);
384       Bldr.takeNodes(NewN);
385
386       assert(!CNE->getType()->getPointeeCXXRecordDecl());
387       evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, LCtx),
388                /*FirstInit=*/IsStandardGlobalOpNewFunction);
389     }
390   }
391 }
392
393 void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, 
394                                     ExplodedNode *Pred, ExplodedNodeSet &Dst) {
395   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
396   ProgramStateRef state = Pred->getState();
397   Bldr.generateNode(CDE, Pred, state);
398 }
399
400 void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS,
401                                    ExplodedNode *Pred,
402                                    ExplodedNodeSet &Dst) {
403   const VarDecl *VD = CS->getExceptionDecl();
404   if (!VD) {
405     Dst.Add(Pred);
406     return;
407   }
408
409   const LocationContext *LCtx = Pred->getLocationContext();
410   SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(),
411                                         currBldrCtx->blockCount());
412   ProgramStateRef state = Pred->getState();
413   state = state->bindLoc(state->getLValue(VD, LCtx), V);
414
415   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
416   Bldr.generateNode(CS, Pred, state);
417 }
418
419 void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
420                                     ExplodedNodeSet &Dst) {
421   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
422
423   // Get the this object region from StoreManager.
424   const LocationContext *LCtx = Pred->getLocationContext();
425   const MemRegion *R =
426     svalBuilder.getRegionManager().getCXXThisRegion(
427                                   getContext().getCanonicalType(TE->getType()),
428                                                     LCtx);
429
430   ProgramStateRef state = Pred->getState();
431   SVal V = state->getSVal(loc::MemRegionVal(R));
432   Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V));
433 }