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