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 
114 const MemRegion *
115 ExprEngine::getRegionForConstructedObject(const CXXConstructExpr *CE,
116                                           ExplodedNode *Pred,
117                                           const ConstructionContext *CC,
118                                           EvalCallOptions &CallOpts) {
119   const LocationContext *LCtx = Pred->getLocationContext();
120   ProgramStateRef State = Pred->getState();
121   MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
122 
123   // See if we're constructing an existing region by looking at the
124   // current construction context.
125   if (CC) {
126     switch (CC->getKind()) {
127     case ConstructionContext::SimpleVariableKind: {
128       const auto *DSCC = cast<SimpleVariableConstructionContext>(CC);
129       const auto *DS = DSCC->getDeclStmt();
130       const auto *Var = cast<VarDecl>(DS->getSingleDecl());
131       SVal LValue = State->getLValue(Var, LCtx);
132       QualType Ty = Var->getType();
133       LValue =
134           makeZeroElementRegion(State, LValue, Ty, CallOpts.IsArrayCtorOrDtor);
135       return LValue.getAsRegion();
136     }
137     case ConstructionContext::ConstructorInitializerKind: {
138       const auto *ICC = cast<ConstructorInitializerConstructionContext>(CC);
139       const auto *Init = ICC->getCXXCtorInitializer();
140       assert(Init->isAnyMemberInitializer());
141       const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
142       Loc ThisPtr =
143       getSValBuilder().getCXXThis(CurCtor, LCtx->getCurrentStackFrame());
144       SVal ThisVal = State->getSVal(ThisPtr);
145 
146       const ValueDecl *Field;
147       SVal FieldVal;
148       if (Init->isIndirectMemberInitializer()) {
149         Field = Init->getIndirectMember();
150         FieldVal = State->getLValue(Init->getIndirectMember(), ThisVal);
151       } else {
152         Field = Init->getMember();
153         FieldVal = State->getLValue(Init->getMember(), ThisVal);
154       }
155 
156       QualType Ty = Field->getType();
157       FieldVal = makeZeroElementRegion(State, FieldVal, Ty,
158                                        CallOpts.IsArrayCtorOrDtor);
159       return FieldVal.getAsRegion();
160     }
161     case ConstructionContext::NewAllocatedObjectKind: {
162       if (AMgr.getAnalyzerOptions().mayInlineCXXAllocator()) {
163         const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
164         const auto *NE = NECC->getCXXNewExpr();
165         // TODO: Detect when the allocator returns a null pointer.
166         // Constructor shall not be called in this case.
167         if (const SubRegion *MR = dyn_cast_or_null<SubRegion>(
168                 getCXXNewAllocatorValue(State, NE, LCtx).getAsRegion())) {
169           if (NE->isArray()) {
170             // TODO: In fact, we need to call the constructor for every
171             // allocated element, not just the first one!
172             CallOpts.IsArrayCtorOrDtor = true;
173             return getStoreManager().GetElementZeroRegion(
174                 MR, NE->getType()->getPointeeType());
175           }
176           return MR;
177         }
178       }
179       break;
180     }
181     case ConstructionContext::TemporaryObjectKind: {
182       const auto *TOCC = cast<TemporaryObjectConstructionContext>(CC);
183       // See if we're lifetime-extended via our field. If so, take a note.
184       // Because automatic destructors aren't quite working in this case.
185       if (const auto *MTE = TOCC->getMaterializedTemporaryExpr()) {
186         if (const ValueDecl *VD = MTE->getExtendingDecl()) {
187           assert(VD->getType()->isReferenceType());
188           if (VD->getType()->getPointeeType().getCanonicalType() !=
189               MTE->GetTemporaryExpr()->getType().getCanonicalType()) {
190             CallOpts.IsTemporaryLifetimeExtendedViaSubobject = true;
191           }
192         }
193       }
194       // TODO: Support temporaries lifetime-extended via static references.
195       // They'd need a getCXXStaticTempObjectRegion().
196       CallOpts.IsTemporaryCtorOrDtor = true;
197       return MRMgr.getCXXTempObjectRegion(CE, LCtx);
198     }
199     case ConstructionContext::ReturnedValueKind: {
200       // The temporary is to be managed by the parent stack frame.
201       // So build it in the parent stack frame if we're not in the
202       // top frame of the analysis.
203       // TODO: What exactly happens when we are? Does the temporary object live
204       // long enough in the region store in this case? Would checkers think
205       // that this object immediately goes out of scope?
206       const LocationContext *TempLCtx = LCtx;
207       if (const LocationContext *CallerLCtx =
208               LCtx->getCurrentStackFrame()->getParent()) {
209         TempLCtx = CallerLCtx;
210       }
211       CallOpts.IsTemporaryCtorOrDtor = true;
212       return MRMgr.getCXXTempObjectRegion(CE, TempLCtx);
213     }
214     }
215   }
216   // If we couldn't find an existing region to construct into, assume we're
217   // constructing a temporary. Notify the caller of our failure.
218   CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
219   return MRMgr.getCXXTempObjectRegion(CE, LCtx);
220 }
221 
222 const CXXConstructExpr *
223 ExprEngine::findDirectConstructorForCurrentCFGElement() {
224   // Go backward in the CFG to see if the previous element (ignoring
225   // destructors) was a CXXConstructExpr. If so, that constructor
226   // was constructed directly into an existing region.
227   // This process is essentially the inverse of that performed in
228   // findElementDirectlyInitializedByCurrentConstructor().
229   if (currStmtIdx == 0)
230     return nullptr;
231 
232   const CFGBlock *B = getBuilderContext().getBlock();
233 
234   unsigned int PreviousStmtIdx = currStmtIdx - 1;
235   CFGElement Previous = (*B)[PreviousStmtIdx];
236 
237   while (Previous.getAs<CFGImplicitDtor>() && PreviousStmtIdx > 0) {
238     --PreviousStmtIdx;
239     Previous = (*B)[PreviousStmtIdx];
240   }
241 
242   if (Optional<CFGStmt> PrevStmtElem = Previous.getAs<CFGStmt>()) {
243     if (auto *CtorExpr = dyn_cast<CXXConstructExpr>(PrevStmtElem->getStmt())) {
244       return CtorExpr;
245     }
246   }
247 
248   return nullptr;
249 }
250 
251 void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE,
252                                        ExplodedNode *Pred,
253                                        ExplodedNodeSet &destNodes) {
254   const LocationContext *LCtx = Pred->getLocationContext();
255   ProgramStateRef State = Pred->getState();
256 
257   const MemRegion *Target = nullptr;
258 
259   // FIXME: Handle arrays, which run the same constructor for every element.
260   // For now, we just run the first constructor (which should still invalidate
261   // the entire array).
262 
263   EvalCallOptions CallOpts;
264   auto C = getCurrentCFGElement().getAs<CFGConstructor>();
265   assert(C || getCurrentCFGElement().getAs<CFGStmt>());
266   const ConstructionContext *CC = C ? C->getConstructionContext() : nullptr;
267 
268   switch (CE->getConstructionKind()) {
269   case CXXConstructExpr::CK_Complete: {
270     Target = getRegionForConstructedObject(CE, Pred, CC, CallOpts);
271     break;
272   }
273   case CXXConstructExpr::CK_VirtualBase:
274     // Make sure we are not calling virtual base class initializers twice.
275     // Only the most-derived object should initialize virtual base classes.
276     if (const Stmt *Outer = LCtx->getCurrentStackFrame()->getCallSite()) {
277       const CXXConstructExpr *OuterCtor = dyn_cast<CXXConstructExpr>(Outer);
278       if (OuterCtor) {
279         switch (OuterCtor->getConstructionKind()) {
280         case CXXConstructExpr::CK_NonVirtualBase:
281         case CXXConstructExpr::CK_VirtualBase:
282           // Bail out!
283           destNodes.Add(Pred);
284           return;
285         case CXXConstructExpr::CK_Complete:
286         case CXXConstructExpr::CK_Delegating:
287           break;
288         }
289       }
290     }
291     // FALLTHROUGH
292   case CXXConstructExpr::CK_NonVirtualBase:
293     // In C++17, classes with non-virtual bases may be aggregates, so they would
294     // be initialized as aggregates without a constructor call, so we may have
295     // a base class constructed directly into an initializer list without
296     // having the derived-class constructor call on the previous stack frame.
297     // Initializer lists may be nested into more initializer lists that
298     // correspond to surrounding aggregate initializations.
299     // FIXME: For now this code essentially bails out. We need to find the
300     // correct target region and set it.
301     // FIXME: Instead of relying on the ParentMap, we should have the
302     // trigger-statement (InitListExpr in this case) passed down from CFG or
303     // otherwise always available during construction.
304     if (dyn_cast_or_null<InitListExpr>(LCtx->getParentMap().getParent(CE))) {
305       MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
306       Target = MRMgr.getCXXTempObjectRegion(CE, LCtx);
307       CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
308       break;
309     }
310     // FALLTHROUGH
311   case CXXConstructExpr::CK_Delegating: {
312     const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
313     Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
314                                               LCtx->getCurrentStackFrame());
315     SVal ThisVal = State->getSVal(ThisPtr);
316 
317     if (CE->getConstructionKind() == CXXConstructExpr::CK_Delegating) {
318       Target = ThisVal.getAsRegion();
319     } else {
320       // Cast to the base type.
321       bool IsVirtual =
322         (CE->getConstructionKind() == CXXConstructExpr::CK_VirtualBase);
323       SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, CE->getType(),
324                                                          IsVirtual);
325       Target = BaseVal.getAsRegion();
326     }
327     break;
328   }
329   }
330 
331   CallEventManager &CEMgr = getStateManager().getCallEventManager();
332   CallEventRef<CXXConstructorCall> Call =
333     CEMgr.getCXXConstructorCall(CE, Target, State, LCtx);
334 
335   ExplodedNodeSet DstPreVisit;
336   getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, CE, *this);
337 
338   // FIXME: Is it possible and/or useful to do this before PreStmt?
339   ExplodedNodeSet PreInitialized;
340   {
341     StmtNodeBuilder Bldr(DstPreVisit, PreInitialized, *currBldrCtx);
342     for (ExplodedNodeSet::iterator I = DstPreVisit.begin(),
343                                    E = DstPreVisit.end();
344          I != E; ++I) {
345       ProgramStateRef State = (*I)->getState();
346       if (CE->requiresZeroInitialization()) {
347         // Type of the zero doesn't matter.
348         SVal ZeroVal = svalBuilder.makeZeroVal(getContext().CharTy);
349 
350         // FIXME: Once we properly handle constructors in new-expressions, we'll
351         // need to invalidate the region before setting a default value, to make
352         // sure there aren't any lingering bindings around. This probably needs
353         // to happen regardless of whether or not the object is zero-initialized
354         // to handle random fields of a placement-initialized object picking up
355         // old bindings. We might only want to do it when we need to, though.
356         // FIXME: This isn't actually correct for arrays -- we need to zero-
357         // initialize the entire array, not just the first element -- but our
358         // handling of arrays everywhere else is weak as well, so this shouldn't
359         // actually make things worse. Placement new makes this tricky as well,
360         // since it's then possible to be initializing one part of a multi-
361         // dimensional array.
362         State = State->bindDefault(loc::MemRegionVal(Target), ZeroVal, LCtx);
363       }
364 
365       State = addAllNecessaryTemporaryInfo(State, CC, LCtx, Target);
366 
367       Bldr.generateNode(CE, *I, State, /*tag=*/nullptr,
368                         ProgramPoint::PreStmtKind);
369     }
370   }
371 
372   ExplodedNodeSet DstPreCall;
373   getCheckerManager().runCheckersForPreCall(DstPreCall, PreInitialized,
374                                             *Call, *this);
375 
376   ExplodedNodeSet DstEvaluated;
377   StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx);
378 
379   if (CE->getConstructor()->isTrivial() &&
380       CE->getConstructor()->isCopyOrMoveConstructor() &&
381       !CallOpts.IsArrayCtorOrDtor) {
382     // FIXME: Handle other kinds of trivial constructors as well.
383     for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
384          I != E; ++I)
385       performTrivialCopy(Bldr, *I, *Call);
386 
387   } else {
388     for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
389          I != E; ++I)
390       defaultEvalCall(Bldr, *I, *Call, CallOpts);
391   }
392 
393   // If the CFG was contructed without elements for temporary destructors
394   // and the just-called constructor created a temporary object then
395   // stop exploration if the temporary object has a noreturn constructor.
396   // This can lose coverage because the destructor, if it were present
397   // in the CFG, would be called at the end of the full expression or
398   // later (for life-time extended temporaries) -- but avoids infeasible
399   // paths when no-return temporary destructors are used for assertions.
400   const AnalysisDeclContext *ADC = LCtx->getAnalysisDeclContext();
401   if (!ADC->getCFGBuildOptions().AddTemporaryDtors) {
402     const MemRegion *Target = Call->getCXXThisVal().getAsRegion();
403     if (Target && isa<CXXTempObjectRegion>(Target) &&
404         Call->getDecl()->getParent()->isAnyDestructorNoReturn()) {
405 
406       // If we've inlined the constructor, then DstEvaluated would be empty.
407       // In this case we still want a sink, which could be implemented
408       // in processCallExit. But we don't have that implemented at the moment,
409       // so if you hit this assertion, see if you can avoid inlining
410       // the respective constructor when analyzer-config cfg-temporary-dtors
411       // is set to false.
412       // Otherwise there's nothing wrong with inlining such constructor.
413       assert(!DstEvaluated.empty() &&
414              "We should not have inlined this constructor!");
415 
416       for (ExplodedNode *N : DstEvaluated) {
417         Bldr.generateSink(CE, N, N->getState());
418       }
419 
420       // There is no need to run the PostCall and PostStmt checker
421       // callbacks because we just generated sinks on all nodes in th
422       // frontier.
423       return;
424     }
425   }
426 
427   ExplodedNodeSet DstPostCall;
428   getCheckerManager().runCheckersForPostCall(DstPostCall, DstEvaluated,
429                                              *Call, *this);
430   getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, CE, *this);
431 }
432 
433 void ExprEngine::VisitCXXDestructor(QualType ObjectType,
434                                     const MemRegion *Dest,
435                                     const Stmt *S,
436                                     bool IsBaseDtor,
437                                     ExplodedNode *Pred,
438                                     ExplodedNodeSet &Dst,
439                                     const EvalCallOptions &CallOpts) {
440   const LocationContext *LCtx = Pred->getLocationContext();
441   ProgramStateRef State = Pred->getState();
442 
443   const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl();
444   assert(RecordDecl && "Only CXXRecordDecls should have destructors");
445   const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
446 
447   CallEventManager &CEMgr = getStateManager().getCallEventManager();
448   CallEventRef<CXXDestructorCall> Call =
449     CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx);
450 
451   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
452                                 Call->getSourceRange().getBegin(),
453                                 "Error evaluating destructor");
454 
455   ExplodedNodeSet DstPreCall;
456   getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
457                                             *Call, *this);
458 
459   ExplodedNodeSet DstInvalidated;
460   StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
461   for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
462        I != E; ++I)
463     defaultEvalCall(Bldr, *I, *Call, CallOpts);
464 
465   ExplodedNodeSet DstPostCall;
466   getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
467                                              *Call, *this);
468 }
469 
470 void ExprEngine::VisitCXXNewAllocatorCall(const CXXNewExpr *CNE,
471                                           ExplodedNode *Pred,
472                                           ExplodedNodeSet &Dst) {
473   ProgramStateRef State = Pred->getState();
474   const LocationContext *LCtx = Pred->getLocationContext();
475   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
476                                 CNE->getStartLoc(),
477                                 "Error evaluating New Allocator Call");
478   CallEventManager &CEMgr = getStateManager().getCallEventManager();
479   CallEventRef<CXXAllocatorCall> Call =
480     CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
481 
482   ExplodedNodeSet DstPreCall;
483   getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
484                                             *Call, *this);
485 
486   ExplodedNodeSet DstPostCall;
487   StmtNodeBuilder CallBldr(DstPreCall, DstPostCall, *currBldrCtx);
488   for (auto I : DstPreCall) {
489     // FIXME: Provide evalCall for checkers?
490     defaultEvalCall(CallBldr, I, *Call);
491   }
492   // If the call is inlined, DstPostCall will be empty and we bail out now.
493 
494   // Store return value of operator new() for future use, until the actual
495   // CXXNewExpr gets processed.
496   ExplodedNodeSet DstPostValue;
497   StmtNodeBuilder ValueBldr(DstPostCall, DstPostValue, *currBldrCtx);
498   for (auto I : DstPostCall) {
499     // FIXME: Because CNE serves as the "call site" for the allocator (due to
500     // lack of a better expression in the AST), the conjured return value symbol
501     // is going to be of the same type (C++ object pointer type). Technically
502     // this is not correct because the operator new's prototype always says that
503     // it returns a 'void *'. So we should change the type of the symbol,
504     // and then evaluate the cast over the symbolic pointer from 'void *' to
505     // the object pointer type. But without changing the symbol's type it
506     // is breaking too much to evaluate the no-op symbolic cast over it, so we
507     // skip it for now.
508     ProgramStateRef State = I->getState();
509     SVal RetVal = State->getSVal(CNE, LCtx);
510 
511     // If this allocation function is not declared as non-throwing, failures
512     // /must/ be signalled by exceptions, and thus the return value will never
513     // be NULL. -fno-exceptions does not influence this semantics.
514     // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
515     // where new can return NULL. If we end up supporting that option, we can
516     // consider adding a check for it here.
517     // C++11 [basic.stc.dynamic.allocation]p3.
518     if (const FunctionDecl *FD = CNE->getOperatorNew()) {
519       QualType Ty = FD->getType();
520       if (const auto *ProtoType = Ty->getAs<FunctionProtoType>())
521         if (!ProtoType->isNothrow(getContext()))
522           State = State->assume(RetVal.castAs<DefinedOrUnknownSVal>(), true);
523     }
524 
525     ValueBldr.generateNode(CNE, I,
526                            setCXXNewAllocatorValue(State, CNE, LCtx, RetVal));
527   }
528 
529   ExplodedNodeSet DstPostPostCallCallback;
530   getCheckerManager().runCheckersForPostCall(DstPostPostCallCallback,
531                                              DstPostValue, *Call, *this);
532   for (auto I : DstPostPostCallCallback) {
533     getCheckerManager().runCheckersForNewAllocator(
534         CNE, getCXXNewAllocatorValue(I->getState(), CNE, LCtx), Dst, I, *this);
535   }
536 }
537 
538 void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
539                                    ExplodedNodeSet &Dst) {
540   // FIXME: Much of this should eventually migrate to CXXAllocatorCall.
541   // Also, we need to decide how allocators actually work -- they're not
542   // really part of the CXXNewExpr because they happen BEFORE the
543   // CXXConstructExpr subexpression. See PR12014 for some discussion.
544 
545   unsigned blockCount = currBldrCtx->blockCount();
546   const LocationContext *LCtx = Pred->getLocationContext();
547   SVal symVal = UnknownVal();
548   FunctionDecl *FD = CNE->getOperatorNew();
549 
550   bool IsStandardGlobalOpNewFunction =
551       FD->isReplaceableGlobalAllocationFunction();
552 
553   ProgramStateRef State = Pred->getState();
554 
555   // Retrieve the stored operator new() return value.
556   if (AMgr.getAnalyzerOptions().mayInlineCXXAllocator()) {
557     symVal = getCXXNewAllocatorValue(State, CNE, LCtx);
558     State = clearCXXNewAllocatorValue(State, CNE, LCtx);
559   }
560 
561   // We assume all standard global 'operator new' functions allocate memory in
562   // heap. We realize this is an approximation that might not correctly model
563   // a custom global allocator.
564   if (symVal.isUnknown()) {
565     if (IsStandardGlobalOpNewFunction)
566       symVal = svalBuilder.getConjuredHeapSymbolVal(CNE, LCtx, blockCount);
567     else
568       symVal = svalBuilder.conjureSymbolVal(nullptr, CNE, LCtx, CNE->getType(),
569                                             blockCount);
570   }
571 
572   CallEventManager &CEMgr = getStateManager().getCallEventManager();
573   CallEventRef<CXXAllocatorCall> Call =
574     CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
575 
576   if (!AMgr.getAnalyzerOptions().mayInlineCXXAllocator()) {
577     // Invalidate placement args.
578     // FIXME: Once we figure out how we want allocators to work,
579     // we should be using the usual pre-/(default-)eval-/post-call checks here.
580     State = Call->invalidateRegions(blockCount);
581     if (!State)
582       return;
583 
584     // If this allocation function is not declared as non-throwing, failures
585     // /must/ be signalled by exceptions, and thus the return value will never
586     // be NULL. -fno-exceptions does not influence this semantics.
587     // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
588     // where new can return NULL. If we end up supporting that option, we can
589     // consider adding a check for it here.
590     // C++11 [basic.stc.dynamic.allocation]p3.
591     if (FD) {
592       QualType Ty = FD->getType();
593       if (const auto *ProtoType = Ty->getAs<FunctionProtoType>())
594         if (!ProtoType->isNothrow(getContext()))
595           if (auto dSymVal = symVal.getAs<DefinedOrUnknownSVal>())
596             State = State->assume(*dSymVal, true);
597     }
598   }
599 
600   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
601 
602   SVal Result = symVal;
603 
604   if (CNE->isArray()) {
605     // FIXME: allocating an array requires simulating the constructors.
606     // For now, just return a symbolicated region.
607     if (const SubRegion *NewReg =
608             dyn_cast_or_null<SubRegion>(symVal.getAsRegion())) {
609       QualType ObjTy = CNE->getType()->getAs<PointerType>()->getPointeeType();
610       const ElementRegion *EleReg =
611           getStoreManager().GetElementZeroRegion(NewReg, ObjTy);
612       Result = loc::MemRegionVal(EleReg);
613     }
614     State = State->BindExpr(CNE, Pred->getLocationContext(), Result);
615     Bldr.generateNode(CNE, Pred, State);
616     return;
617   }
618 
619   // FIXME: Once we have proper support for CXXConstructExprs inside
620   // CXXNewExpr, we need to make sure that the constructed object is not
621   // immediately invalidated here. (The placement call should happen before
622   // the constructor call anyway.)
623   if (FD && FD->isReservedGlobalPlacementOperator()) {
624     // Non-array placement new should always return the placement location.
625     SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx);
626     Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(),
627                                   CNE->getPlacementArg(0)->getType());
628   }
629 
630   // Bind the address of the object, then check to see if we cached out.
631   State = State->BindExpr(CNE, LCtx, Result);
632   ExplodedNode *NewN = Bldr.generateNode(CNE, Pred, State);
633   if (!NewN)
634     return;
635 
636   // If the type is not a record, we won't have a CXXConstructExpr as an
637   // initializer. Copy the value over.
638   if (const Expr *Init = CNE->getInitializer()) {
639     if (!isa<CXXConstructExpr>(Init)) {
640       assert(Bldr.getResults().size() == 1);
641       Bldr.takeNodes(NewN);
642       evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, LCtx),
643                /*FirstInit=*/IsStandardGlobalOpNewFunction);
644     }
645   }
646 }
647 
648 void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE,
649                                     ExplodedNode *Pred, ExplodedNodeSet &Dst) {
650   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
651   ProgramStateRef state = Pred->getState();
652   Bldr.generateNode(CDE, Pred, state);
653 }
654 
655 void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS,
656                                    ExplodedNode *Pred,
657                                    ExplodedNodeSet &Dst) {
658   const VarDecl *VD = CS->getExceptionDecl();
659   if (!VD) {
660     Dst.Add(Pred);
661     return;
662   }
663 
664   const LocationContext *LCtx = Pred->getLocationContext();
665   SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(),
666                                         currBldrCtx->blockCount());
667   ProgramStateRef state = Pred->getState();
668   state = state->bindLoc(state->getLValue(VD, LCtx), V, LCtx);
669 
670   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
671   Bldr.generateNode(CS, Pred, state);
672 }
673 
674 void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
675                                     ExplodedNodeSet &Dst) {
676   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
677 
678   // Get the this object region from StoreManager.
679   const LocationContext *LCtx = Pred->getLocationContext();
680   const MemRegion *R =
681     svalBuilder.getRegionManager().getCXXThisRegion(
682                                   getContext().getCanonicalType(TE->getType()),
683                                                     LCtx);
684 
685   ProgramStateRef state = Pred->getState();
686   SVal V = state->getSVal(loc::MemRegionVal(R));
687   Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V));
688 }
689 
690 void ExprEngine::VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred,
691                                  ExplodedNodeSet &Dst) {
692   const LocationContext *LocCtxt = Pred->getLocationContext();
693 
694   // Get the region of the lambda itself.
695   const MemRegion *R = svalBuilder.getRegionManager().getCXXTempObjectRegion(
696       LE, LocCtxt);
697   SVal V = loc::MemRegionVal(R);
698 
699   ProgramStateRef State = Pred->getState();
700 
701   // If we created a new MemRegion for the lambda, we should explicitly bind
702   // the captures.
703   CXXRecordDecl::field_iterator CurField = LE->getLambdaClass()->field_begin();
704   for (LambdaExpr::const_capture_init_iterator i = LE->capture_init_begin(),
705                                                e = LE->capture_init_end();
706        i != e; ++i, ++CurField) {
707     FieldDecl *FieldForCapture = *CurField;
708     SVal FieldLoc = State->getLValue(FieldForCapture, V);
709 
710     SVal InitVal;
711     if (!FieldForCapture->hasCapturedVLAType()) {
712       Expr *InitExpr = *i;
713       assert(InitExpr && "Capture missing initialization expression");
714       InitVal = State->getSVal(InitExpr, LocCtxt);
715     } else {
716       // The field stores the length of a captured variable-length array.
717       // These captures don't have initialization expressions; instead we
718       // get the length from the VLAType size expression.
719       Expr *SizeExpr = FieldForCapture->getCapturedVLAType()->getSizeExpr();
720       InitVal = State->getSVal(SizeExpr, LocCtxt);
721     }
722 
723     State = State->bindLoc(FieldLoc, InitVal, LocCtxt);
724   }
725 
726   // Decay the Loc into an RValue, because there might be a
727   // MaterializeTemporaryExpr node above this one which expects the bound value
728   // to be an RValue.
729   SVal LambdaRVal = State->getSVal(R);
730 
731   ExplodedNodeSet Tmp;
732   StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
733   // FIXME: is this the right program point kind?
734   Bldr.generateNode(LE, Pred,
735                     State->BindExpr(LE, LocCtxt, LambdaRVal),
736                     nullptr, ProgramPoint::PostLValueKind);
737 
738   // FIXME: Move all post/pre visits to ::Visit().
739   getCheckerManager().runCheckersForPostStmt(Dst, Tmp, LE, *this);
740 }
741