clang  7.0.0svn
ExprEngineCXX.cpp
Go to the documentation of this file.
1 //===- ExprEngineCXX.cpp - ExprEngine support for C++ -----------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the C++ expression evaluation engine.
11 //
12 //===----------------------------------------------------------------------===//
13 
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/StmtCXX.h"
18 #include "clang/AST/ParentMap.h"
23 
24 using namespace clang;
25 using namespace ento;
26 
28  ExplodedNode *Pred,
29  ExplodedNodeSet &Dst) {
30  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
31  const Expr *tempExpr = ME->GetTemporaryExpr()->IgnoreParens();
32  ProgramStateRef state = Pred->getState();
33  const LocationContext *LCtx = Pred->getLocationContext();
34 
35  state = createTemporaryRegionIfNeeded(state, LCtx, tempExpr, ME);
36  Bldr.generateNode(ME, Pred, state);
37 }
38 
39 // FIXME: This is the sort of code that should eventually live in a Core
40 // checker rather than as a special case in ExprEngine.
41 void ExprEngine::performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred,
42  const CallEvent &Call) {
43  SVal ThisVal;
44  bool AlwaysReturnsLValue;
45  const CXXRecordDecl *ThisRD = nullptr;
46  if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) {
47  assert(Ctor->getDecl()->isTrivial());
48  assert(Ctor->getDecl()->isCopyOrMoveConstructor());
49  ThisVal = Ctor->getCXXThisVal();
50  ThisRD = Ctor->getDecl()->getParent();
51  AlwaysReturnsLValue = false;
52  } else {
53  assert(cast<CXXMethodDecl>(Call.getDecl())->isTrivial());
54  assert(cast<CXXMethodDecl>(Call.getDecl())->getOverloadedOperator() ==
55  OO_Equal);
56  ThisVal = cast<CXXInstanceCall>(Call).getCXXThisVal();
57  ThisRD = cast<CXXMethodDecl>(Call.getDecl())->getParent();
58  AlwaysReturnsLValue = true;
59  }
60 
61  assert(ThisRD);
62  if (ThisRD->isEmpty()) {
63  // Do nothing for empty classes. Otherwise it'd retrieve an UnknownVal
64  // and bind it and RegionStore would think that the actual value
65  // in this region at this offset is unknown.
66  return;
67  }
68 
69  const LocationContext *LCtx = Pred->getLocationContext();
70 
71  ExplodedNodeSet Dst;
72  Bldr.takeNodes(Pred);
73 
74  SVal V = Call.getArgSVal(0);
75 
76  // If the value being copied is not unknown, load from its location to get
77  // an aggregate rvalue.
78  if (Optional<Loc> L = V.getAs<Loc>())
79  V = Pred->getState()->getSVal(*L);
80  else
81  assert(V.isUnknownOrUndef());
82 
83  const Expr *CallExpr = Call.getOriginExpr();
84  evalBind(Dst, CallExpr, Pred, ThisVal, V, true);
85 
86  PostStmt PS(CallExpr, LCtx);
87  for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end();
88  I != E; ++I) {
89  ProgramStateRef State = (*I)->getState();
90  if (AlwaysReturnsLValue)
91  State = State->BindExpr(CallExpr, LCtx, ThisVal);
92  else
93  State = bindReturnValue(Call, LCtx, State);
94  Bldr.generateNode(PS, State, *I);
95  }
96 }
97 
98 
99 SVal ExprEngine::makeZeroElementRegion(ProgramStateRef State, SVal LValue,
100  QualType &Ty, bool &IsArray) {
101  SValBuilder &SVB = State->getStateManager().getSValBuilder();
102  ASTContext &Ctx = SVB.getContext();
103 
104  while (const ArrayType *AT = Ctx.getAsArrayType(Ty)) {
105  Ty = AT->getElementType();
106  LValue = State->getLValue(Ty, SVB.makeZeroArrayIndex(), LValue);
107  IsArray = true;
108  }
109 
110  return LValue;
111 }
112 
113 std::pair<ProgramStateRef, SVal> ExprEngine::prepareForObjectConstruction(
114  const Expr *E, ProgramStateRef State, const LocationContext *LCtx,
115  const ConstructionContext *CC, EvalCallOptions &CallOpts) {
117 
118  // See if we're constructing an existing region by looking at the
119  // current construction context.
120  if (CC) {
121  switch (CC->getKind()) {
124  const auto *DSCC = cast<VariableConstructionContext>(CC);
125  const auto *DS = DSCC->getDeclStmt();
126  const auto *Var = cast<VarDecl>(DS->getSingleDecl());
127  SVal LValue = State->getLValue(Var, LCtx);
128  QualType Ty = Var->getType();
129  LValue =
130  makeZeroElementRegion(State, LValue, Ty, CallOpts.IsArrayCtorOrDtor);
131  State =
132  addObjectUnderConstruction(State, DSCC->getDeclStmt(), LCtx, LValue);
133  return std::make_pair(State, LValue);
134  }
137  const auto *ICC = cast<ConstructorInitializerConstructionContext>(CC);
138  const auto *Init = ICC->getCXXCtorInitializer();
139  assert(Init->isAnyMemberInitializer());
140  const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
141  Loc ThisPtr =
142  getSValBuilder().getCXXThis(CurCtor, LCtx->getCurrentStackFrame());
143  SVal ThisVal = State->getSVal(ThisPtr);
144 
145  const ValueDecl *Field;
146  SVal FieldVal;
147  if (Init->isIndirectMemberInitializer()) {
148  Field = Init->getIndirectMember();
149  FieldVal = State->getLValue(Init->getIndirectMember(), ThisVal);
150  } else {
151  Field = Init->getMember();
152  FieldVal = State->getLValue(Init->getMember(), ThisVal);
153  }
154 
155  QualType Ty = Field->getType();
156  FieldVal = makeZeroElementRegion(State, FieldVal, Ty,
157  CallOpts.IsArrayCtorOrDtor);
158  State = addObjectUnderConstruction(State, Init, LCtx, FieldVal);
159  return std::make_pair(State, FieldVal);
160  }
163  const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
164  const auto *NE = NECC->getCXXNewExpr();
165  SVal V = *getObjectUnderConstruction(State, NE, LCtx);
166  if (const SubRegion *MR =
167  dyn_cast_or_null<SubRegion>(V.getAsRegion())) {
168  if (NE->isArray()) {
169  // TODO: In fact, we need to call the constructor for every
170  // allocated element, not just the first one!
171  CallOpts.IsArrayCtorOrDtor = true;
172  return std::make_pair(
173  State, loc::MemRegionVal(getStoreManager().GetElementZeroRegion(
174  MR, NE->getType()->getPointeeType())));
175  }
176  return std::make_pair(State, V);
177  }
178  // TODO: Detect when the allocator returns a null pointer.
179  // Constructor shall not be called in this case.
180  }
181  break;
182  }
185  // The temporary is to be managed by the parent stack frame.
186  // So build it in the parent stack frame if we're not in the
187  // top frame of the analysis.
188  const StackFrameContext *SFC = LCtx->getCurrentStackFrame();
189  if (const LocationContext *CallerLCtx = SFC->getParent()) {
190  auto RTC = (*SFC->getCallSiteBlock())[SFC->getIndex()]
191  .getAs<CFGCXXRecordTypedCall>();
192  if (!RTC) {
193  // We were unable to find the correct construction context for the
194  // call in the parent stack frame. This is equivalent to not being
195  // able to find construction context at all.
196  break;
197  }
198  return prepareForObjectConstruction(
199  cast<Expr>(SFC->getCallSite()), State, CallerLCtx,
200  RTC->getConstructionContext(), CallOpts);
201  } else {
202  // We are on the top frame of the analysis.
203  // TODO: What exactly happens when we are? Does the temporary object
204  // live long enough in the region store in this case? Would checkers
205  // think that this object immediately goes out of scope?
206  CallOpts.IsTemporaryCtorOrDtor = true;
207  SVal V = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx));
208  return std::make_pair(State, V);
209  }
210  llvm_unreachable("Unhandled return value construction context!");
211  }
213  const auto *TCC = cast<TemporaryObjectConstructionContext>(CC);
214  const CXXBindTemporaryExpr *BTE = TCC->getCXXBindTemporaryExpr();
215  const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr();
216 
217  if (!BTE) {
218  // FIXME: Lifetime extension for temporaries without destructors
219  // is not implemented yet.
220  MTE = nullptr;
221  }
222 
223  if (MTE) {
224  if (const ValueDecl *VD = MTE->getExtendingDecl()) {
225  assert(MTE->getStorageDuration() != SD_FullExpression);
226  if (!VD->getType()->isReferenceType()) {
227  // We're lifetime-extended by a surrounding aggregate.
228  // Automatic destructors aren't quite working in this case
229  // on the CFG side. We should warn the caller about that.
230  // FIXME: Is there a better way to retrieve this information from
231  // the MaterializeTemporaryExpr?
233  }
234  }
235  }
236 
237  if (MTE && MTE->getStorageDuration() != SD_FullExpression) {
238  // If the temporary is lifetime-extended, don't save the BTE,
239  // because we don't need a temporary destructor, but an automatic
240  // destructor.
241  BTE = nullptr;
242  }
243 
244  // FIXME: Support temporaries lifetime-extended via static references.
245  // They'd need a getCXXStaticTempObjectRegion().
246  SVal V = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx));
247 
248  if (BTE)
249  State = addObjectUnderConstruction(State, BTE, LCtx, V);
250 
251  if (MTE)
252  State = addObjectUnderConstruction(State, MTE, LCtx, V);
253 
254  CallOpts.IsTemporaryCtorOrDtor = true;
255  return std::make_pair(State, V);
256  }
257  }
258  }
259  // If we couldn't find an existing region to construct into, assume we're
260  // constructing a temporary. Notify the caller of our failure.
262  return std::make_pair(
263  State, loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx)));
264 }
265 
267  ExplodedNode *Pred,
268  ExplodedNodeSet &destNodes) {
269  const LocationContext *LCtx = Pred->getLocationContext();
270  ProgramStateRef State = Pred->getState();
271 
272  SVal Target = UnknownVal();
273 
274  // FIXME: Handle arrays, which run the same constructor for every element.
275  // For now, we just run the first constructor (which should still invalidate
276  // the entire array).
277 
278  EvalCallOptions CallOpts;
280  assert(C || getCurrentCFGElement().getAs<CFGStmt>());
281  const ConstructionContext *CC = C ? C->getConstructionContext() : nullptr;
282 
283  switch (CE->getConstructionKind()) {
285  std::tie(State, Target) =
286  prepareForObjectConstruction(CE, State, LCtx, CC, CallOpts);
287  break;
288  }
290  // Make sure we are not calling virtual base class initializers twice.
291  // Only the most-derived object should initialize virtual base classes.
292  if (const Stmt *Outer = LCtx->getCurrentStackFrame()->getCallSite()) {
293  const CXXConstructExpr *OuterCtor = dyn_cast<CXXConstructExpr>(Outer);
294  if (OuterCtor) {
295  switch (OuterCtor->getConstructionKind()) {
298  // Bail out!
299  destNodes.Add(Pred);
300  return;
303  break;
304  }
305  }
306  }
307  // FALLTHROUGH
309  // In C++17, classes with non-virtual bases may be aggregates, so they would
310  // be initialized as aggregates without a constructor call, so we may have
311  // a base class constructed directly into an initializer list without
312  // having the derived-class constructor call on the previous stack frame.
313  // Initializer lists may be nested into more initializer lists that
314  // correspond to surrounding aggregate initializations.
315  // FIXME: For now this code essentially bails out. We need to find the
316  // correct target region and set it.
317  // FIXME: Instead of relying on the ParentMap, we should have the
318  // trigger-statement (InitListExpr in this case) passed down from CFG or
319  // otherwise always available during construction.
320  if (dyn_cast_or_null<InitListExpr>(LCtx->getParentMap().getParent(CE))) {
322  Target = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(CE, LCtx));
324  break;
325  }
326  // FALLTHROUGH
328  const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
329  Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
330  LCtx->getCurrentStackFrame());
331  SVal ThisVal = State->getSVal(ThisPtr);
332 
334  Target = ThisVal;
335  } else {
336  // Cast to the base type.
337  bool IsVirtual =
339  SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, CE->getType(),
340  IsVirtual);
341  Target = BaseVal;
342  }
343  break;
344  }
345  }
346 
347  if (State != Pred->getState()) {
348  static SimpleProgramPointTag T("ExprEngine",
349  "Prepare for object construction");
350  ExplodedNodeSet DstPrepare;
351  StmtNodeBuilder BldrPrepare(Pred, DstPrepare, *currBldrCtx);
352  BldrPrepare.generateNode(CE, Pred, State, &T, ProgramPoint::PreStmtKind);
353  assert(DstPrepare.size() <= 1);
354  if (DstPrepare.size() == 0)
355  return;
356  Pred = *BldrPrepare.begin();
357  }
358 
361  CEMgr.getCXXConstructorCall(CE, Target.getAsRegion(), State, LCtx);
362 
363  ExplodedNodeSet DstPreVisit;
364  getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, CE, *this);
365 
366  // FIXME: Is it possible and/or useful to do this before PreStmt?
367  ExplodedNodeSet PreInitialized;
368  {
369  StmtNodeBuilder Bldr(DstPreVisit, PreInitialized, *currBldrCtx);
370  for (ExplodedNodeSet::iterator I = DstPreVisit.begin(),
371  E = DstPreVisit.end();
372  I != E; ++I) {
373  ProgramStateRef State = (*I)->getState();
374  if (CE->requiresZeroInitialization()) {
375  // FIXME: Once we properly handle constructors in new-expressions, we'll
376  // need to invalidate the region before setting a default value, to make
377  // sure there aren't any lingering bindings around. This probably needs
378  // to happen regardless of whether or not the object is zero-initialized
379  // to handle random fields of a placement-initialized object picking up
380  // old bindings. We might only want to do it when we need to, though.
381  // FIXME: This isn't actually correct for arrays -- we need to zero-
382  // initialize the entire array, not just the first element -- but our
383  // handling of arrays everywhere else is weak as well, so this shouldn't
384  // actually make things worse. Placement new makes this tricky as well,
385  // since it's then possible to be initializing one part of a multi-
386  // dimensional array.
387  State = State->bindDefaultZero(Target, LCtx);
388  }
389 
390  Bldr.generateNode(CE, *I, State, /*tag=*/nullptr,
392  }
393  }
394 
395  ExplodedNodeSet DstPreCall;
396  getCheckerManager().runCheckersForPreCall(DstPreCall, PreInitialized,
397  *Call, *this);
398 
399  ExplodedNodeSet DstEvaluated;
400  StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx);
401 
402  if (CE->getConstructor()->isTrivial() &&
404  !CallOpts.IsArrayCtorOrDtor) {
405  // FIXME: Handle other kinds of trivial constructors as well.
406  for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
407  I != E; ++I)
408  performTrivialCopy(Bldr, *I, *Call);
409 
410  } else {
411  for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
412  I != E; ++I)
413  defaultEvalCall(Bldr, *I, *Call, CallOpts);
414  }
415 
416  // If the CFG was constructed without elements for temporary destructors
417  // and the just-called constructor created a temporary object then
418  // stop exploration if the temporary object has a noreturn constructor.
419  // This can lose coverage because the destructor, if it were present
420  // in the CFG, would be called at the end of the full expression or
421  // later (for life-time extended temporaries) -- but avoids infeasible
422  // paths when no-return temporary destructors are used for assertions.
423  const AnalysisDeclContext *ADC = LCtx->getAnalysisDeclContext();
425  const MemRegion *Target = Call->getCXXThisVal().getAsRegion();
426  if (Target && isa<CXXTempObjectRegion>(Target) &&
427  Call->getDecl()->getParent()->isAnyDestructorNoReturn()) {
428 
429  // If we've inlined the constructor, then DstEvaluated would be empty.
430  // In this case we still want a sink, which could be implemented
431  // in processCallExit. But we don't have that implemented at the moment,
432  // so if you hit this assertion, see if you can avoid inlining
433  // the respective constructor when analyzer-config cfg-temporary-dtors
434  // is set to false.
435  // Otherwise there's nothing wrong with inlining such constructor.
436  assert(!DstEvaluated.empty() &&
437  "We should not have inlined this constructor!");
438 
439  for (ExplodedNode *N : DstEvaluated) {
440  Bldr.generateSink(CE, N, N->getState());
441  }
442 
443  // There is no need to run the PostCall and PostStmt checker
444  // callbacks because we just generated sinks on all nodes in th
445  // frontier.
446  return;
447  }
448  }
449 
450  ExplodedNodeSet DstPostCall;
451  getCheckerManager().runCheckersForPostCall(DstPostCall, DstEvaluated,
452  *Call, *this);
453  getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, CE, *this);
454 }
455 
457  const MemRegion *Dest,
458  const Stmt *S,
459  bool IsBaseDtor,
460  ExplodedNode *Pred,
461  ExplodedNodeSet &Dst,
462  const EvalCallOptions &CallOpts) {
463  const LocationContext *LCtx = Pred->getLocationContext();
464  ProgramStateRef State = Pred->getState();
465 
466  const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl();
467  assert(RecordDecl && "Only CXXRecordDecls should have destructors");
468  const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
469 
472  CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx);
473 
474  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
475  Call->getSourceRange().getBegin(),
476  "Error evaluating destructor");
477 
478  ExplodedNodeSet DstPreCall;
479  getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
480  *Call, *this);
481 
482  ExplodedNodeSet DstInvalidated;
483  StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
484  for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
485  I != E; ++I)
486  defaultEvalCall(Bldr, *I, *Call, CallOpts);
487 
488  ExplodedNodeSet DstPostCall;
489  getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
490  *Call, *this);
491 }
492 
494  ExplodedNode *Pred,
495  ExplodedNodeSet &Dst) {
496  ProgramStateRef State = Pred->getState();
497  const LocationContext *LCtx = Pred->getLocationContext();
498  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
499  CNE->getStartLoc(),
500  "Error evaluating New Allocator Call");
503  CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
504 
505  ExplodedNodeSet DstPreCall;
506  getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
507  *Call, *this);
508 
509  ExplodedNodeSet DstPostCall;
510  StmtNodeBuilder CallBldr(DstPreCall, DstPostCall, *currBldrCtx);
511  for (auto I : DstPreCall) {
512  // FIXME: Provide evalCall for checkers?
513  defaultEvalCall(CallBldr, I, *Call);
514  }
515  // If the call is inlined, DstPostCall will be empty and we bail out now.
516 
517  // Store return value of operator new() for future use, until the actual
518  // CXXNewExpr gets processed.
519  ExplodedNodeSet DstPostValue;
520  StmtNodeBuilder ValueBldr(DstPostCall, DstPostValue, *currBldrCtx);
521  for (auto I : DstPostCall) {
522  // FIXME: Because CNE serves as the "call site" for the allocator (due to
523  // lack of a better expression in the AST), the conjured return value symbol
524  // is going to be of the same type (C++ object pointer type). Technically
525  // this is not correct because the operator new's prototype always says that
526  // it returns a 'void *'. So we should change the type of the symbol,
527  // and then evaluate the cast over the symbolic pointer from 'void *' to
528  // the object pointer type. But without changing the symbol's type it
529  // is breaking too much to evaluate the no-op symbolic cast over it, so we
530  // skip it for now.
531  ProgramStateRef State = I->getState();
532  SVal RetVal = State->getSVal(CNE, LCtx);
533 
534  // If this allocation function is not declared as non-throwing, failures
535  // /must/ be signalled by exceptions, and thus the return value will never
536  // be NULL. -fno-exceptions does not influence this semantics.
537  // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
538  // where new can return NULL. If we end up supporting that option, we can
539  // consider adding a check for it here.
540  // C++11 [basic.stc.dynamic.allocation]p3.
541  if (const FunctionDecl *FD = CNE->getOperatorNew()) {
542  QualType Ty = FD->getType();
543  if (const auto *ProtoType = Ty->getAs<FunctionProtoType>())
544  if (!ProtoType->isNothrow())
545  State = State->assume(RetVal.castAs<DefinedOrUnknownSVal>(), true);
546  }
547 
548  ValueBldr.generateNode(
549  CNE, I, addObjectUnderConstruction(State, CNE, LCtx, RetVal));
550  }
551 
552  ExplodedNodeSet DstPostPostCallCallback;
553  getCheckerManager().runCheckersForPostCall(DstPostPostCallCallback,
554  DstPostValue, *Call, *this);
555  for (auto I : DstPostPostCallCallback) {
557  CNE, *getObjectUnderConstruction(I->getState(), CNE, LCtx), Dst, I,
558  *this);
559  }
560 }
561 
563  ExplodedNodeSet &Dst) {
564  // FIXME: Much of this should eventually migrate to CXXAllocatorCall.
565  // Also, we need to decide how allocators actually work -- they're not
566  // really part of the CXXNewExpr because they happen BEFORE the
567  // CXXConstructExpr subexpression. See PR12014 for some discussion.
568 
569  unsigned blockCount = currBldrCtx->blockCount();
570  const LocationContext *LCtx = Pred->getLocationContext();
571  SVal symVal = UnknownVal();
572  FunctionDecl *FD = CNE->getOperatorNew();
573 
574  bool IsStandardGlobalOpNewFunction =
576 
577  ProgramStateRef State = Pred->getState();
578 
579  // Retrieve the stored operator new() return value.
581  symVal = *getObjectUnderConstruction(State, CNE, LCtx);
582  State = finishObjectConstruction(State, CNE, LCtx);
583  }
584 
585  // We assume all standard global 'operator new' functions allocate memory in
586  // heap. We realize this is an approximation that might not correctly model
587  // a custom global allocator.
588  if (symVal.isUnknown()) {
589  if (IsStandardGlobalOpNewFunction)
590  symVal = svalBuilder.getConjuredHeapSymbolVal(CNE, LCtx, blockCount);
591  else
592  symVal = svalBuilder.conjureSymbolVal(nullptr, CNE, LCtx, CNE->getType(),
593  blockCount);
594  }
595 
598  CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
599 
601  // Invalidate placement args.
602  // FIXME: Once we figure out how we want allocators to work,
603  // we should be using the usual pre-/(default-)eval-/post-call checks here.
604  State = Call->invalidateRegions(blockCount);
605  if (!State)
606  return;
607 
608  // If this allocation function is not declared as non-throwing, failures
609  // /must/ be signalled by exceptions, and thus the return value will never
610  // be NULL. -fno-exceptions does not influence this semantics.
611  // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
612  // where new can return NULL. If we end up supporting that option, we can
613  // consider adding a check for it here.
614  // C++11 [basic.stc.dynamic.allocation]p3.
615  if (FD) {
616  QualType Ty = FD->getType();
617  if (const auto *ProtoType = Ty->getAs<FunctionProtoType>())
618  if (!ProtoType->isNothrow())
619  if (auto dSymVal = symVal.getAs<DefinedOrUnknownSVal>())
620  State = State->assume(*dSymVal, true);
621  }
622  }
623 
624  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
625 
626  SVal Result = symVal;
627 
628  if (CNE->isArray()) {
629  // FIXME: allocating an array requires simulating the constructors.
630  // For now, just return a symbolicated region.
631  if (const SubRegion *NewReg =
632  dyn_cast_or_null<SubRegion>(symVal.getAsRegion())) {
633  QualType ObjTy = CNE->getType()->getAs<PointerType>()->getPointeeType();
634  const ElementRegion *EleReg =
635  getStoreManager().GetElementZeroRegion(NewReg, ObjTy);
636  Result = loc::MemRegionVal(EleReg);
637  }
638  State = State->BindExpr(CNE, Pred->getLocationContext(), Result);
639  Bldr.generateNode(CNE, Pred, State);
640  return;
641  }
642 
643  // FIXME: Once we have proper support for CXXConstructExprs inside
644  // CXXNewExpr, we need to make sure that the constructed object is not
645  // immediately invalidated here. (The placement call should happen before
646  // the constructor call anyway.)
647  if (FD && FD->isReservedGlobalPlacementOperator()) {
648  // Non-array placement new should always return the placement location.
649  SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx);
650  Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(),
651  CNE->getPlacementArg(0)->getType());
652  }
653 
654  // Bind the address of the object, then check to see if we cached out.
655  State = State->BindExpr(CNE, LCtx, Result);
656  ExplodedNode *NewN = Bldr.generateNode(CNE, Pred, State);
657  if (!NewN)
658  return;
659 
660  // If the type is not a record, we won't have a CXXConstructExpr as an
661  // initializer. Copy the value over.
662  if (const Expr *Init = CNE->getInitializer()) {
663  if (!isa<CXXConstructExpr>(Init)) {
664  assert(Bldr.getResults().size() == 1);
665  Bldr.takeNodes(NewN);
666  evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, LCtx),
667  /*FirstInit=*/IsStandardGlobalOpNewFunction);
668  }
669  }
670 }
671 
673  ExplodedNode *Pred, ExplodedNodeSet &Dst) {
674  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
675  ProgramStateRef state = Pred->getState();
676  Bldr.generateNode(CDE, Pred, state);
677 }
678 
680  ExplodedNode *Pred,
681  ExplodedNodeSet &Dst) {
682  const VarDecl *VD = CS->getExceptionDecl();
683  if (!VD) {
684  Dst.Add(Pred);
685  return;
686  }
687 
688  const LocationContext *LCtx = Pred->getLocationContext();
689  SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(),
690  currBldrCtx->blockCount());
691  ProgramStateRef state = Pred->getState();
692  state = state->bindLoc(state->getLValue(VD, LCtx), V, LCtx);
693 
694  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
695  Bldr.generateNode(CS, Pred, state);
696 }
697 
699  ExplodedNodeSet &Dst) {
700  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
701 
702  // Get the this object region from StoreManager.
703  const LocationContext *LCtx = Pred->getLocationContext();
704  const MemRegion *R =
705  svalBuilder.getRegionManager().getCXXThisRegion(
706  getContext().getCanonicalType(TE->getType()),
707  LCtx);
708 
709  ProgramStateRef state = Pred->getState();
710  SVal V = state->getSVal(loc::MemRegionVal(R));
711  Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V));
712 }
713 
715  ExplodedNodeSet &Dst) {
716  const LocationContext *LocCtxt = Pred->getLocationContext();
717 
718  // Get the region of the lambda itself.
719  const MemRegion *R = svalBuilder.getRegionManager().getCXXTempObjectRegion(
720  LE, LocCtxt);
721  SVal V = loc::MemRegionVal(R);
722 
723  ProgramStateRef State = Pred->getState();
724 
725  // If we created a new MemRegion for the lambda, we should explicitly bind
726  // the captures.
729  e = LE->capture_init_end();
730  i != e; ++i, ++CurField) {
731  FieldDecl *FieldForCapture = *CurField;
732  SVal FieldLoc = State->getLValue(FieldForCapture, V);
733 
734  SVal InitVal;
735  if (!FieldForCapture->hasCapturedVLAType()) {
736  Expr *InitExpr = *i;
737  assert(InitExpr && "Capture missing initialization expression");
738  InitVal = State->getSVal(InitExpr, LocCtxt);
739  } else {
740  // The field stores the length of a captured variable-length array.
741  // These captures don't have initialization expressions; instead we
742  // get the length from the VLAType size expression.
743  Expr *SizeExpr = FieldForCapture->getCapturedVLAType()->getSizeExpr();
744  InitVal = State->getSVal(SizeExpr, LocCtxt);
745  }
746 
747  State = State->bindLoc(FieldLoc, InitVal, LocCtxt);
748  }
749 
750  // Decay the Loc into an RValue, because there might be a
751  // MaterializeTemporaryExpr node above this one which expects the bound value
752  // to be an RValue.
753  SVal LambdaRVal = State->getSVal(R);
754 
755  ExplodedNodeSet Tmp;
756  StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
757  // FIXME: is this the right program point kind?
758  Bldr.generateNode(LE, Pred,
759  State->BindExpr(LE, LocCtxt, LambdaRVal),
761 
762  // FIXME: Move all post/pre visits to ::Visit().
763  getCheckerManager().runCheckersForPostStmt(Dst, Tmp, LE, *this);
764 }
bool hasCapturedVLAType() const
Determine whether this member captures the variable length array type.
Definition: Decl.h:2689
Represents a function declaration or definition.
Definition: Decl.h:1714
bool isReservedGlobalPlacementOperator() const
Determines whether this operator new or delete is one of the reserved global placement operators: voi...
Definition: Decl.cpp:2726
SVal evalDerivedToBase(SVal Derived, const CastExpr *Cast)
Evaluates a chain of derived-to-base casts through the path specified in Cast.
Definition: Store.cpp:248
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2375
A (possibly-)qualified type.
Definition: Type.h:655
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:94
bool IsTemporaryCtorOrDtor
This call is a constructor or a destructor of a temporary value.
Definition: ExprEngine.h:106
unsigned blockCount() const
Returns the number of times the current basic block has been visited on the exploded graph path...
Definition: CoreEngine.h:212
Stmt - This represents one statement.
Definition: Stmt.h:66
This builder class is useful for generating nodes that resulted from visiting a statement.
Definition: CoreEngine.h:370
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
FunctionDecl * getOperatorNew() const
Definition: ExprCXX.h:1945
Manages the lifetime of CallEvent objects.
Definition: CallEvent.h:1009
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called...
Definition: ExprCXX.h:1329
CallEventRef< CXXDestructorCall > getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger, const MemRegion *Target, bool IsBase, ProgramStateRef State, const LocationContext *LCtx)
Definition: CallEvent.h:1083
Stmt * getParent(Stmt *) const
Definition: ParentMap.cpp:123
Hints for figuring out of a call should be inlined during evalCall().
Definition: ExprEngine.h:96
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2650
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1239
bool IsArrayCtorOrDtor
This call is a constructor or a destructor for a single element within an array, a part of array cons...
Definition: ExprEngine.h:103
const ProgramStateRef & getState() const
SVal evalCast(SVal val, QualType castTy, QualType originalType)
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:4039
const Expr * getOriginExpr() const
Returns the expression whose value will be the result of this call.
Definition: CallEvent.h:248
void takeNodes(const ExplodedNodeSet &S)
Definition: CoreEngine.h:321
Represents a variable declaration or definition.
Definition: Decl.h:812
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6456
loc::MemRegionVal getCXXThis(const CXXMethodDecl *D, const StackFrameContext *SFC)
Return a memory region for the &#39;this&#39; object reference.
const ElementRegion * GetElementZeroRegion(const SubRegion *R, QualType T)
Definition: Store.cpp:68
void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition: ExprCXX.cpp:998
CFGCXXRecordTypedCall - Represents a function call that returns a C++ object by value.
Definition: CFG.h:178
Represents a struct/union/class.
Definition: Decl.h:3548
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1317
Expr * GetTemporaryExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue...
Definition: ExprCXX.h:4080
MemRegionManager & getRegionManager()
Definition: SValBuilder.h:175
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:150
LineState State
Represents a member of a struct/union/class.
Definition: Decl.h:2521
AnalysisDeclContext contains the context data for the function or method under analysis.
Expr * getPlacementArg(unsigned i)
Definition: ExprCXX.h:1965
i32 captured_struct **param SharedsTy A type which contains references the shared variables *param Shareds Context with the list of shared variables from the p *TaskFunction *param Data Additional data for task generation like final * state
bool isReplaceableGlobalAllocationFunction(bool *IsAligned=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:2749
ExplodedNode * generateSink(const Stmt *S, ExplodedNode *Pred, ProgramStateRef St, const ProgramPointTag *tag=nullptr, ProgramPoint::Kind K=ProgramPoint::PostStmtKind)
Definition: CoreEngine.h:409
void runCheckersForPreCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &Call, ExprEngine &Eng)
Run checkers for pre-visiting obj-c messages.
CFGElement getCurrentCFGElement()
Return the CFG element corresponding to the worklist element that is currently being processed by Exp...
Definition: ExprEngine.h:636
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition: ExprCXX.h:1728
Expr * getInitializer()
The initializer of this new-expression.
Definition: ExprCXX.h:1990
const StackFrameContext * getCurrentStackFrame() const
const LocationContext * getLocationContext() const
const LocationContext * getParent() const
bool isUnknown() const
Definition: SVals.h:137
If a crash happens while one of these objects are live, the message is printed out along with the spe...
Expr * getSizeExpr() const
Definition: Type.h:2829
field_iterator field_begin() const
Definition: Decl.cpp:4027
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1196
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1583
void runCheckersForPostCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &Call, ExprEngine &Eng, bool wasInlined=false)
Run checkers for post-visiting obj-c messages.
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1663
Represents the this expression in C++.
Definition: ExprCXX.h:945
const CFGBlock * getCallSiteBlock() const
void evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, ExplodedNode *Pred, SVal location, SVal Val, bool atDeclInit=false, const ProgramPoint *PP=nullptr)
evalBind - Handle the semantics of binding a value to a specific location.
CheckerManager & getCheckerManager() const
Definition: ExprEngine.h:186
const ValueDecl * getExtendingDecl() const
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition: ExprCXX.h:4102
ProgramStateRef bindReturnValue(const CallEvent &Call, const LocationContext *LCtx, ProgramStateRef State)
Create a new state in which the call return value is binded to the call origin expression.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1590
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3369
const Stmt * getCallSite() const
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1302
void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void runCheckersForPostStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng, bool wasInlined=false)
Run checkers for post-visiting Stmts.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:636
Expr - This represents one expression.
Definition: Expr.h:106
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition: DeclCXX.cpp:2313
void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
const FunctionProtoType * T
void VisitCXXNewAllocatorCall(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2686
AnalyzerOptions & getAnalyzerOptions() override
VarDecl * getExceptionDecl() const
Definition: StmtCXX.h:50
This is the simplest builder which generates nodes in the ExplodedGraph.
Definition: CoreEngine.h:228
CFGConstructor - Represents C++ constructor call.
Definition: CFG.h:150
void Add(ExplodedNode *N)
const ExplodedNodeSet & getResults()
Definition: CoreEngine.h:298
QualType getType() const
Definition: Expr.h:128
virtual const Decl * getDecl() const
Returns the declaration of the function or method that will be called.
Definition: CallEvent.h:228
ASTContext & getContext() const
getContext - Return the ASTContext associated with this analysis.
Definition: ExprEngine.h:182
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1341
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition: ExprCXX.h:4083
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2050
ParentMap & getParentMap() const
Optional< T > getAs() const
Convert to the specified SVal type, returning None if this SVal is not of the desired type...
Definition: SVals.h:112
void runCheckersForNewAllocator(const CXXNewExpr *NE, SVal Target, ExplodedNodeSet &Dst, ExplodedNode *Pred, ExprEngine &Eng, bool wasInlined=false)
Run checkers between C++ operator new and constructor calls.
CallEventRef< CXXAllocatorCall > getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State, const LocationContext *LCtx)
Definition: CallEvent.h:1090
DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag, const Expr *expr, const LocationContext *LCtx, unsigned count)
Create a new symbol with a unique &#39;name&#39;.
const MemRegion * getAsRegion() const
Definition: SVals.cpp:151
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
Definition: ExprCXX.h:1845
const VariableArrayType * getCapturedVLAType() const
Get the captured variable length array type.
Definition: Decl.h:2694
CallEventManager & getCallEventManager()
Definition: ProgramState.h:566
const CXXTempObjectRegion * getCXXTempObjectRegion(Expr const *Ex, LocationContext const *LC)
Definition: MemRegion.cpp:1015
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2031
ASTContext & getContext()
Definition: SValBuilder.h:156
void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
bool IsCtorOrDtorWithImproperlyModeledTargetRegion
This call is a constructor or a destructor for which we do not currently compute the this-region corr...
Definition: ExprEngine.h:99
SVal - This represents a symbolic expression, which can be either an L-value or an R-value...
Definition: SVals.h:76
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
bool isArray() const
Definition: ExprCXX.h:1950
void runCheckersForPreStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng)
Run checkers for pre-visiting Stmts.
DefinedOrUnknownSVal getConjuredHeapSymbolVal(const Expr *E, const LocationContext *LCtx, unsigned Count)
Conjure a symbol representing heap allocated memory region.
const CXXThisRegion * getCXXThisRegion(QualType thisPointerTy, const LocationContext *LC)
getCXXThisRegion - Retrieve the [artificial] region associated with the parameter &#39;this&#39;...
Definition: MemRegion.cpp:1065
Optional< T > getAs() const
Convert to the specified CFGElement type, returning None if this CFGElement is not of the desired typ...
Definition: CFG.h:109
Dataflow Directional Tag Classes.
CFG::BuildOptions & getCFGBuildOptions()
Return the build options used to construct the CFG.
SValBuilder & getSValBuilder()
Definition: ExprEngine.h:190
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
Definition: ExprCXX.h:2074
StoreManager & getStoreManager()
Definition: ExprEngine.h:372
void VisitCXXDestructor(QualType ObjectType, const MemRegion *Dest, const Stmt *S, bool IsBaseDtor, ExplodedNode *Pred, ExplodedNodeSet &Dst, const EvalCallOptions &Options)
void VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitLambdaExpr - Transfer function logic for LambdaExprs.
Represents an abstract call to a function or method along a particular path.
Definition: CallEvent.h:164
ProgramStateManager & getStateManager() override
Definition: ExprEngine.h:370
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
Definition: DeclBase.h:1606
const Decl * getDecl() const
void defaultEvalCall(NodeBuilder &B, ExplodedNode *Pred, const CallEvent &Call, const EvalCallOptions &CallOpts={})
Default implementation of call evaluation.
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition: SVals.h:104
SubRegion - A region that subsets another larger region.
Definition: MemRegion.h:431
void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
CallEventRef< CXXConstructorCall > getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target, ProgramStateRef State, const LocationContext *LCtx)
Definition: CallEvent.h:1077
ExplodedNode * generateNode(const ProgramPoint &PP, ProgramStateRef State, ExplodedNode *Pred)
Generates a node in the ExplodedGraph.
Definition: CoreEngine.h:281
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
ConstructionContext&#39;s subclasses describe different ways of constructing an object in C++...
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
bool IsTemporaryLifetimeExtendedViaAggregate
This call is a constructor for a temporary that is lifetime-extended by binding it to a reference-typ...
Definition: ExprEngine.h:111
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:29
Full-expression storage duration (for temporaries).
Definition: Specifiers.h:277
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2283
ExplodedNode * generateNode(const Stmt *S, ExplodedNode *Pred, ProgramStateRef St, const ProgramPointTag *tag=nullptr, ProgramPoint::Kind K=ProgramPoint::PostStmtKind)
Definition: CoreEngine.h:399
iterator begin()
Iterators through the results frontier.
Definition: CoreEngine.h:307
ElementRegin is used to represent both array elements and casts.
Definition: MemRegion.h:1076
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression...
Definition: ExprCXX.h:1740
Expr *const * const_capture_init_iterator
Const iterator that walks over the capture initialization arguments.
Definition: ExprCXX.h:1714
SourceLocation getStartLoc() const
Definition: ExprCXX.h:2050
bool mayInlineCXXAllocator()
Returns whether or not allocator call may be considered for inlining.
virtual SVal getArgSVal(unsigned Index) const
Returns the value of a given argument at the time of the call.
Definition: CallEvent.cpp:268
QualType getType() const
Definition: Decl.h:647
AnalysisDeclContext * getAnalysisDeclContext() const
void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Create a C++ temporary object for an rvalue.
Represents a call to a C++ constructor.
Definition: CallEvent.h:786
bool isUnknownOrUndef() const
Definition: SVals.h:145
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2469
ConstructionKind getConstructionKind() const
Determine whether this constructor is actually constructing a base class (rather than a complete obje...
Definition: ExprCXX.h:1336