clang 22.0.0git
ExprEngineCXX.cpp
Go to the documentation of this file.
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
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/ParentMap.h"
17#include "clang/AST/StmtCXX.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
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>(&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>(Call).getCXXThisVal();
63 ThisRD = cast<CXXMethodDecl>(Call.getDecl())->getParent();
64 AlwaysReturnsLValue = true;
65 }
66
67 const LocationContext *LCtx = Pred->getLocationContext();
68 const Expr *CallExpr = Call.getOriginExpr();
69
71 Bldr.takeNodes(Pred);
72
73 assert(ThisRD);
74 SVal V = Call.getArgSVal(0);
75 const Expr *VExpr = Call.getArgExpr(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(*L);
81 else
82 assert(V.isUnknownOrUndef());
83
85 evalLocation(Tmp, CallExpr, VExpr, Pred, Pred->getState(), V,
86 /*isLoad=*/true);
87 for (ExplodedNode *N : Tmp)
88 evalBind(Dst, CallExpr, N, ThisVal, V, !AlwaysReturnsLValue);
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(PS, State, 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(Ty)) {
107 while (AT) {
108 Ty = AT->getElementType();
109 AT = dyn_cast<ArrayType>(AT->getElementType());
110 }
111 LValue = State->getLValue(Ty, SVB.makeArrayIndex(Idx), 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.
123 const Expr *E, ProgramStateRef State, const NodeBuilderContext *BldrCtx,
124 const LocationContext *LCtx, const ConstructionContext *CC,
125 EvalCallOptions &CallOpts, unsigned Idx) {
126
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()) {
136 const auto *DSCC = cast<VariableConstructionContext>(CC);
137 const auto *DS = DSCC->getDeclStmt();
138 const auto *Var = cast<VarDecl>(DS->getSingleDecl());
139 QualType Ty = Var->getType();
140 return makeElementRegion(State, State->getLValue(Var, LCtx), Ty,
141 CallOpts.IsArrayCtorOrDtor, Idx);
142 }
145 const auto *ICC = cast<ConstructorInitializerConstructionContext>(CC);
146 const auto *Init = ICC->getCXXCtorInitializer();
147 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
148 Loc ThisPtr = SVB.getCXXThis(CurCtor, LCtx->getStackFrame());
149 SVal ThisVal = State->getSVal(ThisPtr);
150 if (Init->isBaseInitializer()) {
151 const auto *ThisReg = cast<SubRegion>(ThisVal.getAsRegion());
152 const CXXRecordDecl *BaseClass =
153 Init->getBaseClass()->getAsCXXRecordDecl();
154 const auto *BaseReg =
155 MRMgr.getCXXBaseObjectRegion(BaseClass, ThisReg,
156 Init->isBaseVirtual());
157 return SVB.makeLoc(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(Init->getIndirectMember(), ThisVal);
167 } else {
168 Field = Init->getMember();
169 FieldVal = State->getLValue(Init->getMember(), ThisVal);
170 }
171
172 QualType Ty = Field->getType();
173 return makeElementRegion(State, FieldVal, Ty, CallOpts.IsArrayCtorOrDtor,
174 Idx);
175 }
177 if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
178 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
179 const auto *NE = NECC->getCXXNewExpr();
180 SVal V = *getObjectUnderConstruction(State, NE, LCtx);
181 if (const SubRegion *MR =
182 dyn_cast_or_null<SubRegion>(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(Ty, svalBuilder.makeArrayIndex(Idx),
191 MR, 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 }
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>(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);
227 cast<Expr>(SFC->getCallSite()), State, &CallerBldrCtx, CallerLCtx,
228 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>(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(ReturnTy);
247 return SVB.conjureSymbolVal(&TopLevelSymRegionTag, getCFGElementRef(),
248 SFC, RegionTy, currBldrCtx->blockCount());
249 }
250 llvm_unreachable("Unhandled return value construction context!");
251 }
253 assert(AMgr.getAnalyzerOptions().ShouldElideConstructors);
254 const auto *TCC = cast<ElidedTemporaryObjectConstructionContext>(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
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.
274 return V;
275
276 // Copy elision failed. Revert the changes and proceed as if we have
277 // a simple temporary.
278 CallOpts = PreElideCallOpts;
280 [[fallthrough]];
281 }
283 const auto *TCC = cast<TemporaryObjectConstructionContext>(CC);
284 const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr();
285
286 CallOpts.IsTemporaryCtorOrDtor = true;
287 if (MTE) {
288 if (const ValueDecl *VD = MTE->getExtendingDecl()) {
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?
298 }
299
300 if (SD == SD_Static || SD == SD_Thread)
301 return loc::MemRegionVal(
303
304 return loc::MemRegionVal(
305 MRMgr.getCXXLifetimeExtendedObjectRegion(E, VD, LCtx));
306 }
307 assert(MTE->getStorageDuration() == SD_FullExpression);
308 }
309
310 return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx));
311 }
313 CallOpts.IsTemporaryCtorOrDtor = true;
314
315 const auto *LCC = cast<LambdaCaptureConstructionContext>(CC);
316
318 MRMgr.getCXXTempObjectRegion(LCC->getInitializer(), LCtx));
319
320 const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E);
321 if (getIndexOfElementToConstruct(State, CE, LCtx)) {
322 CallOpts.IsArrayCtorOrDtor = true;
323 Base = State->getLValue(E->getType(), svalBuilder.makeArrayIndex(Idx),
324 Base);
325 }
326
327 return Base;
328 }
330 // Arguments are technically temporaries.
331 CallOpts.IsTemporaryCtorOrDtor = true;
332
333 const auto *ACC = cast<ArgumentConstructionContext>(CC);
334 const Expr *E = ACC->getCallLikeExpr();
335 unsigned Idx = ACC->getIndex();
336
338 auto getArgLoc = [&](CallEventRef<> Caller) -> std::optional<SVal> {
339 const LocationContext *FutureSFC =
340 Caller->getCalleeStackFrame(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(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 *Caller->getAdjustedParameterIndex(Idx), 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>(E)) {
367 CallEventRef<> Caller =
368 CEMgr.getSimpleCall(CE, State, LCtx, 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>(E)) {
374 // Don't bother figuring out the target region for the future
375 // constructor because we won't need it.
377 CCE, /*Target=*/nullptr, State, LCtx, 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>(E)) {
383 CallEventRef<> Caller =
384 CEMgr.getObjCMethodCall(ME, State, LCtx, 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.
397 return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx));
398}
399
401 SVal V, const Expr *E, ProgramStateRef State, const LocationContext *LCtx,
402 const ConstructionContext *CC, const EvalCallOptions &CallOpts) {
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()) {
415 const auto *DSCC = cast<VariableConstructionContext>(CC);
416 return addObjectUnderConstruction(State, DSCC->getDeclStmt(), LCtx, V);
417 }
420 const auto *ICC = cast<ConstructorInitializerConstructionContext>(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, Init, LCtx, V);
427 }
429 return State;
430 }
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>(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
451 cast<Expr>(SFC->getCallSite()), State, CallerLCtx,
452 RTC->getConstructionContext(), CallOpts);
453 }
455 assert(AMgr.getAnalyzerOptions().ShouldElideConstructors);
457 const auto *TCC = cast<ElidedTemporaryObjectConstructionContext>(CC);
459 V, TCC->getConstructorAfterElision(), State, LCtx,
460 TCC->getConstructionContextAfterElision(), CallOpts);
461
462 // Remember that we've elided the constructor.
463 State = addObjectUnderConstruction(
464 State, TCC->getConstructorAfterElision(), LCtx, V);
465
466 // Remember that we've elided the destructor.
467 if (const auto *BTE = TCC->getCXXBindTemporaryExpr())
468 State = elideDestructor(State, BTE, LCtx);
469
470 // Instead of materialization, shamelessly return
471 // the final object destination.
472 if (const auto *MTE = TCC->getMaterializedTemporaryExpr())
473 State = addObjectUnderConstruction(State, MTE, 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 }
482 const auto *TCC = cast<TemporaryObjectConstructionContext>(CC);
483 if (const auto *BTE = TCC->getCXXBindTemporaryExpr())
484 State = addObjectUnderConstruction(State, BTE, LCtx, V);
485
486 if (const auto *MTE = TCC->getMaterializedTemporaryExpr())
487 State = addObjectUnderConstruction(State, MTE, LCtx, V);
488
489 return State;
490 }
492 const auto *LCC = cast<LambdaCaptureConstructionContext>(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>(V.getAsRegion()))
497 V = loc::MemRegionVal(EL->getSuperRegion());
498
499 return addObjectUnderConstruction(
500 State, {LCC->getLambdaExpr(), LCC->getIndex()}, LCtx, V);
501 }
503 const auto *ACC = cast<ArgumentConstructionContext>(CC);
504 if (const auto *BTE = ACC->getCXXBindTemporaryExpr())
505 State = addObjectUnderConstruction(State, BTE, LCtx, V);
506
507 return addObjectUnderConstruction(
508 State, {ACC->getCallLikeExpr(), ACC->getIndex()}, LCtx, V);
509 }
510 }
511 llvm_unreachable("Unhandled construction context!");
512}
513
514static ProgramStateRef
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>(extractElementInitializerFromNestedAILE(AILE));
528
529 const auto *SourceArrayRegion =
530 cast<SubRegion>(State->getSVal(SourceArray, LCtx).getAsRegion());
532 MRMgr.getElementRegion(Ctor->getType(), Idx, SourceArrayRegion, Ctx);
533
534 return State->BindExpr(Ctor->getArg(0), LCtx,
536}
537
538void ExprEngine::handleConstructor(const Expr *E,
539 ExplodedNode *Pred,
540 ExplodedNodeSet &destNodes) {
541 const auto *CE = dyn_cast<CXXConstructExpr>(E);
542 const auto *CIE = dyn_cast<CXXInheritedCtorInitExpr>(E);
543 assert(CE || CIE);
544
545 const LocationContext *LCtx = Pred->getLocationContext();
546 ProgramStateRef State = Pred->getState();
547
549
550 if (CE) {
551 if (std::optional<SVal> ElidedTarget =
552 getObjectUnderConstruction(State, CE, 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, CE, LCtx);
559 if (auto L = Target.getAs<Loc>())
560 State = State->BindExpr(CE, LCtx, State->getSVal(*L, CE->getType()));
561 Bldr.generateNode(CE, Pred, State);
562 return;
563 }
564 }
565
566 EvalCallOptions CallOpts;
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) {
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()))
590 else if (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, CE, LCtx).value_or(0u);
606 State = setIndexOfElementToConstruct(State, CE, LCtx, Idx + 1);
607 }
608
609 if (AILE) {
610 // Only set this once even though we loop through it multiple times.
611 if (!getPendingInitLoop(State, CE, LCtx))
612 State = setPendingInitLoop(
613 State, CE, LCtx,
614 getContext().getArrayInitLoopExprElementCount(AILE));
615
617 State, AILE, LCtx, svalBuilder.makeArrayIndex(Idx));
618 }
619
620 // The target region is found from construction context.
621 std::tie(State, Target) = handleConstructionContext(
622 CE, State, currBldrCtx, LCtx, CC, CallOpts, Idx);
623 break;
624 }
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 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 }
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))) {
656 break;
657 }
658 [[fallthrough]];
660 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
661 Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
662 LCtx->getStackFrame());
663 SVal ThisVal = State->getSVal(ThisPtr);
664
666 Target = ThisVal;
667 } else {
668 // Cast to the base type.
669 bool IsVirtual = (CK == CXXConstructionKind::VirtualBase);
670 SVal BaseVal =
671 getStoreManager().evalDerivedToBase(ThisVal, 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();
694 CIE, TargetRegion, State, LCtx, getCFGElementRef())
696 CE, TargetRegion, State, LCtx, 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(Target, LCtx);
725 }
726
727 Bldr.generateNode(CE, N, State, /*tag=*/nullptr,
729 }
730 } else {
731 PreInitialized = DstPreVisit;
732 }
733
734 ExplodedNodeSet DstPreCall;
735 getCheckerManager().runCheckersForPreCall(DstPreCall, PreInitialized,
736 *Call, *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, N, *Call);
747
748 } else {
749 for (ExplodedNode *N : DstPreCall)
750 getCheckerManager().runCheckersForEvalCall(DstEvaluated, N, *Call, *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();
765 if (llvm::isa_and_nonnull<CXXTempObjectRegion,
766 CXXLifetimeExtendedObjectRegion>(TargetRegion) &&
767 cast<CXXConstructorDecl>(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(DstPostArgumentCleanup, I, *Call);
795
796 // If there were other constructors called for object-type arguments
797 // of this constructor, clean them up.
798 ExplodedNodeSet DstPostCall;
800 DstPostArgumentCleanup,
801 *Call, *this);
802 getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, E, *this);
803}
804
806 ExplodedNode *Pred,
807 ExplodedNodeSet &Dst) {
808 handleConstructor(CE, Pred, Dst);
809}
810
812 const CXXInheritedCtorInitExpr *CE, ExplodedNode *Pred,
813 ExplodedNodeSet &Dst) {
814 handleConstructor(CE, Pred, Dst);
815}
816
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, 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.
852 if (const Expr *E = dyn_cast_or_null<Expr>(S)) {
853 Dest = MRMgr.getCXXTempObjectRegion(E, Pred->getLocationContext());
854 } else {
855 static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor");
856 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
857 Bldr.generateSink(Pred->getLocation().withTag(&T),
858 Pred->getState(), Pred);
859 return;
860 }
861 }
862
865 DtorDecl, S, Dest, IsBaseDtor, State, LCtx, getCFGElementRef());
866
867 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
868 Call->getSourceRange().getBegin(),
869 "Error evaluating destructor");
870
871 ExplodedNodeSet DstPreCall;
872 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
873 *Call, *this);
874
875 ExplodedNodeSet DstInvalidated;
876 StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
877 for (ExplodedNode *N : DstPreCall)
878 defaultEvalCall(Bldr, N, *Call, CallOpts);
879
880 getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
881 *Call, *this);
882}
883
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");
894 CEMgr.getCXXAllocatorCall(CNE, State, LCtx, getCFGElementRef());
895
896 ExplodedNodeSet DstPreCall;
897 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
898 *Call, *this);
899
900 ExplodedNodeSet DstPostCall;
901 StmtNodeBuilder CallBldr(DstPreCall, DstPostCall, *currBldrCtx);
902 for (ExplodedNode *I : DstPreCall) {
903 // FIXME: Provide evalCall for checkers?
904 defaultEvalCall(CallBldr, I, *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(RetVal, 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(RetVal.castAs<DefinedOrUnknownSVal>(), true);
942 }
943
944 ValueBldr.generateNode(
945 CNE, I, addObjectUnderConstruction(State, CNE, LCtx, RetVal));
946 }
947
948 ExplodedNodeSet DstPostPostCallCallback;
949 getCheckerManager().runCheckersForPostCall(DstPostPostCallCallback,
950 DstPostValue, *Call, *this);
951 for (ExplodedNode *I : DstPostPostCallCallback) {
953 }
954}
955
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 =
970
971 ProgramStateRef State = Pred->getState();
972
973 // Retrieve the stored operator new() return value.
974 if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
975 symVal = *getObjectUnderConstruction(State, CNE, LCtx);
976 State = finishObjectConstruction(State, CNE, 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(getCFGElementRef(), LCtx,
985 CNE->getType(), blockCount);
986 else
987 symVal = svalBuilder.conjureSymbolVal(
988 /*symbolTag=*/nullptr, getCFGElementRef(), LCtx, blockCount);
989 }
990
993 CEMgr.getCXXAllocatorCall(CNE, State, LCtx, 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);
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(*dSymVal, 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>(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>(Init);
1030
1031 QualType ObjTy =
1032 isInitList ? Init->getType() : CNE->getType()->getPointeeType();
1033 const ElementRegion *EleReg =
1034 MRMgr.getElementRegion(ObjTy, svalBuilder.makeArrayIndex(0), NewReg,
1035 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(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(Pred);
1049 Bldr.addNodes(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.)
1066 // Non-array placement new should always return the placement location.
1067 SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx);
1068 Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(),
1069 CNE->getPlacementArg(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>(Init)) {
1082 assert(Bldr.getResults().size() == 1);
1083 Bldr.takeNodes(NewN);
1084 evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, LCtx),
1085 /*FirstInit=*/IsStandardGlobalOpNewFunction);
1086 }
1087 }
1088}
1089
1091 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
1092
1095 CDE, Pred->getState(), Pred->getLocationContext(), getCFGElementRef());
1096
1097 ExplodedNodeSet DstPreCall;
1098 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, *Call, *this);
1099 ExplodedNodeSet DstPostCall;
1100
1101 if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
1102 StmtNodeBuilder Bldr(DstPreCall, DstPostCall, *currBldrCtx);
1103 for (ExplodedNode *I : DstPreCall) {
1104 defaultEvalCall(Bldr, I, *Call);
1105 }
1106 } else {
1107 DstPostCall = DstPreCall;
1108 }
1109 getCheckerManager().runCheckersForPostCall(Dst, DstPostCall, *Call, *this);
1110}
1111
1113 ExplodedNodeSet &Dst) {
1114 const VarDecl *VD = CS->getExceptionDecl();
1115 if (!VD) {
1116 Dst.Add(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(state->getLValue(VD, LCtx), V, LCtx);
1125
1126 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1127 Bldr.generateNode(CS, Pred, state);
1128}
1129
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 getContext().getCanonicalType(TE->getType()),
1139 LCtx);
1140
1141 ProgramStateRef state = Pred->getState();
1142 SVal V = state->getSVal(loc::MemRegionVal(R));
1143 Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V));
1144}
1145
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);
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),
1215
1216 // FIXME: Move all post/pre visits to ::Visit().
1217 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, LE, *this);
1218}
1219
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()->IgnoreParens(), N, EvalSet);
1231 }
1232 }
1233
1234 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
1235}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3597
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
static ProgramStateRef bindRequiredArrayElementToEnvironment(ProgramStateRef State, const ArrayInitLoopExpr *AILE, const LocationContext *LCtx, NonLoc Idx)
llvm::MachO::Target Target
Definition: MachO.h:51
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
AnalysisDeclContext contains the context data for the function, method or block under analysis.
CFG::BuildOptions & getCFGBuildOptions()
Represents a loop initializing the elements of an array.
Definition: Expr.h:5904
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition: Expr.h:5919
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: TypeBase.h:3738
Attr - This represents one attribute.
Definition: Attr.h:44
Represents an attribute applied to a statement.
Definition: Stmt.h:2203
ArrayRef< const Attr * > getAttrs() const
Definition: Stmt.h:2235
Represents a function call that returns a C++ object by value.
Definition: CFG.h:186
Represents C++ constructor call.
Definition: CFG.h:157
std::optional< T > getAs() const
Convert to the specified CFGElement type, returning std::nullopt if this CFGElement is not of the des...
Definition: CFG.h:109
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:28
VarDecl * getExceptionDecl() const
Definition: StmtCXX.h:49
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1549
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition: ExprCXX.h:2620
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2869
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition: ExprCXX.h:1753
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2129
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2349
bool isArray() const
Definition: ExprCXX.h:2458
Expr * getPlacementArg(unsigned I)
Definition: ExprCXX.h:2497
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2600
FunctionDecl * getOperatorNew() const
Definition: ExprCXX.h:2453
Expr * getInitializer()
The initializer of this new-expression.
Definition: ExprCXX.h:2527
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1186
Represents the this expression in C++.
Definition: ExprCXX.h:1155
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2879
ConstructionContext's subclasses describe different ways of constructing an object in C++.
virtual const ArrayInitLoopExpr * getArrayInitLoop() const
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2109
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
This represents one expression.
Definition: Expr.h:112
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3069
QualType getType() const
Definition: Expr.h:144
Represents a function declaration or definition.
Definition: Decl.h:1999
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.h:2593
bool isReservedGlobalPlacementOperator() const
Determines whether this operator new or delete is one of the reserved global placement operators: voi...
Definition: Decl.cpp:3391
Represents a prototype with parameter type info, e.g.
Definition: TypeBase.h:5282
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1970
It wraps the AnalysisDeclContext to represent both the call stack with the help of StackFrameContext ...
const Decl * getDecl() const
const ParentMap & getParentMap() const
LLVM_ATTRIBUTE_RETURNS_NONNULL AnalysisDeclContext * getAnalysisDeclContext() const
const LocationContext * getParent() const
It might return null.
const StackFrameContext * getStackFrame() const
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition: ExprCXX.h:4914
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition: ExprCXX.h:4939
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition: ExprCXX.h:4931
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition: ExprCXX.h:4964
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition: Expr.h:1230
Stmt * getParent(Stmt *) const
Definition: ParentMap.cpp:142
Represents a program point just after an implicit call event.
Definition: ProgramPoint.h:607
If a crash happens while one of these objects are live, the message is printed out along with the spe...
ProgramPoint withTag(const ProgramPointTag *tag) const
Create a new ProgramPoint object that is the same as the original except for using the specified tag ...
Definition: ProgramPoint.h:135
A (possibly-)qualified type.
Definition: TypeBase.h:937
Represents a struct/union/class.
Definition: Decl.h:4309
It represents a stack frame of the call stack (based on CallEvent).
const Stmt * getCallSite() const
const CFGBlock * getCallSiteBlock() const
Stmt - This represents one statement.
Definition: Stmt.h:85
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.h:26
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:752
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:711
QualType getType() const
Definition: Decl.h:722
Represents a variable declaration or definition.
Definition: Decl.h:925
AnalyzerOptions & getAnalyzerOptions() override
Represents a call to a C++ constructor.
Definition: CallEvent.h:986
Manages the lifetime of CallEvent objects.
Definition: CallEvent.h:1363
CallEventRef< CXXDestructorCall > getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger, const MemRegion *Target, bool IsBase, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.h:1456
CallEventRef< CXXDeallocatorCall > getCXXDeallocatorCall(const CXXDeleteExpr *E, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.h:1472
CallEventRef getSimpleCall(const CallExpr *E, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.cpp:1426
CallEventRef< ObjCMethodCall > getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.h:1434
CallEventRef< CXXAllocatorCall > getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.h:1465
CallEventRef< CXXConstructorCall > getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.h:1441
CallEventRef< CXXInheritedConstructorCall > getCXXInheritedConstructorCall(const CXXInheritedCtorInitExpr *E, const MemRegion *Target, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.h:1448
Represents an abstract call to a function or method along a particular path.
Definition: CallEvent.h:153
static bool isVariadic(const Decl *D)
Returns true if the given decl is known to be variadic.
Definition: CallEvent.cpp:379
void runCheckersForPreCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &Call, ExprEngine &Eng)
Run checkers for pre-visiting obj-c messages.
void runCheckersForEvalCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &CE, ExprEngine &Eng, const EvalCallOptions &CallOpts)
Run checkers for evaluating a call.
void runCheckersForPostStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng, bool wasInlined=false)
Run checkers for post-visiting Stmts.
void runCheckersForNewAllocator(const CXXAllocatorCall &Call, ExplodedNodeSet &Dst, ExplodedNode *Pred, ExprEngine &Eng, bool wasInlined=false)
Run checkers between C++ operator new and constructor calls.
void runCheckersForPreStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng)
Run checkers for pre-visiting Stmts.
void runCheckersForPostCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &Call, ExprEngine &Eng, bool wasInlined=false)
Run checkers for post-visiting obj-c messages.
ElementRegion is used to represent both array elements and casts.
Definition: MemRegion.h:1227
void Add(ExplodedNode *N)
const ProgramStateRef & getState() const
ProgramPoint getLocation() const
getLocation - Returns the edge associated with the given node.
const LocationContext * getLocationContext() const
ProgramStateManager & getStateManager()
Definition: ExprEngine.h:421
std::pair< ProgramStateRef, SVal > handleConstructionContext(const Expr *E, ProgramStateRef State, const NodeBuilderContext *BldrCtx, const LocationContext *LCtx, const ConstructionContext *CC, EvalCallOptions &CallOpts, unsigned Idx=0)
A convenient wrapper around computeObjectUnderConstruction and updateObjectsUnderConstruction.
Definition: ExprEngine.h:763
void VisitCXXDestructor(QualType ObjectType, const MemRegion *Dest, const Stmt *S, bool IsBaseDtor, ExplodedNode *Pred, ExplodedNodeSet &Dst, EvalCallOptions &Options)
const CoreEngine & getCoreEngine() const
Definition: ExprEngine.h:452
void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitLambdaExpr - Transfer function logic for LambdaExprs.
static std::optional< SVal > getObjectUnderConstruction(ProgramStateRef State, const ConstructionContextItem &Item, const LocationContext *LC)
By looking at a certain item that may be potentially part of an object's ConstructionContext,...
Definition: ExprEngine.cpp:604
CFGElement getCurrentCFGElement()
Return the CFG element corresponding to the worklist element that is currently being processed by Exp...
Definition: ExprEngine.h:712
SVal computeObjectUnderConstruction(const Expr *E, ProgramStateRef State, const NodeBuilderContext *BldrCtx, const LocationContext *LCtx, const ConstructionContext *CC, EvalCallOptions &CallOpts, unsigned Idx=0)
Find location of the object that is being constructed by a given constructor.
static std::optional< unsigned > getIndexOfElementToConstruct(ProgramStateRef State, const CXXConstructExpr *E, const LocationContext *LCtx)
Retreives which element is being constructed in a non-POD type array.
Definition: ExprEngine.cpp:514
ASTContext & getContext() const
getContext - Return the ASTContext associated with this analysis.
Definition: ExprEngine.h:196
StoreManager & getStoreManager()
Definition: ExprEngine.h:424
void VisitCXXNewAllocatorCall(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Create a C++ temporary object for an rvalue.
ConstCFGElementRef getCFGElementRef() const
Definition: ExprEngine.h:232
CheckerManager & getCheckerManager() const
Definition: ExprEngine.h:205
ProgramStateRef bindReturnValue(const CallEvent &Call, const LocationContext *LCtx, ProgramStateRef State)
Create a new state in which the call return value is binded to the call origin expression.
void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Visit - Transfer function logic for all statements.
void defaultEvalCall(NodeBuilder &B, ExplodedNode *Pred, const CallEvent &Call, const EvalCallOptions &CallOpts={})
Default implementation of call evaluation.
void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, ExplodedNodeSet &Dst)
SValBuilder & getSValBuilder()
Definition: ExprEngine.h:209
ProgramStateRef updateObjectsUnderConstruction(SVal V, const Expr *E, ProgramStateRef State, const LocationContext *LCtx, const ConstructionContext *CC, const EvalCallOptions &CallOpts)
Update the program state with all the path-sensitive information that's necessary to perform construc...
void VisitAttributedStmt(const AttributedStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitAttributedStmt - Transfer function logic for AttributedStmt.
static std::optional< unsigned > getPendingInitLoop(ProgramStateRef State, const CXXConstructExpr *E, const LocationContext *LCtx)
Retreives the size of the array in the pending ArrayInitLoopExpr.
Definition: ExprEngine.cpp:487
const CXXThisRegion * getCXXThisRegion(QualType thisPointerTy, const LocationContext *LC)
getCXXThisRegion - Retrieve the [artificial] region associated with the parameter 'this'.
Definition: MemRegion.cpp:1357
const ElementRegion * getElementRegion(QualType elementType, NonLoc Idx, const SubRegion *superRegion, const ASTContext &Ctx)
getElementRegion - Retrieve the memory region associated with the associated element type,...
Definition: MemRegion.cpp:1217
const CXXLifetimeExtendedObjectRegion * getCXXLifetimeExtendedObjectRegion(Expr const *Ex, ValueDecl const *VD, LocationContext const *LC)
Create a CXXLifetimeExtendedObjectRegion for temporaries which are lifetime-extended by local referen...
Definition: MemRegion.cpp:1292
const CXXTempObjectRegion * getCXXTempObjectRegion(Expr const *Ex, LocationContext const *LC)
Definition: MemRegion.cpp:1284
const CXXBaseObjectRegion * getCXXBaseObjectRegion(const CXXRecordDecl *BaseClass, const SubRegion *Super, bool IsVirtual)
Create a CXXBaseObjectRegion with the given base class for region Super.
Definition: MemRegion.cpp:1331
const CXXLifetimeExtendedObjectRegion * getCXXStaticLifetimeExtendedObjectRegion(const Expr *Ex, ValueDecl const *VD)
Create a CXXLifetimeExtendedObjectRegion for temporaries which are lifetime-extended by static refere...
Definition: MemRegion.cpp:1301
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:98
unsigned blockCount() const
Returns the number of times the current basic block has been visited on the exploded graph path.
Definition: CoreEngine.h:224
This is the simplest builder which generates nodes in the ExplodedGraph.
Definition: CoreEngine.h:240
ExplodedNode * generateNode(const ProgramPoint &PP, ProgramStateRef State, ExplodedNode *Pred)
Generates a node in the ExplodedGraph.
Definition: CoreEngine.h:293
void takeNodes(const ExplodedNodeSet &S)
Definition: CoreEngine.h:335
ExplodedNode * generateSink(const ProgramPoint &PP, ProgramStateRef State, ExplodedNode *Pred)
Generates a sink in the ExplodedGraph.
Definition: CoreEngine.h:306
void addNodes(const ExplodedNodeSet &S)
Definition: CoreEngine.h:341
const ExplodedNodeSet & getResults()
Definition: CoreEngine.h:312
CallEventManager & getCallEventManager()
Definition: ProgramState.h:572
DefinedSVal getConjuredHeapSymbolVal(ConstCFGElementRef elem, const LocationContext *LCtx, QualType type, unsigned Count)
Conjure a symbol representing heap allocated memory region.
MemRegionManager & getRegionManager()
Definition: SValBuilder.h:168
NonLoc makeArrayIndex(uint64_t idx)
Definition: SValBuilder.h:271
ASTContext & getContext()
Definition: SValBuilder.h:149
loc::MemRegionVal makeLoc(SymbolRef sym)
Definition: SValBuilder.h:363
SVal evalCast(SVal V, QualType CastTy, QualType OriginalTy)
Cast a given SVal to another SVal using given QualType's.
loc::MemRegionVal getCXXThis(const CXXMethodDecl *D, const StackFrameContext *SFC)
Return a memory region for the 'this' object reference.
DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag, ConstCFGElementRef elem, const LocationContext *LCtx, unsigned count)
Create a new symbol with a unique 'name'.
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition: SVals.h:56
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
Definition: SVals.h:87
const MemRegion * getAsRegion() const
Definition: SVals.cpp:119
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition: SVals.h:83
bool isUnknown() const
Definition: SVals.h:105
This builder class is useful for generating nodes that resulted from visiting a statement.
Definition: CoreEngine.h:384
ExplodedNode * generateNode(const Stmt *S, ExplodedNode *Pred, ProgramStateRef St, const ProgramPointTag *tag=nullptr, ProgramPoint::Kind K=ProgramPoint::PostStmtKind)
Definition: CoreEngine.h:413
SVal evalDerivedToBase(SVal Derived, const CastExpr *Cast)
Evaluates a chain of derived-to-base casts through the path specified in Cast.
Definition: Store.cpp:254
SubRegion - A region that subsets another larger region.
Definition: MemRegion.h:474
TypedValueRegion - An abstract class representing regions having a typed value.
Definition: MemRegion.h:563
Definition: ARM.cpp:1134
The JSON file list parser is used to communicate input to InstallAPI.
CXXConstructionKind
Definition: ExprCXX.h:1541
StorageDuration
The storage duration for an object (per C++ [basic.stc]).
Definition: Specifiers.h:339
@ SD_Thread
Thread storage duration.
Definition: Specifiers.h:342
@ SD_Static
Static storage duration.
Definition: Specifiers.h:343
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition: Specifiers.h:340
@ Result
The result type of a method or function.
const FunctionProtoType * T
Expr * extractElementInitializerFromNestedAILE(const ArrayInitLoopExpr *AILE)
Definition: CFG.cpp:1448
unsigned long uint64_t
Hints for figuring out of a call should be inlined during evalCall().
Definition: ExprEngine.h:97
bool IsTemporaryLifetimeExtendedViaAggregate
This call is a constructor for a temporary that is lifetime-extended by binding it to a reference-typ...
Definition: ExprEngine.h:112
bool IsTemporaryCtorOrDtor
This call is a constructor or a destructor of a temporary value.
Definition: ExprEngine.h:107
bool IsArrayCtorOrDtor
This call is a constructor or a destructor for a single element within an array, a part of array cons...
Definition: ExprEngine.h:104
bool IsElidableCtorThatHasNotBeenElided
This call is a pre-C++17 elidable constructor that we failed to elide because we failed to compute th...
Definition: ExprEngine.h:119
bool IsCtorOrDtorWithImproperlyModeledTargetRegion
This call is a constructor or a destructor for which we do not currently compute the this-region corr...
Definition: ExprEngine.h:100