1 //===- ExprEngineCXX.cpp - ExprEngine support for C++ -----------*- 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 defines the C++ expression evaluation engine.
12 //===----------------------------------------------------------------------===//
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"
22 using namespace clang;
25 void ExprEngine::CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
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();
33 SVal V = state->getSVal(tempExpr, LCtx);
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);
46 if (state == Pred->getState())
47 state = createTemporaryRegionIfNeeded(state, LCtx, tempExpr, ME);
48 Bldr.generateNode(ME, Pred, state);
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) {
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;
63 assert(cast<CXXMethodDecl>(Call.getDecl())->isTrivial());
64 assert(cast<CXXMethodDecl>(Call.getDecl())->getOverloadedOperator() ==
66 ThisVal = cast<CXXInstanceCall>(Call).getCXXThisVal();
67 AlwaysReturnsLValue = true;
70 const LocationContext *LCtx = Pred->getLocationContext();
75 SVal V = Call.getArgSVal(0);
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);
82 assert(V.isUnknown());
84 const Expr *CallExpr = Call.getOriginExpr();
85 evalBind(Dst, CallExpr, Pred, ThisVal, V, true);
87 PostStmt PS(CallExpr, LCtx);
88 for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end();
90 ProgramStateRef State = (*I)->getState();
91 if (AlwaysReturnsLValue)
92 State = State->BindExpr(CallExpr, LCtx, ThisVal);
94 State = bindReturnValue(Call, LCtx, State);
95 Bldr.generateNode(PS, State, *I);
100 /// Returns a region representing the first element of a (possibly
101 /// multi-dimensional) array.
103 /// On return, \p Ty will be set to the base type of the array.
105 /// If the type is not an array type at all, the original value is returned.
106 static SVal makeZeroElementRegion(ProgramStateRef State, SVal LValue,
108 SValBuilder &SVB = State->getStateManager().getSValBuilder();
109 ASTContext &Ctx = SVB.getContext();
111 while (const ArrayType *AT = Ctx.getAsArrayType(Ty)) {
112 Ty = AT->getElementType();
113 LValue = State->getLValue(Ty, SVB.makeZeroArrayIndex(), LValue);
119 void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE,
121 ExplodedNodeSet &destNodes) {
122 const LocationContext *LCtx = Pred->getLocationContext();
123 ProgramStateRef State = Pred->getState();
125 const MemRegion *Target = 0;
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).
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];
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();
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());
158 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
159 Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
160 LCtx->getCurrentStackFrame());
161 SVal ThisVal = State->getSVal(ThisPtr);
163 const ValueDecl *Field;
165 if (Init->isIndirectMemberInitializer()) {
166 Field = Init->getIndirectMember();
167 FieldVal = State->getLValue(Init->getIndirectMember(), ThisVal);
169 Field = Init->getMember();
170 FieldVal = State->getLValue(Init->getMember(), ThisVal);
173 QualType Ty = Field->getType();
174 FieldVal = makeZeroElementRegion(State, FieldVal, Ty);
175 Target = FieldVal.getAsRegion();
178 // FIXME: This will eventually need to handle new-expressions as well.
181 // If we couldn't find an existing region to construct into, assume we're
182 // constructing a temporary.
184 MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
185 Target = MRMgr.getCXXTempObjectRegion(CE, LCtx);
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);
198 if (CE->getConstructionKind() == CXXConstructExpr::CK_Delegating) {
199 Target = ThisVal.getAsRegion();
201 // Cast to the base type.
203 (CE->getConstructionKind() == CXXConstructExpr::CK_VirtualBase);
204 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, CE->getType(),
206 Target = BaseVal.getAsRegion();
212 CallEventManager &CEMgr = getStateManager().getCallEventManager();
213 CallEventRef<CXXConstructorCall> Call =
214 CEMgr.getCXXConstructorCall(CE, Target, State, LCtx);
216 ExplodedNodeSet DstPreVisit;
217 getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, CE, *this);
218 ExplodedNodeSet DstPreCall;
219 getCheckerManager().runCheckersForPreCall(DstPreCall, DstPreVisit,
222 ExplodedNodeSet DstEvaluated;
223 StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx);
225 bool IsArray = isa<ElementRegion>(Target);
226 if (CE->getConstructor()->isTrivial() &&
227 CE->getConstructor()->isCopyOrMoveConstructor() &&
229 // FIXME: Handle other kinds of trivial constructors as well.
230 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
232 performTrivialCopy(Bldr, *I, *Call);
235 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
237 defaultEvalCall(Bldr, *I, *Call);
240 ExplodedNodeSet DstPostCall;
241 getCheckerManager().runCheckersForPostCall(DstPostCall, DstEvaluated,
243 getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, CE, *this);
246 void ExprEngine::VisitCXXDestructor(QualType ObjectType,
247 const MemRegion *Dest,
251 ExplodedNodeSet &Dst) {
252 const LocationContext *LCtx = Pred->getLocationContext();
253 ProgramStateRef State = Pred->getState();
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();
262 const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl();
263 assert(RecordDecl && "Only CXXRecordDecls should have destructors");
264 const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
266 CallEventManager &CEMgr = getStateManager().getCallEventManager();
267 CallEventRef<CXXDestructorCall> Call =
268 CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx);
270 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
271 Call->getSourceRange().getBegin(),
272 "Error evaluating destructor");
274 ExplodedNodeSet DstPreCall;
275 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
278 ExplodedNodeSet DstInvalidated;
279 StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
280 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
282 defaultEvalCall(Bldr, *I, *Call);
284 ExplodedNodeSet DstPostCall;
285 getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
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.
296 unsigned blockCount = currBldrCtx->blockCount();
297 const LocationContext *LCtx = Pred->getLocationContext();
298 DefinedOrUnknownSVal symVal = UnknownVal();
299 FunctionDecl *FD = CNE->getOperatorNew();
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");
310 // Placement forms are considered non-standard.
311 IsStandardGlobalOpNewFunction = (FD->getNumParams() == 1);
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);
320 symVal = svalBuilder.conjureSymbolVal(0, CNE, LCtx, CNE->getType(),
323 ProgramStateRef State = Pred->getState();
324 CallEventManager &CEMgr = getStateManager().getCallEventManager();
325 CallEventRef<CXXAllocatorCall> Call =
326 CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
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);
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);
346 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
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);
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());
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);
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);
386 assert(!CNE->getType()->getPointeeCXXRecordDecl());
387 evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, LCtx),
388 /*FirstInit=*/IsStandardGlobalOpNewFunction);
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);
400 void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS,
402 ExplodedNodeSet &Dst) {
403 const VarDecl *VD = CS->getExceptionDecl();
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);
415 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
416 Bldr.generateNode(CS, Pred, state);
419 void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
420 ExplodedNodeSet &Dst) {
421 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
423 // Get the this object region from StoreManager.
424 const LocationContext *LCtx = Pred->getLocationContext();
426 svalBuilder.getRegionManager().getCXXThisRegion(
427 getContext().getCanonicalType(TE->getType()),
430 ProgramStateRef state = Pred->getState();
431 SVal V = state->getSVal(loc::MemRegionVal(R));
432 Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V));