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