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

Provided by KDAB

Privacy Policy
Improve your Profiling and Debugging skills
Find out more

source code of clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp