1e5dd7070Spatrick //===- ExprEngineCXX.cpp - ExprEngine support for C++ -----------*- C++ -*-===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This file defines the C++ expression evaluation engine.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick
13e5dd7070Spatrick #include "clang/AST/DeclCXX.h"
14e5dd7070Spatrick #include "clang/AST/ParentMap.h"
15*12c85518Srobert #include "clang/AST/StmtCXX.h"
16*12c85518Srobert #include "clang/Analysis/ConstructionContext.h"
17e5dd7070Spatrick #include "clang/Basic/PrettyStackTrace.h"
18e5dd7070Spatrick #include "clang/StaticAnalyzer/Core/CheckerManager.h"
19e5dd7070Spatrick #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
20e5dd7070Spatrick #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
21*12c85518Srobert #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
22*12c85518Srobert #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
23*12c85518Srobert #include <optional>
24e5dd7070Spatrick
25e5dd7070Spatrick using namespace clang;
26e5dd7070Spatrick using namespace ento;
27e5dd7070Spatrick
CreateCXXTemporaryObject(const MaterializeTemporaryExpr * ME,ExplodedNode * Pred,ExplodedNodeSet & Dst)28e5dd7070Spatrick void ExprEngine::CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
29e5dd7070Spatrick ExplodedNode *Pred,
30e5dd7070Spatrick ExplodedNodeSet &Dst) {
31e5dd7070Spatrick StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
32e5dd7070Spatrick const Expr *tempExpr = ME->getSubExpr()->IgnoreParens();
33e5dd7070Spatrick ProgramStateRef state = Pred->getState();
34e5dd7070Spatrick const LocationContext *LCtx = Pred->getLocationContext();
35e5dd7070Spatrick
36e5dd7070Spatrick state = createTemporaryRegionIfNeeded(state, LCtx, tempExpr, ME);
37e5dd7070Spatrick Bldr.generateNode(ME, Pred, state);
38e5dd7070Spatrick }
39e5dd7070Spatrick
40e5dd7070Spatrick // FIXME: This is the sort of code that should eventually live in a Core
41e5dd7070Spatrick // checker rather than as a special case in ExprEngine.
performTrivialCopy(NodeBuilder & Bldr,ExplodedNode * Pred,const CallEvent & Call)42e5dd7070Spatrick void ExprEngine::performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred,
43e5dd7070Spatrick const CallEvent &Call) {
44e5dd7070Spatrick SVal ThisVal;
45e5dd7070Spatrick bool AlwaysReturnsLValue;
46e5dd7070Spatrick const CXXRecordDecl *ThisRD = nullptr;
47e5dd7070Spatrick if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) {
48e5dd7070Spatrick assert(Ctor->getDecl()->isTrivial());
49e5dd7070Spatrick assert(Ctor->getDecl()->isCopyOrMoveConstructor());
50e5dd7070Spatrick ThisVal = Ctor->getCXXThisVal();
51e5dd7070Spatrick ThisRD = Ctor->getDecl()->getParent();
52e5dd7070Spatrick AlwaysReturnsLValue = false;
53e5dd7070Spatrick } else {
54e5dd7070Spatrick assert(cast<CXXMethodDecl>(Call.getDecl())->isTrivial());
55e5dd7070Spatrick assert(cast<CXXMethodDecl>(Call.getDecl())->getOverloadedOperator() ==
56e5dd7070Spatrick OO_Equal);
57e5dd7070Spatrick ThisVal = cast<CXXInstanceCall>(Call).getCXXThisVal();
58e5dd7070Spatrick ThisRD = cast<CXXMethodDecl>(Call.getDecl())->getParent();
59e5dd7070Spatrick AlwaysReturnsLValue = true;
60e5dd7070Spatrick }
61e5dd7070Spatrick
62e5dd7070Spatrick assert(ThisRD);
63e5dd7070Spatrick if (ThisRD->isEmpty()) {
64e5dd7070Spatrick // Do nothing for empty classes. Otherwise it'd retrieve an UnknownVal
65e5dd7070Spatrick // and bind it and RegionStore would think that the actual value
66e5dd7070Spatrick // in this region at this offset is unknown.
67e5dd7070Spatrick return;
68e5dd7070Spatrick }
69e5dd7070Spatrick
70e5dd7070Spatrick const LocationContext *LCtx = Pred->getLocationContext();
71e5dd7070Spatrick
72e5dd7070Spatrick ExplodedNodeSet Dst;
73e5dd7070Spatrick Bldr.takeNodes(Pred);
74e5dd7070Spatrick
75e5dd7070Spatrick SVal V = Call.getArgSVal(0);
76e5dd7070Spatrick
77e5dd7070Spatrick // If the value being copied is not unknown, load from its location to get
78e5dd7070Spatrick // an aggregate rvalue.
79*12c85518Srobert if (std::optional<Loc> L = V.getAs<Loc>())
80e5dd7070Spatrick V = Pred->getState()->getSVal(*L);
81e5dd7070Spatrick else
82e5dd7070Spatrick assert(V.isUnknownOrUndef());
83e5dd7070Spatrick
84e5dd7070Spatrick const Expr *CallExpr = Call.getOriginExpr();
85e5dd7070Spatrick evalBind(Dst, CallExpr, Pred, ThisVal, V, true);
86e5dd7070Spatrick
87e5dd7070Spatrick PostStmt PS(CallExpr, LCtx);
88e5dd7070Spatrick for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end();
89e5dd7070Spatrick I != E; ++I) {
90e5dd7070Spatrick ProgramStateRef State = (*I)->getState();
91e5dd7070Spatrick if (AlwaysReturnsLValue)
92e5dd7070Spatrick State = State->BindExpr(CallExpr, LCtx, ThisVal);
93e5dd7070Spatrick else
94e5dd7070Spatrick State = bindReturnValue(Call, LCtx, State);
95e5dd7070Spatrick Bldr.generateNode(PS, State, *I);
96e5dd7070Spatrick }
97e5dd7070Spatrick }
98e5dd7070Spatrick
makeElementRegion(ProgramStateRef State,SVal LValue,QualType & Ty,bool & IsArray,unsigned Idx)99*12c85518Srobert SVal ExprEngine::makeElementRegion(ProgramStateRef State, SVal LValue,
100*12c85518Srobert QualType &Ty, bool &IsArray, unsigned Idx) {
101e5dd7070Spatrick SValBuilder &SVB = State->getStateManager().getSValBuilder();
102e5dd7070Spatrick ASTContext &Ctx = SVB.getContext();
103e5dd7070Spatrick
104*12c85518Srobert if (const ArrayType *AT = Ctx.getAsArrayType(Ty)) {
105*12c85518Srobert while (AT) {
106e5dd7070Spatrick Ty = AT->getElementType();
107*12c85518Srobert AT = dyn_cast<ArrayType>(AT->getElementType());
108*12c85518Srobert }
109*12c85518Srobert LValue = State->getLValue(Ty, SVB.makeArrayIndex(Idx), LValue);
110e5dd7070Spatrick IsArray = true;
111e5dd7070Spatrick }
112e5dd7070Spatrick
113e5dd7070Spatrick return LValue;
114e5dd7070Spatrick }
115e5dd7070Spatrick
116*12c85518Srobert // In case when the prvalue is returned from the function (kind is one of
117*12c85518Srobert // SimpleReturnedValueKind, CXX17ElidedCopyReturnedValueKind), then
118*12c85518Srobert // it's materialization happens in context of the caller.
119*12c85518Srobert // We pass BldrCtx explicitly, as currBldrCtx always refers to callee's context.
computeObjectUnderConstruction(const Expr * E,ProgramStateRef State,const NodeBuilderContext * BldrCtx,const LocationContext * LCtx,const ConstructionContext * CC,EvalCallOptions & CallOpts,unsigned Idx)120ec727ea7Spatrick SVal ExprEngine::computeObjectUnderConstruction(
121*12c85518Srobert const Expr *E, ProgramStateRef State, const NodeBuilderContext *BldrCtx,
122*12c85518Srobert const LocationContext *LCtx, const ConstructionContext *CC,
123*12c85518Srobert EvalCallOptions &CallOpts, unsigned Idx) {
124*12c85518Srobert
125e5dd7070Spatrick SValBuilder &SVB = getSValBuilder();
126e5dd7070Spatrick MemRegionManager &MRMgr = SVB.getRegionManager();
127e5dd7070Spatrick ASTContext &ACtx = SVB.getContext();
128e5dd7070Spatrick
129ec727ea7Spatrick // Compute the target region by exploring the construction context.
130e5dd7070Spatrick if (CC) {
131e5dd7070Spatrick switch (CC->getKind()) {
132e5dd7070Spatrick case ConstructionContext::CXX17ElidedCopyVariableKind:
133e5dd7070Spatrick case ConstructionContext::SimpleVariableKind: {
134e5dd7070Spatrick const auto *DSCC = cast<VariableConstructionContext>(CC);
135e5dd7070Spatrick const auto *DS = DSCC->getDeclStmt();
136e5dd7070Spatrick const auto *Var = cast<VarDecl>(DS->getSingleDecl());
137e5dd7070Spatrick QualType Ty = Var->getType();
138*12c85518Srobert return makeElementRegion(State, State->getLValue(Var, LCtx), Ty,
139*12c85518Srobert CallOpts.IsArrayCtorOrDtor, Idx);
140e5dd7070Spatrick }
141e5dd7070Spatrick case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind:
142e5dd7070Spatrick case ConstructionContext::SimpleConstructorInitializerKind: {
143e5dd7070Spatrick const auto *ICC = cast<ConstructorInitializerConstructionContext>(CC);
144e5dd7070Spatrick const auto *Init = ICC->getCXXCtorInitializer();
145e5dd7070Spatrick const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
146ec727ea7Spatrick Loc ThisPtr = SVB.getCXXThis(CurCtor, LCtx->getStackFrame());
147e5dd7070Spatrick SVal ThisVal = State->getSVal(ThisPtr);
148a9ac8606Spatrick if (Init->isBaseInitializer()) {
149a9ac8606Spatrick const auto *ThisReg = cast<SubRegion>(ThisVal.getAsRegion());
150a9ac8606Spatrick const CXXRecordDecl *BaseClass =
151a9ac8606Spatrick Init->getBaseClass()->getAsCXXRecordDecl();
152a9ac8606Spatrick const auto *BaseReg =
153a9ac8606Spatrick MRMgr.getCXXBaseObjectRegion(BaseClass, ThisReg,
154a9ac8606Spatrick Init->isBaseVirtual());
155a9ac8606Spatrick return SVB.makeLoc(BaseReg);
156a9ac8606Spatrick }
157a9ac8606Spatrick if (Init->isDelegatingInitializer())
158a9ac8606Spatrick return ThisVal;
159e5dd7070Spatrick
160e5dd7070Spatrick const ValueDecl *Field;
161e5dd7070Spatrick SVal FieldVal;
162e5dd7070Spatrick if (Init->isIndirectMemberInitializer()) {
163e5dd7070Spatrick Field = Init->getIndirectMember();
164e5dd7070Spatrick FieldVal = State->getLValue(Init->getIndirectMember(), ThisVal);
165e5dd7070Spatrick } else {
166e5dd7070Spatrick Field = Init->getMember();
167e5dd7070Spatrick FieldVal = State->getLValue(Init->getMember(), ThisVal);
168e5dd7070Spatrick }
169e5dd7070Spatrick
170e5dd7070Spatrick QualType Ty = Field->getType();
171*12c85518Srobert return makeElementRegion(State, FieldVal, Ty, CallOpts.IsArrayCtorOrDtor,
172*12c85518Srobert Idx);
173e5dd7070Spatrick }
174e5dd7070Spatrick case ConstructionContext::NewAllocatedObjectKind: {
175e5dd7070Spatrick if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
176e5dd7070Spatrick const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
177e5dd7070Spatrick const auto *NE = NECC->getCXXNewExpr();
178e5dd7070Spatrick SVal V = *getObjectUnderConstruction(State, NE, LCtx);
179e5dd7070Spatrick if (const SubRegion *MR =
180e5dd7070Spatrick dyn_cast_or_null<SubRegion>(V.getAsRegion())) {
181e5dd7070Spatrick if (NE->isArray()) {
182e5dd7070Spatrick CallOpts.IsArrayCtorOrDtor = true;
183*12c85518Srobert
184*12c85518Srobert auto Ty = NE->getType()->getPointeeType();
185*12c85518Srobert while (const auto *AT = getContext().getAsArrayType(Ty))
186*12c85518Srobert Ty = AT->getElementType();
187*12c85518Srobert
188*12c85518Srobert auto R = MRMgr.getElementRegion(Ty, svalBuilder.makeArrayIndex(Idx),
189*12c85518Srobert MR, SVB.getContext());
190*12c85518Srobert
191*12c85518Srobert return loc::MemRegionVal(R);
192e5dd7070Spatrick }
193ec727ea7Spatrick return V;
194e5dd7070Spatrick }
195e5dd7070Spatrick // TODO: Detect when the allocator returns a null pointer.
196e5dd7070Spatrick // Constructor shall not be called in this case.
197e5dd7070Spatrick }
198e5dd7070Spatrick break;
199e5dd7070Spatrick }
200e5dd7070Spatrick case ConstructionContext::SimpleReturnedValueKind:
201e5dd7070Spatrick case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
202e5dd7070Spatrick // The temporary is to be managed by the parent stack frame.
203e5dd7070Spatrick // So build it in the parent stack frame if we're not in the
204e5dd7070Spatrick // top frame of the analysis.
205e5dd7070Spatrick const StackFrameContext *SFC = LCtx->getStackFrame();
206e5dd7070Spatrick if (const LocationContext *CallerLCtx = SFC->getParent()) {
207e5dd7070Spatrick auto RTC = (*SFC->getCallSiteBlock())[SFC->getIndex()]
208e5dd7070Spatrick .getAs<CFGCXXRecordTypedCall>();
209e5dd7070Spatrick if (!RTC) {
210e5dd7070Spatrick // We were unable to find the correct construction context for the
211e5dd7070Spatrick // call in the parent stack frame. This is equivalent to not being
212e5dd7070Spatrick // able to find construction context at all.
213e5dd7070Spatrick break;
214e5dd7070Spatrick }
215e5dd7070Spatrick if (isa<BlockInvocationContext>(CallerLCtx)) {
216e5dd7070Spatrick // Unwrap block invocation contexts. They're mostly part of
217e5dd7070Spatrick // the current stack frame.
218e5dd7070Spatrick CallerLCtx = CallerLCtx->getParent();
219e5dd7070Spatrick assert(!isa<BlockInvocationContext>(CallerLCtx));
220e5dd7070Spatrick }
221*12c85518Srobert
222*12c85518Srobert NodeBuilderContext CallerBldrCtx(getCoreEngine(),
223*12c85518Srobert SFC->getCallSiteBlock(), CallerLCtx);
224ec727ea7Spatrick return computeObjectUnderConstruction(
225*12c85518Srobert cast<Expr>(SFC->getCallSite()), State, &CallerBldrCtx, CallerLCtx,
226e5dd7070Spatrick RTC->getConstructionContext(), CallOpts);
227e5dd7070Spatrick } else {
228e5dd7070Spatrick // We are on the top frame of the analysis. We do not know where is the
229e5dd7070Spatrick // object returned to. Conjure a symbolic region for the return value.
230e5dd7070Spatrick // TODO: We probably need a new MemRegion kind to represent the storage
231e5dd7070Spatrick // of that SymbolicRegion, so that we cound produce a fancy symbol
232e5dd7070Spatrick // instead of an anonymous conjured symbol.
233e5dd7070Spatrick // TODO: Do we need to track the region to avoid having it dead
234e5dd7070Spatrick // too early? It does die too early, at least in C++17, but because
235e5dd7070Spatrick // putting anything into a SymbolicRegion causes an immediate escape,
236e5dd7070Spatrick // it doesn't cause any leak false positives.
237e5dd7070Spatrick const auto *RCC = cast<ReturnedValueConstructionContext>(CC);
238e5dd7070Spatrick // Make sure that this doesn't coincide with any other symbol
239e5dd7070Spatrick // conjured for the returned expression.
240e5dd7070Spatrick static const int TopLevelSymRegionTag = 0;
241e5dd7070Spatrick const Expr *RetE = RCC->getReturnStmt()->getRetValue();
242e5dd7070Spatrick assert(RetE && "Void returns should not have a construction context");
243e5dd7070Spatrick QualType ReturnTy = RetE->getType();
244e5dd7070Spatrick QualType RegionTy = ACtx.getPointerType(ReturnTy);
245ec727ea7Spatrick return SVB.conjureSymbolVal(&TopLevelSymRegionTag, RetE, SFC, RegionTy,
246ec727ea7Spatrick currBldrCtx->blockCount());
247e5dd7070Spatrick }
248e5dd7070Spatrick llvm_unreachable("Unhandled return value construction context!");
249e5dd7070Spatrick }
250e5dd7070Spatrick case ConstructionContext::ElidedTemporaryObjectKind: {
251e5dd7070Spatrick assert(AMgr.getAnalyzerOptions().ShouldElideConstructors);
252e5dd7070Spatrick const auto *TCC = cast<ElidedTemporaryObjectConstructionContext>(CC);
253e5dd7070Spatrick
254e5dd7070Spatrick // Support pre-C++17 copy elision. We'll have the elidable copy
255e5dd7070Spatrick // constructor in the AST and in the CFG, but we'll skip it
256e5dd7070Spatrick // and construct directly into the final object. This call
257e5dd7070Spatrick // also sets the CallOpts flags for us.
258e5dd7070Spatrick // If the elided copy/move constructor is not supported, there's still
259e5dd7070Spatrick // benefit in trying to model the non-elided constructor.
260e5dd7070Spatrick // Stash our state before trying to elide, as it'll get overwritten.
261e5dd7070Spatrick ProgramStateRef PreElideState = State;
262e5dd7070Spatrick EvalCallOptions PreElideCallOpts = CallOpts;
263e5dd7070Spatrick
264ec727ea7Spatrick SVal V = computeObjectUnderConstruction(
265*12c85518Srobert TCC->getConstructorAfterElision(), State, BldrCtx, LCtx,
266ec727ea7Spatrick TCC->getConstructionContextAfterElision(), CallOpts);
267e5dd7070Spatrick
268e5dd7070Spatrick // FIXME: This definition of "copy elision has not failed" is unreliable.
269e5dd7070Spatrick // It doesn't indicate that the constructor will actually be inlined
270ec727ea7Spatrick // later; this is still up to evalCall() to decide.
271ec727ea7Spatrick if (!CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion)
272ec727ea7Spatrick return V;
273e5dd7070Spatrick
274e5dd7070Spatrick // Copy elision failed. Revert the changes and proceed as if we have
275e5dd7070Spatrick // a simple temporary.
276e5dd7070Spatrick CallOpts = PreElideCallOpts;
277ec727ea7Spatrick CallOpts.IsElidableCtorThatHasNotBeenElided = true;
278*12c85518Srobert [[fallthrough]];
279e5dd7070Spatrick }
280e5dd7070Spatrick case ConstructionContext::SimpleTemporaryObjectKind: {
281e5dd7070Spatrick const auto *TCC = cast<TemporaryObjectConstructionContext>(CC);
282e5dd7070Spatrick const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr();
283e5dd7070Spatrick
284ec727ea7Spatrick CallOpts.IsTemporaryCtorOrDtor = true;
285e5dd7070Spatrick if (MTE) {
286e5dd7070Spatrick if (const ValueDecl *VD = MTE->getExtendingDecl()) {
287e5dd7070Spatrick assert(MTE->getStorageDuration() != SD_FullExpression);
288e5dd7070Spatrick if (!VD->getType()->isReferenceType()) {
289e5dd7070Spatrick // We're lifetime-extended by a surrounding aggregate.
290e5dd7070Spatrick // Automatic destructors aren't quite working in this case
291e5dd7070Spatrick // on the CFG side. We should warn the caller about that.
292e5dd7070Spatrick // FIXME: Is there a better way to retrieve this information from
293e5dd7070Spatrick // the MaterializeTemporaryExpr?
294e5dd7070Spatrick CallOpts.IsTemporaryLifetimeExtendedViaAggregate = true;
295e5dd7070Spatrick }
296e5dd7070Spatrick }
297e5dd7070Spatrick
298e5dd7070Spatrick if (MTE->getStorageDuration() == SD_Static ||
299e5dd7070Spatrick MTE->getStorageDuration() == SD_Thread)
300ec727ea7Spatrick return loc::MemRegionVal(MRMgr.getCXXStaticTempObjectRegion(E));
301e5dd7070Spatrick }
302e5dd7070Spatrick
303ec727ea7Spatrick return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx));
304e5dd7070Spatrick }
305*12c85518Srobert case ConstructionContext::LambdaCaptureKind: {
306*12c85518Srobert CallOpts.IsTemporaryCtorOrDtor = true;
307*12c85518Srobert
308*12c85518Srobert const auto *LCC = cast<LambdaCaptureConstructionContext>(CC);
309*12c85518Srobert
310*12c85518Srobert SVal Base = loc::MemRegionVal(
311*12c85518Srobert MRMgr.getCXXTempObjectRegion(LCC->getInitializer(), LCtx));
312*12c85518Srobert
313*12c85518Srobert const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E);
314*12c85518Srobert if (getIndexOfElementToConstruct(State, CE, LCtx)) {
315*12c85518Srobert CallOpts.IsArrayCtorOrDtor = true;
316*12c85518Srobert Base = State->getLValue(E->getType(), svalBuilder.makeArrayIndex(Idx),
317*12c85518Srobert Base);
318*12c85518Srobert }
319*12c85518Srobert
320*12c85518Srobert return Base;
321*12c85518Srobert }
322e5dd7070Spatrick case ConstructionContext::ArgumentKind: {
323e5dd7070Spatrick // Arguments are technically temporaries.
324e5dd7070Spatrick CallOpts.IsTemporaryCtorOrDtor = true;
325e5dd7070Spatrick
326e5dd7070Spatrick const auto *ACC = cast<ArgumentConstructionContext>(CC);
327e5dd7070Spatrick const Expr *E = ACC->getCallLikeExpr();
328e5dd7070Spatrick unsigned Idx = ACC->getIndex();
329e5dd7070Spatrick
330e5dd7070Spatrick CallEventManager &CEMgr = getStateManager().getCallEventManager();
331*12c85518Srobert auto getArgLoc = [&](CallEventRef<> Caller) -> std::optional<SVal> {
332e5dd7070Spatrick const LocationContext *FutureSFC =
333*12c85518Srobert Caller->getCalleeStackFrame(BldrCtx->blockCount());
334e5dd7070Spatrick // Return early if we are unable to reliably foresee
335e5dd7070Spatrick // the future stack frame.
336e5dd7070Spatrick if (!FutureSFC)
337*12c85518Srobert return std::nullopt;
338e5dd7070Spatrick
339e5dd7070Spatrick // This should be equivalent to Caller->getDecl() for now, but
340e5dd7070Spatrick // FutureSFC->getDecl() is likely to support better stuff (like
341e5dd7070Spatrick // virtual functions) earlier.
342e5dd7070Spatrick const Decl *CalleeD = FutureSFC->getDecl();
343e5dd7070Spatrick
344e5dd7070Spatrick // FIXME: Support for variadic arguments is not implemented here yet.
345e5dd7070Spatrick if (CallEvent::isVariadic(CalleeD))
346*12c85518Srobert return std::nullopt;
347e5dd7070Spatrick
348e5dd7070Spatrick // Operator arguments do not correspond to operator parameters
349e5dd7070Spatrick // because this-argument is implemented as a normal argument in
350e5dd7070Spatrick // operator call expressions but not in operator declarations.
351ec727ea7Spatrick const TypedValueRegion *TVR = Caller->getParameterLocation(
352*12c85518Srobert *Caller->getAdjustedParameterIndex(Idx), BldrCtx->blockCount());
353ec727ea7Spatrick if (!TVR)
354*12c85518Srobert return std::nullopt;
355e5dd7070Spatrick
356ec727ea7Spatrick return loc::MemRegionVal(TVR);
357e5dd7070Spatrick };
358e5dd7070Spatrick
359e5dd7070Spatrick if (const auto *CE = dyn_cast<CallExpr>(E)) {
360e5dd7070Spatrick CallEventRef<> Caller = CEMgr.getSimpleCall(CE, State, LCtx);
361*12c85518Srobert if (std::optional<SVal> V = getArgLoc(Caller))
362ec727ea7Spatrick return *V;
363e5dd7070Spatrick else
364e5dd7070Spatrick break;
365e5dd7070Spatrick } else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) {
366e5dd7070Spatrick // Don't bother figuring out the target region for the future
367e5dd7070Spatrick // constructor because we won't need it.
368e5dd7070Spatrick CallEventRef<> Caller =
369e5dd7070Spatrick CEMgr.getCXXConstructorCall(CCE, /*Target=*/nullptr, State, LCtx);
370*12c85518Srobert if (std::optional<SVal> V = getArgLoc(Caller))
371ec727ea7Spatrick return *V;
372e5dd7070Spatrick else
373e5dd7070Spatrick break;
374e5dd7070Spatrick } else if (const auto *ME = dyn_cast<ObjCMessageExpr>(E)) {
375e5dd7070Spatrick CallEventRef<> Caller = CEMgr.getObjCMethodCall(ME, State, LCtx);
376*12c85518Srobert if (std::optional<SVal> V = getArgLoc(Caller))
377ec727ea7Spatrick return *V;
378e5dd7070Spatrick else
379e5dd7070Spatrick break;
380ec727ea7Spatrick }
381ec727ea7Spatrick }
382ec727ea7Spatrick } // switch (CC->getKind())
383e5dd7070Spatrick }
384e5dd7070Spatrick
385e5dd7070Spatrick // If we couldn't find an existing region to construct into, assume we're
386e5dd7070Spatrick // constructing a temporary. Notify the caller of our failure.
387e5dd7070Spatrick CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
388ec727ea7Spatrick return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx));
389e5dd7070Spatrick }
390e5dd7070Spatrick
updateObjectsUnderConstruction(SVal V,const Expr * E,ProgramStateRef State,const LocationContext * LCtx,const ConstructionContext * CC,const EvalCallOptions & CallOpts)391ec727ea7Spatrick ProgramStateRef ExprEngine::updateObjectsUnderConstruction(
392ec727ea7Spatrick SVal V, const Expr *E, ProgramStateRef State, const LocationContext *LCtx,
393ec727ea7Spatrick const ConstructionContext *CC, const EvalCallOptions &CallOpts) {
394ec727ea7Spatrick if (CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion) {
395ec727ea7Spatrick // Sounds like we failed to find the target region and therefore
396ec727ea7Spatrick // copy elision failed. There's nothing we can do about it here.
397ec727ea7Spatrick return State;
398ec727ea7Spatrick }
399ec727ea7Spatrick
400ec727ea7Spatrick // See if we're constructing an existing region by looking at the
401ec727ea7Spatrick // current construction context.
402ec727ea7Spatrick assert(CC && "Computed target region without construction context?");
403ec727ea7Spatrick switch (CC->getKind()) {
404ec727ea7Spatrick case ConstructionContext::CXX17ElidedCopyVariableKind:
405ec727ea7Spatrick case ConstructionContext::SimpleVariableKind: {
406ec727ea7Spatrick const auto *DSCC = cast<VariableConstructionContext>(CC);
407ec727ea7Spatrick return addObjectUnderConstruction(State, DSCC->getDeclStmt(), LCtx, V);
408ec727ea7Spatrick }
409ec727ea7Spatrick case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind:
410ec727ea7Spatrick case ConstructionContext::SimpleConstructorInitializerKind: {
411ec727ea7Spatrick const auto *ICC = cast<ConstructorInitializerConstructionContext>(CC);
412a9ac8606Spatrick const auto *Init = ICC->getCXXCtorInitializer();
413a9ac8606Spatrick // Base and delegating initializers handled above
414a9ac8606Spatrick assert(Init->isAnyMemberInitializer() &&
415a9ac8606Spatrick "Base and delegating initializers should have been handled by"
416a9ac8606Spatrick "computeObjectUnderConstruction()");
417a9ac8606Spatrick return addObjectUnderConstruction(State, Init, LCtx, V);
418ec727ea7Spatrick }
419ec727ea7Spatrick case ConstructionContext::NewAllocatedObjectKind: {
420ec727ea7Spatrick return State;
421ec727ea7Spatrick }
422ec727ea7Spatrick case ConstructionContext::SimpleReturnedValueKind:
423ec727ea7Spatrick case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
424ec727ea7Spatrick const StackFrameContext *SFC = LCtx->getStackFrame();
425ec727ea7Spatrick const LocationContext *CallerLCtx = SFC->getParent();
426ec727ea7Spatrick if (!CallerLCtx) {
427ec727ea7Spatrick // No extra work is necessary in top frame.
428ec727ea7Spatrick return State;
429ec727ea7Spatrick }
430ec727ea7Spatrick
431ec727ea7Spatrick auto RTC = (*SFC->getCallSiteBlock())[SFC->getIndex()]
432ec727ea7Spatrick .getAs<CFGCXXRecordTypedCall>();
433ec727ea7Spatrick assert(RTC && "Could not have had a target region without it");
434ec727ea7Spatrick if (isa<BlockInvocationContext>(CallerLCtx)) {
435ec727ea7Spatrick // Unwrap block invocation contexts. They're mostly part of
436ec727ea7Spatrick // the current stack frame.
437ec727ea7Spatrick CallerLCtx = CallerLCtx->getParent();
438ec727ea7Spatrick assert(!isa<BlockInvocationContext>(CallerLCtx));
439ec727ea7Spatrick }
440ec727ea7Spatrick
441ec727ea7Spatrick return updateObjectsUnderConstruction(V,
442ec727ea7Spatrick cast<Expr>(SFC->getCallSite()), State, CallerLCtx,
443ec727ea7Spatrick RTC->getConstructionContext(), CallOpts);
444ec727ea7Spatrick }
445ec727ea7Spatrick case ConstructionContext::ElidedTemporaryObjectKind: {
446ec727ea7Spatrick assert(AMgr.getAnalyzerOptions().ShouldElideConstructors);
447ec727ea7Spatrick if (!CallOpts.IsElidableCtorThatHasNotBeenElided) {
448ec727ea7Spatrick const auto *TCC = cast<ElidedTemporaryObjectConstructionContext>(CC);
449ec727ea7Spatrick State = updateObjectsUnderConstruction(
450ec727ea7Spatrick V, TCC->getConstructorAfterElision(), State, LCtx,
451ec727ea7Spatrick TCC->getConstructionContextAfterElision(), CallOpts);
452ec727ea7Spatrick
453ec727ea7Spatrick // Remember that we've elided the constructor.
454ec727ea7Spatrick State = addObjectUnderConstruction(
455ec727ea7Spatrick State, TCC->getConstructorAfterElision(), LCtx, V);
456ec727ea7Spatrick
457ec727ea7Spatrick // Remember that we've elided the destructor.
458ec727ea7Spatrick if (const auto *BTE = TCC->getCXXBindTemporaryExpr())
459ec727ea7Spatrick State = elideDestructor(State, BTE, LCtx);
460ec727ea7Spatrick
461ec727ea7Spatrick // Instead of materialization, shamelessly return
462ec727ea7Spatrick // the final object destination.
463ec727ea7Spatrick if (const auto *MTE = TCC->getMaterializedTemporaryExpr())
464ec727ea7Spatrick State = addObjectUnderConstruction(State, MTE, LCtx, V);
465ec727ea7Spatrick
466ec727ea7Spatrick return State;
467ec727ea7Spatrick }
468ec727ea7Spatrick // If we decided not to elide the constructor, proceed as if
469ec727ea7Spatrick // it's a simple temporary.
470*12c85518Srobert [[fallthrough]];
471ec727ea7Spatrick }
472ec727ea7Spatrick case ConstructionContext::SimpleTemporaryObjectKind: {
473ec727ea7Spatrick const auto *TCC = cast<TemporaryObjectConstructionContext>(CC);
474ec727ea7Spatrick if (const auto *BTE = TCC->getCXXBindTemporaryExpr())
475ec727ea7Spatrick State = addObjectUnderConstruction(State, BTE, LCtx, V);
476ec727ea7Spatrick
477ec727ea7Spatrick if (const auto *MTE = TCC->getMaterializedTemporaryExpr())
478ec727ea7Spatrick State = addObjectUnderConstruction(State, MTE, LCtx, V);
479ec727ea7Spatrick
480ec727ea7Spatrick return State;
481ec727ea7Spatrick }
482*12c85518Srobert case ConstructionContext::LambdaCaptureKind: {
483*12c85518Srobert const auto *LCC = cast<LambdaCaptureConstructionContext>(CC);
484*12c85518Srobert
485*12c85518Srobert // If we capture and array, we want to store the super region, not a
486*12c85518Srobert // sub-region.
487*12c85518Srobert if (const auto *EL = dyn_cast_or_null<ElementRegion>(V.getAsRegion()))
488*12c85518Srobert V = loc::MemRegionVal(EL->getSuperRegion());
489*12c85518Srobert
490*12c85518Srobert return addObjectUnderConstruction(
491*12c85518Srobert State, {LCC->getLambdaExpr(), LCC->getIndex()}, LCtx, V);
492*12c85518Srobert }
493ec727ea7Spatrick case ConstructionContext::ArgumentKind: {
494ec727ea7Spatrick const auto *ACC = cast<ArgumentConstructionContext>(CC);
495ec727ea7Spatrick if (const auto *BTE = ACC->getCXXBindTemporaryExpr())
496ec727ea7Spatrick State = addObjectUnderConstruction(State, BTE, LCtx, V);
497ec727ea7Spatrick
498ec727ea7Spatrick return addObjectUnderConstruction(
499ec727ea7Spatrick State, {ACC->getCallLikeExpr(), ACC->getIndex()}, LCtx, V);
500ec727ea7Spatrick }
501ec727ea7Spatrick }
502ec727ea7Spatrick llvm_unreachable("Unhandled construction context!");
503ec727ea7Spatrick }
504ec727ea7Spatrick
505*12c85518Srobert static ProgramStateRef
bindRequiredArrayElementToEnvironment(ProgramStateRef State,const ArrayInitLoopExpr * AILE,const LocationContext * LCtx,SVal Idx)506*12c85518Srobert bindRequiredArrayElementToEnvironment(ProgramStateRef State,
507*12c85518Srobert const ArrayInitLoopExpr *AILE,
508*12c85518Srobert const LocationContext *LCtx, SVal Idx) {
509*12c85518Srobert // The ctor in this case is guaranteed to be a copy ctor, otherwise we hit a
510*12c85518Srobert // compile time error.
511*12c85518Srobert //
512*12c85518Srobert // -ArrayInitLoopExpr <-- we're here
513*12c85518Srobert // |-OpaqueValueExpr
514*12c85518Srobert // | `-DeclRefExpr <-- match this
515*12c85518Srobert // `-CXXConstructExpr
516*12c85518Srobert // `-ImplicitCastExpr
517*12c85518Srobert // `-ArraySubscriptExpr
518*12c85518Srobert // |-ImplicitCastExpr
519*12c85518Srobert // | `-OpaqueValueExpr
520*12c85518Srobert // | `-DeclRefExpr
521*12c85518Srobert // `-ArrayInitIndexExpr
522*12c85518Srobert //
523*12c85518Srobert // The resulting expression might look like the one below in an implicit
524*12c85518Srobert // copy/move ctor.
525*12c85518Srobert //
526*12c85518Srobert // ArrayInitLoopExpr <-- we're here
527*12c85518Srobert // |-OpaqueValueExpr
528*12c85518Srobert // | `-MemberExpr <-- match this
529*12c85518Srobert // | (`-CXXStaticCastExpr) <-- move ctor only
530*12c85518Srobert // | `-DeclRefExpr
531*12c85518Srobert // `-CXXConstructExpr
532*12c85518Srobert // `-ArraySubscriptExpr
533*12c85518Srobert // |-ImplicitCastExpr
534*12c85518Srobert // | `-OpaqueValueExpr
535*12c85518Srobert // | `-MemberExpr
536*12c85518Srobert // | `-DeclRefExpr
537*12c85518Srobert // `-ArrayInitIndexExpr
538*12c85518Srobert //
539*12c85518Srobert // The resulting expression for a multidimensional array.
540*12c85518Srobert // ArrayInitLoopExpr <-- we're here
541*12c85518Srobert // |-OpaqueValueExpr
542*12c85518Srobert // | `-DeclRefExpr <-- match this
543*12c85518Srobert // `-ArrayInitLoopExpr
544*12c85518Srobert // |-OpaqueValueExpr
545*12c85518Srobert // | `-ArraySubscriptExpr
546*12c85518Srobert // | |-ImplicitCastExpr
547*12c85518Srobert // | | `-OpaqueValueExpr
548*12c85518Srobert // | | `-DeclRefExpr
549*12c85518Srobert // | `-ArrayInitIndexExpr
550*12c85518Srobert // `-CXXConstructExpr <-- extract this
551*12c85518Srobert // ` ...
552*12c85518Srobert
553*12c85518Srobert const auto *OVESrc = AILE->getCommonExpr()->getSourceExpr();
554*12c85518Srobert
555*12c85518Srobert // HACK: There is no way we can put the index of the array element into the
556*12c85518Srobert // CFG unless we unroll the loop, so we manually select and bind the required
557*12c85518Srobert // parameter to the environment.
558*12c85518Srobert const auto *CE =
559*12c85518Srobert cast<CXXConstructExpr>(extractElementInitializerFromNestedAILE(AILE));
560*12c85518Srobert
561*12c85518Srobert SVal Base = UnknownVal();
562*12c85518Srobert if (const auto *ME = dyn_cast<MemberExpr>(OVESrc))
563*12c85518Srobert Base = State->getSVal(ME, LCtx);
564*12c85518Srobert else if (const auto *DRE = dyn_cast<DeclRefExpr>(OVESrc))
565*12c85518Srobert Base = State->getLValue(cast<VarDecl>(DRE->getDecl()), LCtx);
566*12c85518Srobert else
567*12c85518Srobert llvm_unreachable("ArrayInitLoopExpr contains unexpected source expression");
568*12c85518Srobert
569*12c85518Srobert SVal NthElem = State->getLValue(CE->getType(), Idx, Base);
570*12c85518Srobert
571*12c85518Srobert return State->BindExpr(CE->getArg(0), LCtx, NthElem);
572*12c85518Srobert }
573*12c85518Srobert
handleConstructor(const Expr * E,ExplodedNode * Pred,ExplodedNodeSet & destNodes)574ec727ea7Spatrick void ExprEngine::handleConstructor(const Expr *E,
575e5dd7070Spatrick ExplodedNode *Pred,
576e5dd7070Spatrick ExplodedNodeSet &destNodes) {
577ec727ea7Spatrick const auto *CE = dyn_cast<CXXConstructExpr>(E);
578ec727ea7Spatrick const auto *CIE = dyn_cast<CXXInheritedCtorInitExpr>(E);
579ec727ea7Spatrick assert(CE || CIE);
580ec727ea7Spatrick
581e5dd7070Spatrick const LocationContext *LCtx = Pred->getLocationContext();
582e5dd7070Spatrick ProgramStateRef State = Pred->getState();
583e5dd7070Spatrick
584e5dd7070Spatrick SVal Target = UnknownVal();
585e5dd7070Spatrick
586ec727ea7Spatrick if (CE) {
587*12c85518Srobert if (std::optional<SVal> ElidedTarget =
588e5dd7070Spatrick getObjectUnderConstruction(State, CE, LCtx)) {
589*12c85518Srobert // We've previously modeled an elidable constructor by pretending that
590*12c85518Srobert // it in fact constructs into the correct target. This constructor can
591ec727ea7Spatrick // therefore be skipped.
592e5dd7070Spatrick Target = *ElidedTarget;
593e5dd7070Spatrick StmtNodeBuilder Bldr(Pred, destNodes, *currBldrCtx);
594e5dd7070Spatrick State = finishObjectConstruction(State, CE, LCtx);
595e5dd7070Spatrick if (auto L = Target.getAs<Loc>())
596e5dd7070Spatrick State = State->BindExpr(CE, LCtx, State->getSVal(*L, CE->getType()));
597e5dd7070Spatrick Bldr.generateNode(CE, Pred, State);
598e5dd7070Spatrick return;
599e5dd7070Spatrick }
600ec727ea7Spatrick }
601e5dd7070Spatrick
602e5dd7070Spatrick EvalCallOptions CallOpts;
603e5dd7070Spatrick auto C = getCurrentCFGElement().getAs<CFGConstructor>();
604e5dd7070Spatrick assert(C || getCurrentCFGElement().getAs<CFGStmt>());
605e5dd7070Spatrick const ConstructionContext *CC = C ? C->getConstructionContext() : nullptr;
606e5dd7070Spatrick
607ec727ea7Spatrick const CXXConstructExpr::ConstructionKind CK =
608ec727ea7Spatrick CE ? CE->getConstructionKind() : CIE->getConstructionKind();
609ec727ea7Spatrick switch (CK) {
610e5dd7070Spatrick case CXXConstructExpr::CK_Complete: {
611ec727ea7Spatrick // Inherited constructors are always base class constructors.
612ec727ea7Spatrick assert(CE && !CIE && "A complete constructor is inherited?!");
613ec727ea7Spatrick
614*12c85518Srobert // If the ctor is part of an ArrayInitLoopExpr, we want to handle it
615*12c85518Srobert // differently.
616*12c85518Srobert auto *AILE = CC ? CC->getArrayInitLoop() : nullptr;
617*12c85518Srobert
618*12c85518Srobert unsigned Idx = 0;
619*12c85518Srobert if (CE->getType()->isArrayType() || AILE) {
620*12c85518Srobert
621*12c85518Srobert auto isZeroSizeArray = [&] {
622*12c85518Srobert uint64_t Size = 1;
623*12c85518Srobert
624*12c85518Srobert if (const auto *CAT = dyn_cast<ConstantArrayType>(CE->getType()))
625*12c85518Srobert Size = getContext().getConstantArrayElementCount(CAT);
626*12c85518Srobert else if (AILE)
627*12c85518Srobert Size = getContext().getArrayInitLoopExprElementCount(AILE);
628*12c85518Srobert
629*12c85518Srobert return Size == 0;
630*12c85518Srobert };
631*12c85518Srobert
632*12c85518Srobert // No element construction will happen in a 0 size array.
633*12c85518Srobert if (isZeroSizeArray()) {
634*12c85518Srobert StmtNodeBuilder Bldr(Pred, destNodes, *currBldrCtx);
635*12c85518Srobert static SimpleProgramPointTag T{"ExprEngine",
636*12c85518Srobert "Skipping 0 size array construction"};
637*12c85518Srobert Bldr.generateNode(CE, Pred, State, &T);
638*12c85518Srobert return;
639*12c85518Srobert }
640*12c85518Srobert
641*12c85518Srobert Idx = getIndexOfElementToConstruct(State, CE, LCtx).value_or(0u);
642*12c85518Srobert State = setIndexOfElementToConstruct(State, CE, LCtx, Idx + 1);
643*12c85518Srobert }
644*12c85518Srobert
645*12c85518Srobert if (AILE) {
646*12c85518Srobert // Only set this once even though we loop through it multiple times.
647*12c85518Srobert if (!getPendingInitLoop(State, CE, LCtx))
648*12c85518Srobert State = setPendingInitLoop(
649*12c85518Srobert State, CE, LCtx,
650*12c85518Srobert getContext().getArrayInitLoopExprElementCount(AILE));
651*12c85518Srobert
652*12c85518Srobert State = bindRequiredArrayElementToEnvironment(
653*12c85518Srobert State, AILE, LCtx, svalBuilder.makeArrayIndex(Idx));
654*12c85518Srobert }
655*12c85518Srobert
656ec727ea7Spatrick // The target region is found from construction context.
657*12c85518Srobert std::tie(State, Target) = handleConstructionContext(
658*12c85518Srobert CE, State, currBldrCtx, LCtx, CC, CallOpts, Idx);
659e5dd7070Spatrick break;
660e5dd7070Spatrick }
661e5dd7070Spatrick case CXXConstructExpr::CK_VirtualBase: {
662e5dd7070Spatrick // Make sure we are not calling virtual base class initializers twice.
663e5dd7070Spatrick // Only the most-derived object should initialize virtual base classes.
664e5dd7070Spatrick const auto *OuterCtor = dyn_cast_or_null<CXXConstructExpr>(
665e5dd7070Spatrick LCtx->getStackFrame()->getCallSite());
666e5dd7070Spatrick assert(
667e5dd7070Spatrick (!OuterCtor ||
668e5dd7070Spatrick OuterCtor->getConstructionKind() == CXXConstructExpr::CK_Complete ||
669e5dd7070Spatrick OuterCtor->getConstructionKind() == CXXConstructExpr::CK_Delegating) &&
670e5dd7070Spatrick ("This virtual base should have already been initialized by "
671e5dd7070Spatrick "the most derived class!"));
672e5dd7070Spatrick (void)OuterCtor;
673*12c85518Srobert [[fallthrough]];
674e5dd7070Spatrick }
675e5dd7070Spatrick case CXXConstructExpr::CK_NonVirtualBase:
676e5dd7070Spatrick // In C++17, classes with non-virtual bases may be aggregates, so they would
677e5dd7070Spatrick // be initialized as aggregates without a constructor call, so we may have
678e5dd7070Spatrick // a base class constructed directly into an initializer list without
679e5dd7070Spatrick // having the derived-class constructor call on the previous stack frame.
680e5dd7070Spatrick // Initializer lists may be nested into more initializer lists that
681e5dd7070Spatrick // correspond to surrounding aggregate initializations.
682e5dd7070Spatrick // FIXME: For now this code essentially bails out. We need to find the
683e5dd7070Spatrick // correct target region and set it.
684e5dd7070Spatrick // FIXME: Instead of relying on the ParentMap, we should have the
685e5dd7070Spatrick // trigger-statement (InitListExpr in this case) passed down from CFG or
686e5dd7070Spatrick // otherwise always available during construction.
687*12c85518Srobert if (isa_and_nonnull<InitListExpr>(LCtx->getParentMap().getParent(E))) {
688e5dd7070Spatrick MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
689ec727ea7Spatrick Target = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx));
690e5dd7070Spatrick CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
691e5dd7070Spatrick break;
692e5dd7070Spatrick }
693*12c85518Srobert [[fallthrough]];
694e5dd7070Spatrick case CXXConstructExpr::CK_Delegating: {
695e5dd7070Spatrick const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
696e5dd7070Spatrick Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
697e5dd7070Spatrick LCtx->getStackFrame());
698e5dd7070Spatrick SVal ThisVal = State->getSVal(ThisPtr);
699e5dd7070Spatrick
700ec727ea7Spatrick if (CK == CXXConstructExpr::CK_Delegating) {
701e5dd7070Spatrick Target = ThisVal;
702e5dd7070Spatrick } else {
703e5dd7070Spatrick // Cast to the base type.
704ec727ea7Spatrick bool IsVirtual = (CK == CXXConstructExpr::CK_VirtualBase);
705ec727ea7Spatrick SVal BaseVal =
706ec727ea7Spatrick getStoreManager().evalDerivedToBase(ThisVal, E->getType(), IsVirtual);
707e5dd7070Spatrick Target = BaseVal;
708e5dd7070Spatrick }
709e5dd7070Spatrick break;
710e5dd7070Spatrick }
711e5dd7070Spatrick }
712e5dd7070Spatrick
713e5dd7070Spatrick if (State != Pred->getState()) {
714e5dd7070Spatrick static SimpleProgramPointTag T("ExprEngine",
715e5dd7070Spatrick "Prepare for object construction");
716e5dd7070Spatrick ExplodedNodeSet DstPrepare;
717e5dd7070Spatrick StmtNodeBuilder BldrPrepare(Pred, DstPrepare, *currBldrCtx);
718ec727ea7Spatrick BldrPrepare.generateNode(E, Pred, State, &T, ProgramPoint::PreStmtKind);
719e5dd7070Spatrick assert(DstPrepare.size() <= 1);
720e5dd7070Spatrick if (DstPrepare.size() == 0)
721e5dd7070Spatrick return;
722e5dd7070Spatrick Pred = *BldrPrepare.begin();
723e5dd7070Spatrick }
724e5dd7070Spatrick
725ec727ea7Spatrick const MemRegion *TargetRegion = Target.getAsRegion();
726e5dd7070Spatrick CallEventManager &CEMgr = getStateManager().getCallEventManager();
727ec727ea7Spatrick CallEventRef<> Call =
728ec727ea7Spatrick CIE ? (CallEventRef<>)CEMgr.getCXXInheritedConstructorCall(
729ec727ea7Spatrick CIE, TargetRegion, State, LCtx)
730ec727ea7Spatrick : (CallEventRef<>)CEMgr.getCXXConstructorCall(
731ec727ea7Spatrick CE, TargetRegion, State, LCtx);
732e5dd7070Spatrick
733e5dd7070Spatrick ExplodedNodeSet DstPreVisit;
734ec727ea7Spatrick getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, E, *this);
735e5dd7070Spatrick
736e5dd7070Spatrick ExplodedNodeSet PreInitialized;
737ec727ea7Spatrick if (CE) {
738ec727ea7Spatrick // FIXME: Is it possible and/or useful to do this before PreStmt?
739e5dd7070Spatrick StmtNodeBuilder Bldr(DstPreVisit, PreInitialized, *currBldrCtx);
740e5dd7070Spatrick for (ExplodedNodeSet::iterator I = DstPreVisit.begin(),
741e5dd7070Spatrick E = DstPreVisit.end();
742e5dd7070Spatrick I != E; ++I) {
743e5dd7070Spatrick ProgramStateRef State = (*I)->getState();
744e5dd7070Spatrick if (CE->requiresZeroInitialization()) {
745e5dd7070Spatrick // FIXME: Once we properly handle constructors in new-expressions, we'll
746e5dd7070Spatrick // need to invalidate the region before setting a default value, to make
747e5dd7070Spatrick // sure there aren't any lingering bindings around. This probably needs
748e5dd7070Spatrick // to happen regardless of whether or not the object is zero-initialized
749e5dd7070Spatrick // to handle random fields of a placement-initialized object picking up
750e5dd7070Spatrick // old bindings. We might only want to do it when we need to, though.
751e5dd7070Spatrick // FIXME: This isn't actually correct for arrays -- we need to zero-
752e5dd7070Spatrick // initialize the entire array, not just the first element -- but our
753e5dd7070Spatrick // handling of arrays everywhere else is weak as well, so this shouldn't
754e5dd7070Spatrick // actually make things worse. Placement new makes this tricky as well,
755e5dd7070Spatrick // since it's then possible to be initializing one part of a multi-
756e5dd7070Spatrick // dimensional array.
757e5dd7070Spatrick State = State->bindDefaultZero(Target, LCtx);
758e5dd7070Spatrick }
759e5dd7070Spatrick
760e5dd7070Spatrick Bldr.generateNode(CE, *I, State, /*tag=*/nullptr,
761e5dd7070Spatrick ProgramPoint::PreStmtKind);
762e5dd7070Spatrick }
763ec727ea7Spatrick } else {
764ec727ea7Spatrick PreInitialized = DstPreVisit;
765e5dd7070Spatrick }
766e5dd7070Spatrick
767e5dd7070Spatrick ExplodedNodeSet DstPreCall;
768e5dd7070Spatrick getCheckerManager().runCheckersForPreCall(DstPreCall, PreInitialized,
769e5dd7070Spatrick *Call, *this);
770e5dd7070Spatrick
771e5dd7070Spatrick ExplodedNodeSet DstEvaluated;
772e5dd7070Spatrick
773ec727ea7Spatrick if (CE && CE->getConstructor()->isTrivial() &&
774e5dd7070Spatrick CE->getConstructor()->isCopyOrMoveConstructor() &&
775e5dd7070Spatrick !CallOpts.IsArrayCtorOrDtor) {
776a9ac8606Spatrick StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx);
777e5dd7070Spatrick // FIXME: Handle other kinds of trivial constructors as well.
778e5dd7070Spatrick for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
779e5dd7070Spatrick I != E; ++I)
780e5dd7070Spatrick performTrivialCopy(Bldr, *I, *Call);
781e5dd7070Spatrick
782e5dd7070Spatrick } else {
783e5dd7070Spatrick for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
784e5dd7070Spatrick I != E; ++I)
785ec727ea7Spatrick getCheckerManager().runCheckersForEvalCall(DstEvaluated, *I, *Call, *this,
786ec727ea7Spatrick CallOpts);
787e5dd7070Spatrick }
788e5dd7070Spatrick
789e5dd7070Spatrick // If the CFG was constructed without elements for temporary destructors
790e5dd7070Spatrick // and the just-called constructor created a temporary object then
791e5dd7070Spatrick // stop exploration if the temporary object has a noreturn constructor.
792e5dd7070Spatrick // This can lose coverage because the destructor, if it were present
793e5dd7070Spatrick // in the CFG, would be called at the end of the full expression or
794e5dd7070Spatrick // later (for life-time extended temporaries) -- but avoids infeasible
795e5dd7070Spatrick // paths when no-return temporary destructors are used for assertions.
796a9ac8606Spatrick ExplodedNodeSet DstEvaluatedPostProcessed;
797a9ac8606Spatrick StmtNodeBuilder Bldr(DstEvaluated, DstEvaluatedPostProcessed, *currBldrCtx);
798e5dd7070Spatrick const AnalysisDeclContext *ADC = LCtx->getAnalysisDeclContext();
799e5dd7070Spatrick if (!ADC->getCFGBuildOptions().AddTemporaryDtors) {
800ec727ea7Spatrick if (llvm::isa_and_nonnull<CXXTempObjectRegion>(TargetRegion) &&
801ec727ea7Spatrick cast<CXXConstructorDecl>(Call->getDecl())
802ec727ea7Spatrick ->getParent()
803ec727ea7Spatrick ->isAnyDestructorNoReturn()) {
804e5dd7070Spatrick
805e5dd7070Spatrick // If we've inlined the constructor, then DstEvaluated would be empty.
806e5dd7070Spatrick // In this case we still want a sink, which could be implemented
807e5dd7070Spatrick // in processCallExit. But we don't have that implemented at the moment,
808e5dd7070Spatrick // so if you hit this assertion, see if you can avoid inlining
809e5dd7070Spatrick // the respective constructor when analyzer-config cfg-temporary-dtors
810e5dd7070Spatrick // is set to false.
811e5dd7070Spatrick // Otherwise there's nothing wrong with inlining such constructor.
812e5dd7070Spatrick assert(!DstEvaluated.empty() &&
813e5dd7070Spatrick "We should not have inlined this constructor!");
814e5dd7070Spatrick
815e5dd7070Spatrick for (ExplodedNode *N : DstEvaluated) {
816ec727ea7Spatrick Bldr.generateSink(E, N, N->getState());
817e5dd7070Spatrick }
818e5dd7070Spatrick
819e5dd7070Spatrick // There is no need to run the PostCall and PostStmt checker
820e5dd7070Spatrick // callbacks because we just generated sinks on all nodes in th
821e5dd7070Spatrick // frontier.
822e5dd7070Spatrick return;
823e5dd7070Spatrick }
824e5dd7070Spatrick }
825e5dd7070Spatrick
826e5dd7070Spatrick ExplodedNodeSet DstPostArgumentCleanup;
827a9ac8606Spatrick for (ExplodedNode *I : DstEvaluatedPostProcessed)
828e5dd7070Spatrick finishArgumentConstruction(DstPostArgumentCleanup, I, *Call);
829e5dd7070Spatrick
830e5dd7070Spatrick // If there were other constructors called for object-type arguments
831e5dd7070Spatrick // of this constructor, clean them up.
832e5dd7070Spatrick ExplodedNodeSet DstPostCall;
833e5dd7070Spatrick getCheckerManager().runCheckersForPostCall(DstPostCall,
834e5dd7070Spatrick DstPostArgumentCleanup,
835e5dd7070Spatrick *Call, *this);
836ec727ea7Spatrick getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, E, *this);
837ec727ea7Spatrick }
838ec727ea7Spatrick
VisitCXXConstructExpr(const CXXConstructExpr * CE,ExplodedNode * Pred,ExplodedNodeSet & Dst)839ec727ea7Spatrick void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE,
840ec727ea7Spatrick ExplodedNode *Pred,
841ec727ea7Spatrick ExplodedNodeSet &Dst) {
842ec727ea7Spatrick handleConstructor(CE, Pred, Dst);
843ec727ea7Spatrick }
844ec727ea7Spatrick
VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr * CE,ExplodedNode * Pred,ExplodedNodeSet & Dst)845ec727ea7Spatrick void ExprEngine::VisitCXXInheritedCtorInitExpr(
846ec727ea7Spatrick const CXXInheritedCtorInitExpr *CE, ExplodedNode *Pred,
847ec727ea7Spatrick ExplodedNodeSet &Dst) {
848ec727ea7Spatrick handleConstructor(CE, Pred, Dst);
849e5dd7070Spatrick }
850e5dd7070Spatrick
VisitCXXDestructor(QualType ObjectType,const MemRegion * Dest,const Stmt * S,bool IsBaseDtor,ExplodedNode * Pred,ExplodedNodeSet & Dst,EvalCallOptions & CallOpts)851e5dd7070Spatrick void ExprEngine::VisitCXXDestructor(QualType ObjectType,
852e5dd7070Spatrick const MemRegion *Dest,
853e5dd7070Spatrick const Stmt *S,
854e5dd7070Spatrick bool IsBaseDtor,
855e5dd7070Spatrick ExplodedNode *Pred,
856e5dd7070Spatrick ExplodedNodeSet &Dst,
857e5dd7070Spatrick EvalCallOptions &CallOpts) {
858e5dd7070Spatrick assert(S && "A destructor without a trigger!");
859e5dd7070Spatrick const LocationContext *LCtx = Pred->getLocationContext();
860e5dd7070Spatrick ProgramStateRef State = Pred->getState();
861e5dd7070Spatrick
862e5dd7070Spatrick const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl();
863e5dd7070Spatrick assert(RecordDecl && "Only CXXRecordDecls should have destructors");
864e5dd7070Spatrick const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
865e5dd7070Spatrick // FIXME: There should always be a Decl, otherwise the destructor call
866e5dd7070Spatrick // shouldn't have been added to the CFG in the first place.
867e5dd7070Spatrick if (!DtorDecl) {
868e5dd7070Spatrick // Skip the invalid destructor. We cannot simply return because
869e5dd7070Spatrick // it would interrupt the analysis instead.
870e5dd7070Spatrick static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor");
871e5dd7070Spatrick // FIXME: PostImplicitCall with a null decl may crash elsewhere anyway.
872e5dd7070Spatrick PostImplicitCall PP(/*Decl=*/nullptr, S->getEndLoc(), LCtx, &T);
873e5dd7070Spatrick NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
874e5dd7070Spatrick Bldr.generateNode(PP, Pred->getState(), Pred);
875e5dd7070Spatrick return;
876e5dd7070Spatrick }
877e5dd7070Spatrick
878e5dd7070Spatrick if (!Dest) {
879e5dd7070Spatrick // We're trying to destroy something that is not a region. This may happen
880e5dd7070Spatrick // for a variety of reasons (unknown target region, concrete integer instead
881e5dd7070Spatrick // of target region, etc.). The current code makes an attempt to recover.
882e5dd7070Spatrick // FIXME: We probably don't really need to recover when we're dealing
883e5dd7070Spatrick // with concrete integers specifically.
884e5dd7070Spatrick CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
885e5dd7070Spatrick if (const Expr *E = dyn_cast_or_null<Expr>(S)) {
886e5dd7070Spatrick Dest = MRMgr.getCXXTempObjectRegion(E, Pred->getLocationContext());
887e5dd7070Spatrick } else {
888e5dd7070Spatrick static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor");
889e5dd7070Spatrick NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
890e5dd7070Spatrick Bldr.generateSink(Pred->getLocation().withTag(&T),
891e5dd7070Spatrick Pred->getState(), Pred);
892e5dd7070Spatrick return;
893e5dd7070Spatrick }
894e5dd7070Spatrick }
895e5dd7070Spatrick
896e5dd7070Spatrick CallEventManager &CEMgr = getStateManager().getCallEventManager();
897e5dd7070Spatrick CallEventRef<CXXDestructorCall> Call =
898e5dd7070Spatrick CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx);
899e5dd7070Spatrick
900e5dd7070Spatrick PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
901e5dd7070Spatrick Call->getSourceRange().getBegin(),
902e5dd7070Spatrick "Error evaluating destructor");
903e5dd7070Spatrick
904e5dd7070Spatrick ExplodedNodeSet DstPreCall;
905e5dd7070Spatrick getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
906e5dd7070Spatrick *Call, *this);
907e5dd7070Spatrick
908e5dd7070Spatrick ExplodedNodeSet DstInvalidated;
909e5dd7070Spatrick StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
910e5dd7070Spatrick for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
911e5dd7070Spatrick I != E; ++I)
912e5dd7070Spatrick defaultEvalCall(Bldr, *I, *Call, CallOpts);
913e5dd7070Spatrick
914e5dd7070Spatrick getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
915e5dd7070Spatrick *Call, *this);
916e5dd7070Spatrick }
917e5dd7070Spatrick
VisitCXXNewAllocatorCall(const CXXNewExpr * CNE,ExplodedNode * Pred,ExplodedNodeSet & Dst)918e5dd7070Spatrick void ExprEngine::VisitCXXNewAllocatorCall(const CXXNewExpr *CNE,
919e5dd7070Spatrick ExplodedNode *Pred,
920e5dd7070Spatrick ExplodedNodeSet &Dst) {
921e5dd7070Spatrick ProgramStateRef State = Pred->getState();
922e5dd7070Spatrick const LocationContext *LCtx = Pred->getLocationContext();
923e5dd7070Spatrick PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
924e5dd7070Spatrick CNE->getBeginLoc(),
925e5dd7070Spatrick "Error evaluating New Allocator Call");
926e5dd7070Spatrick CallEventManager &CEMgr = getStateManager().getCallEventManager();
927e5dd7070Spatrick CallEventRef<CXXAllocatorCall> Call =
928e5dd7070Spatrick CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
929e5dd7070Spatrick
930e5dd7070Spatrick ExplodedNodeSet DstPreCall;
931e5dd7070Spatrick getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
932e5dd7070Spatrick *Call, *this);
933e5dd7070Spatrick
934e5dd7070Spatrick ExplodedNodeSet DstPostCall;
935e5dd7070Spatrick StmtNodeBuilder CallBldr(DstPreCall, DstPostCall, *currBldrCtx);
936ec727ea7Spatrick for (ExplodedNode *I : DstPreCall) {
937e5dd7070Spatrick // FIXME: Provide evalCall for checkers?
938e5dd7070Spatrick defaultEvalCall(CallBldr, I, *Call);
939e5dd7070Spatrick }
940e5dd7070Spatrick // If the call is inlined, DstPostCall will be empty and we bail out now.
941e5dd7070Spatrick
942e5dd7070Spatrick // Store return value of operator new() for future use, until the actual
943e5dd7070Spatrick // CXXNewExpr gets processed.
944e5dd7070Spatrick ExplodedNodeSet DstPostValue;
945e5dd7070Spatrick StmtNodeBuilder ValueBldr(DstPostCall, DstPostValue, *currBldrCtx);
946ec727ea7Spatrick for (ExplodedNode *I : DstPostCall) {
947e5dd7070Spatrick // FIXME: Because CNE serves as the "call site" for the allocator (due to
948e5dd7070Spatrick // lack of a better expression in the AST), the conjured return value symbol
949e5dd7070Spatrick // is going to be of the same type (C++ object pointer type). Technically
950e5dd7070Spatrick // this is not correct because the operator new's prototype always says that
951e5dd7070Spatrick // it returns a 'void *'. So we should change the type of the symbol,
952e5dd7070Spatrick // and then evaluate the cast over the symbolic pointer from 'void *' to
953e5dd7070Spatrick // the object pointer type. But without changing the symbol's type it
954e5dd7070Spatrick // is breaking too much to evaluate the no-op symbolic cast over it, so we
955e5dd7070Spatrick // skip it for now.
956e5dd7070Spatrick ProgramStateRef State = I->getState();
957e5dd7070Spatrick SVal RetVal = State->getSVal(CNE, LCtx);
958*12c85518Srobert // [basic.stc.dynamic.allocation] (on the return value of an allocation
959*12c85518Srobert // function):
960*12c85518Srobert // "The order, contiguity, and initial value of storage allocated by
961*12c85518Srobert // successive calls to an allocation function are unspecified."
962*12c85518Srobert State = State->bindDefaultInitial(RetVal, UndefinedVal{}, LCtx);
963e5dd7070Spatrick
964e5dd7070Spatrick // If this allocation function is not declared as non-throwing, failures
965e5dd7070Spatrick // /must/ be signalled by exceptions, and thus the return value will never
966e5dd7070Spatrick // be NULL. -fno-exceptions does not influence this semantics.
967e5dd7070Spatrick // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
968e5dd7070Spatrick // where new can return NULL. If we end up supporting that option, we can
969e5dd7070Spatrick // consider adding a check for it here.
970e5dd7070Spatrick // C++11 [basic.stc.dynamic.allocation]p3.
971e5dd7070Spatrick if (const FunctionDecl *FD = CNE->getOperatorNew()) {
972e5dd7070Spatrick QualType Ty = FD->getType();
973e5dd7070Spatrick if (const auto *ProtoType = Ty->getAs<FunctionProtoType>())
974e5dd7070Spatrick if (!ProtoType->isNothrow())
975e5dd7070Spatrick State = State->assume(RetVal.castAs<DefinedOrUnknownSVal>(), true);
976e5dd7070Spatrick }
977e5dd7070Spatrick
978e5dd7070Spatrick ValueBldr.generateNode(
979e5dd7070Spatrick CNE, I, addObjectUnderConstruction(State, CNE, LCtx, RetVal));
980e5dd7070Spatrick }
981e5dd7070Spatrick
982e5dd7070Spatrick ExplodedNodeSet DstPostPostCallCallback;
983e5dd7070Spatrick getCheckerManager().runCheckersForPostCall(DstPostPostCallCallback,
984e5dd7070Spatrick DstPostValue, *Call, *this);
985ec727ea7Spatrick for (ExplodedNode *I : DstPostPostCallCallback) {
986ec727ea7Spatrick getCheckerManager().runCheckersForNewAllocator(*Call, Dst, I, *this);
987e5dd7070Spatrick }
988e5dd7070Spatrick }
989e5dd7070Spatrick
VisitCXXNewExpr(const CXXNewExpr * CNE,ExplodedNode * Pred,ExplodedNodeSet & Dst)990e5dd7070Spatrick void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
991e5dd7070Spatrick ExplodedNodeSet &Dst) {
992e5dd7070Spatrick // FIXME: Much of this should eventually migrate to CXXAllocatorCall.
993e5dd7070Spatrick // Also, we need to decide how allocators actually work -- they're not
994e5dd7070Spatrick // really part of the CXXNewExpr because they happen BEFORE the
995e5dd7070Spatrick // CXXConstructExpr subexpression. See PR12014 for some discussion.
996e5dd7070Spatrick
997e5dd7070Spatrick unsigned blockCount = currBldrCtx->blockCount();
998e5dd7070Spatrick const LocationContext *LCtx = Pred->getLocationContext();
999e5dd7070Spatrick SVal symVal = UnknownVal();
1000e5dd7070Spatrick FunctionDecl *FD = CNE->getOperatorNew();
1001e5dd7070Spatrick
1002e5dd7070Spatrick bool IsStandardGlobalOpNewFunction =
1003e5dd7070Spatrick FD->isReplaceableGlobalAllocationFunction();
1004e5dd7070Spatrick
1005e5dd7070Spatrick ProgramStateRef State = Pred->getState();
1006e5dd7070Spatrick
1007e5dd7070Spatrick // Retrieve the stored operator new() return value.
1008e5dd7070Spatrick if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
1009e5dd7070Spatrick symVal = *getObjectUnderConstruction(State, CNE, LCtx);
1010e5dd7070Spatrick State = finishObjectConstruction(State, CNE, LCtx);
1011e5dd7070Spatrick }
1012e5dd7070Spatrick
1013e5dd7070Spatrick // We assume all standard global 'operator new' functions allocate memory in
1014e5dd7070Spatrick // heap. We realize this is an approximation that might not correctly model
1015e5dd7070Spatrick // a custom global allocator.
1016e5dd7070Spatrick if (symVal.isUnknown()) {
1017e5dd7070Spatrick if (IsStandardGlobalOpNewFunction)
1018e5dd7070Spatrick symVal = svalBuilder.getConjuredHeapSymbolVal(CNE, LCtx, blockCount);
1019e5dd7070Spatrick else
1020e5dd7070Spatrick symVal = svalBuilder.conjureSymbolVal(nullptr, CNE, LCtx, CNE->getType(),
1021e5dd7070Spatrick blockCount);
1022e5dd7070Spatrick }
1023e5dd7070Spatrick
1024e5dd7070Spatrick CallEventManager &CEMgr = getStateManager().getCallEventManager();
1025e5dd7070Spatrick CallEventRef<CXXAllocatorCall> Call =
1026e5dd7070Spatrick CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
1027e5dd7070Spatrick
1028e5dd7070Spatrick if (!AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
1029e5dd7070Spatrick // Invalidate placement args.
1030e5dd7070Spatrick // FIXME: Once we figure out how we want allocators to work,
1031e5dd7070Spatrick // we should be using the usual pre-/(default-)eval-/post-call checkers
1032e5dd7070Spatrick // here.
1033e5dd7070Spatrick State = Call->invalidateRegions(blockCount);
1034e5dd7070Spatrick if (!State)
1035e5dd7070Spatrick return;
1036e5dd7070Spatrick
1037e5dd7070Spatrick // If this allocation function is not declared as non-throwing, failures
1038e5dd7070Spatrick // /must/ be signalled by exceptions, and thus the return value will never
1039e5dd7070Spatrick // be NULL. -fno-exceptions does not influence this semantics.
1040e5dd7070Spatrick // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
1041e5dd7070Spatrick // where new can return NULL. If we end up supporting that option, we can
1042e5dd7070Spatrick // consider adding a check for it here.
1043e5dd7070Spatrick // C++11 [basic.stc.dynamic.allocation]p3.
1044*12c85518Srobert if (const auto *ProtoType = FD->getType()->getAs<FunctionProtoType>())
1045e5dd7070Spatrick if (!ProtoType->isNothrow())
1046e5dd7070Spatrick if (auto dSymVal = symVal.getAs<DefinedOrUnknownSVal>())
1047e5dd7070Spatrick State = State->assume(*dSymVal, true);
1048e5dd7070Spatrick }
1049e5dd7070Spatrick
1050e5dd7070Spatrick StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1051e5dd7070Spatrick
1052e5dd7070Spatrick SVal Result = symVal;
1053e5dd7070Spatrick
1054e5dd7070Spatrick if (CNE->isArray()) {
1055*12c85518Srobert
1056e5dd7070Spatrick if (const auto *NewReg = cast_or_null<SubRegion>(symVal.getAsRegion())) {
1057*12c85518Srobert // If each element is initialized by their default constructor, the field
1058*12c85518Srobert // values are properly placed inside the required region, however if an
1059*12c85518Srobert // initializer list is used, this doesn't happen automatically.
1060*12c85518Srobert auto *Init = CNE->getInitializer();
1061*12c85518Srobert bool isInitList = isa_and_nonnull<InitListExpr>(Init);
1062*12c85518Srobert
1063*12c85518Srobert QualType ObjTy =
1064*12c85518Srobert isInitList ? Init->getType() : CNE->getType()->getPointeeType();
1065e5dd7070Spatrick const ElementRegion *EleReg =
1066*12c85518Srobert MRMgr.getElementRegion(ObjTy, svalBuilder.makeArrayIndex(0), NewReg,
1067*12c85518Srobert svalBuilder.getContext());
1068e5dd7070Spatrick Result = loc::MemRegionVal(EleReg);
1069*12c85518Srobert
1070*12c85518Srobert // If the array is list initialized, we bind the initializer list to the
1071*12c85518Srobert // memory region here, otherwise we would lose it.
1072*12c85518Srobert if (isInitList) {
1073*12c85518Srobert Bldr.takeNodes(Pred);
1074*12c85518Srobert Pred = Bldr.generateNode(CNE, Pred, State);
1075*12c85518Srobert
1076*12c85518Srobert SVal V = State->getSVal(Init, LCtx);
1077*12c85518Srobert ExplodedNodeSet evaluated;
1078*12c85518Srobert evalBind(evaluated, CNE, Pred, Result, V, true);
1079*12c85518Srobert
1080*12c85518Srobert Bldr.takeNodes(Pred);
1081*12c85518Srobert Bldr.addNodes(evaluated);
1082*12c85518Srobert
1083*12c85518Srobert Pred = *evaluated.begin();
1084*12c85518Srobert State = Pred->getState();
1085e5dd7070Spatrick }
1086*12c85518Srobert }
1087*12c85518Srobert
1088e5dd7070Spatrick State = State->BindExpr(CNE, Pred->getLocationContext(), Result);
1089e5dd7070Spatrick Bldr.generateNode(CNE, Pred, State);
1090e5dd7070Spatrick return;
1091e5dd7070Spatrick }
1092e5dd7070Spatrick
1093e5dd7070Spatrick // FIXME: Once we have proper support for CXXConstructExprs inside
1094e5dd7070Spatrick // CXXNewExpr, we need to make sure that the constructed object is not
1095e5dd7070Spatrick // immediately invalidated here. (The placement call should happen before
1096e5dd7070Spatrick // the constructor call anyway.)
1097*12c85518Srobert if (FD->isReservedGlobalPlacementOperator()) {
1098e5dd7070Spatrick // Non-array placement new should always return the placement location.
1099e5dd7070Spatrick SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx);
1100e5dd7070Spatrick Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(),
1101e5dd7070Spatrick CNE->getPlacementArg(0)->getType());
1102e5dd7070Spatrick }
1103e5dd7070Spatrick
1104e5dd7070Spatrick // Bind the address of the object, then check to see if we cached out.
1105e5dd7070Spatrick State = State->BindExpr(CNE, LCtx, Result);
1106e5dd7070Spatrick ExplodedNode *NewN = Bldr.generateNode(CNE, Pred, State);
1107e5dd7070Spatrick if (!NewN)
1108e5dd7070Spatrick return;
1109e5dd7070Spatrick
1110e5dd7070Spatrick // If the type is not a record, we won't have a CXXConstructExpr as an
1111e5dd7070Spatrick // initializer. Copy the value over.
1112e5dd7070Spatrick if (const Expr *Init = CNE->getInitializer()) {
1113e5dd7070Spatrick if (!isa<CXXConstructExpr>(Init)) {
1114e5dd7070Spatrick assert(Bldr.getResults().size() == 1);
1115e5dd7070Spatrick Bldr.takeNodes(NewN);
1116e5dd7070Spatrick evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, LCtx),
1117e5dd7070Spatrick /*FirstInit=*/IsStandardGlobalOpNewFunction);
1118e5dd7070Spatrick }
1119e5dd7070Spatrick }
1120e5dd7070Spatrick }
1121e5dd7070Spatrick
VisitCXXDeleteExpr(const CXXDeleteExpr * CDE,ExplodedNode * Pred,ExplodedNodeSet & Dst)1122e5dd7070Spatrick void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE,
1123e5dd7070Spatrick ExplodedNode *Pred, ExplodedNodeSet &Dst) {
1124ec727ea7Spatrick
1125ec727ea7Spatrick CallEventManager &CEMgr = getStateManager().getCallEventManager();
1126ec727ea7Spatrick CallEventRef<CXXDeallocatorCall> Call = CEMgr.getCXXDeallocatorCall(
1127ec727ea7Spatrick CDE, Pred->getState(), Pred->getLocationContext());
1128ec727ea7Spatrick
1129ec727ea7Spatrick ExplodedNodeSet DstPreCall;
1130ec727ea7Spatrick getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, *Call, *this);
1131*12c85518Srobert ExplodedNodeSet DstPostCall;
1132ec727ea7Spatrick
1133*12c85518Srobert if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
1134*12c85518Srobert StmtNodeBuilder Bldr(DstPreCall, DstPostCall, *currBldrCtx);
1135*12c85518Srobert for (ExplodedNode *I : DstPreCall) {
1136*12c85518Srobert defaultEvalCall(Bldr, I, *Call);
1137*12c85518Srobert }
1138*12c85518Srobert } else {
1139*12c85518Srobert DstPostCall = DstPreCall;
1140*12c85518Srobert }
1141*12c85518Srobert getCheckerManager().runCheckersForPostCall(Dst, DstPostCall, *Call, *this);
1142e5dd7070Spatrick }
1143e5dd7070Spatrick
VisitCXXCatchStmt(const CXXCatchStmt * CS,ExplodedNode * Pred,ExplodedNodeSet & Dst)1144ec727ea7Spatrick void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred,
1145e5dd7070Spatrick ExplodedNodeSet &Dst) {
1146e5dd7070Spatrick const VarDecl *VD = CS->getExceptionDecl();
1147e5dd7070Spatrick if (!VD) {
1148e5dd7070Spatrick Dst.Add(Pred);
1149e5dd7070Spatrick return;
1150e5dd7070Spatrick }
1151e5dd7070Spatrick
1152e5dd7070Spatrick const LocationContext *LCtx = Pred->getLocationContext();
1153e5dd7070Spatrick SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(),
1154e5dd7070Spatrick currBldrCtx->blockCount());
1155e5dd7070Spatrick ProgramStateRef state = Pred->getState();
1156e5dd7070Spatrick state = state->bindLoc(state->getLValue(VD, LCtx), V, LCtx);
1157e5dd7070Spatrick
1158e5dd7070Spatrick StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1159e5dd7070Spatrick Bldr.generateNode(CS, Pred, state);
1160e5dd7070Spatrick }
1161e5dd7070Spatrick
VisitCXXThisExpr(const CXXThisExpr * TE,ExplodedNode * Pred,ExplodedNodeSet & Dst)1162e5dd7070Spatrick void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
1163e5dd7070Spatrick ExplodedNodeSet &Dst) {
1164e5dd7070Spatrick StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1165e5dd7070Spatrick
1166e5dd7070Spatrick // Get the this object region from StoreManager.
1167e5dd7070Spatrick const LocationContext *LCtx = Pred->getLocationContext();
1168e5dd7070Spatrick const MemRegion *R =
1169e5dd7070Spatrick svalBuilder.getRegionManager().getCXXThisRegion(
1170e5dd7070Spatrick getContext().getCanonicalType(TE->getType()),
1171e5dd7070Spatrick LCtx);
1172e5dd7070Spatrick
1173e5dd7070Spatrick ProgramStateRef state = Pred->getState();
1174e5dd7070Spatrick SVal V = state->getSVal(loc::MemRegionVal(R));
1175e5dd7070Spatrick Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V));
1176e5dd7070Spatrick }
1177e5dd7070Spatrick
VisitLambdaExpr(const LambdaExpr * LE,ExplodedNode * Pred,ExplodedNodeSet & Dst)1178e5dd7070Spatrick void ExprEngine::VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred,
1179e5dd7070Spatrick ExplodedNodeSet &Dst) {
1180e5dd7070Spatrick const LocationContext *LocCtxt = Pred->getLocationContext();
1181e5dd7070Spatrick
1182e5dd7070Spatrick // Get the region of the lambda itself.
1183e5dd7070Spatrick const MemRegion *R = svalBuilder.getRegionManager().getCXXTempObjectRegion(
1184e5dd7070Spatrick LE, LocCtxt);
1185e5dd7070Spatrick SVal V = loc::MemRegionVal(R);
1186e5dd7070Spatrick
1187e5dd7070Spatrick ProgramStateRef State = Pred->getState();
1188e5dd7070Spatrick
1189e5dd7070Spatrick // If we created a new MemRegion for the lambda, we should explicitly bind
1190e5dd7070Spatrick // the captures.
1191*12c85518Srobert unsigned Idx = 0;
1192e5dd7070Spatrick CXXRecordDecl::field_iterator CurField = LE->getLambdaClass()->field_begin();
1193e5dd7070Spatrick for (LambdaExpr::const_capture_init_iterator i = LE->capture_init_begin(),
1194e5dd7070Spatrick e = LE->capture_init_end();
1195*12c85518Srobert i != e; ++i, ++CurField, ++Idx) {
1196e5dd7070Spatrick FieldDecl *FieldForCapture = *CurField;
1197e5dd7070Spatrick SVal FieldLoc = State->getLValue(FieldForCapture, V);
1198e5dd7070Spatrick
1199e5dd7070Spatrick SVal InitVal;
1200e5dd7070Spatrick if (!FieldForCapture->hasCapturedVLAType()) {
1201*12c85518Srobert const Expr *InitExpr = *i;
1202*12c85518Srobert
1203e5dd7070Spatrick assert(InitExpr && "Capture missing initialization expression");
1204*12c85518Srobert
1205*12c85518Srobert // Capturing a 0 length array is a no-op, so we ignore it to get a more
1206*12c85518Srobert // accurate analysis. If it's not ignored, it would set the default
1207*12c85518Srobert // binding of the lambda to 'Unknown', which can lead to falsely detecting
1208*12c85518Srobert // 'Uninitialized' values as 'Unknown' and not reporting a warning.
1209*12c85518Srobert const auto FTy = FieldForCapture->getType();
1210*12c85518Srobert if (FTy->isConstantArrayType() &&
1211*12c85518Srobert getContext().getConstantArrayElementCount(
1212*12c85518Srobert getContext().getAsConstantArrayType(FTy)) == 0)
1213*12c85518Srobert continue;
1214*12c85518Srobert
1215*12c85518Srobert // With C++17 copy elision the InitExpr can be anything, so instead of
1216*12c85518Srobert // pattern matching all cases, we simple check if the current field is
1217*12c85518Srobert // under construction or not, regardless what it's InitExpr is.
1218*12c85518Srobert if (const auto OUC =
1219*12c85518Srobert getObjectUnderConstruction(State, {LE, Idx}, LocCtxt)) {
1220*12c85518Srobert InitVal = State->getSVal(OUC->getAsRegion());
1221*12c85518Srobert
1222*12c85518Srobert State = finishObjectConstruction(State, {LE, Idx}, LocCtxt);
1223*12c85518Srobert } else
1224e5dd7070Spatrick InitVal = State->getSVal(InitExpr, LocCtxt);
1225*12c85518Srobert
1226e5dd7070Spatrick } else {
1227*12c85518Srobert
1228*12c85518Srobert assert(!getObjectUnderConstruction(State, {LE, Idx}, LocCtxt) &&
1229*12c85518Srobert "VLA capture by value is a compile time error!");
1230*12c85518Srobert
1231e5dd7070Spatrick // The field stores the length of a captured variable-length array.
1232e5dd7070Spatrick // These captures don't have initialization expressions; instead we
1233e5dd7070Spatrick // get the length from the VLAType size expression.
1234e5dd7070Spatrick Expr *SizeExpr = FieldForCapture->getCapturedVLAType()->getSizeExpr();
1235e5dd7070Spatrick InitVal = State->getSVal(SizeExpr, LocCtxt);
1236e5dd7070Spatrick }
1237e5dd7070Spatrick
1238e5dd7070Spatrick State = State->bindLoc(FieldLoc, InitVal, LocCtxt);
1239e5dd7070Spatrick }
1240e5dd7070Spatrick
1241e5dd7070Spatrick // Decay the Loc into an RValue, because there might be a
1242e5dd7070Spatrick // MaterializeTemporaryExpr node above this one which expects the bound value
1243e5dd7070Spatrick // to be an RValue.
1244e5dd7070Spatrick SVal LambdaRVal = State->getSVal(R);
1245e5dd7070Spatrick
1246e5dd7070Spatrick ExplodedNodeSet Tmp;
1247e5dd7070Spatrick StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
1248e5dd7070Spatrick // FIXME: is this the right program point kind?
1249e5dd7070Spatrick Bldr.generateNode(LE, Pred,
1250e5dd7070Spatrick State->BindExpr(LE, LocCtxt, LambdaRVal),
1251e5dd7070Spatrick nullptr, ProgramPoint::PostLValueKind);
1252e5dd7070Spatrick
1253e5dd7070Spatrick // FIXME: Move all post/pre visits to ::Visit().
1254e5dd7070Spatrick getCheckerManager().runCheckersForPostStmt(Dst, Tmp, LE, *this);
1255e5dd7070Spatrick }
1256