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