110e25031STed Kremenek //===- ExprEngineCXX.cpp - ExprEngine support for C++ -----------*- C++ -*-===//
210e25031STed Kremenek //
310e25031STed Kremenek //                     The LLVM Compiler Infrastructure
410e25031STed Kremenek //
510e25031STed Kremenek // This file is distributed under the University of Illinois Open Source
610e25031STed Kremenek // License. See LICENSE.TXT for details.
710e25031STed Kremenek //
810e25031STed Kremenek //===----------------------------------------------------------------------===//
910e25031STed Kremenek //
1010e25031STed Kremenek //  This file defines the C++ expression evaluation engine.
1110e25031STed Kremenek //
1210e25031STed Kremenek //===----------------------------------------------------------------------===//
1310e25031STed Kremenek 
1410e25031STed Kremenek #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
154068481bSArtem Dergachev #include "clang/Analysis/ConstructionContext.h"
1610e25031STed Kremenek #include "clang/AST/DeclCXX.h"
178fdb59f9STed Kremenek #include "clang/AST/StmtCXX.h"
18e8ba3ec4SArtem Dergachev #include "clang/AST/ParentMap.h"
1917a8757aSJordan Rose #include "clang/Basic/PrettyStackTrace.h"
203a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/CheckerManager.h"
213a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
223a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
2310e25031STed Kremenek 
2410e25031STed Kremenek using namespace clang;
2510e25031STed Kremenek using namespace ento;
2610e25031STed Kremenek 
2710e25031STed Kremenek void ExprEngine::CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
2810e25031STed Kremenek                                           ExplodedNode *Pred,
2910e25031STed Kremenek                                           ExplodedNodeSet &Dst) {
30d94854a4STed Kremenek   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
312a14c695STed Kremenek   const Expr *tempExpr = ME->GetTemporaryExpr()->IgnoreParens();
3249b1e38eSTed Kremenek   ProgramStateRef state = Pred->getState();
33632e3b7eSTed Kremenek   const LocationContext *LCtx = Pred->getLocationContext();
3410e25031STed Kremenek 
35861a1740SJordan Rose   state = createTemporaryRegionIfNeeded(state, LCtx, tempExpr, ME);
365772f82dSJordan Rose   Bldr.generateNode(ME, Pred, state);
3710e25031STed Kremenek }
3810e25031STed Kremenek 
393d7b7f52SJordan Rose // FIXME: This is the sort of code that should eventually live in a Core
403d7b7f52SJordan Rose // checker rather than as a special case in ExprEngine.
4188bb563cSJordan Rose void ExprEngine::performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred,
423d7b7f52SJordan Rose                                     const CallEvent &Call) {
433d7b7f52SJordan Rose   SVal ThisVal;
443d7b7f52SJordan Rose   bool AlwaysReturnsLValue;
454449e7f0SArtem Dergachev   const CXXRecordDecl *ThisRD = nullptr;
463d7b7f52SJordan Rose   if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) {
473d7b7f52SJordan Rose     assert(Ctor->getDecl()->isTrivial());
483d7b7f52SJordan Rose     assert(Ctor->getDecl()->isCopyOrMoveConstructor());
493d7b7f52SJordan Rose     ThisVal = Ctor->getCXXThisVal();
504449e7f0SArtem Dergachev     ThisRD = Ctor->getDecl()->getParent();
513d7b7f52SJordan Rose     AlwaysReturnsLValue = false;
523d7b7f52SJordan Rose   } else {
533d7b7f52SJordan Rose     assert(cast<CXXMethodDecl>(Call.getDecl())->isTrivial());
543d7b7f52SJordan Rose     assert(cast<CXXMethodDecl>(Call.getDecl())->getOverloadedOperator() ==
553d7b7f52SJordan Rose            OO_Equal);
563d7b7f52SJordan Rose     ThisVal = cast<CXXInstanceCall>(Call).getCXXThisVal();
574449e7f0SArtem Dergachev     ThisRD = cast<CXXMethodDecl>(Call.getDecl())->getParent();
583d7b7f52SJordan Rose     AlwaysReturnsLValue = true;
593d7b7f52SJordan Rose   }
6088bb563cSJordan Rose 
614449e7f0SArtem Dergachev   assert(ThisRD);
624449e7f0SArtem Dergachev   if (ThisRD->isEmpty()) {
634449e7f0SArtem Dergachev     // Do nothing for empty classes. Otherwise it'd retrieve an UnknownVal
644449e7f0SArtem Dergachev     // and bind it and RegionStore would think that the actual value
654449e7f0SArtem Dergachev     // in this region at this offset is unknown.
664449e7f0SArtem Dergachev     return;
674449e7f0SArtem Dergachev   }
684449e7f0SArtem Dergachev 
6988bb563cSJordan Rose   const LocationContext *LCtx = Pred->getLocationContext();
7088bb563cSJordan Rose 
7188bb563cSJordan Rose   ExplodedNodeSet Dst;
7288bb563cSJordan Rose   Bldr.takeNodes(Pred);
7388bb563cSJordan Rose 
7488bb563cSJordan Rose   SVal V = Call.getArgSVal(0);
7588bb563cSJordan Rose 
763d7b7f52SJordan Rose   // If the value being copied is not unknown, load from its location to get
773d7b7f52SJordan Rose   // an aggregate rvalue.
7805785d16SDavid Blaikie   if (Optional<Loc> L = V.getAs<Loc>())
7988bb563cSJordan Rose     V = Pred->getState()->getSVal(*L);
803d7b7f52SJordan Rose   else
8175f9d3acSArtem Dergachev     assert(V.isUnknownOrUndef());
8288bb563cSJordan Rose 
833d7b7f52SJordan Rose   const Expr *CallExpr = Call.getOriginExpr();
843d7b7f52SJordan Rose   evalBind(Dst, CallExpr, Pred, ThisVal, V, true);
8588bb563cSJordan Rose 
863d7b7f52SJordan Rose   PostStmt PS(CallExpr, LCtx);
8788bb563cSJordan Rose   for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end();
8888bb563cSJordan Rose        I != E; ++I) {
8988bb563cSJordan Rose     ProgramStateRef State = (*I)->getState();
903d7b7f52SJordan Rose     if (AlwaysReturnsLValue)
913d7b7f52SJordan Rose       State = State->BindExpr(CallExpr, LCtx, ThisVal);
923d7b7f52SJordan Rose     else
9388bb563cSJordan Rose       State = bindReturnValue(Call, LCtx, State);
9488bb563cSJordan Rose     Bldr.generateNode(PS, State, *I);
9588bb563cSJordan Rose   }
9688bb563cSJordan Rose }
9788bb563cSJordan Rose 
98bc74eb1cSJordan Rose 
99168e29f6SArtem Dergachev SVal ExprEngine::makeZeroElementRegion(ProgramStateRef State, SVal LValue,
100690ab040SArtem Dergachev                                        QualType &Ty, bool &IsArray) {
101bc74eb1cSJordan Rose   SValBuilder &SVB = State->getStateManager().getSValBuilder();
102bc74eb1cSJordan Rose   ASTContext &Ctx = SVB.getContext();
103bc74eb1cSJordan Rose 
104bc74eb1cSJordan Rose   while (const ArrayType *AT = Ctx.getAsArrayType(Ty)) {
105bc74eb1cSJordan Rose     Ty = AT->getElementType();
106bc74eb1cSJordan Rose     LValue = State->getLValue(Ty, SVB.makeZeroArrayIndex(), LValue);
107690ab040SArtem Dergachev     IsArray = true;
108bc74eb1cSJordan Rose   }
109bc74eb1cSJordan Rose 
110bc74eb1cSJordan Rose   return LValue;
111bc74eb1cSJordan Rose }
112bc74eb1cSJordan Rose 
113239452caSArtem Dergachev std::pair<ProgramStateRef, SVal> ExprEngine::prepareForObjectConstruction(
114239452caSArtem Dergachev     const Expr *E, ProgramStateRef State, const LocationContext *LCtx,
115239452caSArtem Dergachev     const ConstructionContext *CC, EvalCallOptions &CallOpts) {
116*17906498SArtem Dergachev   SValBuilder &SVB = getSValBuilder();
117*17906498SArtem Dergachev   MemRegionManager &MRMgr = SVB.getRegionManager();
118*17906498SArtem Dergachev   ASTContext &ACtx = SVB.getContext();
11905375eb4SJordan Rose 
120afb158c2SArtem Dergachev   // See if we're constructing an existing region by looking at the
121afb158c2SArtem Dergachev   // current construction context.
122661ab34aSArtem Dergachev   if (CC) {
1234068481bSArtem Dergachev     switch (CC->getKind()) {
12453b8ce0eSArtem Dergachev     case ConstructionContext::CXX17ElidedCopyVariableKind:
1254068481bSArtem Dergachev     case ConstructionContext::SimpleVariableKind: {
12653b8ce0eSArtem Dergachev       const auto *DSCC = cast<VariableConstructionContext>(CC);
1274068481bSArtem Dergachev       const auto *DS = DSCC->getDeclStmt();
128e231bd34SArtem Dergachev       const auto *Var = cast<VarDecl>(DS->getSingleDecl());
129bc74eb1cSJordan Rose       SVal LValue = State->getLValue(Var, LCtx);
13020edae87SJordan Rose       QualType Ty = Var->getType();
1311fe52474SArtem Dergachev       LValue =
1321fe52474SArtem Dergachev           makeZeroElementRegion(State, LValue, Ty, CallOpts.IsArrayCtorOrDtor);
1331fe52474SArtem Dergachev       State =
1341fe52474SArtem Dergachev           addObjectUnderConstruction(State, DSCC->getDeclStmt(), LCtx, LValue);
1351fe52474SArtem Dergachev       return std::make_pair(State, LValue);
13620edae87SJordan Rose     }
13753b8ce0eSArtem Dergachev     case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind:
138922455feSArtem Dergachev     case ConstructionContext::SimpleConstructorInitializerKind: {
1394068481bSArtem Dergachev       const auto *ICC = cast<ConstructorInitializerConstructionContext>(CC);
1404068481bSArtem Dergachev       const auto *Init = ICC->getCXXCtorInitializer();
14154529a34SJordan Rose       assert(Init->isAnyMemberInitializer());
14254529a34SJordan Rose       const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
143412c0af2SDevin Coughlin       Loc ThisPtr =
144*17906498SArtem Dergachev       SVB.getCXXThis(CurCtor, LCtx->getStackFrame());
14554529a34SJordan Rose       SVal ThisVal = State->getSVal(ThisPtr);
14654529a34SJordan Rose 
147bc74eb1cSJordan Rose       const ValueDecl *Field;
148bc74eb1cSJordan Rose       SVal FieldVal;
14954529a34SJordan Rose       if (Init->isIndirectMemberInitializer()) {
150bc74eb1cSJordan Rose         Field = Init->getIndirectMember();
151bc74eb1cSJordan Rose         FieldVal = State->getLValue(Init->getIndirectMember(), ThisVal);
15254529a34SJordan Rose       } else {
153bc74eb1cSJordan Rose         Field = Init->getMember();
154bc74eb1cSJordan Rose         FieldVal = State->getLValue(Init->getMember(), ThisVal);
15554529a34SJordan Rose       }
156bc74eb1cSJordan Rose 
157bc74eb1cSJordan Rose       QualType Ty = Field->getType();
158690ab040SArtem Dergachev       FieldVal = makeZeroElementRegion(State, FieldVal, Ty,
159168e29f6SArtem Dergachev                                        CallOpts.IsArrayCtorOrDtor);
160a84374dcSArtem Dergachev       State = addObjectUnderConstruction(State, Init, LCtx, FieldVal);
161239452caSArtem Dergachev       return std::make_pair(State, FieldVal);
16254529a34SJordan Rose     }
1634068481bSArtem Dergachev     case ConstructionContext::NewAllocatedObjectKind: {
164549f9cd4SKristof Umann       if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
1654068481bSArtem Dergachev         const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
1664068481bSArtem Dergachev         const auto *NE = NECC->getCXXNewExpr();
167f83d5479SArtem Dergachev         SVal V = *getObjectUnderConstruction(State, NE, LCtx);
168f83d5479SArtem Dergachev         if (const SubRegion *MR =
169f83d5479SArtem Dergachev                 dyn_cast_or_null<SubRegion>(V.getAsRegion())) {
1704068481bSArtem Dergachev           if (NE->isArray()) {
1714068481bSArtem Dergachev             // TODO: In fact, we need to call the constructor for every
1724068481bSArtem Dergachev             // allocated element, not just the first one!
1734068481bSArtem Dergachev             CallOpts.IsArrayCtorOrDtor = true;
174239452caSArtem Dergachev             return std::make_pair(
175239452caSArtem Dergachev                 State, loc::MemRegionVal(getStoreManager().GetElementZeroRegion(
176239452caSArtem Dergachev                            MR, NE->getType()->getPointeeType())));
1774068481bSArtem Dergachev           }
178239452caSArtem Dergachev           return std::make_pair(State, V);
1794068481bSArtem Dergachev         }
180f83d5479SArtem Dergachev         // TODO: Detect when the allocator returns a null pointer.
181f83d5479SArtem Dergachev         // Constructor shall not be called in this case.
1824068481bSArtem Dergachev       }
1834068481bSArtem Dergachev       break;
1844068481bSArtem Dergachev     }
185f28d7f17SArtem Dergachev     case ConstructionContext::SimpleReturnedValueKind:
186f28d7f17SArtem Dergachev     case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
187239452caSArtem Dergachev       // The temporary is to be managed by the parent stack frame.
188239452caSArtem Dergachev       // So build it in the parent stack frame if we're not in the
189239452caSArtem Dergachev       // top frame of the analysis.
190dd18b11bSGeorge Karpenkov       const StackFrameContext *SFC = LCtx->getStackFrame();
191239452caSArtem Dergachev       if (const LocationContext *CallerLCtx = SFC->getParent()) {
192239452caSArtem Dergachev         auto RTC = (*SFC->getCallSiteBlock())[SFC->getIndex()]
193239452caSArtem Dergachev                        .getAs<CFGCXXRecordTypedCall>();
194239452caSArtem Dergachev         if (!RTC) {
195239452caSArtem Dergachev           // We were unable to find the correct construction context for the
196239452caSArtem Dergachev           // call in the parent stack frame. This is equivalent to not being
197239452caSArtem Dergachev           // able to find construction context at all.
198239452caSArtem Dergachev           break;
199239452caSArtem Dergachev         }
200f28d7f17SArtem Dergachev         return prepareForObjectConstruction(
201f28d7f17SArtem Dergachev             cast<Expr>(SFC->getCallSite()), State, CallerLCtx,
202f28d7f17SArtem Dergachev             RTC->getConstructionContext(), CallOpts);
203239452caSArtem Dergachev       } else {
204*17906498SArtem Dergachev         // We are on the top frame of the analysis. We do not know where is the
205*17906498SArtem Dergachev         // object returned to. Conjure a symbolic region for the return value.
206*17906498SArtem Dergachev         // TODO: We probably need a new MemRegion kind to represent the storage
207*17906498SArtem Dergachev         // of that SymbolicRegion, so that we cound produce a fancy symbol
208*17906498SArtem Dergachev         // instead of an anonymous conjured symbol.
209*17906498SArtem Dergachev         // TODO: Do we need to track the region to avoid having it dead
210*17906498SArtem Dergachev         // too early? It does die too early, at least in C++17, but because
211*17906498SArtem Dergachev         // putting anything into a SymbolicRegion causes an immediate escape,
212*17906498SArtem Dergachev         // it doesn't cause any leak false positives.
213*17906498SArtem Dergachev         const auto *RCC = cast<ReturnedValueConstructionContext>(CC);
214*17906498SArtem Dergachev         // Make sure that this doesn't coincide with any other symbol
215*17906498SArtem Dergachev         // conjured for the returned expression.
216*17906498SArtem Dergachev         static const int TopLevelSymRegionTag = 0;
217*17906498SArtem Dergachev         const Expr *RetE = RCC->getReturnStmt()->getRetValue();
218*17906498SArtem Dergachev         assert(RetE && "Void returns should not have a construction context");
219*17906498SArtem Dergachev         QualType ReturnTy = RetE->getType();
220*17906498SArtem Dergachev         QualType RegionTy = ACtx.getPointerType(ReturnTy);
221*17906498SArtem Dergachev         SVal V = SVB.conjureSymbolVal(&TopLevelSymRegionTag, RetE, SFC,
222*17906498SArtem Dergachev                                       RegionTy, currBldrCtx->blockCount());
223239452caSArtem Dergachev         return std::make_pair(State, V);
224239452caSArtem Dergachev       }
225f28d7f17SArtem Dergachev       llvm_unreachable("Unhandled return value construction context!");
226239452caSArtem Dergachev     }
2279a209ad1SArtem Dergachev     case ConstructionContext::ElidedTemporaryObjectKind: {
228549f9cd4SKristof Umann       assert(AMgr.getAnalyzerOptions().ShouldElideConstructors);
2299a209ad1SArtem Dergachev       const auto *TCC = cast<ElidedTemporaryObjectConstructionContext>(CC);
2309a209ad1SArtem Dergachev       const CXXBindTemporaryExpr *BTE = TCC->getCXXBindTemporaryExpr();
2319a209ad1SArtem Dergachev       const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr();
2329a209ad1SArtem Dergachev       const CXXConstructExpr *CE = TCC->getConstructorAfterElision();
2339a209ad1SArtem Dergachev 
2349a209ad1SArtem Dergachev       // Support pre-C++17 copy elision. We'll have the elidable copy
2359a209ad1SArtem Dergachev       // constructor in the AST and in the CFG, but we'll skip it
2369a209ad1SArtem Dergachev       // and construct directly into the final object. This call
2379a209ad1SArtem Dergachev       // also sets the CallOpts flags for us.
2389a209ad1SArtem Dergachev       SVal V;
239a657a32cSArtem Dergachev       // If the elided copy/move constructor is not supported, there's still
240a657a32cSArtem Dergachev       // benefit in trying to model the non-elided constructor.
241a657a32cSArtem Dergachev       // Stash our state before trying to elide, as it'll get overwritten.
242a657a32cSArtem Dergachev       ProgramStateRef PreElideState = State;
243a657a32cSArtem Dergachev       EvalCallOptions PreElideCallOpts = CallOpts;
244a657a32cSArtem Dergachev 
2459a209ad1SArtem Dergachev       std::tie(State, V) = prepareForObjectConstruction(
2469a209ad1SArtem Dergachev           CE, State, LCtx, TCC->getConstructionContextAfterElision(), CallOpts);
2479a209ad1SArtem Dergachev 
248a657a32cSArtem Dergachev       // FIXME: This definition of "copy elision has not failed" is unreliable.
249a657a32cSArtem Dergachev       // It doesn't indicate that the constructor will actually be inlined
250a657a32cSArtem Dergachev       // later; it is still up to evalCall() to decide.
251a657a32cSArtem Dergachev       if (!CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion) {
2529a209ad1SArtem Dergachev         // Remember that we've elided the constructor.
2539a209ad1SArtem Dergachev         State = addObjectUnderConstruction(State, CE, LCtx, V);
2549a209ad1SArtem Dergachev 
2559a209ad1SArtem Dergachev         // Remember that we've elided the destructor.
2569a209ad1SArtem Dergachev         if (BTE)
2579a209ad1SArtem Dergachev           State = elideDestructor(State, BTE, LCtx);
2589a209ad1SArtem Dergachev 
2599a209ad1SArtem Dergachev         // Instead of materialization, shamelessly return
2609a209ad1SArtem Dergachev         // the final object destination.
2619a209ad1SArtem Dergachev         if (MTE)
2629a209ad1SArtem Dergachev           State = addObjectUnderConstruction(State, MTE, LCtx, V);
2639a209ad1SArtem Dergachev 
2649a209ad1SArtem Dergachev         return std::make_pair(State, V);
265a657a32cSArtem Dergachev       } else {
266a657a32cSArtem Dergachev         // Copy elision failed. Revert the changes and proceed as if we have
267a657a32cSArtem Dergachev         // a simple temporary.
268a657a32cSArtem Dergachev         State = PreElideState;
269a657a32cSArtem Dergachev         CallOpts = PreElideCallOpts;
270a657a32cSArtem Dergachev       }
271080b8709SSimon Pilgrim       LLVM_FALLTHROUGH;
2729a209ad1SArtem Dergachev     }
273ff267df0SArtem Dergachev     case ConstructionContext::SimpleTemporaryObjectKind: {
274a657a32cSArtem Dergachev       const auto *TCC = cast<TemporaryObjectConstructionContext>(CC);
275239452caSArtem Dergachev       const CXXBindTemporaryExpr *BTE = TCC->getCXXBindTemporaryExpr();
276239452caSArtem Dergachev       const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr();
277d18639bdSArtem Dergachev       SVal V = UnknownVal();
278239452caSArtem Dergachev 
279239452caSArtem Dergachev       if (MTE) {
2808cd7961aSArtem Dergachev         if (const ValueDecl *VD = MTE->getExtendingDecl()) {
281643102dfSArtem Dergachev           assert(MTE->getStorageDuration() != SD_FullExpression);
282643102dfSArtem Dergachev           if (!VD->getType()->isReferenceType()) {
283643102dfSArtem Dergachev             // We're lifetime-extended by a surrounding aggregate.
284643102dfSArtem Dergachev             // Automatic destructors aren't quite working in this case
285643102dfSArtem Dergachev             // on the CFG side. We should warn the caller about that.
286310bca01SArtem Dergachev             // FIXME: Is there a better way to retrieve this information from
287310bca01SArtem Dergachev             // the MaterializeTemporaryExpr?
288310bca01SArtem Dergachev             CallOpts.IsTemporaryLifetimeExtendedViaAggregate = true;
289310bca01SArtem Dergachev           }
2908cd7961aSArtem Dergachev         }
2914fb586c3SArtem Dergachev 
2924fb586c3SArtem Dergachev         if (MTE->getStorageDuration() == SD_Static ||
2934fb586c3SArtem Dergachev             MTE->getStorageDuration() == SD_Thread)
2944fb586c3SArtem Dergachev           V = loc::MemRegionVal(MRMgr.getCXXStaticTempObjectRegion(E));
295239452caSArtem Dergachev       }
296239452caSArtem Dergachev 
2974fb586c3SArtem Dergachev       if (V.isUnknown())
2984fb586c3SArtem Dergachev         V = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx));
299239452caSArtem Dergachev 
300239452caSArtem Dergachev       if (BTE)
301239452caSArtem Dergachev         State = addObjectUnderConstruction(State, BTE, LCtx, V);
302239452caSArtem Dergachev 
303239452caSArtem Dergachev       if (MTE)
304239452caSArtem Dergachev         State = addObjectUnderConstruction(State, MTE, LCtx, V);
305239452caSArtem Dergachev 
3064068481bSArtem Dergachev       CallOpts.IsTemporaryCtorOrDtor = true;
307239452caSArtem Dergachev       return std::make_pair(State, V);
3084068481bSArtem Dergachev     }
309a657a32cSArtem Dergachev     case ConstructionContext::ArgumentKind: {
3103ccf14ebSArtem Dergachev       // Arguments are technically temporaries.
3113ccf14ebSArtem Dergachev       CallOpts.IsTemporaryCtorOrDtor = true;
3123ccf14ebSArtem Dergachev 
3133ccf14ebSArtem Dergachev       const auto *ACC = cast<ArgumentConstructionContext>(CC);
3143ccf14ebSArtem Dergachev       const Expr *E = ACC->getCallLikeExpr();
3153ccf14ebSArtem Dergachev       unsigned Idx = ACC->getIndex();
3163ccf14ebSArtem Dergachev       const CXXBindTemporaryExpr *BTE = ACC->getCXXBindTemporaryExpr();
3173ccf14ebSArtem Dergachev 
3183ccf14ebSArtem Dergachev       CallEventManager &CEMgr = getStateManager().getCallEventManager();
3193ccf14ebSArtem Dergachev       SVal V = UnknownVal();
3203ccf14ebSArtem Dergachev       auto getArgLoc = [&](CallEventRef<> Caller) -> Optional<SVal> {
3213ccf14ebSArtem Dergachev         const LocationContext *FutureSFC = Caller->getCalleeStackFrame();
3223ccf14ebSArtem Dergachev         // Return early if we are unable to reliably foresee
3233ccf14ebSArtem Dergachev         // the future stack frame.
3243ccf14ebSArtem Dergachev         if (!FutureSFC)
3253ccf14ebSArtem Dergachev           return None;
3263ccf14ebSArtem Dergachev 
3273ccf14ebSArtem Dergachev         // This should be equivalent to Caller->getDecl() for now, but
3283ccf14ebSArtem Dergachev         // FutureSFC->getDecl() is likely to support better stuff (like
3293ccf14ebSArtem Dergachev         // virtual functions) earlier.
3303ccf14ebSArtem Dergachev         const Decl *CalleeD = FutureSFC->getDecl();
3313ccf14ebSArtem Dergachev 
3323ccf14ebSArtem Dergachev         // FIXME: Support for variadic arguments is not implemented here yet.
3333ccf14ebSArtem Dergachev         if (CallEvent::isVariadic(CalleeD))
3343ccf14ebSArtem Dergachev           return None;
3353ccf14ebSArtem Dergachev 
3363ccf14ebSArtem Dergachev         // Operator arguments do not correspond to operator parameters
3373ccf14ebSArtem Dergachev         // because this-argument is implemented as a normal argument in
3383ccf14ebSArtem Dergachev         // operator call expressions but not in operator declarations.
3393ccf14ebSArtem Dergachev         const VarRegion *VR = Caller->getParameterLocation(
3403ccf14ebSArtem Dergachev             *Caller->getAdjustedParameterIndex(Idx));
3413ccf14ebSArtem Dergachev         if (!VR)
3423ccf14ebSArtem Dergachev           return None;
3433ccf14ebSArtem Dergachev 
3443ccf14ebSArtem Dergachev         return loc::MemRegionVal(VR);
3453ccf14ebSArtem Dergachev       };
3463ccf14ebSArtem Dergachev 
3473ccf14ebSArtem Dergachev       if (const auto *CE = dyn_cast<CallExpr>(E)) {
3483ccf14ebSArtem Dergachev         CallEventRef<> Caller = CEMgr.getSimpleCall(CE, State, LCtx);
3493ccf14ebSArtem Dergachev         if (auto OptV = getArgLoc(Caller))
3503ccf14ebSArtem Dergachev           V = *OptV;
3513ccf14ebSArtem Dergachev         else
352a657a32cSArtem Dergachev           break;
3533ccf14ebSArtem Dergachev         State = addObjectUnderConstruction(State, {CE, Idx}, LCtx, V);
3543ccf14ebSArtem Dergachev       } else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) {
3553ccf14ebSArtem Dergachev         // Don't bother figuring out the target region for the future
3563ccf14ebSArtem Dergachev         // constructor because we won't need it.
3573ccf14ebSArtem Dergachev         CallEventRef<> Caller =
3583ccf14ebSArtem Dergachev             CEMgr.getCXXConstructorCall(CCE, /*Target=*/nullptr, State, LCtx);
3593ccf14ebSArtem Dergachev         if (auto OptV = getArgLoc(Caller))
3603ccf14ebSArtem Dergachev           V = *OptV;
3613ccf14ebSArtem Dergachev         else
3623ccf14ebSArtem Dergachev           break;
3633ccf14ebSArtem Dergachev         State = addObjectUnderConstruction(State, {CCE, Idx}, LCtx, V);
3643ccf14ebSArtem Dergachev       } else if (const auto *ME = dyn_cast<ObjCMessageExpr>(E)) {
3653ccf14ebSArtem Dergachev         CallEventRef<> Caller = CEMgr.getObjCMethodCall(ME, State, LCtx);
3663ccf14ebSArtem Dergachev         if (auto OptV = getArgLoc(Caller))
3673ccf14ebSArtem Dergachev           V = *OptV;
3683ccf14ebSArtem Dergachev         else
3693ccf14ebSArtem Dergachev           break;
3703ccf14ebSArtem Dergachev         State = addObjectUnderConstruction(State, {ME, Idx}, LCtx, V);
3713ccf14ebSArtem Dergachev       }
3723ccf14ebSArtem Dergachev 
3733ccf14ebSArtem Dergachev       assert(!V.isUnknown());
3743ccf14ebSArtem Dergachev 
3753ccf14ebSArtem Dergachev       if (BTE)
3763ccf14ebSArtem Dergachev         State = addObjectUnderConstruction(State, BTE, LCtx, V);
3773ccf14ebSArtem Dergachev 
3783ccf14ebSArtem Dergachev       return std::make_pair(State, V);
379a657a32cSArtem Dergachev     }
3804068481bSArtem Dergachev     }
38105375eb4SJordan Rose   }
382c9318304SJordan Rose   // If we couldn't find an existing region to construct into, assume we're
383690ab040SArtem Dergachev   // constructing a temporary. Notify the caller of our failure.
384168e29f6SArtem Dergachev   CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
385239452caSArtem Dergachev   return std::make_pair(
386239452caSArtem Dergachev       State, loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx)));
387c9318304SJordan Rose }
38805375eb4SJordan Rose 
38917f41608SJordan Rose void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE,
39017f41608SJordan Rose                                        ExplodedNode *Pred,
39117f41608SJordan Rose                                        ExplodedNodeSet &destNodes) {
39217f41608SJordan Rose   const LocationContext *LCtx = Pred->getLocationContext();
39317f41608SJordan Rose   ProgramStateRef State = Pred->getState();
39417f41608SJordan Rose 
395f83d5479SArtem Dergachev   SVal Target = UnknownVal();
39617f41608SJordan Rose 
3979a209ad1SArtem Dergachev   if (Optional<SVal> ElidedTarget =
3989a209ad1SArtem Dergachev           getObjectUnderConstruction(State, CE, LCtx)) {
3999a209ad1SArtem Dergachev     // We've previously modeled an elidable constructor by pretending that it in
4009a209ad1SArtem Dergachev     // fact constructs into the correct target. This constructor can therefore
4019a209ad1SArtem Dergachev     // be skipped.
4029a209ad1SArtem Dergachev     Target = *ElidedTarget;
4039a209ad1SArtem Dergachev     StmtNodeBuilder Bldr(Pred, destNodes, *currBldrCtx);
4049a209ad1SArtem Dergachev     State = finishObjectConstruction(State, CE, LCtx);
4059a209ad1SArtem Dergachev     if (auto L = Target.getAs<Loc>())
4069a209ad1SArtem Dergachev       State = State->BindExpr(CE, LCtx, State->getSVal(*L, CE->getType()));
4079a209ad1SArtem Dergachev     Bldr.generateNode(CE, Pred, State);
4089a209ad1SArtem Dergachev     return;
4099a209ad1SArtem Dergachev   }
4109a209ad1SArtem Dergachev 
41117f41608SJordan Rose   // FIXME: Handle arrays, which run the same constructor for every element.
41217f41608SJordan Rose   // For now, we just run the first constructor (which should still invalidate
41317f41608SJordan Rose   // the entire array).
41417f41608SJordan Rose 
415690ab040SArtem Dergachev   EvalCallOptions CallOpts;
416661ab34aSArtem Dergachev   auto C = getCurrentCFGElement().getAs<CFGConstructor>();
4174068481bSArtem Dergachev   assert(C || getCurrentCFGElement().getAs<CFGStmt>());
418661ab34aSArtem Dergachev   const ConstructionContext *CC = C ? C->getConstructionContext() : nullptr;
419661ab34aSArtem Dergachev 
42017f41608SJordan Rose   switch (CE->getConstructionKind()) {
42117f41608SJordan Rose   case CXXConstructExpr::CK_Complete: {
422239452caSArtem Dergachev     std::tie(State, Target) =
423239452caSArtem Dergachev         prepareForObjectConstruction(CE, State, LCtx, CC, CallOpts);
424b970505dSJordan Rose     break;
425b970505dSJordan Rose   }
426b3b976f0SJordan Rose   case CXXConstructExpr::CK_VirtualBase:
427b3b976f0SJordan Rose     // Make sure we are not calling virtual base class initializers twice.
428b3b976f0SJordan Rose     // Only the most-derived object should initialize virtual base classes.
429dd18b11bSGeorge Karpenkov     if (const Stmt *Outer = LCtx->getStackFrame()->getCallSite()) {
430b3b976f0SJordan Rose       const CXXConstructExpr *OuterCtor = dyn_cast<CXXConstructExpr>(Outer);
431b3b976f0SJordan Rose       if (OuterCtor) {
432b3b976f0SJordan Rose         switch (OuterCtor->getConstructionKind()) {
433b970505dSJordan Rose         case CXXConstructExpr::CK_NonVirtualBase:
434b970505dSJordan Rose         case CXXConstructExpr::CK_VirtualBase:
435b3b976f0SJordan Rose           // Bail out!
436b3b976f0SJordan Rose           destNodes.Add(Pred);
437b3b976f0SJordan Rose           return;
438b3b976f0SJordan Rose         case CXXConstructExpr::CK_Complete:
439b3b976f0SJordan Rose         case CXXConstructExpr::CK_Delegating:
440b3b976f0SJordan Rose           break;
441b3b976f0SJordan Rose         }
442b3b976f0SJordan Rose       }
443b3b976f0SJordan Rose     }
4444dc0b1acSReid Kleckner     LLVM_FALLTHROUGH;
445b3b976f0SJordan Rose   case CXXConstructExpr::CK_NonVirtualBase:
446e8ba3ec4SArtem Dergachev     // In C++17, classes with non-virtual bases may be aggregates, so they would
447e8ba3ec4SArtem Dergachev     // be initialized as aggregates without a constructor call, so we may have
448e8ba3ec4SArtem Dergachev     // a base class constructed directly into an initializer list without
449e8ba3ec4SArtem Dergachev     // having the derived-class constructor call on the previous stack frame.
450e8ba3ec4SArtem Dergachev     // Initializer lists may be nested into more initializer lists that
451e8ba3ec4SArtem Dergachev     // correspond to surrounding aggregate initializations.
452e8ba3ec4SArtem Dergachev     // FIXME: For now this code essentially bails out. We need to find the
453e8ba3ec4SArtem Dergachev     // correct target region and set it.
454e8ba3ec4SArtem Dergachev     // FIXME: Instead of relying on the ParentMap, we should have the
455e8ba3ec4SArtem Dergachev     // trigger-statement (InitListExpr in this case) passed down from CFG or
456e8ba3ec4SArtem Dergachev     // otherwise always available during construction.
457e8ba3ec4SArtem Dergachev     if (dyn_cast_or_null<InitListExpr>(LCtx->getParentMap().getParent(CE))) {
458e8ba3ec4SArtem Dergachev       MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
459f83d5479SArtem Dergachev       Target = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(CE, LCtx));
460168e29f6SArtem Dergachev       CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
461e8ba3ec4SArtem Dergachev       break;
462e8ba3ec4SArtem Dergachev     }
4634dc0b1acSReid Kleckner     LLVM_FALLTHROUGH;
464b970505dSJordan Rose   case CXXConstructExpr::CK_Delegating: {
465b970505dSJordan Rose     const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
466b970505dSJordan Rose     Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
467dd18b11bSGeorge Karpenkov                                               LCtx->getStackFrame());
46805375eb4SJordan Rose     SVal ThisVal = State->getSVal(ThisPtr);
469b970505dSJordan Rose 
470b970505dSJordan Rose     if (CE->getConstructionKind() == CXXConstructExpr::CK_Delegating) {
471f83d5479SArtem Dergachev       Target = ThisVal;
472b970505dSJordan Rose     } else {
473b970505dSJordan Rose       // Cast to the base type.
474599f85abSJordan Rose       bool IsVirtual =
475599f85abSJordan Rose         (CE->getConstructionKind() == CXXConstructExpr::CK_VirtualBase);
476599f85abSJordan Rose       SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, CE->getType(),
477599f85abSJordan Rose                                                          IsVirtual);
478f83d5479SArtem Dergachev       Target = BaseVal;
479b970505dSJordan Rose     }
480b970505dSJordan Rose     break;
481b970505dSJordan Rose   }
482b970505dSJordan Rose   }
483b970505dSJordan Rose 
484239452caSArtem Dergachev   if (State != Pred->getState()) {
485239452caSArtem Dergachev     static SimpleProgramPointTag T("ExprEngine",
486239452caSArtem Dergachev                                    "Prepare for object construction");
487239452caSArtem Dergachev     ExplodedNodeSet DstPrepare;
488239452caSArtem Dergachev     StmtNodeBuilder BldrPrepare(Pred, DstPrepare, *currBldrCtx);
489239452caSArtem Dergachev     BldrPrepare.generateNode(CE, Pred, State, &T, ProgramPoint::PreStmtKind);
490239452caSArtem Dergachev     assert(DstPrepare.size() <= 1);
491239452caSArtem Dergachev     if (DstPrepare.size() == 0)
492239452caSArtem Dergachev       return;
493239452caSArtem Dergachev     Pred = *BldrPrepare.begin();
494239452caSArtem Dergachev   }
495239452caSArtem Dergachev 
496fcd016e5SJordan Rose   CallEventManager &CEMgr = getStateManager().getCallEventManager();
497fcd016e5SJordan Rose   CallEventRef<CXXConstructorCall> Call =
498f83d5479SArtem Dergachev     CEMgr.getCXXConstructorCall(CE, Target.getAsRegion(), State, LCtx);
49910e25031STed Kremenek 
500f3c12ac3SJordan Rose   ExplodedNodeSet DstPreVisit;
501f3c12ac3SJordan Rose   getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, CE, *this);
502b8e28654SJordan Rose 
503661ab34aSArtem Dergachev   // FIXME: Is it possible and/or useful to do this before PreStmt?
504b8e28654SJordan Rose   ExplodedNodeSet PreInitialized;
505b8e28654SJordan Rose   {
506b8e28654SJordan Rose     StmtNodeBuilder Bldr(DstPreVisit, PreInitialized, *currBldrCtx);
507b8e28654SJordan Rose     for (ExplodedNodeSet::iterator I = DstPreVisit.begin(),
508b8e28654SJordan Rose                                    E = DstPreVisit.end();
509b8e28654SJordan Rose          I != E; ++I) {
510b8e28654SJordan Rose       ProgramStateRef State = (*I)->getState();
511661ab34aSArtem Dergachev       if (CE->requiresZeroInitialization()) {
512b8e28654SJordan Rose         // FIXME: Once we properly handle constructors in new-expressions, we'll
513b8e28654SJordan Rose         // need to invalidate the region before setting a default value, to make
514b8e28654SJordan Rose         // sure there aren't any lingering bindings around. This probably needs
515b8e28654SJordan Rose         // to happen regardless of whether or not the object is zero-initialized
516b8e28654SJordan Rose         // to handle random fields of a placement-initialized object picking up
517b8e28654SJordan Rose         // old bindings. We might only want to do it when we need to, though.
518b8e28654SJordan Rose         // FIXME: This isn't actually correct for arrays -- we need to zero-
519b8e28654SJordan Rose         // initialize the entire array, not just the first element -- but our
520b8e28654SJordan Rose         // handling of arrays everywhere else is weak as well, so this shouldn't
521b8e28654SJordan Rose         // actually make things worse. Placement new makes this tricky as well,
522b8e28654SJordan Rose         // since it's then possible to be initializing one part of a multi-
523b8e28654SJordan Rose         // dimensional array.
524f83d5479SArtem Dergachev         State = State->bindDefaultZero(Target, LCtx);
525661ab34aSArtem Dergachev       }
526661ab34aSArtem Dergachev 
5270dbb783cSCraig Topper       Bldr.generateNode(CE, *I, State, /*tag=*/nullptr,
5280dbb783cSCraig Topper                         ProgramPoint::PreStmtKind);
529b8e28654SJordan Rose     }
530b8e28654SJordan Rose   }
531b8e28654SJordan Rose 
532afe7c2c2SJordan Rose   ExplodedNodeSet DstPreCall;
533b8e28654SJordan Rose   getCheckerManager().runCheckersForPreCall(DstPreCall, PreInitialized,
534fcd016e5SJordan Rose                                             *Call, *this);
53510e25031STed Kremenek 
53688bb563cSJordan Rose   ExplodedNodeSet DstEvaluated;
53788bb563cSJordan Rose   StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx);
53888bb563cSJordan Rose 
539e83cb092SJordan Rose   if (CE->getConstructor()->isTrivial() &&
540e83cb092SJordan Rose       CE->getConstructor()->isCopyOrMoveConstructor() &&
541168e29f6SArtem Dergachev       !CallOpts.IsArrayCtorOrDtor) {
542e83cb092SJordan Rose     // FIXME: Handle other kinds of trivial constructors as well.
543e83cb092SJordan Rose     for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
54488bb563cSJordan Rose          I != E; ++I)
54588bb563cSJordan Rose       performTrivialCopy(Bldr, *I, *Call);
54688bb563cSJordan Rose 
54788bb563cSJordan Rose   } else {
548afe7c2c2SJordan Rose     for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
549f3c12ac3SJordan Rose          I != E; ++I)
550690ab040SArtem Dergachev       defaultEvalCall(Bldr, *I, *Call, CallOpts);
55188bb563cSJordan Rose   }
55210e25031STed Kremenek 
5532a8c18d9SAlexander Kornienko   // If the CFG was constructed without elements for temporary destructors
5545b1ee2faSDevin Coughlin   // and the just-called constructor created a temporary object then
5555b1ee2faSDevin Coughlin   // stop exploration if the temporary object has a noreturn constructor.
5565b1ee2faSDevin Coughlin   // This can lose coverage because the destructor, if it were present
5575b1ee2faSDevin Coughlin   // in the CFG, would be called at the end of the full expression or
5585b1ee2faSDevin Coughlin   // later (for life-time extended temporaries) -- but avoids infeasible
5595b1ee2faSDevin Coughlin   // paths when no-return temporary destructors are used for assertions.
5605b1ee2faSDevin Coughlin   const AnalysisDeclContext *ADC = LCtx->getAnalysisDeclContext();
5615b1ee2faSDevin Coughlin   if (!ADC->getCFGBuildOptions().AddTemporaryDtors) {
5625b1ee2faSDevin Coughlin     const MemRegion *Target = Call->getCXXThisVal().getAsRegion();
5635b1ee2faSDevin Coughlin     if (Target && isa<CXXTempObjectRegion>(Target) &&
5645b1ee2faSDevin Coughlin         Call->getDecl()->getParent()->isAnyDestructorNoReturn()) {
5655b1ee2faSDevin Coughlin 
5663da72051SArtem Dergachev       // If we've inlined the constructor, then DstEvaluated would be empty.
5673da72051SArtem Dergachev       // In this case we still want a sink, which could be implemented
5683da72051SArtem Dergachev       // in processCallExit. But we don't have that implemented at the moment,
5693da72051SArtem Dergachev       // so if you hit this assertion, see if you can avoid inlining
5703da72051SArtem Dergachev       // the respective constructor when analyzer-config cfg-temporary-dtors
5713da72051SArtem Dergachev       // is set to false.
5723da72051SArtem Dergachev       // Otherwise there's nothing wrong with inlining such constructor.
5733da72051SArtem Dergachev       assert(!DstEvaluated.empty() &&
5743da72051SArtem Dergachev              "We should not have inlined this constructor!");
5753da72051SArtem Dergachev 
5765b1ee2faSDevin Coughlin       for (ExplodedNode *N : DstEvaluated) {
5775b1ee2faSDevin Coughlin         Bldr.generateSink(CE, N, N->getState());
5785b1ee2faSDevin Coughlin       }
5795b1ee2faSDevin Coughlin 
5805b1ee2faSDevin Coughlin       // There is no need to run the PostCall and PostStmt checker
5815b1ee2faSDevin Coughlin       // callbacks because we just generated sinks on all nodes in th
5825b1ee2faSDevin Coughlin       // frontier.
5835b1ee2faSDevin Coughlin       return;
5845b1ee2faSDevin Coughlin     }
5855b1ee2faSDevin Coughlin   }
5865b1ee2faSDevin Coughlin 
5873ccf14ebSArtem Dergachev   ExplodedNodeSet DstPostArgumentCleanup;
5883ccf14ebSArtem Dergachev   for (auto I : DstEvaluated)
5893ccf14ebSArtem Dergachev     finishArgumentConstruction(DstPostArgumentCleanup, I, *Call);
5903ccf14ebSArtem Dergachev 
5913ccf14ebSArtem Dergachev   // If there were other constructors called for object-type arguments
5923ccf14ebSArtem Dergachev   // of this constructor, clean them up.
593afe7c2c2SJordan Rose   ExplodedNodeSet DstPostCall;
5943ccf14ebSArtem Dergachev   getCheckerManager().runCheckersForPostCall(DstPostCall,
5953ccf14ebSArtem Dergachev                                              DstPostArgumentCleanup,
596fcd016e5SJordan Rose                                              *Call, *this);
597afe7c2c2SJordan Rose   getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, CE, *this);
59810e25031STed Kremenek }
59910e25031STed Kremenek 
600b970505dSJordan Rose void ExprEngine::VisitCXXDestructor(QualType ObjectType,
60110e25031STed Kremenek                                     const MemRegion *Dest,
60210e25031STed Kremenek                                     const Stmt *S,
6032bc9674bSJordan Rose                                     bool IsBaseDtor,
60410e25031STed Kremenek                                     ExplodedNode *Pred,
605168e29f6SArtem Dergachev                                     ExplodedNodeSet &Dst,
606168e29f6SArtem Dergachev                                     const EvalCallOptions &CallOpts) {
607fcd016e5SJordan Rose   const LocationContext *LCtx = Pred->getLocationContext();
608fcd016e5SJordan Rose   ProgramStateRef State = Pred->getState();
609fcd016e5SJordan Rose 
610b970505dSJordan Rose   const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl();
611b970505dSJordan Rose   assert(RecordDecl && "Only CXXRecordDecls should have destructors");
612b970505dSJordan Rose   const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
613b970505dSJordan Rose 
614fcd016e5SJordan Rose   CallEventManager &CEMgr = getStateManager().getCallEventManager();
615fcd016e5SJordan Rose   CallEventRef<CXXDestructorCall> Call =
6162bc9674bSJordan Rose     CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx);
617142adc49STed Kremenek 
61817a8757aSJordan Rose   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
61917a8757aSJordan Rose                                 Call->getSourceRange().getBegin(),
62017a8757aSJordan Rose                                 "Error evaluating destructor");
62117a8757aSJordan Rose 
6224ee71b8aSJordan Rose   ExplodedNodeSet DstPreCall;
6234ee71b8aSJordan Rose   getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
624fcd016e5SJordan Rose                                             *Call, *this);
62510e25031STed Kremenek 
6264ee71b8aSJordan Rose   ExplodedNodeSet DstInvalidated;
627d94854a4STed Kremenek   StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
6284ee71b8aSJordan Rose   for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
6294ee71b8aSJordan Rose        I != E; ++I)
630690ab040SArtem Dergachev     defaultEvalCall(Bldr, *I, *Call, CallOpts);
6314ee71b8aSJordan Rose 
6324ee71b8aSJordan Rose   ExplodedNodeSet DstPostCall;
6334ee71b8aSJordan Rose   getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
634fcd016e5SJordan Rose                                              *Call, *this);
63510e25031STed Kremenek }
63610e25031STed Kremenek 
6378b808d64SJordan Rose void ExprEngine::VisitCXXNewAllocatorCall(const CXXNewExpr *CNE,
6388b808d64SJordan Rose                                           ExplodedNode *Pred,
6398b808d64SJordan Rose                                           ExplodedNodeSet &Dst) {
6408b808d64SJordan Rose   ProgramStateRef State = Pred->getState();
6418b808d64SJordan Rose   const LocationContext *LCtx = Pred->getLocationContext();
6428b808d64SJordan Rose   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
643a6e4358fSStephen Kelly                                 CNE->getBeginLoc(),
6448b808d64SJordan Rose                                 "Error evaluating New Allocator Call");
6458b808d64SJordan Rose   CallEventManager &CEMgr = getStateManager().getCallEventManager();
6468b808d64SJordan Rose   CallEventRef<CXXAllocatorCall> Call =
6478b808d64SJordan Rose     CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
6488b808d64SJordan Rose 
6498b808d64SJordan Rose   ExplodedNodeSet DstPreCall;
6508b808d64SJordan Rose   getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
6518b808d64SJordan Rose                                             *Call, *this);
6528b808d64SJordan Rose 
65355796302SArtem Dergachev   ExplodedNodeSet DstPostCall;
65455796302SArtem Dergachev   StmtNodeBuilder CallBldr(DstPreCall, DstPostCall, *currBldrCtx);
6551084de52SArtem Dergachev   for (auto I : DstPreCall) {
6561084de52SArtem Dergachev     // FIXME: Provide evalCall for checkers?
65755796302SArtem Dergachev     defaultEvalCall(CallBldr, I, *Call);
6581084de52SArtem Dergachev   }
659beba5307SArtem Dergachev   // If the call is inlined, DstPostCall will be empty and we bail out now.
66055796302SArtem Dergachev 
66155796302SArtem Dergachev   // Store return value of operator new() for future use, until the actual
66255796302SArtem Dergachev   // CXXNewExpr gets processed.
66355796302SArtem Dergachev   ExplodedNodeSet DstPostValue;
66455796302SArtem Dergachev   StmtNodeBuilder ValueBldr(DstPostCall, DstPostValue, *currBldrCtx);
66555796302SArtem Dergachev   for (auto I : DstPostCall) {
666beba5307SArtem Dergachev     // FIXME: Because CNE serves as the "call site" for the allocator (due to
667beba5307SArtem Dergachev     // lack of a better expression in the AST), the conjured return value symbol
668beba5307SArtem Dergachev     // is going to be of the same type (C++ object pointer type). Technically
669beba5307SArtem Dergachev     // this is not correct because the operator new's prototype always says that
670beba5307SArtem Dergachev     // it returns a 'void *'. So we should change the type of the symbol,
671beba5307SArtem Dergachev     // and then evaluate the cast over the symbolic pointer from 'void *' to
672beba5307SArtem Dergachev     // the object pointer type. But without changing the symbol's type it
673beba5307SArtem Dergachev     // is breaking too much to evaluate the no-op symbolic cast over it, so we
674beba5307SArtem Dergachev     // skip it for now.
67555796302SArtem Dergachev     ProgramStateRef State = I->getState();
67650e0372fSArtem Dergachev     SVal RetVal = State->getSVal(CNE, LCtx);
67750e0372fSArtem Dergachev 
67850e0372fSArtem Dergachev     // If this allocation function is not declared as non-throwing, failures
67950e0372fSArtem Dergachev     // /must/ be signalled by exceptions, and thus the return value will never
68050e0372fSArtem Dergachev     // be NULL. -fno-exceptions does not influence this semantics.
68150e0372fSArtem Dergachev     // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
68250e0372fSArtem Dergachev     // where new can return NULL. If we end up supporting that option, we can
68350e0372fSArtem Dergachev     // consider adding a check for it here.
68450e0372fSArtem Dergachev     // C++11 [basic.stc.dynamic.allocation]p3.
68550e0372fSArtem Dergachev     if (const FunctionDecl *FD = CNE->getOperatorNew()) {
68650e0372fSArtem Dergachev       QualType Ty = FD->getType();
68750e0372fSArtem Dergachev       if (const auto *ProtoType = Ty->getAs<FunctionProtoType>())
688eaf11ad7SRichard Smith         if (!ProtoType->isNothrow())
68950e0372fSArtem Dergachev           State = State->assume(RetVal.castAs<DefinedOrUnknownSVal>(), true);
69050e0372fSArtem Dergachev     }
69150e0372fSArtem Dergachev 
692f83d5479SArtem Dergachev     ValueBldr.generateNode(
693f83d5479SArtem Dergachev         CNE, I, addObjectUnderConstruction(State, CNE, LCtx, RetVal));
69455796302SArtem Dergachev   }
69555796302SArtem Dergachev 
69613b2026bSArtem Dergachev   ExplodedNodeSet DstPostPostCallCallback;
69713b2026bSArtem Dergachev   getCheckerManager().runCheckersForPostCall(DstPostPostCallCallback,
69813b2026bSArtem Dergachev                                              DstPostValue, *Call, *this);
69913b2026bSArtem Dergachev   for (auto I : DstPostPostCallCallback) {
70013b2026bSArtem Dergachev     getCheckerManager().runCheckersForNewAllocator(
701f83d5479SArtem Dergachev         CNE, *getObjectUnderConstruction(I->getState(), CNE, LCtx), Dst, I,
702f83d5479SArtem Dergachev         *this);
70313b2026bSArtem Dergachev   }
7048b808d64SJordan Rose }
7058b808d64SJordan Rose 
70610e25031STed Kremenek void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
70710e25031STed Kremenek                                    ExplodedNodeSet &Dst) {
708a4ee064cSJordan Rose   // FIXME: Much of this should eventually migrate to CXXAllocatorCall.
709a4ee064cSJordan Rose   // Also, we need to decide how allocators actually work -- they're not
710a4ee064cSJordan Rose   // really part of the CXXNewExpr because they happen BEFORE the
711a4ee064cSJordan Rose   // CXXConstructExpr subexpression. See PR12014 for some discussion.
71210e25031STed Kremenek 
713d94854a4STed Kremenek   unsigned blockCount = currBldrCtx->blockCount();
714d519cae8STed Kremenek   const LocationContext *LCtx = Pred->getLocationContext();
71555796302SArtem Dergachev   SVal symVal = UnknownVal();
7168b662704SAnton Yartsev   FunctionDecl *FD = CNE->getOperatorNew();
71710e25031STed Kremenek 
7181084de52SArtem Dergachev   bool IsStandardGlobalOpNewFunction =
7191084de52SArtem Dergachev       FD->isReplaceableGlobalAllocationFunction();
7208b662704SAnton Yartsev 
72155796302SArtem Dergachev   ProgramStateRef State = Pred->getState();
72255796302SArtem Dergachev 
72355796302SArtem Dergachev   // Retrieve the stored operator new() return value.
724549f9cd4SKristof Umann   if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
725f83d5479SArtem Dergachev     symVal = *getObjectUnderConstruction(State, CNE, LCtx);
726f83d5479SArtem Dergachev     State = finishObjectConstruction(State, CNE, LCtx);
72755796302SArtem Dergachev   }
72855796302SArtem Dergachev 
7298b662704SAnton Yartsev   // We assume all standard global 'operator new' functions allocate memory in
7308b662704SAnton Yartsev   // heap. We realize this is an approximation that might not correctly model
7318b662704SAnton Yartsev   // a custom global allocator.
73255796302SArtem Dergachev   if (symVal.isUnknown()) {
7338b662704SAnton Yartsev     if (IsStandardGlobalOpNewFunction)
7348b662704SAnton Yartsev       symVal = svalBuilder.getConjuredHeapSymbolVal(CNE, LCtx, blockCount);
7358b662704SAnton Yartsev     else
7360dbb783cSCraig Topper       symVal = svalBuilder.conjureSymbolVal(nullptr, CNE, LCtx, CNE->getType(),
7378b662704SAnton Yartsev                                             blockCount);
73855796302SArtem Dergachev   }
7398b662704SAnton Yartsev 
740fcd016e5SJordan Rose   CallEventManager &CEMgr = getStateManager().getCallEventManager();
741fcd016e5SJordan Rose   CallEventRef<CXXAllocatorCall> Call =
742fcd016e5SJordan Rose     CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
743fcd016e5SJordan Rose 
744549f9cd4SKristof Umann   if (!AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
745a4ee064cSJordan Rose     // Invalidate placement args.
746fcd016e5SJordan Rose     // FIXME: Once we figure out how we want allocators to work,
747fcd016e5SJordan Rose     // we should be using the usual pre-/(default-)eval-/post-call checks here.
748fcd016e5SJordan Rose     State = Call->invalidateRegions(blockCount);
749b8cb8359SJordan Rose     if (!State)
750b8cb8359SJordan Rose       return;
751a4ee064cSJordan Rose 
752fce1b03eSPavel Labath     // If this allocation function is not declared as non-throwing, failures
75350e0372fSArtem Dergachev     // /must/ be signalled by exceptions, and thus the return value will never
75450e0372fSArtem Dergachev     // be NULL. -fno-exceptions does not influence this semantics.
755fce1b03eSPavel Labath     // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
756fce1b03eSPavel Labath     // where new can return NULL. If we end up supporting that option, we can
757fce1b03eSPavel Labath     // consider adding a check for it here.
7583957fd58SJordan Rose     // C++11 [basic.stc.dynamic.allocation]p3.
759fce1b03eSPavel Labath     if (FD) {
7603957fd58SJordan Rose       QualType Ty = FD->getType();
76150e0372fSArtem Dergachev       if (const auto *ProtoType = Ty->getAs<FunctionProtoType>())
762eaf11ad7SRichard Smith         if (!ProtoType->isNothrow())
76355796302SArtem Dergachev           if (auto dSymVal = symVal.getAs<DefinedOrUnknownSVal>())
76455796302SArtem Dergachev             State = State->assume(*dSymVal, true);
7653957fd58SJordan Rose     }
76650e0372fSArtem Dergachev   }
7673957fd58SJordan Rose 
768b8cb8359SJordan Rose   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
769b8cb8359SJordan Rose 
770beba5307SArtem Dergachev   SVal Result = symVal;
771beba5307SArtem Dergachev 
77210e25031STed Kremenek   if (CNE->isArray()) {
77310e25031STed Kremenek     // FIXME: allocating an array requires simulating the constructors.
77410e25031STed Kremenek     // For now, just return a symbolicated region.
7751084de52SArtem Dergachev     if (const SubRegion *NewReg =
7761084de52SArtem Dergachev             dyn_cast_or_null<SubRegion>(symVal.getAsRegion())) {
777a4ee064cSJordan Rose       QualType ObjTy = CNE->getType()->getAs<PointerType>()->getPointeeType();
778a4ee064cSJordan Rose       const ElementRegion *EleReg =
779a4ee064cSJordan Rose           getStoreManager().GetElementZeroRegion(NewReg, ObjTy);
780beba5307SArtem Dergachev       Result = loc::MemRegionVal(EleReg);
781beba5307SArtem Dergachev     }
782beba5307SArtem Dergachev     State = State->BindExpr(CNE, Pred->getLocationContext(), Result);
78344320367SJordan Rose     Bldr.generateNode(CNE, Pred, State);
78410e25031STed Kremenek     return;
78510e25031STed Kremenek   }
78610e25031STed Kremenek 
787a4ee064cSJordan Rose   // FIXME: Once we have proper support for CXXConstructExprs inside
788a4ee064cSJordan Rose   // CXXNewExpr, we need to make sure that the constructed object is not
789a4ee064cSJordan Rose   // immediately invalidated here. (The placement call should happen before
790a4ee064cSJordan Rose   // the constructor call anyway.)
79144320367SJordan Rose   if (FD && FD->isReservedGlobalPlacementOperator()) {
79244320367SJordan Rose     // Non-array placement new should always return the placement location.
79344320367SJordan Rose     SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx);
794b8cb8359SJordan Rose     Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(),
795aaf83184SJordan Rose                                   CNE->getPlacementArg(0)->getType());
79644320367SJordan Rose   }
79744320367SJordan Rose 
798b8cb8359SJordan Rose   // Bind the address of the object, then check to see if we cached out.
799b8cb8359SJordan Rose   State = State->BindExpr(CNE, LCtx, Result);
8008f6b4b04SJordan Rose   ExplodedNode *NewN = Bldr.generateNode(CNE, Pred, State);
8018f6b4b04SJordan Rose   if (!NewN)
8028f6b4b04SJordan Rose     return;
8033503cb35SJordan Rose 
8045089f3b3SJordan Rose   // If the type is not a record, we won't have a CXXConstructExpr as an
8055089f3b3SJordan Rose   // initializer. Copy the value over.
8065089f3b3SJordan Rose   if (const Expr *Init = CNE->getInitializer()) {
8075089f3b3SJordan Rose     if (!isa<CXXConstructExpr>(Init)) {
8083503cb35SJordan Rose       assert(Bldr.getResults().size() == 1);
8098f6b4b04SJordan Rose       Bldr.takeNodes(NewN);
810b8cb8359SJordan Rose       evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, LCtx),
811b8cb8359SJordan Rose                /*FirstInit=*/IsStandardGlobalOpNewFunction);
8123503cb35SJordan Rose     }
8133503cb35SJordan Rose   }
81410e25031STed Kremenek }
81510e25031STed Kremenek 
81610e25031STed Kremenek void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE,
81710e25031STed Kremenek                                     ExplodedNode *Pred, ExplodedNodeSet &Dst) {
818d94854a4STed Kremenek   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
81964aea652SErik Verbruggen   ProgramStateRef state = Pred->getState();
82064aea652SErik Verbruggen   Bldr.generateNode(CDE, Pred, state);
82110e25031STed Kremenek }
82210e25031STed Kremenek 
8238fdb59f9STed Kremenek void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS,
8248fdb59f9STed Kremenek                                    ExplodedNode *Pred,
8258fdb59f9STed Kremenek                                    ExplodedNodeSet &Dst) {
8268fdb59f9STed Kremenek   const VarDecl *VD = CS->getExceptionDecl();
827b1279b5cSTed Kremenek   if (!VD) {
828b1279b5cSTed Kremenek     Dst.Add(Pred);
829b1279b5cSTed Kremenek     return;
830b1279b5cSTed Kremenek   }
831b1279b5cSTed Kremenek 
8328fdb59f9STed Kremenek   const LocationContext *LCtx = Pred->getLocationContext();
833d227833cSTed Kremenek   SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(),
834d94854a4STed Kremenek                                         currBldrCtx->blockCount());
8358fdb59f9STed Kremenek   ProgramStateRef state = Pred->getState();
836b570195cSAnna Zaks   state = state->bindLoc(state->getLValue(VD, LCtx), V, LCtx);
8378fdb59f9STed Kremenek 
838d94854a4STed Kremenek   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
8398fdb59f9STed Kremenek   Bldr.generateNode(CS, Pred, state);
8408fdb59f9STed Kremenek }
8418fdb59f9STed Kremenek 
84210e25031STed Kremenek void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
84310e25031STed Kremenek                                     ExplodedNodeSet &Dst) {
844d94854a4STed Kremenek   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
845e594034fSAnna Zaks 
84610e25031STed Kremenek   // Get the this object region from StoreManager.
847632e3b7eSTed Kremenek   const LocationContext *LCtx = Pred->getLocationContext();
84810e25031STed Kremenek   const MemRegion *R =
84910e25031STed Kremenek     svalBuilder.getRegionManager().getCXXThisRegion(
85010e25031STed Kremenek                                   getContext().getCanonicalType(TE->getType()),
851632e3b7eSTed Kremenek                                                     LCtx);
85210e25031STed Kremenek 
85349b1e38eSTed Kremenek   ProgramStateRef state = Pred->getState();
85410e25031STed Kremenek   SVal V = state->getSVal(loc::MemRegionVal(R));
855632e3b7eSTed Kremenek   Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V));
85610e25031STed Kremenek }
85715843343SGabor Horvath 
85815843343SGabor Horvath void ExprEngine::VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred,
85915843343SGabor Horvath                                  ExplodedNodeSet &Dst) {
86015843343SGabor Horvath   const LocationContext *LocCtxt = Pred->getLocationContext();
86115843343SGabor Horvath 
86215843343SGabor Horvath   // Get the region of the lambda itself.
86315843343SGabor Horvath   const MemRegion *R = svalBuilder.getRegionManager().getCXXTempObjectRegion(
86415843343SGabor Horvath       LE, LocCtxt);
86515843343SGabor Horvath   SVal V = loc::MemRegionVal(R);
86615843343SGabor Horvath 
86715843343SGabor Horvath   ProgramStateRef State = Pred->getState();
86815843343SGabor Horvath 
86915843343SGabor Horvath   // If we created a new MemRegion for the lambda, we should explicitly bind
87015843343SGabor Horvath   // the captures.
87115843343SGabor Horvath   CXXRecordDecl::field_iterator CurField = LE->getLambdaClass()->field_begin();
87215843343SGabor Horvath   for (LambdaExpr::const_capture_init_iterator i = LE->capture_init_begin(),
87315843343SGabor Horvath                                                e = LE->capture_init_end();
87415843343SGabor Horvath        i != e; ++i, ++CurField) {
8757bdca8b2SDevin Coughlin     FieldDecl *FieldForCapture = *CurField;
8767bdca8b2SDevin Coughlin     SVal FieldLoc = State->getLValue(FieldForCapture, V);
8777bdca8b2SDevin Coughlin 
8787bdca8b2SDevin Coughlin     SVal InitVal;
8797bdca8b2SDevin Coughlin     if (!FieldForCapture->hasCapturedVLAType()) {
8807bdca8b2SDevin Coughlin       Expr *InitExpr = *i;
8817bdca8b2SDevin Coughlin       assert(InitExpr && "Capture missing initialization expression");
8827bdca8b2SDevin Coughlin       InitVal = State->getSVal(InitExpr, LocCtxt);
8837bdca8b2SDevin Coughlin     } else {
8847bdca8b2SDevin Coughlin       // The field stores the length of a captured variable-length array.
8857bdca8b2SDevin Coughlin       // These captures don't have initialization expressions; instead we
8867bdca8b2SDevin Coughlin       // get the length from the VLAType size expression.
8877bdca8b2SDevin Coughlin       Expr *SizeExpr = FieldForCapture->getCapturedVLAType()->getSizeExpr();
8887bdca8b2SDevin Coughlin       InitVal = State->getSVal(SizeExpr, LocCtxt);
8897bdca8b2SDevin Coughlin     }
8907bdca8b2SDevin Coughlin 
891b570195cSAnna Zaks     State = State->bindLoc(FieldLoc, InitVal, LocCtxt);
89215843343SGabor Horvath   }
89315843343SGabor Horvath 
89415843343SGabor Horvath   // Decay the Loc into an RValue, because there might be a
89515843343SGabor Horvath   // MaterializeTemporaryExpr node above this one which expects the bound value
89615843343SGabor Horvath   // to be an RValue.
89715843343SGabor Horvath   SVal LambdaRVal = State->getSVal(R);
89815843343SGabor Horvath 
89915843343SGabor Horvath   ExplodedNodeSet Tmp;
90015843343SGabor Horvath   StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
90115843343SGabor Horvath   // FIXME: is this the right program point kind?
90215843343SGabor Horvath   Bldr.generateNode(LE, Pred,
90315843343SGabor Horvath                     State->BindExpr(LE, LocCtxt, LambdaRVal),
90415843343SGabor Horvath                     nullptr, ProgramPoint::PostLValueKind);
90515843343SGabor Horvath 
90615843343SGabor Horvath   // FIXME: Move all post/pre visits to ::Visit().
90715843343SGabor Horvath   getCheckerManager().runCheckersForPostStmt(Dst, Tmp, LE, *this);
90815843343SGabor Horvath }
909