Coverage Report

Created: 2020-09-19 12:23

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ExprEngineCXX.cpp - ExprEngine support for C++ -----------*- C++ -*-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file defines the C++ expression evaluation engine.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
14
#include "clang/Analysis/ConstructionContext.h"
15
#include "clang/AST/DeclCXX.h"
16
#include "clang/AST/StmtCXX.h"
17
#include "clang/AST/ParentMap.h"
18
#include "clang/Basic/PrettyStackTrace.h"
19
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
20
#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
21
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22
23
using namespace clang;
24
using namespace ento;
25
26
void ExprEngine::CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
27
                                          ExplodedNode *Pred,
28
9.18k
                                          ExplodedNodeSet &Dst) {
29
9.18k
  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
30
9.18k
  const Expr *tempExpr = ME->getSubExpr()->IgnoreParens();
31
9.18k
  ProgramStateRef state = Pred->getState();
32
9.18k
  const LocationContext *LCtx = Pred->getLocationContext();
33
9.18k
34
9.18k
  state = createTemporaryRegionIfNeeded(state, LCtx, tempExpr, ME);
35
9.18k
  Bldr.generateNode(ME, Pred, state);
36
9.18k
}
37
38
// FIXME: This is the sort of code that should eventually live in a Core
39
// checker rather than as a special case in ExprEngine.
40
void ExprEngine::performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred,
41
12.6k
                                    const CallEvent &Call) {
42
12.6k
  SVal ThisVal;
43
12.6k
  bool AlwaysReturnsLValue;
44
12.6k
  const CXXRecordDecl *ThisRD = nullptr;
45
12.6k
  if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) {
46
12.5k
    assert(Ctor->getDecl()->isTrivial());
47
12.5k
    assert(Ctor->getDecl()->isCopyOrMoveConstructor());
48
12.5k
    ThisVal = Ctor->getCXXThisVal();
49
12.5k
    ThisRD = Ctor->getDecl()->getParent();
50
12.5k
    AlwaysReturnsLValue = false;
51
110
  } else {
52
110
    assert(cast<CXXMethodDecl>(Call.getDecl())->isTrivial());
53
110
    assert(cast<CXXMethodDecl>(Call.getDecl())->getOverloadedOperator() ==
54
110
           OO_Equal);
55
110
    ThisVal = cast<CXXInstanceCall>(Call).getCXXThisVal();
56
110
    ThisRD = cast<CXXMethodDecl>(Call.getDecl())->getParent();
57
110
    AlwaysReturnsLValue = true;
58
110
  }
59
12.6k
60
12.6k
  assert(ThisRD);
61
12.6k
  if (ThisRD->isEmpty()) {
62
    // Do nothing for empty classes. Otherwise it'd retrieve an UnknownVal
63
    // and bind it and RegionStore would think that the actual value
64
    // in this region at this offset is unknown.
65
1.74k
    return;
66
1.74k
  }
67
10.8k
68
10.8k
  const LocationContext *LCtx = Pred->getLocationContext();
69
10.8k
70
10.8k
  ExplodedNodeSet Dst;
71
10.8k
  Bldr.takeNodes(Pred);
72
10.8k
73
10.8k
  SVal V = Call.getArgSVal(0);
74
10.8k
75
  // If the value being copied is not unknown, load from its location to get
76
  // an aggregate rvalue.
77
10.8k
  if (Optional<Loc> L = V.getAs<Loc>())
78
10.8k
    V = Pred->getState()->getSVal(*L);
79
10.8k
  else
80
10.8k
    assert(V.isUnknownOrUndef());
81
10.8k
82
10.8k
  const Expr *CallExpr = Call.getOriginExpr();
83
10.8k
  evalBind(Dst, CallExpr, Pred, ThisVal, V, true);
84
10.8k
85
10.8k
  PostStmt PS(CallExpr, LCtx);
86
10.8k
  for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end();
87
21.7k
       I != E; 
++I10.8k
) {
88
10.8k
    ProgramStateRef State = (*I)->getState();
89
10.8k
    if (AlwaysReturnsLValue)
90
79
      State = State->BindExpr(CallExpr, LCtx, ThisVal);
91
10.7k
    else
92
10.7k
      State = bindReturnValue(Call, LCtx, State);
93
10.8k
    Bldr.generateNode(PS, State, *I);
94
10.8k
  }
95
10.8k
}
96
97
98
SVal ExprEngine::makeZeroElementRegion(ProgramStateRef State, SVal LValue,
99
10.5k
                                       QualType &Ty, bool &IsArray) {
100
10.5k
  SValBuilder &SVB = State->getStateManager().getSValBuilder();
101
10.5k
  ASTContext &Ctx = SVB.getContext();
102
10.5k
103
10.7k
  while (const ArrayType *AT = Ctx.getAsArrayType(Ty)) {
104
138
    Ty = AT->getElementType();
105
138
    LValue = State->getLValue(Ty, SVB.makeZeroArrayIndex(), LValue);
106
138
    IsArray = true;
107
138
  }
108
10.5k
109
10.5k
  return LValue;
110
10.5k
}
111
112
SVal ExprEngine::computeObjectUnderConstruction(
113
    const Expr *E, ProgramStateRef State, const LocationContext *LCtx,
114
33.3k
    const ConstructionContext *CC, EvalCallOptions &CallOpts) {
115
33.3k
  SValBuilder &SVB = getSValBuilder();
116
33.3k
  MemRegionManager &MRMgr = SVB.getRegionManager();
117
33.3k
  ASTContext &ACtx = SVB.getContext();
118
33.3k
119
  // Compute the target region by exploring the construction context.
120
33.3k
  if (CC) {
121
33.0k
    switch (CC->getKind()) {
122
7.36k
    case ConstructionContext::CXX17ElidedCopyVariableKind:
123
7.36k
    case ConstructionContext::SimpleVariableKind: {
124
7.36k
      const auto *DSCC = cast<VariableConstructionContext>(CC);
125
7.36k
      const auto *DS = DSCC->getDeclStmt();
126
7.36k
      const auto *Var = cast<VarDecl>(DS->getSingleDecl());
127
7.36k
      QualType Ty = Var->getType();
128
7.36k
      return makeZeroElementRegion(State, State->getLValue(Var, LCtx), Ty,
129
7.36k
                                   CallOpts.IsArrayCtorOrDtor);
130
7.36k
    }
131
2.57k
    case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind:
132
2.57k
    case ConstructionContext::SimpleConstructorInitializerKind: {
133
2.57k
      const auto *ICC = cast<ConstructorInitializerConstructionContext>(CC);
134
2.57k
      const auto *Init = ICC->getCXXCtorInitializer();
135
2.57k
      assert(Init->isAnyMemberInitializer());
136
2.57k
      const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
137
2.57k
      Loc ThisPtr = SVB.getCXXThis(CurCtor, LCtx->getStackFrame());
138
2.57k
      SVal ThisVal = State->getSVal(ThisPtr);
139
2.57k
140
2.57k
      const ValueDecl *Field;
141
2.57k
      SVal FieldVal;
142
2.57k
      if (Init->isIndirectMemberInitializer()) {
143
0
        Field = Init->getIndirectMember();
144
0
        FieldVal = State->getLValue(Init->getIndirectMember(), ThisVal);
145
2.57k
      } else {
146
2.57k
        Field = Init->getMember();
147
2.57k
        FieldVal = State->getLValue(Init->getMember(), ThisVal);
148
2.57k
      }
149
2.57k
150
2.57k
      QualType Ty = Field->getType();
151
2.57k
      return makeZeroElementRegion(State, FieldVal, Ty,
152
2.57k
                                   CallOpts.IsArrayCtorOrDtor);
153
2.57k
    }
154
490
    case ConstructionContext::NewAllocatedObjectKind: {
155
490
      if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
156
487
        const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
157
487
        const auto *NE = NECC->getCXXNewExpr();
158
487
        SVal V = *getObjectUnderConstruction(State, NE, LCtx);
159
487
        if (const SubRegion *MR =
160
475
                dyn_cast_or_null<SubRegion>(V.getAsRegion())) {
161
475
          if (NE->isArray()) {
162
            // TODO: In fact, we need to call the constructor for every
163
            // allocated element, not just the first one!
164
41
            CallOpts.IsArrayCtorOrDtor = true;
165
41
            return loc::MemRegionVal(getStoreManager().GetElementZeroRegion(
166
41
                MR, NE->getType()->getPointeeType()));
167
41
          }
168
434
          return  V;
169
434
        }
170
        // TODO: Detect when the allocator returns a null pointer.
171
        // Constructor shall not be called in this case.
172
487
      }
173
15
      break;
174
15
    }
175
2.60k
    case ConstructionContext::SimpleReturnedValueKind:
176
2.60k
    case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
177
      // The temporary is to be managed by the parent stack frame.
178
      // So build it in the parent stack frame if we're not in the
179
      // top frame of the analysis.
180
2.60k
      const StackFrameContext *SFC = LCtx->getStackFrame();
181
2.60k
      if (const LocationContext *CallerLCtx = SFC->getParent()) {
182
2.54k
        auto RTC = (*SFC->getCallSiteBlock())[SFC->getIndex()]
183
2.54k
                       .getAs<CFGCXXRecordTypedCall>();
184
2.54k
        if (!RTC) {
185
          // We were unable to find the correct construction context for the
186
          // call in the parent stack frame. This is equivalent to not being
187
          // able to find construction context at all.
188
379
          break;
189
379
        }
190
2.16k
        if (isa<BlockInvocationContext>(CallerLCtx)) {
191
          // Unwrap block invocation contexts. They're mostly part of
192
          // the current stack frame.
193
1
          CallerLCtx = CallerLCtx->getParent();
194
1
          assert(!isa<BlockInvocationContext>(CallerLCtx));
195
1
        }
196
2.16k
        return computeObjectUnderConstruction(
197
2.16k
            cast<Expr>(SFC->getCallSite()), State, CallerLCtx,
198
2.16k
            RTC->getConstructionContext(), CallOpts);
199
57
      } else {
200
        // We are on the top frame of the analysis. We do not know where is the
201
        // object returned to. Conjure a symbolic region for the return value.
202
        // TODO: We probably need a new MemRegion kind to represent the storage
203
        // of that SymbolicRegion, so that we cound produce a fancy symbol
204
        // instead of an anonymous conjured symbol.
205
        // TODO: Do we need to track the region to avoid having it dead
206
        // too early? It does die too early, at least in C++17, but because
207
        // putting anything into a SymbolicRegion causes an immediate escape,
208
        // it doesn't cause any leak false positives.
209
57
        const auto *RCC = cast<ReturnedValueConstructionContext>(CC);
210
        // Make sure that this doesn't coincide with any other symbol
211
        // conjured for the returned expression.
212
57
        static const int TopLevelSymRegionTag = 0;
213
57
        const Expr *RetE = RCC->getReturnStmt()->getRetValue();
214
57
        assert(RetE && "Void returns should not have a construction context");
215
57
        QualType ReturnTy = RetE->getType();
216
57
        QualType RegionTy = ACtx.getPointerType(ReturnTy);
217
57
        return SVB.conjureSymbolVal(&TopLevelSymRegionTag, RetE, SFC, RegionTy,
218
57
                                    currBldrCtx->blockCount());
219
57
      }
220
0
      llvm_unreachable("Unhandled return value construction context!");
221
0
    }
222
6.79k
    case ConstructionContext::ElidedTemporaryObjectKind: {
223
6.79k
      assert(AMgr.getAnalyzerOptions().ShouldElideConstructors);
224
6.79k
      const auto *TCC = cast<ElidedTemporaryObjectConstructionContext>(CC);
225
6.79k
226
      // Support pre-C++17 copy elision. We'll have the elidable copy
227
      // constructor in the AST and in the CFG, but we'll skip it
228
      // and construct directly into the final object. This call
229
      // also sets the CallOpts flags for us.
230
      // If the elided copy/move constructor is not supported, there's still
231
      // benefit in trying to model the non-elided constructor.
232
      // Stash our state before trying to elide, as it'll get overwritten.
233
6.79k
      ProgramStateRef PreElideState = State;
234
6.79k
      EvalCallOptions PreElideCallOpts = CallOpts;
235
6.79k
236
6.79k
      SVal V = computeObjectUnderConstruction(
237
6.79k
          TCC->getConstructorAfterElision(), State, LCtx,
238
6.79k
          TCC->getConstructionContextAfterElision(), CallOpts);
239
6.79k
240
      // FIXME: This definition of "copy elision has not failed" is unreliable.
241
      // It doesn't indicate that the constructor will actually be inlined
242
      // later; this is still up to evalCall() to decide.
243
6.79k
      if (!CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion)
244
6.66k
        return V;
245
131
246
      // Copy elision failed. Revert the changes and proceed as if we have
247
      // a simple temporary.
248
131
      CallOpts = PreElideCallOpts;
249
131
      CallOpts.IsElidableCtorThatHasNotBeenElided = true;
250
131
      LLVM_FALLTHROUGH;
251
131
    }
252
2.08k
    case ConstructionContext::SimpleTemporaryObjectKind: {
253
2.08k
      const auto *TCC = cast<TemporaryObjectConstructionContext>(CC);
254
2.08k
      const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr();
255
2.08k
256
2.08k
      CallOpts.IsTemporaryCtorOrDtor = true;
257
2.08k
      if (MTE) {
258
1.96k
        if (const ValueDecl *VD = MTE->getExtendingDecl()) {
259
183
          assert(MTE->getStorageDuration() != SD_FullExpression);
260
183
          if (!VD->getType()->isReferenceType()) {
261
            // We're lifetime-extended by a surrounding aggregate.
262
            // Automatic destructors aren't quite working in this case
263
            // on the CFG side. We should warn the caller about that.
264
            // FIXME: Is there a better way to retrieve this information from
265
            // the MaterializeTemporaryExpr?
266
24
            CallOpts.IsTemporaryLifetimeExtendedViaAggregate = true;
267
24
          }
268
183
        }
269
1.96k
270
1.96k
        if (MTE->getStorageDuration() == SD_Static ||
271
1.95k
            MTE->getStorageDuration() == SD_Thread)
272
14
          return loc::MemRegionVal(MRMgr.getCXXStaticTempObjectRegion(E));
273
2.06k
      }
274
2.06k
275
2.06k
      return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx));
276
2.06k
    }
277
11.2k
    case ConstructionContext::ArgumentKind: {
278
      // Arguments are technically temporaries.
279
11.2k
      CallOpts.IsTemporaryCtorOrDtor = true;
280
11.2k
281
11.2k
      const auto *ACC = cast<ArgumentConstructionContext>(CC);
282
11.2k
      const Expr *E = ACC->getCallLikeExpr();
283
11.2k
      unsigned Idx = ACC->getIndex();
284
11.2k
285
11.2k
      CallEventManager &CEMgr = getStateManager().getCallEventManager();
286
11.2k
      auto getArgLoc = [&](CallEventRef<> Caller) -> Optional<SVal> {
287
11.2k
        const LocationContext *FutureSFC =
288
11.2k
            Caller->getCalleeStackFrame(currBldrCtx->blockCount());
289
        // Return early if we are unable to reliably foresee
290
        // the future stack frame.
291
11.2k
        if (!FutureSFC)
292
0
          return None;
293
11.2k
294
        // This should be equivalent to Caller->getDecl() for now, but
295
        // FutureSFC->getDecl() is likely to support better stuff (like
296
        // virtual functions) earlier.
297
11.2k
        const Decl *CalleeD = FutureSFC->getDecl();
298
11.2k
299
        // FIXME: Support for variadic arguments is not implemented here yet.
300
11.2k
        if (CallEvent::isVariadic(CalleeD))
301
0
          return None;
302
11.2k
303
        // Operator arguments do not correspond to operator parameters
304
        // because this-argument is implemented as a normal argument in
305
        // operator call expressions but not in operator declarations.
306
11.2k
        const TypedValueRegion *TVR = Caller->getParameterLocation(
307
11.2k
            *Caller->getAdjustedParameterIndex(Idx), currBldrCtx->blockCount());
308
11.2k
        if (!TVR)
309
0
          return None;
310
11.2k
311
11.2k
        return loc::MemRegionVal(TVR);
312
11.2k
      };
313
11.2k
314
11.2k
      if (const auto *CE = dyn_cast<CallExpr>(E)) {
315
11.1k
        CallEventRef<> Caller = CEMgr.getSimpleCall(CE, State, LCtx);
316
11.1k
        if (Optional<SVal> V = getArgLoc(Caller))
317
11.1k
          return *V;
318
0
        else
319
0
          break;
320
58
      } else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) {
321
        // Don't bother figuring out the target region for the future
322
        // constructor because we won't need it.
323
48
        CallEventRef<> Caller =
324
48
            CEMgr.getCXXConstructorCall(CCE, /*Target=*/nullptr, State, LCtx);
325
48
        if (Optional<SVal> V = getArgLoc(Caller))
326
48
          return *V;
327
0
        else
328
0
          break;
329
10
      } else if (const auto *ME = dyn_cast<ObjCMessageExpr>(E)) {
330
10
        CallEventRef<> Caller = CEMgr.getObjCMethodCall(ME, State, LCtx);
331
10
        if (Optional<SVal> V = getArgLoc(Caller))
332
10
          return *V;
333
0
        else
334
0
          break;
335
693
      }
336
11.2k
    }
337
33.0k
    } // switch (CC->getKind())
338
33.0k
  }
339
693
340
  // If we couldn't find an existing region to construct into, assume we're
341
  // constructing a temporary. Notify the caller of our failure.
342
693
  CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
343
693
  return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx));
344
693
}
345
346
ProgramStateRef ExprEngine::updateObjectsUnderConstruction(
347
    SVal V, const Expr *E, ProgramStateRef State, const LocationContext *LCtx,
348
33.1k
    const ConstructionContext *CC, const EvalCallOptions &CallOpts) {
349
33.1k
  if (CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion) {
350
    // Sounds like we failed to find the target region and therefore
351
    // copy elision failed. There's nothing we can do about it here.
352
562
    return State;
353
562
  }
354
32.6k
355
  // See if we're constructing an existing region by looking at the
356
  // current construction context.
357
32.6k
  assert(CC && "Computed target region without construction context?");
358
32.6k
  switch (CC->getKind()) {
359
7.36k
  case ConstructionContext::CXX17ElidedCopyVariableKind:
360
7.36k
  case ConstructionContext::SimpleVariableKind: {
361
7.36k
    const auto *DSCC = cast<VariableConstructionContext>(CC);
362
7.36k
    return addObjectUnderConstruction(State, DSCC->getDeclStmt(), LCtx, V);
363
7.36k
    }
364
2.57k
    case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind:
365
2.57k
    case ConstructionContext::SimpleConstructorInitializerKind: {
366
2.57k
      const auto *ICC = cast<ConstructorInitializerConstructionContext>(CC);
367
2.57k
      return addObjectUnderConstruction(State, ICC->getCXXCtorInitializer(),
368
2.57k
                                        LCtx, V);
369
2.57k
    }
370
475
    case ConstructionContext::NewAllocatedObjectKind: {
371
475
      return State;
372
2.57k
    }
373
2.22k
    case ConstructionContext::SimpleReturnedValueKind:
374
2.22k
    case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
375
2.22k
      const StackFrameContext *SFC = LCtx->getStackFrame();
376
2.22k
      const LocationContext *CallerLCtx = SFC->getParent();
377
2.22k
      if (!CallerLCtx) {
378
        // No extra work is necessary in top frame.
379
57
        return State;
380
57
      }
381
2.16k
382
2.16k
      auto RTC = (*SFC->getCallSiteBlock())[SFC->getIndex()]
383
2.16k
                     .getAs<CFGCXXRecordTypedCall>();
384
2.16k
      assert(RTC && "Could not have had a target region without it");
385
2.16k
      if (isa<BlockInvocationContext>(CallerLCtx)) {
386
        // Unwrap block invocation contexts. They're mostly part of
387
        // the current stack frame.
388
1
        CallerLCtx = CallerLCtx->getParent();
389
1
        assert(!isa<BlockInvocationContext>(CallerLCtx));
390
1
      }
391
2.16k
392
2.16k
      return updateObjectsUnderConstruction(V,
393
2.16k
          cast<Expr>(SFC->getCallSite()), State, CallerLCtx,
394
2.16k
          RTC->getConstructionContext(), CallOpts);
395
2.16k
    }
396
6.79k
    case ConstructionContext::ElidedTemporaryObjectKind: {
397
6.79k
      assert(AMgr.getAnalyzerOptions().ShouldElideConstructors);
398
6.79k
      if (!CallOpts.IsElidableCtorThatHasNotBeenElided) {
399
6.65k
        const auto *TCC = cast<ElidedTemporaryObjectConstructionContext>(CC);
400
6.65k
        State = updateObjectsUnderConstruction(
401
6.65k
            V, TCC->getConstructorAfterElision(), State, LCtx,
402
6.65k
            TCC->getConstructionContextAfterElision(), CallOpts);
403
6.65k
404
        // Remember that we've elided the constructor.
405
6.65k
        State = addObjectUnderConstruction(
406
6.65k
            State, TCC->getConstructorAfterElision(), LCtx, V);
407
6.65k
408
        // Remember that we've elided the destructor.
409
6.65k
        if (const auto *BTE = TCC->getCXXBindTemporaryExpr())
410
586
          State = elideDestructor(State, BTE, LCtx);
411
6.65k
412
        // Instead of materialization, shamelessly return
413
        // the final object destination.
414
6.65k
        if (const auto *MTE = TCC->getMaterializedTemporaryExpr())
415
6.65k
          State = addObjectUnderConstruction(State, MTE, LCtx, V);
416
6.65k
417
6.65k
        return State;
418
6.65k
      }
419
      // If we decided not to elide the constructor, proceed as if
420
      // it's a simple temporary.
421
131
      LLVM_FALLTHROUGH;
422
131
    }
423
2.08k
    case ConstructionContext::SimpleTemporaryObjectKind: {
424
2.08k
      const auto *TCC = cast<TemporaryObjectConstructionContext>(CC);
425
2.08k
      if (const auto *BTE = TCC->getCXXBindTemporaryExpr())
426
350
        State = addObjectUnderConstruction(State, BTE, LCtx, V);
427
2.08k
428
2.08k
      if (const auto *MTE = TCC->getMaterializedTemporaryExpr())
429
1.96k
        State = addObjectUnderConstruction(State, MTE, LCtx, V);
430
2.08k
431
2.08k
      return State;
432
131
    }
433
11.2k
    case ConstructionContext::ArgumentKind: {
434
11.2k
      const auto *ACC = cast<ArgumentConstructionContext>(CC);
435
11.2k
      if (const auto *BTE = ACC->getCXXBindTemporaryExpr())
436
293
        State = addObjectUnderConstruction(State, BTE, LCtx, V);
437
11.2k
438
11.2k
      return addObjectUnderConstruction(
439
11.2k
          State, {ACC->getCallLikeExpr(), ACC->getIndex()}, LCtx, V);
440
0
    }
441
0
  }
442
0
  llvm_unreachable("Unhandled construction context!");
443
0
}
444
445
void ExprEngine::handleConstructor(const Expr *E,
446
                                   ExplodedNode *Pred,
447
29.6k
                                   ExplodedNodeSet &destNodes) {
448
29.6k
  const auto *CE = dyn_cast<CXXConstructExpr>(E);
449
29.6k
  const auto *CIE = dyn_cast<CXXInheritedCtorInitExpr>(E);
450
29.6k
  assert(CE || CIE);
451
29.6k
452
29.6k
  const LocationContext *LCtx = Pred->getLocationContext();
453
29.6k
  ProgramStateRef State = Pred->getState();
454
29.6k
455
29.6k
  SVal Target = UnknownVal();
456
29.6k
457
29.6k
  if (CE) {
458
29.6k
    if (Optional<SVal> ElidedTarget =
459
6.65k
            getObjectUnderConstruction(State, CE, LCtx)) {
460
      // We've previously modeled an elidable constructor by pretending that it
461
      // in fact constructs into the correct target. This constructor can
462
      // therefore be skipped.
463
6.65k
      Target = *ElidedTarget;
464
6.65k
      StmtNodeBuilder Bldr(Pred, destNodes, *currBldrCtx);
465
6.65k
      State = finishObjectConstruction(State, CE, LCtx);
466
6.65k
      if (auto L = Target.getAs<Loc>())
467
6.65k
        State = State->BindExpr(CE, LCtx, State->getSVal(*L, CE->getType()));
468
6.65k
      Bldr.generateNode(CE, Pred, State);
469
6.65k
      return;
470
6.65k
    }
471
22.9k
  }
472
22.9k
473
  // FIXME: Handle arrays, which run the same constructor for every element.
474
  // For now, we just run the first constructor (which should still invalidate
475
  // the entire array).
476
22.9k
477
22.9k
  EvalCallOptions CallOpts;
478
22.9k
  auto C = getCurrentCFGElement().getAs<CFGConstructor>();
479
22.9k
  assert(C || getCurrentCFGElement().getAs<CFGStmt>());
480
22.6k
  const ConstructionContext *CC = C ? C->getConstructionContext() : 
nullptr328
;
481
22.9k
482
22.9k
  const CXXConstructExpr::ConstructionKind CK =
483
22.9k
      CE ? CE->getConstructionKind() : 
CIE->getConstructionKind()5
;
484
22.9k
  switch (CK) {
485
22.2k
  case CXXConstructExpr::CK_Complete: {
486
    // Inherited constructors are always base class constructors.
487
22.2k
    assert(CE && !CIE && "A complete constructor is inherited?!");
488
22.2k
489
    // The target region is found from construction context.
490
22.2k
    std::tie(State, Target) =
491
22.2k
        handleConstructionContext(CE, State, LCtx, CC, CallOpts);
492
22.2k
    break;
493
0
  }
494
116
  case CXXConstructExpr::CK_VirtualBase: {
495
    // Make sure we are not calling virtual base class initializers twice.
496
    // Only the most-derived object should initialize virtual base classes.
497
116
    const auto *OuterCtor = dyn_cast_or_null<CXXConstructExpr>(
498
116
        LCtx->getStackFrame()->getCallSite());
499
116
    assert(
500
116
        (!OuterCtor ||
501
116
         OuterCtor->getConstructionKind() == CXXConstructExpr::CK_Complete ||
502
116
         OuterCtor->getConstructionKind() == CXXConstructExpr::CK_Delegating) &&
503
116
        ("This virtual base should have already been initialized by "
504
116
         "the most derived class!"));
505
116
    (void)OuterCtor;
506
116
    LLVM_FALLTHROUGH;
507
116
  }
508
759
  case CXXConstructExpr::CK_NonVirtualBase:
509
    // In C++17, classes with non-virtual bases may be aggregates, so they would
510
    // be initialized as aggregates without a constructor call, so we may have
511
    // a base class constructed directly into an initializer list without
512
    // having the derived-class constructor call on the previous stack frame.
513
    // Initializer lists may be nested into more initializer lists that
514
    // correspond to surrounding aggregate initializations.
515
    // FIXME: For now this code essentially bails out. We need to find the
516
    // correct target region and set it.
517
    // FIXME: Instead of relying on the ParentMap, we should have the
518
    // trigger-statement (InitListExpr in this case) passed down from CFG or
519
    // otherwise always available during construction.
520
759
    if (dyn_cast_or_null<InitListExpr>(LCtx->getParentMap().getParent(E))) {
521
24
      MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
522
24
      Target = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx));
523
24
      CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
524
24
      break;
525
24
    }
526
735
    LLVM_FALLTHROUGH;
527
745
  case CXXConstructExpr::CK_Delegating: {
528
745
    const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
529
745
    Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
530
745
                                              LCtx->getStackFrame());
531
745
    SVal ThisVal = State->getSVal(ThisPtr);
532
745
533
745
    if (CK == CXXConstructExpr::CK_Delegating) {
534
10
      Target = ThisVal;
535
735
    } else {
536
      // Cast to the base type.
537
735
      bool IsVirtual = (CK == CXXConstructExpr::CK_VirtualBase);
538
735
      SVal BaseVal =
539
735
          getStoreManager().evalDerivedToBase(ThisVal, E->getType(), IsVirtual);
540
735
      Target = BaseVal;
541
735
    }
542
745
    break;
543
22.9k
  }
544
22.9k
  }
545
22.9k
546
22.9k
  if (State != Pred->getState()) {
547
21.1k
    static SimpleProgramPointTag T("ExprEngine",
548
21.1k
                                   "Prepare for object construction");
549
21.1k
    ExplodedNodeSet DstPrepare;
550
21.1k
    StmtNodeBuilder BldrPrepare(Pred, DstPrepare, *currBldrCtx);
551
21.1k
    BldrPrepare.generateNode(E, Pred, State, &T, ProgramPoint::PreStmtKind);
552
21.1k
    assert(DstPrepare.size() <= 1);
553
21.1k
    if (DstPrepare.size() == 0)
554
27
      return;
555
21.1k
    Pred = *BldrPrepare.begin();
556
21.1k
  }
557
22.9k
558
22.9k
  const MemRegion *TargetRegion = Target.getAsRegion();
559
22.9k
  CallEventManager &CEMgr = getStateManager().getCallEventManager();
560
22.9k
  CallEventRef<> Call =
561
5
      CIE ? (CallEventRef<>)CEMgr.getCXXInheritedConstructorCall(
562
5
                CIE, TargetRegion, State, LCtx)
563
22.9k
          : (CallEventRef<>)CEMgr.getCXXConstructorCall(
564
22.9k
                CE, TargetRegion, State, LCtx);
565
22.9k
566
22.9k
  ExplodedNodeSet DstPreVisit;
567
22.9k
  getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, E, *this);
568
22.9k
569
22.9k
  ExplodedNodeSet PreInitialized;
570
22.9k
  if (CE) {
571
    // FIXME: Is it possible and/or useful to do this before PreStmt?
572
22.9k
    StmtNodeBuilder Bldr(DstPreVisit, PreInitialized, *currBldrCtx);
573
22.9k
    for (ExplodedNodeSet::iterator I = DstPreVisit.begin(),
574
22.9k
                                   E = DstPreVisit.end();
575
45.9k
         I != E; 
++I22.9k
) {
576
22.9k
      ProgramStateRef State = (*I)->getState();
577
22.9k
      if (CE->requiresZeroInitialization()) {
578
        // FIXME: Once we properly handle constructors in new-expressions, we'll
579
        // need to invalidate the region before setting a default value, to make
580
        // sure there aren't any lingering bindings around. This probably needs
581
        // to happen regardless of whether or not the object is zero-initialized
582
        // to handle random fields of a placement-initialized object picking up
583
        // old bindings. We might only want to do it when we need to, though.
584
        // FIXME: This isn't actually correct for arrays -- we need to zero-
585
        // initialize the entire array, not just the first element -- but our
586
        // handling of arrays everywhere else is weak as well, so this shouldn't
587
        // actually make things worse. Placement new makes this tricky as well,
588
        // since it's then possible to be initializing one part of a multi-
589
        // dimensional array.
590
1.95k
        State = State->bindDefaultZero(Target, LCtx);
591
1.95k
      }
592
22.9k
593
22.9k
      Bldr.generateNode(CE, *I, State, /*tag=*/nullptr,
594
22.9k
                        ProgramPoint::PreStmtKind);
595
22.9k
    }
596
5
  } else {
597
5
    PreInitialized = DstPreVisit;
598
5
  }
599
22.9k
600
22.9k
  ExplodedNodeSet DstPreCall;
601
22.9k
  getCheckerManager().runCheckersForPreCall(DstPreCall, PreInitialized,
602
22.9k
                                            *Call, *this);
603
22.9k
604
22.9k
  ExplodedNodeSet DstEvaluated;
605
22.9k
606
22.9k
  if (CE && 
CE->getConstructor()->isTrivial()22.9k
&&
607
15.2k
      CE->getConstructor()->isCopyOrMoveConstructor() &&
608
12.5k
      !CallOpts.IsArrayCtorOrDtor) {
609
12.5k
    StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx);
610
    // FIXME: Handle other kinds of trivial constructors as well.
611
12.5k
    for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
612
25.0k
         I != E; 
++I12.5k
)
613
12.5k
      performTrivialCopy(Bldr, *I, *Call);
614
12.5k
615
10.4k
  } else {
616
10.4k
    for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
617
20.9k
         I != E; 
++I10.4k
)
618
10.4k
      getCheckerManager().runCheckersForEvalCall(DstEvaluated, *I, *Call, *this,
619
10.4k
                                                 CallOpts);
620
10.4k
  }
621
22.9k
622
  // If the CFG was constructed without elements for temporary destructors
623
  // and the just-called constructor created a temporary object then
624
  // stop exploration if the temporary object has a noreturn constructor.
625
  // This can lose coverage because the destructor, if it were present
626
  // in the CFG, would be called at the end of the full expression or
627
  // later (for life-time extended temporaries) -- but avoids infeasible
628
  // paths when no-return temporary destructors are used for assertions.
629
22.9k
  ExplodedNodeSet DstEvaluatedPostProcessed;
630
22.9k
  StmtNodeBuilder Bldr(DstEvaluated, DstEvaluatedPostProcessed, *currBldrCtx);
631
22.9k
  const AnalysisDeclContext *ADC = LCtx->getAnalysisDeclContext();
632
22.9k
  if (!ADC->getCFGBuildOptions().AddTemporaryDtors) {
633
283
    if (llvm::isa_and_nonnull<CXXTempObjectRegion>(TargetRegion) &&
634
110
        cast<CXXConstructorDecl>(Call->getDecl())
635
110
            ->getParent()
636
4
            ->isAnyDestructorNoReturn()) {
637
4
638
      // If we've inlined the constructor, then DstEvaluated would be empty.
639
      // In this case we still want a sink, which could be implemented
640
      // in processCallExit. But we don't have that implemented at the moment,
641
      // so if you hit this assertion, see if you can avoid inlining
642
      // the respective constructor when analyzer-config cfg-temporary-dtors
643
      // is set to false.
644
      // Otherwise there's nothing wrong with inlining such constructor.
645
4
      assert(!DstEvaluated.empty() &&
646
4
             "We should not have inlined this constructor!");
647
4
648
4
      for (ExplodedNode *N : DstEvaluated) {
649
4
        Bldr.generateSink(E, N, N->getState());
650
4
      }
651
4
652
      // There is no need to run the PostCall and PostStmt checker
653
      // callbacks because we just generated sinks on all nodes in th
654
      // frontier.
655
4
      return;
656
4
    }
657
22.9k
  }
658
22.9k
659
22.9k
  ExplodedNodeSet DstPostArgumentCleanup;
660
22.9k
  for (ExplodedNode *I : DstEvaluatedPostProcessed)
661
14.1k
    finishArgumentConstruction(DstPostArgumentCleanup, I, *Call);
662
22.9k
663
  // If there were other constructors called for object-type arguments
664
  // of this constructor, clean them up.
665
22.9k
  ExplodedNodeSet DstPostCall;
666
22.9k
  getCheckerManager().runCheckersForPostCall(DstPostCall,
667
22.9k
                                             DstPostArgumentCleanup,
668
22.9k
                                             *Call, *this);
669
22.9k
  getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, E, *this);
670
22.9k
}
671
672
void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE,
673
                                       ExplodedNode *Pred,
674
29.6k
                                       ExplodedNodeSet &Dst) {
675
29.6k
  handleConstructor(CE, Pred, Dst);
676
29.6k
}
677
678
void ExprEngine::VisitCXXInheritedCtorInitExpr(
679
    const CXXInheritedCtorInitExpr *CE, ExplodedNode *Pred,
680
5
    ExplodedNodeSet &Dst) {
681
5
  handleConstructor(CE, Pred, Dst);
682
5
}
683
684
void ExprEngine::VisitCXXDestructor(QualType ObjectType,
685
                                    const MemRegion *Dest,
686
                                    const Stmt *S,
687
                                    bool IsBaseDtor,
688
                                    ExplodedNode *Pred,
689
                                    ExplodedNodeSet &Dst,
690
1.49k
                                    EvalCallOptions &CallOpts) {
691
1.49k
  assert(S && "A destructor without a trigger!");
692
1.49k
  const LocationContext *LCtx = Pred->getLocationContext();
693
1.49k
  ProgramStateRef State = Pred->getState();
694
1.49k
695
1.49k
  const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl();
696
1.49k
  assert(RecordDecl && "Only CXXRecordDecls should have destructors");
697
1.49k
  const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
698
  // FIXME: There should always be a Decl, otherwise the destructor call
699
  // shouldn't have been added to the CFG in the first place.
700
1.49k
  if (!DtorDecl) {
701
    // Skip the invalid destructor. We cannot simply return because
702
    // it would interrupt the analysis instead.
703
1
    static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor");
704
    // FIXME: PostImplicitCall with a null decl may crash elsewhere anyway.
705
1
    PostImplicitCall PP(/*Decl=*/nullptr, S->getEndLoc(), LCtx, &T);
706
1
    NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
707
1
    Bldr.generateNode(PP, Pred->getState(), Pred);
708
1
    return;
709
1
  }
710
1.49k
711
1.49k
  if (!Dest) {
712
    // We're trying to destroy something that is not a region. This may happen
713
    // for a variety of reasons (unknown target region, concrete integer instead
714
    // of target region, etc.). The current code makes an attempt to recover.
715
    // FIXME: We probably don't really need to recover when we're dealing
716
    // with concrete integers specifically.
717
70
    CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
718
70
    if (const Expr *E = dyn_cast_or_null<Expr>(S)) {
719
68
      Dest = MRMgr.getCXXTempObjectRegion(E, Pred->getLocationContext());
720
2
    } else {
721
2
      static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor");
722
2
      NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
723
2
      Bldr.generateSink(Pred->getLocation().withTag(&T),
724
2
                        Pred->getState(), Pred);
725
2
      return;
726
2
    }
727
1.49k
  }
728
1.49k
729
1.49k
  CallEventManager &CEMgr = getStateManager().getCallEventManager();
730
1.49k
  CallEventRef<CXXDestructorCall> Call =
731
1.49k
      CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx);
732
1.49k
733
1.49k
  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
734
1.49k
                                Call->getSourceRange().getBegin(),
735
1.49k
                                "Error evaluating destructor");
736
1.49k
737
1.49k
  ExplodedNodeSet DstPreCall;
738
1.49k
  getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
739
1.49k
                                            *Call, *this);
740
1.49k
741
1.49k
  ExplodedNodeSet DstInvalidated;
742
1.49k
  StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
743
1.49k
  for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
744
2.98k
       I != E; 
++I1.48k
)
745
1.48k
    defaultEvalCall(Bldr, *I, *Call, CallOpts);
746
1.49k
747
1.49k
  getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
748
1.49k
                                             *Call, *this);
749
1.49k
}
750
751
void ExprEngine::VisitCXXNewAllocatorCall(const CXXNewExpr *CNE,
752
                                          ExplodedNode *Pred,
753
1.02k
                                          ExplodedNodeSet &Dst) {
754
1.02k
  ProgramStateRef State = Pred->getState();
755
1.02k
  const LocationContext *LCtx = Pred->getLocationContext();
756
1.02k
  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
757
1.02k
                                CNE->getBeginLoc(),
758
1.02k
                                "Error evaluating New Allocator Call");
759
1.02k
  CallEventManager &CEMgr = getStateManager().getCallEventManager();
760
1.02k
  CallEventRef<CXXAllocatorCall> Call =
761
1.02k
    CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
762
1.02k
763
1.02k
  ExplodedNodeSet DstPreCall;
764
1.02k
  getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
765
1.02k
                                            *Call, *this);
766
1.02k
767
1.02k
  ExplodedNodeSet DstPostCall;
768
1.02k
  StmtNodeBuilder CallBldr(DstPreCall, DstPostCall, *currBldrCtx);
769
1.01k
  for (ExplodedNode *I : DstPreCall) {
770
    // FIXME: Provide evalCall for checkers?
771
1.01k
    defaultEvalCall(CallBldr, I, *Call);
772
1.01k
  }
773
  // If the call is inlined, DstPostCall will be empty and we bail out now.
774
1.02k
775
  // Store return value of operator new() for future use, until the actual
776
  // CXXNewExpr gets processed.
777
1.02k
  ExplodedNodeSet DstPostValue;
778
1.02k
  StmtNodeBuilder ValueBldr(DstPostCall, DstPostValue, *currBldrCtx);
779
652
  for (ExplodedNode *I : DstPostCall) {
780
    // FIXME: Because CNE serves as the "call site" for the allocator (due to
781
    // lack of a better expression in the AST), the conjured return value symbol
782
    // is going to be of the same type (C++ object pointer type). Technically
783
    // this is not correct because the operator new's prototype always says that
784
    // it returns a 'void *'. So we should change the type of the symbol,
785
    // and then evaluate the cast over the symbolic pointer from 'void *' to
786
    // the object pointer type. But without changing the symbol's type it
787
    // is breaking too much to evaluate the no-op symbolic cast over it, so we
788
    // skip it for now.
789
652
    ProgramStateRef State = I->getState();
790
652
    SVal RetVal = State->getSVal(CNE, LCtx);
791
652
792
    // If this allocation function is not declared as non-throwing, failures
793
    // /must/ be signalled by exceptions, and thus the return value will never
794
    // be NULL. -fno-exceptions does not influence this semantics.
795
    // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
796
    // where new can return NULL. If we end up supporting that option, we can
797
    // consider adding a check for it here.
798
    // C++11 [basic.stc.dynamic.allocation]p3.
799
652
    if (const FunctionDecl *FD = CNE->getOperatorNew()) {
800
652
      QualType Ty = FD->getType();
801
652
      if (const auto *ProtoType = Ty->getAs<FunctionProtoType>())
802
652
        if (!ProtoType->isNothrow())
803
628
          State = State->assume(RetVal.castAs<DefinedOrUnknownSVal>(), true);
804
652
    }
805
652
806
652
    ValueBldr.generateNode(
807
652
        CNE, I, addObjectUnderConstruction(State, CNE, LCtx, RetVal));
808
652
  }
809
1.02k
810
1.02k
  ExplodedNodeSet DstPostPostCallCallback;
811
1.02k
  getCheckerManager().runCheckersForPostCall(DstPostPostCallCallback,
812
1.02k
                                             DstPostValue, *Call, *this);
813
652
  for (ExplodedNode *I : DstPostPostCallCallback) {
814
652
    getCheckerManager().runCheckersForNewAllocator(*Call, Dst, I, *this);
815
652
  }
816
1.02k
}
817
818
void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
819
994
                                   ExplodedNodeSet &Dst) {
820
  // FIXME: Much of this should eventually migrate to CXXAllocatorCall.
821
  // Also, we need to decide how allocators actually work -- they're not
822
  // really part of the CXXNewExpr because they happen BEFORE the
823
  // CXXConstructExpr subexpression. See PR12014 for some discussion.
824
994
825
994
  unsigned blockCount = currBldrCtx->blockCount();
826
994
  const LocationContext *LCtx = Pred->getLocationContext();
827
994
  SVal symVal = UnknownVal();
828
994
  FunctionDecl *FD = CNE->getOperatorNew();
829
994
830
994
  bool IsStandardGlobalOpNewFunction =
831
994
      FD->isReplaceableGlobalAllocationFunction();
832
994
833
994
  ProgramStateRef State = Pred->getState();
834
994
835
  // Retrieve the stored operator new() return value.
836
994
  if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
837
987
    symVal = *getObjectUnderConstruction(State, CNE, LCtx);
838
987
    State = finishObjectConstruction(State, CNE, LCtx);
839
987
  }
840
994
841
  // We assume all standard global 'operator new' functions allocate memory in
842
  // heap. We realize this is an approximation that might not correctly model
843
  // a custom global allocator.
844
994
  if (symVal.isUnknown()) {
845
7
    if (IsStandardGlobalOpNewFunction)
846
5
      symVal = svalBuilder.getConjuredHeapSymbolVal(CNE, LCtx, blockCount);
847
2
    else
848
2
      symVal = svalBuilder.conjureSymbolVal(nullptr, CNE, LCtx, CNE->getType(),
849
2
                                            blockCount);
850
7
  }
851
994
852
994
  CallEventManager &CEMgr = getStateManager().getCallEventManager();
853
994
  CallEventRef<CXXAllocatorCall> Call =
854
994
    CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
855
994
856
994
  if (!AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
857
    // Invalidate placement args.
858
    // FIXME: Once we figure out how we want allocators to work,
859
    // we should be using the usual pre-/(default-)eval-/post-call checkers
860
    // here.
861
7
    State = Call->invalidateRegions(blockCount);
862
7
    if (!State)
863
0
      return;
864
7
865
    // If this allocation function is not declared as non-throwing, failures
866
    // /must/ be signalled by exceptions, and thus the return value will never
867
    // be NULL. -fno-exceptions does not influence this semantics.
868
    // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
869
    // where new can return NULL. If we end up supporting that option, we can
870
    // consider adding a check for it here.
871
    // C++11 [basic.stc.dynamic.allocation]p3.
872
7
    if (FD) {
873
7
      QualType Ty = FD->getType();
874
7
      if (const auto *ProtoType = Ty->getAs<FunctionProtoType>())
875
7
        if (!ProtoType->isNothrow())
876
3
          if (auto dSymVal = symVal.getAs<DefinedOrUnknownSVal>())
877
3
            State = State->assume(*dSymVal, true);
878
7
    }
879
7
  }
880
994
881
994
  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
882
994
883
994
  SVal Result = symVal;
884
994
885
994
  if (CNE->isArray()) {
886
    // FIXME: allocating an array requires simulating the constructors.
887
    // For now, just return a symbolicated region.
888
126
    if (const auto *NewReg = cast_or_null<SubRegion>(symVal.getAsRegion())) {
889
121
      QualType ObjTy = CNE->getType()->getPointeeType();
890
121
      const ElementRegion *EleReg =
891
121
          getStoreManager().GetElementZeroRegion(NewReg, ObjTy);
892
121
      Result = loc::MemRegionVal(EleReg);
893
121
    }
894
126
    State = State->BindExpr(CNE, Pred->getLocationContext(), Result);
895
126
    Bldr.generateNode(CNE, Pred, State);
896
126
    return;
897
126
  }
898
868
899
  // FIXME: Once we have proper support for CXXConstructExprs inside
900
  // CXXNewExpr, we need to make sure that the constructed object is not
901
  // immediately invalidated here. (The placement call should happen before
902
  // the constructor call anyway.)
903
868
  if (FD && FD->isReservedGlobalPlacementOperator()) {
904
    // Non-array placement new should always return the placement location.
905
295
    SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx);
906
295
    Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(),
907
295
                                  CNE->getPlacementArg(0)->getType());
908
295
  }
909
868
910
  // Bind the address of the object, then check to see if we cached out.
911
868
  State = State->BindExpr(CNE, LCtx, Result);
912
868
  ExplodedNode *NewN = Bldr.generateNode(CNE, Pred, State);
913
868
  if (!NewN)
914
0
    return;
915
868
916
  // If the type is not a record, we won't have a CXXConstructExpr as an
917
  // initializer. Copy the value over.
918
868
  if (const Expr *Init = CNE->getInitializer()) {
919
618
    if (!isa<CXXConstructExpr>(Init)) {
920
175
      assert(Bldr.getResults().size() == 1);
921
175
      Bldr.takeNodes(NewN);
922
175
      evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, LCtx),
923
175
               /*FirstInit=*/IsStandardGlobalOpNewFunction);
924
175
    }
925
618
  }
926
868
}
927
928
void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE,
929
436
                                    ExplodedNode *Pred, ExplodedNodeSet &Dst) {
930
436
931
436
  CallEventManager &CEMgr = getStateManager().getCallEventManager();
932
436
  CallEventRef<CXXDeallocatorCall> Call = CEMgr.getCXXDeallocatorCall(
933
436
      CDE, Pred->getState(), Pred->getLocationContext());
934
436
935
436
  ExplodedNodeSet DstPreCall;
936
436
  getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, *Call, *this);
937
436
938
436
  getCheckerManager().runCheckersForPostCall(Dst, DstPreCall, *Call, *this);
939
436
}
940
941
void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred,
942
0
                                   ExplodedNodeSet &Dst) {
943
0
  const VarDecl *VD = CS->getExceptionDecl();
944
0
  if (!VD) {
945
0
    Dst.Add(Pred);
946
0
    return;
947
0
  }
948
0
949
0
  const LocationContext *LCtx = Pred->getLocationContext();
950
0
  SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(),
951
0
                                        currBldrCtx->blockCount());
952
0
  ProgramStateRef state = Pred->getState();
953
0
  state = state->bindLoc(state->getLValue(VD, LCtx), V, LCtx);
954
0
955
0
  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
956
0
  Bldr.generateNode(CS, Pred, state);
957
0
}
958
959
void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
960
9.58k
                                    ExplodedNodeSet &Dst) {
961
9.58k
  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
962
9.58k
963
  // Get the this object region from StoreManager.
964
9.58k
  const LocationContext *LCtx = Pred->getLocationContext();
965
9.58k
  const MemRegion *R =
966
9.58k
    svalBuilder.getRegionManager().getCXXThisRegion(
967
9.58k
                                  getContext().getCanonicalType(TE->getType()),
968
9.58k
                                                    LCtx);
969
9.58k
970
9.58k
  ProgramStateRef state = Pred->getState();
971
9.58k
  SVal V = state->getSVal(loc::MemRegionVal(R));
972
9.58k
  Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V));
973
9.58k
}
974
975
void ExprEngine::VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred,
976
195
                                 ExplodedNodeSet &Dst) {
977
195
  const LocationContext *LocCtxt = Pred->getLocationContext();
978
195
979
  // Get the region of the lambda itself.
980
195
  const MemRegion *R = svalBuilder.getRegionManager().getCXXTempObjectRegion(
981
195
      LE, LocCtxt);
982
195
  SVal V = loc::MemRegionVal(R);
983
195
984
195
  ProgramStateRef State = Pred->getState();
985
195
986
  // If we created a new MemRegion for the lambda, we should explicitly bind
987
  // the captures.
988
195
  CXXRecordDecl::field_iterator CurField = LE->getLambdaClass()->field_begin();
989
195
  for (LambdaExpr::const_capture_init_iterator i = LE->capture_init_begin(),
990
195
                                               e = LE->capture_init_end();
991
396
       i != e; 
++i, ++CurField201
) {
992
201
    FieldDecl *FieldForCapture = *CurField;
993
201
    SVal FieldLoc = State->getLValue(FieldForCapture, V);
994
201
995
201
    SVal InitVal;
996
201
    if (!FieldForCapture->hasCapturedVLAType()) {
997
199
      Expr *InitExpr = *i;
998
199
      assert(InitExpr && "Capture missing initialization expression");
999
199
      InitVal = State->getSVal(InitExpr, LocCtxt);
1000
2
    } else {
1001
      // The field stores the length of a captured variable-length array.
1002
      // These captures don't have initialization expressions; instead we
1003
      // get the length from the VLAType size expression.
1004
2
      Expr *SizeExpr = FieldForCapture->getCapturedVLAType()->getSizeExpr();
1005
2
      InitVal = State->getSVal(SizeExpr, LocCtxt);
1006
2
    }
1007
201
1008
201
    State = State->bindLoc(FieldLoc, InitVal, LocCtxt);
1009
201
  }
1010
195
1011
  // Decay the Loc into an RValue, because there might be a
1012
  // MaterializeTemporaryExpr node above this one which expects the bound value
1013
  // to be an RValue.
1014
195
  SVal LambdaRVal = State->getSVal(R);
1015
195
1016
195
  ExplodedNodeSet Tmp;
1017
195
  StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
1018
  // FIXME: is this the right program point kind?
1019
195
  Bldr.generateNode(LE, Pred,
1020
195
                    State->BindExpr(LE, LocCtxt, LambdaRVal),
1021
195
                    nullptr, ProgramPoint::PostLValueKind);
1022
195
1023
  // FIXME: Move all post/pre visits to ::Visit().
1024
195
  getCheckerManager().runCheckersForPostStmt(Dst, Tmp, LE, *this);
1025
195
}