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