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