clang  3.9.0
ExprEngine.cpp
Go to the documentation of this file.
1 //=-- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- 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 a meta-engine for path-sensitive dataflow analysis that
11 // is built on GREngine, but provides the boilerplate to execute transfer
12 // functions and build the ExplodedGraph at the expression level.
13 //
14 //===----------------------------------------------------------------------===//
15 
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ParentMap.h"
20 #include "clang/AST/StmtCXX.h"
21 #include "clang/AST/StmtObjC.h"
22 #include "clang/Basic/Builtins.h"
30 #include "llvm/ADT/ImmutableList.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Support/SaveAndRestore.h"
34 
35 #ifndef NDEBUG
36 #include "llvm/Support/GraphWriter.h"
37 #endif
38 
39 using namespace clang;
40 using namespace ento;
41 using llvm::APSInt;
42 
43 #define DEBUG_TYPE "ExprEngine"
44 
45 STATISTIC(NumRemoveDeadBindings,
46  "The # of times RemoveDeadBindings is called");
47 STATISTIC(NumMaxBlockCountReached,
48  "The # of aborted paths due to reaching the maximum block count in "
49  "a top level function");
50 STATISTIC(NumMaxBlockCountReachedInInlined,
51  "The # of aborted paths due to reaching the maximum block count in "
52  "an inlined function");
53 STATISTIC(NumTimesRetriedWithoutInlining,
54  "The # of times we re-evaluated a call without inlining");
55 
56 typedef std::pair<const CXXBindTemporaryExpr *, const StackFrameContext *>
58 
59 // Keeps track of whether CXXBindTemporaryExpr nodes have been evaluated.
60 // The StackFrameContext assures that nested calls due to inlined recursive
61 // functions do not interfere.
62 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedTemporariesSet,
64 
65 //===----------------------------------------------------------------------===//
66 // Engine construction and deletion.
67 //===----------------------------------------------------------------------===//
68 
69 static const char* TagProviderName = "ExprEngine";
70 
71 ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled,
72  SetOfConstDecls *VisitedCalleesIn,
74  InliningModes HowToInlineIn)
75  : AMgr(mgr),
76  AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
77  Engine(*this, FS),
78  G(Engine.getGraph()),
79  StateMgr(getContext(), mgr.getStoreManagerCreator(),
80  mgr.getConstraintManagerCreator(), G.getAllocator(),
81  this),
82  SymMgr(StateMgr.getSymbolManager()),
83  svalBuilder(StateMgr.getSValBuilder()),
84  currStmtIdx(0), currBldrCtx(nullptr),
85  ObjCNoRet(mgr.getASTContext()),
86  ObjCGCEnabled(gcEnabled), BR(mgr, *this),
87  VisitedCallees(VisitedCalleesIn),
88  HowToInline(HowToInlineIn)
89 {
90  unsigned TrimInterval = mgr.options.getGraphTrimInterval();
91  if (TrimInterval != 0) {
92  // Enable eager node reclaimation when constructing the ExplodedGraph.
93  G.enableNodeReclamation(TrimInterval);
94  }
95 }
96 
98  BR.FlushReports();
99 }
100 
101 //===----------------------------------------------------------------------===//
102 // Utility methods.
103 //===----------------------------------------------------------------------===//
104 
106  ProgramStateRef state = StateMgr.getInitialState(InitLoc);
107  const Decl *D = InitLoc->getDecl();
108 
109  // Preconditions.
110  // FIXME: It would be nice if we had a more general mechanism to add
111  // such preconditions. Some day.
112  do {
113 
114  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
115  // Precondition: the first argument of 'main' is an integer guaranteed
116  // to be > 0.
117  const IdentifierInfo *II = FD->getIdentifier();
118  if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
119  break;
120 
121  const ParmVarDecl *PD = FD->getParamDecl(0);
122  QualType T = PD->getType();
123  const BuiltinType *BT = dyn_cast<BuiltinType>(T);
124  if (!BT || !BT->isInteger())
125  break;
126 
127  const MemRegion *R = state->getRegion(PD, InitLoc);
128  if (!R)
129  break;
130 
131  SVal V = state->getSVal(loc::MemRegionVal(R));
132  SVal Constraint_untested = evalBinOp(state, BO_GT, V,
133  svalBuilder.makeZeroVal(T),
134  svalBuilder.getConditionType());
135 
136  Optional<DefinedOrUnknownSVal> Constraint =
137  Constraint_untested.getAs<DefinedOrUnknownSVal>();
138 
139  if (!Constraint)
140  break;
141 
142  if (ProgramStateRef newState = state->assume(*Constraint, true))
143  state = newState;
144  }
145  break;
146  }
147  while (0);
148 
149  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
150  // Precondition: 'self' is always non-null upon entry to an Objective-C
151  // method.
152  const ImplicitParamDecl *SelfD = MD->getSelfDecl();
153  const MemRegion *R = state->getRegion(SelfD, InitLoc);
154  SVal V = state->getSVal(loc::MemRegionVal(R));
155 
156  if (Optional<Loc> LV = V.getAs<Loc>()) {
157  // Assume that the pointer value in 'self' is non-null.
158  state = state->assume(*LV, true);
159  assert(state && "'self' cannot be null");
160  }
161  }
162 
163  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
164  if (!MD->isStatic()) {
165  // Precondition: 'this' is always non-null upon entry to the
166  // top-level function. This is our starting assumption for
167  // analyzing an "open" program.
168  const StackFrameContext *SFC = InitLoc->getCurrentStackFrame();
169  if (SFC->getParent() == nullptr) {
170  loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
171  SVal V = state->getSVal(L);
172  if (Optional<Loc> LV = V.getAs<Loc>()) {
173  state = state->assume(*LV, true);
174  assert(state && "'this' cannot be null");
175  }
176  }
177  }
178  }
179 
180  return state;
181 }
182 
184 ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State,
185  const LocationContext *LC,
186  const Expr *Ex,
187  const Expr *Result) {
188  SVal V = State->getSVal(Ex, LC);
189  if (!Result) {
190  // If we don't have an explicit result expression, we're in "if needed"
191  // mode. Only create a region if the current value is a NonLoc.
192  if (!V.getAs<NonLoc>())
193  return State;
194  Result = Ex;
195  } else {
196  // We need to create a region no matter what. For sanity, make sure we don't
197  // try to stuff a Loc into a non-pointer temporary region.
198  assert(!V.getAs<Loc>() || Loc::isLocType(Result->getType()) ||
199  Result->getType()->isMemberPointerType());
200  }
201 
202  ProgramStateManager &StateMgr = State->getStateManager();
203  MemRegionManager &MRMgr = StateMgr.getRegionManager();
204  StoreManager &StoreMgr = StateMgr.getStoreManager();
205 
206  // We need to be careful about treating a derived type's value as
207  // bindings for a base type. Unless we're creating a temporary pointer region,
208  // start by stripping and recording base casts.
210  const Expr *Inner = Ex->IgnoreParens();
211  if (!Loc::isLocType(Result->getType())) {
212  while (const CastExpr *CE = dyn_cast<CastExpr>(Inner)) {
213  if (CE->getCastKind() == CK_DerivedToBase ||
214  CE->getCastKind() == CK_UncheckedDerivedToBase)
215  Casts.push_back(CE);
216  else if (CE->getCastKind() != CK_NoOp)
217  break;
218 
219  Inner = CE->getSubExpr()->IgnoreParens();
220  }
221  }
222 
223  // Create a temporary object region for the inner expression (which may have
224  // a more derived type) and bind the value into it.
225  const TypedValueRegion *TR = nullptr;
226  if (const MaterializeTemporaryExpr *MT =
227  dyn_cast<MaterializeTemporaryExpr>(Result)) {
228  StorageDuration SD = MT->getStorageDuration();
229  // If this object is bound to a reference with static storage duration, we
230  // put it in a different region to prevent "address leakage" warnings.
231  if (SD == SD_Static || SD == SD_Thread)
232  TR = MRMgr.getCXXStaticTempObjectRegion(Inner);
233  }
234  if (!TR)
235  TR = MRMgr.getCXXTempObjectRegion(Inner, LC);
236 
237  SVal Reg = loc::MemRegionVal(TR);
238 
239  if (V.isUnknown())
240  V = getSValBuilder().conjureSymbolVal(Result, LC, TR->getValueType(),
241  currBldrCtx->blockCount());
242  State = State->bindLoc(Reg, V);
243 
244  // Re-apply the casts (from innermost to outermost) for type sanity.
246  E = Casts.rend();
247  I != E; ++I) {
248  Reg = StoreMgr.evalDerivedToBase(Reg, *I);
249  }
250 
251  State = State->BindExpr(Result, LC, Reg);
252  return State;
253 }
254 
255 //===----------------------------------------------------------------------===//
256 // Top-level transfer function logic (Dispatcher).
257 //===----------------------------------------------------------------------===//
258 
259 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
260 /// logic for handling assumptions on symbolic values.
262  SVal cond, bool assumption) {
263  return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
264 }
265 
268 }
269 
272  const InvalidatedSymbols *invalidated,
273  ArrayRef<const MemRegion *> Explicits,
275  const CallEvent *Call) {
276  return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
277  Explicits, Regions, Call);
278 }
279 
280 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
281  const char *NL, const char *Sep) {
282  getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
283 }
284 
285 void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
287 }
288 
290  unsigned StmtIdx, NodeBuilderContext *Ctx) {
292  currStmtIdx = StmtIdx;
293  currBldrCtx = Ctx;
294 
295  switch (E.getKind()) {
297  ProcessStmt(const_cast<Stmt*>(E.castAs<CFGStmt>().getStmt()), Pred);
298  return;
301  return;
304  Pred);
305  return;
312  return;
313  }
314 }
315 
317  const CFGStmt S,
318  const ExplodedNode *Pred,
319  const LocationContext *LC) {
320 
321  // Are we never purging state values?
322  if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
323  return false;
324 
325  // Is this the beginning of a basic block?
326  if (Pred->getLocation().getAs<BlockEntrance>())
327  return true;
328 
329  // Is this on a non-expression?
330  if (!isa<Expr>(S.getStmt()))
331  return true;
332 
333  // Run before processing a call.
335  return true;
336 
337  // Is this an expression that is consumed by another expression? If so,
338  // postpone cleaning out the state.
340  return !PM.isConsumedExpr(cast<Expr>(S.getStmt()));
341 }
342 
344  const Stmt *ReferenceStmt,
345  const LocationContext *LC,
346  const Stmt *DiagnosticStmt,
347  ProgramPoint::Kind K) {
349  ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
350  && "PostStmt is not generally supported by the SymbolReaper yet");
351  assert(LC && "Must pass the current (or expiring) LocationContext");
352 
353  if (!DiagnosticStmt) {
354  DiagnosticStmt = ReferenceStmt;
355  assert(DiagnosticStmt && "Required for clearing a LocationContext");
356  }
357 
358  NumRemoveDeadBindings++;
359  ProgramStateRef CleanedState = Pred->getState();
360 
361  // LC is the location context being destroyed, but SymbolReaper wants a
362  // location context that is still live. (If this is the top-level stack
363  // frame, this will be null.)
364  if (!ReferenceStmt) {
366  "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
367  LC = LC->getParent();
368  }
369 
370  const StackFrameContext *SFC = LC ? LC->getCurrentStackFrame() : nullptr;
371  SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
372 
373  getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
374 
375  // Create a state in which dead bindings are removed from the environment
376  // and the store. TODO: The function should just return new env and store,
377  // not a new state.
378  CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
379 
380  // Process any special transfer function for dead symbols.
381  // A tag to track convenience transitions, which can be removed at cleanup.
382  static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
383  if (!SymReaper.hasDeadSymbols()) {
384  // Generate a CleanedNode that has the environment and store cleaned
385  // up. Since no symbols are dead, we can optimize and not clean out
386  // the constraint manager.
387  StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx);
388  Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K);
389 
390  } else {
391  // Call checkers with the non-cleaned state so that they could query the
392  // values of the soon to be dead symbols.
393  ExplodedNodeSet CheckedSet;
394  getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
395  DiagnosticStmt, *this, K);
396 
397  // For each node in CheckedSet, generate CleanedNodes that have the
398  // environment, the store, and the constraints cleaned up but have the
399  // user-supplied states as the predecessors.
400  StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
402  I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) {
403  ProgramStateRef CheckerState = (*I)->getState();
404 
405  // The constraint manager has not been cleaned up yet, so clean up now.
406  CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
407  SymReaper);
408 
409  assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
410  "Checkers are not allowed to modify the Environment as a part of "
411  "checkDeadSymbols processing.");
412  assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
413  "Checkers are not allowed to modify the Store as a part of "
414  "checkDeadSymbols processing.");
415 
416  // Create a state based on CleanedState with CheckerState GDM and
417  // generate a transition to that state.
418  ProgramStateRef CleanedCheckerSt =
419  StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
420  Bldr.generateNode(DiagnosticStmt, *I, CleanedCheckerSt, &cleanupTag, K);
421  }
422  }
423 }
424 
426  ExplodedNode *Pred) {
427  // Reclaim any unnecessary nodes in the ExplodedGraph.
429 
430  const Stmt *currStmt = S.getStmt();
431  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
432  currStmt->getLocStart(),
433  "Error evaluating statement");
434 
435  // Remove dead bindings and symbols.
436  ExplodedNodeSet CleanedStates;
437  if (shouldRemoveDeadBindings(AMgr, S, Pred, Pred->getLocationContext())){
438  removeDead(Pred, CleanedStates, currStmt, Pred->getLocationContext());
439  } else
440  CleanedStates.Add(Pred);
441 
442  // Visit the statement.
443  ExplodedNodeSet Dst;
444  for (ExplodedNodeSet::iterator I = CleanedStates.begin(),
445  E = CleanedStates.end(); I != E; ++I) {
446  ExplodedNodeSet DstI;
447  // Visit the statement.
448  Visit(currStmt, *I, DstI);
449  Dst.insert(DstI);
450  }
451 
452  // Enqueue the new nodes onto the work list.
453  Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
454 }
455 
457  ExplodedNode *Pred) {
458  const CXXCtorInitializer *BMI = Init.getInitializer();
459 
460  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
461  BMI->getSourceLocation(),
462  "Error evaluating initializer");
463 
464  // We don't clean up dead bindings here.
465  const StackFrameContext *stackFrame =
466  cast<StackFrameContext>(Pred->getLocationContext());
467  const CXXConstructorDecl *decl =
468  cast<CXXConstructorDecl>(stackFrame->getDecl());
469 
470  ProgramStateRef State = Pred->getState();
471  SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
472 
473  ExplodedNodeSet Tmp(Pred);
474  SVal FieldLoc;
475 
476  // Evaluate the initializer, if necessary
477  if (BMI->isAnyMemberInitializer()) {
478  // Constructors build the object directly in the field,
479  // but non-objects must be copied in from the initializer.
480  if (auto *CtorExpr = findDirectConstructorForCurrentCFGElement()) {
481  assert(BMI->getInit()->IgnoreImplicit() == CtorExpr);
482  (void)CtorExpr;
483  // The field was directly constructed, so there is no need to bind.
484  } else {
485  const Expr *Init = BMI->getInit()->IgnoreImplicit();
486  const ValueDecl *Field;
487  if (BMI->isIndirectMemberInitializer()) {
488  Field = BMI->getIndirectMember();
489  FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
490  } else {
491  Field = BMI->getMember();
492  FieldLoc = State->getLValue(BMI->getMember(), thisVal);
493  }
494 
495  SVal InitVal;
496  if (BMI->getNumArrayIndices() > 0) {
497  // Handle arrays of trivial type. We can represent this with a
498  // primitive load/copy from the base array region.
499  const ArraySubscriptExpr *ASE;
500  while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
501  Init = ASE->getBase()->IgnoreImplicit();
502 
503  SVal LValue = State->getSVal(Init, stackFrame);
504  if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
505  InitVal = State->getSVal(*LValueLoc);
506 
507  // If we fail to get the value for some reason, use a symbolic value.
508  if (InitVal.isUnknownOrUndef()) {
509  SValBuilder &SVB = getSValBuilder();
510  InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
511  Field->getType(),
512  currBldrCtx->blockCount());
513  }
514  } else {
515  InitVal = State->getSVal(BMI->getInit(), stackFrame);
516  }
517 
518  assert(Tmp.size() == 1 && "have not generated any new nodes yet");
519  assert(*Tmp.begin() == Pred && "have not generated any new nodes yet");
520  Tmp.clear();
521 
522  PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
523  evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
524  }
525  } else {
526  assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
527  // We already did all the work when visiting the CXXConstructExpr.
528  }
529 
530  // Construct PostInitializer nodes whether the state changed or not,
531  // so that the diagnostics don't get confused.
532  PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
533  ExplodedNodeSet Dst;
534  NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
535  for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) {
536  ExplodedNode *N = *I;
537  Bldr.generateNode(PP, N->getState(), N);
538  }
539 
540  // Enqueue the new nodes onto the work list.
541  Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
542 }
543 
545  ExplodedNode *Pred) {
546  ExplodedNodeSet Dst;
547  switch (D.getKind()) {
550  break;
552  ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
553  break;
555  ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
556  break;
559  break;
561  ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
562  break;
563  default:
564  llvm_unreachable("Unexpected dtor kind.");
565  }
566 
567  // Enqueue the new nodes onto the work list.
568  Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
569 }
570 
572  ExplodedNode *Pred) {
573  ExplodedNodeSet Dst;
575  AnalyzerOptions &Opts = AMgr.options;
576  // TODO: We're not evaluating allocators for all cases just yet as
577  // we're not handling the return value correctly, which causes false
578  // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
579  if (Opts.mayInlineCXXAllocator())
580  VisitCXXNewAllocatorCall(NE, Pred, Dst);
581  else {
582  NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
583  const LocationContext *LCtx = Pred->getLocationContext();
584  PostImplicitCall PP(NE->getOperatorNew(), NE->getLocStart(), LCtx);
585  Bldr.generateNode(PP, Pred->getState(), Pred);
586  }
587  Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
588 }
589 
591  ExplodedNode *Pred,
592  ExplodedNodeSet &Dst) {
593  const VarDecl *varDecl = Dtor.getVarDecl();
594  QualType varType = varDecl->getType();
595 
596  ProgramStateRef state = Pred->getState();
597  SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
598  const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
599 
600  if (const ReferenceType *refType = varType->getAs<ReferenceType>()) {
601  varType = refType->getPointeeType();
602  Region = state->getSVal(Region).getAsRegion();
603  }
604 
605  VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
606  Pred, Dst);
607 }
608 
610  ExplodedNode *Pred,
611  ExplodedNodeSet &Dst) {
612  ProgramStateRef State = Pred->getState();
613  const LocationContext *LCtx = Pred->getLocationContext();
614  const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
615  const Stmt *Arg = DE->getArgument();
616  SVal ArgVal = State->getSVal(Arg, LCtx);
617 
618  // If the argument to delete is known to be a null value,
619  // don't run destructor.
620  if (State->isNull(ArgVal).isConstrainedTrue()) {
621  QualType DTy = DE->getDestroyedType();
623  const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
624  const CXXDestructorDecl *Dtor = RD->getDestructor();
625 
626  PostImplicitCall PP(Dtor, DE->getLocStart(), LCtx);
627  NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
628  Bldr.generateNode(PP, Pred->getState(), Pred);
629  return;
630  }
631 
633  ArgVal.getAsRegion(),
634  DE, /*IsBase=*/ false,
635  Pred, Dst);
636 }
637 
639  ExplodedNode *Pred, ExplodedNodeSet &Dst) {
640  const LocationContext *LCtx = Pred->getLocationContext();
641 
642  const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
643  Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
644  LCtx->getCurrentStackFrame());
645  SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
646 
647  // Create the base object region.
649  QualType BaseTy = Base->getType();
650  SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
651  Base->isVirtual());
652 
654  CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst);
655 }
656 
658  ExplodedNode *Pred, ExplodedNodeSet &Dst) {
659  const FieldDecl *Member = D.getFieldDecl();
660  ProgramStateRef State = Pred->getState();
661  const LocationContext *LCtx = Pred->getLocationContext();
662 
663  const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
664  Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
665  LCtx->getCurrentStackFrame());
666  SVal FieldVal =
667  State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
668 
669  VisitCXXDestructor(Member->getType(),
670  FieldVal.castAs<loc::MemRegionVal>().getRegion(),
671  CurDtor->getBody(), /*IsBase=*/false, Pred, Dst);
672 }
673 
675  ExplodedNode *Pred,
676  ExplodedNodeSet &Dst) {
677  ExplodedNodeSet CleanDtorState;
678  StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx);
679  ProgramStateRef State = Pred->getState();
680  if (State->contains<InitializedTemporariesSet>(
681  std::make_pair(D.getBindTemporaryExpr(), Pred->getStackFrame()))) {
682  // FIXME: Currently we insert temporary destructors for default parameters,
683  // but we don't insert the constructors.
684  State = State->remove<InitializedTemporariesSet>(
685  std::make_pair(D.getBindTemporaryExpr(), Pred->getStackFrame()));
686  }
687  StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
688 
689  QualType varType = D.getBindTemporaryExpr()->getSubExpr()->getType();
690  // FIXME: Currently CleanDtorState can be empty here due to temporaries being
691  // bound to default parameters.
692  assert(CleanDtorState.size() <= 1);
693  ExplodedNode *CleanPred =
694  CleanDtorState.empty() ? Pred : *CleanDtorState.begin();
695  // FIXME: Inlining of temporary destructors is not supported yet anyway, so
696  // we just put a NULL region for now. This will need to be changed later.
697  VisitCXXDestructor(varType, nullptr, D.getBindTemporaryExpr(),
698  /*IsBase=*/false, CleanPred, Dst);
699 }
700 
702  NodeBuilderContext &BldCtx,
703  ExplodedNode *Pred,
704  ExplodedNodeSet &Dst,
705  const CFGBlock *DstT,
706  const CFGBlock *DstF) {
707  BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF);
708  if (Pred->getState()->contains<InitializedTemporariesSet>(
709  std::make_pair(BTE, Pred->getStackFrame()))) {
710  TempDtorBuilder.markInfeasible(false);
711  TempDtorBuilder.generateNode(Pred->getState(), true, Pred);
712  } else {
713  TempDtorBuilder.markInfeasible(true);
714  TempDtorBuilder.generateNode(Pred->getState(), false, Pred);
715  }
716 }
717 
719  ExplodedNodeSet &PreVisit,
720  ExplodedNodeSet &Dst) {
721  if (!getAnalysisManager().options.includeTemporaryDtorsInCFG()) {
722  // In case we don't have temporary destructors in the CFG, do not mark
723  // the initialization - we would otherwise never clean it up.
724  Dst = PreVisit;
725  return;
726  }
727  StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
728  for (ExplodedNode *Node : PreVisit) {
729  ProgramStateRef State = Node->getState();
730 
731  if (!State->contains<InitializedTemporariesSet>(
732  std::make_pair(BTE, Node->getStackFrame()))) {
733  // FIXME: Currently the state might already contain the marker due to
734  // incorrect handling of temporaries bound to default parameters; for
735  // those, we currently skip the CXXBindTemporaryExpr but rely on adding
736  // temporary destructor nodes.
737  State = State->add<InitializedTemporariesSet>(
738  std::make_pair(BTE, Node->getStackFrame()));
739  }
740  StmtBldr.generateNode(BTE, Node, State);
741  }
742 }
743 
745  ExplodedNodeSet &DstTop) {
746  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
747  S->getLocStart(),
748  "Error evaluating statement");
749  ExplodedNodeSet Dst;
750  StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
751 
752  assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
753 
754  switch (S->getStmtClass()) {
755  // C++ and ARC stuff we don't support yet.
756  case Expr::ObjCIndirectCopyRestoreExprClass:
757  case Stmt::CXXDependentScopeMemberExprClass:
758  case Stmt::CXXInheritedCtorInitExprClass:
759  case Stmt::CXXTryStmtClass:
760  case Stmt::CXXTypeidExprClass:
761  case Stmt::CXXUuidofExprClass:
762  case Stmt::CXXFoldExprClass:
763  case Stmt::MSPropertyRefExprClass:
764  case Stmt::MSPropertySubscriptExprClass:
765  case Stmt::CXXUnresolvedConstructExprClass:
766  case Stmt::DependentScopeDeclRefExprClass:
767  case Stmt::ArrayTypeTraitExprClass:
768  case Stmt::ExpressionTraitExprClass:
769  case Stmt::UnresolvedLookupExprClass:
770  case Stmt::UnresolvedMemberExprClass:
771  case Stmt::TypoExprClass:
772  case Stmt::CXXNoexceptExprClass:
773  case Stmt::PackExpansionExprClass:
774  case Stmt::SubstNonTypeTemplateParmPackExprClass:
775  case Stmt::FunctionParmPackExprClass:
776  case Stmt::CoroutineBodyStmtClass:
777  case Stmt::CoawaitExprClass:
778  case Stmt::CoreturnStmtClass:
779  case Stmt::CoyieldExprClass:
780  case Stmt::SEHTryStmtClass:
781  case Stmt::SEHExceptStmtClass:
782  case Stmt::SEHLeaveStmtClass:
783  case Stmt::SEHFinallyStmtClass: {
784  const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
785  Engine.addAbortedBlock(node, currBldrCtx->getBlock());
786  break;
787  }
788 
789  case Stmt::ParenExprClass:
790  llvm_unreachable("ParenExprs already handled.");
791  case Stmt::GenericSelectionExprClass:
792  llvm_unreachable("GenericSelectionExprs already handled.");
793  // Cases that should never be evaluated simply because they shouldn't
794  // appear in the CFG.
795  case Stmt::BreakStmtClass:
796  case Stmt::CaseStmtClass:
797  case Stmt::CompoundStmtClass:
798  case Stmt::ContinueStmtClass:
799  case Stmt::CXXForRangeStmtClass:
800  case Stmt::DefaultStmtClass:
801  case Stmt::DoStmtClass:
802  case Stmt::ForStmtClass:
803  case Stmt::GotoStmtClass:
804  case Stmt::IfStmtClass:
805  case Stmt::IndirectGotoStmtClass:
806  case Stmt::LabelStmtClass:
807  case Stmt::NoStmtClass:
808  case Stmt::NullStmtClass:
809  case Stmt::SwitchStmtClass:
810  case Stmt::WhileStmtClass:
811  case Expr::MSDependentExistsStmtClass:
812  case Stmt::CapturedStmtClass:
813  case Stmt::OMPParallelDirectiveClass:
814  case Stmt::OMPSimdDirectiveClass:
815  case Stmt::OMPForDirectiveClass:
816  case Stmt::OMPForSimdDirectiveClass:
817  case Stmt::OMPSectionsDirectiveClass:
818  case Stmt::OMPSectionDirectiveClass:
819  case Stmt::OMPSingleDirectiveClass:
820  case Stmt::OMPMasterDirectiveClass:
821  case Stmt::OMPCriticalDirectiveClass:
822  case Stmt::OMPParallelForDirectiveClass:
823  case Stmt::OMPParallelForSimdDirectiveClass:
824  case Stmt::OMPParallelSectionsDirectiveClass:
825  case Stmt::OMPTaskDirectiveClass:
826  case Stmt::OMPTaskyieldDirectiveClass:
827  case Stmt::OMPBarrierDirectiveClass:
828  case Stmt::OMPTaskwaitDirectiveClass:
829  case Stmt::OMPTaskgroupDirectiveClass:
830  case Stmt::OMPFlushDirectiveClass:
831  case Stmt::OMPOrderedDirectiveClass:
832  case Stmt::OMPAtomicDirectiveClass:
833  case Stmt::OMPTargetDirectiveClass:
834  case Stmt::OMPTargetDataDirectiveClass:
835  case Stmt::OMPTargetEnterDataDirectiveClass:
836  case Stmt::OMPTargetExitDataDirectiveClass:
837  case Stmt::OMPTargetParallelDirectiveClass:
838  case Stmt::OMPTargetParallelForDirectiveClass:
839  case Stmt::OMPTargetUpdateDirectiveClass:
840  case Stmt::OMPTeamsDirectiveClass:
841  case Stmt::OMPCancellationPointDirectiveClass:
842  case Stmt::OMPCancelDirectiveClass:
843  case Stmt::OMPTaskLoopDirectiveClass:
844  case Stmt::OMPTaskLoopSimdDirectiveClass:
845  case Stmt::OMPDistributeDirectiveClass:
846  case Stmt::OMPDistributeParallelForDirectiveClass:
847  case Stmt::OMPDistributeParallelForSimdDirectiveClass:
848  case Stmt::OMPDistributeSimdDirectiveClass:
849  case Stmt::OMPTargetParallelForSimdDirectiveClass:
850  llvm_unreachable("Stmt should not be in analyzer evaluation loop");
851 
852  case Stmt::ObjCSubscriptRefExprClass:
853  case Stmt::ObjCPropertyRefExprClass:
854  llvm_unreachable("These are handled by PseudoObjectExpr");
855 
856  case Stmt::GNUNullExprClass: {
857  // GNU __null is a pointer-width integer, not an actual pointer.
858  ProgramStateRef state = Pred->getState();
859  state = state->BindExpr(S, Pred->getLocationContext(),
860  svalBuilder.makeIntValWithPtrWidth(0, false));
861  Bldr.generateNode(S, Pred, state);
862  break;
863  }
864 
865  case Stmt::ObjCAtSynchronizedStmtClass:
866  Bldr.takeNodes(Pred);
867  VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
868  Bldr.addNodes(Dst);
869  break;
870 
871  case Stmt::ExprWithCleanupsClass:
872  // Handled due to fully linearised CFG.
873  break;
874 
875  case Stmt::CXXBindTemporaryExprClass: {
876  Bldr.takeNodes(Pred);
877  ExplodedNodeSet PreVisit;
878  getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
880  VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
881  getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
882  Bldr.addNodes(Dst);
883  break;
884  }
885 
886  // Cases not handled yet; but will handle some day.
887  case Stmt::DesignatedInitExprClass:
888  case Stmt::DesignatedInitUpdateExprClass:
889  case Stmt::ExtVectorElementExprClass:
890  case Stmt::ImaginaryLiteralClass:
891  case Stmt::ObjCAtCatchStmtClass:
892  case Stmt::ObjCAtFinallyStmtClass:
893  case Stmt::ObjCAtTryStmtClass:
894  case Stmt::ObjCAutoreleasePoolStmtClass:
895  case Stmt::ObjCEncodeExprClass:
896  case Stmt::ObjCIsaExprClass:
897  case Stmt::ObjCProtocolExprClass:
898  case Stmt::ObjCSelectorExprClass:
899  case Stmt::ParenListExprClass:
900  case Stmt::ShuffleVectorExprClass:
901  case Stmt::ConvertVectorExprClass:
902  case Stmt::VAArgExprClass:
903  case Stmt::CUDAKernelCallExprClass:
904  case Stmt::OpaqueValueExprClass:
905  case Stmt::AsTypeExprClass:
906  // Fall through.
907 
908  // Cases we intentionally don't evaluate, since they don't need
909  // to be explicitly evaluated.
910  case Stmt::PredefinedExprClass:
911  case Stmt::AddrLabelExprClass:
912  case Stmt::AttributedStmtClass:
913  case Stmt::IntegerLiteralClass:
914  case Stmt::CharacterLiteralClass:
915  case Stmt::ImplicitValueInitExprClass:
916  case Stmt::CXXScalarValueInitExprClass:
917  case Stmt::CXXBoolLiteralExprClass:
918  case Stmt::ObjCBoolLiteralExprClass:
919  case Stmt::ObjCAvailabilityCheckExprClass:
920  case Stmt::FloatingLiteralClass:
921  case Stmt::NoInitExprClass:
922  case Stmt::SizeOfPackExprClass:
923  case Stmt::StringLiteralClass:
924  case Stmt::ObjCStringLiteralClass:
925  case Stmt::CXXPseudoDestructorExprClass:
926  case Stmt::SubstNonTypeTemplateParmExprClass:
927  case Stmt::CXXNullPtrLiteralExprClass:
928  case Stmt::OMPArraySectionExprClass:
929  case Stmt::TypeTraitExprClass: {
930  Bldr.takeNodes(Pred);
931  ExplodedNodeSet preVisit;
932  getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
933  getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
934  Bldr.addNodes(Dst);
935  break;
936  }
937 
938  case Stmt::CXXDefaultArgExprClass:
939  case Stmt::CXXDefaultInitExprClass: {
940  Bldr.takeNodes(Pred);
941  ExplodedNodeSet PreVisit;
942  getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
943 
944  ExplodedNodeSet Tmp;
945  StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
946 
947  const Expr *ArgE;
948  if (const CXXDefaultArgExpr *DefE = dyn_cast<CXXDefaultArgExpr>(S))
949  ArgE = DefE->getExpr();
950  else if (const CXXDefaultInitExpr *DefE = dyn_cast<CXXDefaultInitExpr>(S))
951  ArgE = DefE->getExpr();
952  else
953  llvm_unreachable("unknown constant wrapper kind");
954 
955  bool IsTemporary = false;
956  if (const MaterializeTemporaryExpr *MTE =
957  dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
958  ArgE = MTE->GetTemporaryExpr();
959  IsTemporary = true;
960  }
961 
962  Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
963  if (!ConstantVal)
964  ConstantVal = UnknownVal();
965 
966  const LocationContext *LCtx = Pred->getLocationContext();
967  for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end();
968  I != E; ++I) {
969  ProgramStateRef State = (*I)->getState();
970  State = State->BindExpr(S, LCtx, *ConstantVal);
971  if (IsTemporary)
972  State = createTemporaryRegionIfNeeded(State, LCtx,
973  cast<Expr>(S),
974  cast<Expr>(S));
975  Bldr2.generateNode(S, *I, State);
976  }
977 
978  getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
979  Bldr.addNodes(Dst);
980  break;
981  }
982 
983  // Cases we evaluate as opaque expressions, conjuring a symbol.
984  case Stmt::CXXStdInitializerListExprClass:
985  case Expr::ObjCArrayLiteralClass:
986  case Expr::ObjCDictionaryLiteralClass:
987  case Expr::ObjCBoxedExprClass: {
988  Bldr.takeNodes(Pred);
989 
990  ExplodedNodeSet preVisit;
991  getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
992 
993  ExplodedNodeSet Tmp;
994  StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
995 
996  const Expr *Ex = cast<Expr>(S);
997  QualType resultType = Ex->getType();
998 
999  for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end();
1000  it != et; ++it) {
1001  ExplodedNode *N = *it;
1002  const LocationContext *LCtx = N->getLocationContext();
1003  SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
1004  resultType,
1005  currBldrCtx->blockCount());
1006  ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result);
1007  Bldr2.generateNode(S, N, state);
1008  }
1009 
1010  getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1011  Bldr.addNodes(Dst);
1012  break;
1013  }
1014 
1015  case Stmt::ArraySubscriptExprClass:
1016  Bldr.takeNodes(Pred);
1017  VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
1018  Bldr.addNodes(Dst);
1019  break;
1020 
1021  case Stmt::GCCAsmStmtClass:
1022  Bldr.takeNodes(Pred);
1023  VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
1024  Bldr.addNodes(Dst);
1025  break;
1026 
1027  case Stmt::MSAsmStmtClass:
1028  Bldr.takeNodes(Pred);
1029  VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
1030  Bldr.addNodes(Dst);
1031  break;
1032 
1033  case Stmt::BlockExprClass:
1034  Bldr.takeNodes(Pred);
1035  VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
1036  Bldr.addNodes(Dst);
1037  break;
1038 
1039  case Stmt::LambdaExprClass:
1040  if (AMgr.options.shouldInlineLambdas()) {
1041  Bldr.takeNodes(Pred);
1042  VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
1043  Bldr.addNodes(Dst);
1044  } else {
1045  const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1046  Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1047  }
1048  break;
1049 
1050  case Stmt::BinaryOperatorClass: {
1051  const BinaryOperator* B = cast<BinaryOperator>(S);
1052  if (B->isLogicalOp()) {
1053  Bldr.takeNodes(Pred);
1054  VisitLogicalExpr(B, Pred, Dst);
1055  Bldr.addNodes(Dst);
1056  break;
1057  }
1058  else if (B->getOpcode() == BO_Comma) {
1059  ProgramStateRef state = Pred->getState();
1060  Bldr.generateNode(B, Pred,
1061  state->BindExpr(B, Pred->getLocationContext(),
1062  state->getSVal(B->getRHS(),
1063  Pred->getLocationContext())));
1064  break;
1065  }
1066 
1067  Bldr.takeNodes(Pred);
1068 
1070  (B->isRelationalOp() || B->isEqualityOp())) {
1071  ExplodedNodeSet Tmp;
1072  VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
1073  evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
1074  }
1075  else
1076  VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1077 
1078  Bldr.addNodes(Dst);
1079  break;
1080  }
1081 
1082  case Stmt::CXXOperatorCallExprClass: {
1083  const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S);
1084 
1085  // For instance method operators, make sure the 'this' argument has a
1086  // valid region.
1087  const Decl *Callee = OCE->getCalleeDecl();
1088  if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
1089  if (MD->isInstance()) {
1090  ProgramStateRef State = Pred->getState();
1091  const LocationContext *LCtx = Pred->getLocationContext();
1092  ProgramStateRef NewState =
1093  createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
1094  if (NewState != State) {
1095  Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
1097  // Did we cache out?
1098  if (!Pred)
1099  break;
1100  }
1101  }
1102  }
1103  // FALLTHROUGH
1104  }
1105  case Stmt::CallExprClass:
1106  case Stmt::CXXMemberCallExprClass:
1107  case Stmt::UserDefinedLiteralClass: {
1108  Bldr.takeNodes(Pred);
1109  VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
1110  Bldr.addNodes(Dst);
1111  break;
1112  }
1113 
1114  case Stmt::CXXCatchStmtClass: {
1115  Bldr.takeNodes(Pred);
1116  VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
1117  Bldr.addNodes(Dst);
1118  break;
1119  }
1120 
1121  case Stmt::CXXTemporaryObjectExprClass:
1122  case Stmt::CXXConstructExprClass: {
1123  Bldr.takeNodes(Pred);
1124  VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
1125  Bldr.addNodes(Dst);
1126  break;
1127  }
1128 
1129  case Stmt::CXXNewExprClass: {
1130  Bldr.takeNodes(Pred);
1131  ExplodedNodeSet PostVisit;
1132  VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit);
1133  getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1134  Bldr.addNodes(Dst);
1135  break;
1136  }
1137 
1138  case Stmt::CXXDeleteExprClass: {
1139  Bldr.takeNodes(Pred);
1140  ExplodedNodeSet PreVisit;
1141  const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
1142  getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1143 
1144  for (ExplodedNodeSet::iterator i = PreVisit.begin(),
1145  e = PreVisit.end(); i != e ; ++i)
1146  VisitCXXDeleteExpr(CDE, *i, Dst);
1147 
1148  Bldr.addNodes(Dst);
1149  break;
1150  }
1151  // FIXME: ChooseExpr is really a constant. We need to fix
1152  // the CFG do not model them as explicit control-flow.
1153 
1154  case Stmt::ChooseExprClass: { // __builtin_choose_expr
1155  Bldr.takeNodes(Pred);
1156  const ChooseExpr *C = cast<ChooseExpr>(S);
1157  VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
1158  Bldr.addNodes(Dst);
1159  break;
1160  }
1161 
1162  case Stmt::CompoundAssignOperatorClass:
1163  Bldr.takeNodes(Pred);
1164  VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1165  Bldr.addNodes(Dst);
1166  break;
1167 
1168  case Stmt::CompoundLiteralExprClass:
1169  Bldr.takeNodes(Pred);
1170  VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
1171  Bldr.addNodes(Dst);
1172  break;
1173 
1174  case Stmt::BinaryConditionalOperatorClass:
1175  case Stmt::ConditionalOperatorClass: { // '?' operator
1176  Bldr.takeNodes(Pred);
1178  = cast<AbstractConditionalOperator>(S);
1179  VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
1180  Bldr.addNodes(Dst);
1181  break;
1182  }
1183 
1184  case Stmt::CXXThisExprClass:
1185  Bldr.takeNodes(Pred);
1186  VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
1187  Bldr.addNodes(Dst);
1188  break;
1189 
1190  case Stmt::DeclRefExprClass: {
1191  Bldr.takeNodes(Pred);
1192  const DeclRefExpr *DE = cast<DeclRefExpr>(S);
1193  VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
1194  Bldr.addNodes(Dst);
1195  break;
1196  }
1197 
1198  case Stmt::DeclStmtClass:
1199  Bldr.takeNodes(Pred);
1200  VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
1201  Bldr.addNodes(Dst);
1202  break;
1203 
1204  case Stmt::ImplicitCastExprClass:
1205  case Stmt::CStyleCastExprClass:
1206  case Stmt::CXXStaticCastExprClass:
1207  case Stmt::CXXDynamicCastExprClass:
1208  case Stmt::CXXReinterpretCastExprClass:
1209  case Stmt::CXXConstCastExprClass:
1210  case Stmt::CXXFunctionalCastExprClass:
1211  case Stmt::ObjCBridgedCastExprClass: {
1212  Bldr.takeNodes(Pred);
1213  const CastExpr *C = cast<CastExpr>(S);
1214  // Handle the previsit checks.
1215  ExplodedNodeSet dstPrevisit;
1216  getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this);
1217 
1218  // Handle the expression itself.
1219  ExplodedNodeSet dstExpr;
1220  for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
1221  e = dstPrevisit.end(); i != e ; ++i) {
1222  VisitCast(C, C->getSubExpr(), *i, dstExpr);
1223  }
1224 
1225  // Handle the postvisit checks.
1226  getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1227  Bldr.addNodes(Dst);
1228  break;
1229  }
1230 
1231  case Expr::MaterializeTemporaryExprClass: {
1232  Bldr.takeNodes(Pred);
1233  const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
1234  CreateCXXTemporaryObject(MTE, Pred, Dst);
1235  Bldr.addNodes(Dst);
1236  break;
1237  }
1238 
1239  case Stmt::InitListExprClass:
1240  Bldr.takeNodes(Pred);
1241  VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1242  Bldr.addNodes(Dst);
1243  break;
1244 
1245  case Stmt::MemberExprClass:
1246  Bldr.takeNodes(Pred);
1247  VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1248  Bldr.addNodes(Dst);
1249  break;
1250 
1251  case Stmt::AtomicExprClass:
1252  Bldr.takeNodes(Pred);
1253  VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
1254  Bldr.addNodes(Dst);
1255  break;
1256 
1257  case Stmt::ObjCIvarRefExprClass:
1258  Bldr.takeNodes(Pred);
1259  VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1260  Bldr.addNodes(Dst);
1261  break;
1262 
1263  case Stmt::ObjCForCollectionStmtClass:
1264  Bldr.takeNodes(Pred);
1265  VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1266  Bldr.addNodes(Dst);
1267  break;
1268 
1269  case Stmt::ObjCMessageExprClass:
1270  Bldr.takeNodes(Pred);
1271  VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1272  Bldr.addNodes(Dst);
1273  break;
1274 
1275  case Stmt::ObjCAtThrowStmtClass:
1276  case Stmt::CXXThrowExprClass:
1277  // FIXME: This is not complete. We basically treat @throw as
1278  // an abort.
1279  Bldr.generateSink(S, Pred, Pred->getState());
1280  break;
1281 
1282  case Stmt::ReturnStmtClass:
1283  Bldr.takeNodes(Pred);
1284  VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1285  Bldr.addNodes(Dst);
1286  break;
1287 
1288  case Stmt::OffsetOfExprClass:
1289  Bldr.takeNodes(Pred);
1290  VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
1291  Bldr.addNodes(Dst);
1292  break;
1293 
1294  case Stmt::UnaryExprOrTypeTraitExprClass:
1295  Bldr.takeNodes(Pred);
1296  VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1297  Pred, Dst);
1298  Bldr.addNodes(Dst);
1299  break;
1300 
1301  case Stmt::StmtExprClass: {
1302  const StmtExpr *SE = cast<StmtExpr>(S);
1303 
1304  if (SE->getSubStmt()->body_empty()) {
1305  // Empty statement expression.
1306  assert(SE->getType() == getContext().VoidTy
1307  && "Empty statement expression must have void type.");
1308  break;
1309  }
1310 
1311  if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1312  ProgramStateRef state = Pred->getState();
1313  Bldr.generateNode(SE, Pred,
1314  state->BindExpr(SE, Pred->getLocationContext(),
1315  state->getSVal(LastExpr,
1316  Pred->getLocationContext())));
1317  }
1318  break;
1319  }
1320 
1321  case Stmt::UnaryOperatorClass: {
1322  Bldr.takeNodes(Pred);
1323  const UnaryOperator *U = cast<UnaryOperator>(S);
1324  if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
1325  ExplodedNodeSet Tmp;
1326  VisitUnaryOperator(U, Pred, Tmp);
1327  evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1328  }
1329  else
1330  VisitUnaryOperator(U, Pred, Dst);
1331  Bldr.addNodes(Dst);
1332  break;
1333  }
1334 
1335  case Stmt::PseudoObjectExprClass: {
1336  Bldr.takeNodes(Pred);
1337  ProgramStateRef state = Pred->getState();
1338  const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
1339  if (const Expr *Result = PE->getResultExpr()) {
1340  SVal V = state->getSVal(Result, Pred->getLocationContext());
1341  Bldr.generateNode(S, Pred,
1342  state->BindExpr(S, Pred->getLocationContext(), V));
1343  }
1344  else
1345  Bldr.generateNode(S, Pred,
1346  state->BindExpr(S, Pred->getLocationContext(),
1347  UnknownVal()));
1348 
1349  Bldr.addNodes(Dst);
1350  break;
1351  }
1352  }
1353 }
1354 
1355 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1356  const LocationContext *CalleeLC) {
1357  const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1358  const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
1359  assert(CalleeSF && CallerSF);
1360  ExplodedNode *BeforeProcessingCall = nullptr;
1361  const Stmt *CE = CalleeSF->getCallSite();
1362 
1363  // Find the first node before we started processing the call expression.
1364  while (N) {
1365  ProgramPoint L = N->getLocation();
1366  BeforeProcessingCall = N;
1367  N = N->pred_empty() ? nullptr : *(N->pred_begin());
1368 
1369  // Skip the nodes corresponding to the inlined code.
1370  if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
1371  continue;
1372  // We reached the caller. Find the node right before we started
1373  // processing the call.
1374  if (L.isPurgeKind())
1375  continue;
1376  if (L.getAs<PreImplicitCall>())
1377  continue;
1378  if (L.getAs<CallEnter>())
1379  continue;
1380  if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1381  if (SP->getStmt() == CE)
1382  continue;
1383  break;
1384  }
1385 
1386  if (!BeforeProcessingCall)
1387  return false;
1388 
1389  // TODO: Clean up the unneeded nodes.
1390 
1391  // Build an Epsilon node from which we will restart the analyzes.
1392  // Note that CE is permitted to be NULL!
1393  ProgramPoint NewNodeLoc =
1394  EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1395  // Add the special flag to GDM to signal retrying with no inlining.
1396  // Note, changing the state ensures that we are not going to cache out.
1397  ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1398  NewNodeState =
1399  NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1400 
1401  // Make the new node a successor of BeforeProcessingCall.
1402  bool IsNew = false;
1403  ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1404  // We cached out at this point. Caching out is common due to us backtracking
1405  // from the inlined function, which might spawn several paths.
1406  if (!IsNew)
1407  return true;
1408 
1409  NewNode->addPredecessor(BeforeProcessingCall, G);
1410 
1411  // Add the new node to the work list.
1412  Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1413  CalleeSF->getIndex());
1414  NumTimesRetriedWithoutInlining++;
1415  return true;
1416 }
1417 
1418 /// Block entrance. (Update counters).
1420  NodeBuilderWithSinks &nodeBuilder,
1421  ExplodedNode *Pred) {
1423 
1424  // If this block is terminated by a loop and it has already been visited the
1425  // maximum number of times, widen the loop.
1426  unsigned int BlockCount = nodeBuilder.getContext().blockCount();
1427  if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
1428  AMgr.options.shouldWidenLoops()) {
1429  const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
1430  if (!(Term &&
1431  (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
1432  return;
1433  // Widen.
1434  const LocationContext *LCtx = Pred->getLocationContext();
1435  ProgramStateRef WidenedState =
1436  getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
1437  nodeBuilder.generateNode(WidenedState, Pred);
1438  return;
1439  }
1440 
1441  // FIXME: Refactor this into a checker.
1442  if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
1443  static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
1444  const ExplodedNode *Sink =
1445  nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1446 
1447  // Check if we stopped at the top level function or not.
1448  // Root node should have the location context of the top most function.
1449  const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1450  const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
1451  const LocationContext *RootLC =
1452  (*G.roots_begin())->getLocation().getLocationContext();
1453  if (RootLC->getCurrentStackFrame() != CalleeSF) {
1454  Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1455 
1456  // Re-run the call evaluation without inlining it, by storing the
1457  // no-inlining policy in the state and enqueuing the new work item on
1458  // the list. Replay should almost never fail. Use the stats to catch it
1459  // if it does.
1460  if ((!AMgr.options.NoRetryExhausted &&
1461  replayWithoutInlining(Pred, CalleeLC)))
1462  return;
1463  NumMaxBlockCountReachedInInlined++;
1464  } else
1465  NumMaxBlockCountReached++;
1466 
1467  // Make sink nodes as exhausted(for stats) only if retry failed.
1468  Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1469  }
1470 }
1471 
1472 //===----------------------------------------------------------------------===//
1473 // Branch processing.
1474 //===----------------------------------------------------------------------===//
1475 
1476 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1477 /// to try to recover some path-sensitivity for casts of symbolic
1478 /// integers that promote their values (which are currently not tracked well).
1479 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1480 // cast(s) did was sign-extend the original value.
1483  const Stmt *Condition,
1484  const LocationContext *LCtx,
1485  ASTContext &Ctx) {
1486 
1487  const Expr *Ex = dyn_cast<Expr>(Condition);
1488  if (!Ex)
1489  return UnknownVal();
1490 
1491  uint64_t bits = 0;
1492  bool bitsInit = false;
1493 
1494  while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
1495  QualType T = CE->getType();
1496 
1497  if (!T->isIntegralOrEnumerationType())
1498  return UnknownVal();
1499 
1500  uint64_t newBits = Ctx.getTypeSize(T);
1501  if (!bitsInit || newBits < bits) {
1502  bitsInit = true;
1503  bits = newBits;
1504  }
1505 
1506  Ex = CE->getSubExpr();
1507  }
1508 
1509  // We reached a non-cast. Is it a symbolic value?
1510  QualType T = Ex->getType();
1511 
1512  if (!bitsInit || !T->isIntegralOrEnumerationType() ||
1513  Ctx.getTypeSize(T) > bits)
1514  return UnknownVal();
1515 
1516  return state->getSVal(Ex, LCtx);
1517 }
1518 
1519 #ifndef NDEBUG
1520 static const Stmt *getRightmostLeaf(const Stmt *Condition) {
1521  while (Condition) {
1522  const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1523  if (!BO || !BO->isLogicalOp()) {
1524  return Condition;
1525  }
1526  Condition = BO->getRHS()->IgnoreParens();
1527  }
1528  return nullptr;
1529 }
1530 #endif
1531 
1532 // Returns the condition the branch at the end of 'B' depends on and whose value
1533 // has been evaluated within 'B'.
1534 // In most cases, the terminator condition of 'B' will be evaluated fully in
1535 // the last statement of 'B'; in those cases, the resolved condition is the
1536 // given 'Condition'.
1537 // If the condition of the branch is a logical binary operator tree, the CFG is
1538 // optimized: in that case, we know that the expression formed by all but the
1539 // rightmost leaf of the logical binary operator tree must be true, and thus
1540 // the branch condition is at this point equivalent to the truth value of that
1541 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
1542 // expression in its final statement. As the full condition in that case was
1543 // not evaluated, and is thus not in the SVal cache, we need to use that leaf
1544 // expression to evaluate the truth value of the condition in the current state
1545 // space.
1546 static const Stmt *ResolveCondition(const Stmt *Condition,
1547  const CFGBlock *B) {
1548  if (const Expr *Ex = dyn_cast<Expr>(Condition))
1549  Condition = Ex->IgnoreParens();
1550 
1551  const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
1552  if (!BO || !BO->isLogicalOp())
1553  return Condition;
1554 
1555  assert(!B->getTerminator().isTemporaryDtorsBranch() &&
1556  "Temporary destructor branches handled by processBindTemporary.");
1557 
1558  // For logical operations, we still have the case where some branches
1559  // use the traditional "merge" approach and others sink the branch
1560  // directly into the basic blocks representing the logical operation.
1561  // We need to distinguish between those two cases here.
1562 
1563  // The invariants are still shifting, but it is possible that the
1564  // last element in a CFGBlock is not a CFGStmt. Look for the last
1565  // CFGStmt as the value of the condition.
1567  for (; I != E; ++I) {
1568  CFGElement Elem = *I;
1569  Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
1570  if (!CS)
1571  continue;
1572  const Stmt *LastStmt = CS->getStmt();
1573  assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
1574  return LastStmt;
1575  }
1576  llvm_unreachable("could not resolve condition");
1577 }
1578 
1579 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
1580  NodeBuilderContext& BldCtx,
1581  ExplodedNode *Pred,
1582  ExplodedNodeSet &Dst,
1583  const CFGBlock *DstT,
1584  const CFGBlock *DstF) {
1585  assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
1586  "CXXBindTemporaryExprs are handled by processBindTemporary.");
1587  const LocationContext *LCtx = Pred->getLocationContext();
1588  PrettyStackTraceLocationContext StackCrashInfo(LCtx);
1589  currBldrCtx = &BldCtx;
1590 
1591  // Check for NULL conditions; e.g. "for(;;)"
1592  if (!Condition) {
1593  BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
1594  NullCondBldr.markInfeasible(false);
1595  NullCondBldr.generateNode(Pred->getState(), true, Pred);
1596  return;
1597  }
1598 
1599  if (const Expr *Ex = dyn_cast<Expr>(Condition))
1600  Condition = Ex->IgnoreParens();
1601 
1602  Condition = ResolveCondition(Condition, BldCtx.getBlock());
1603  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1604  Condition->getLocStart(),
1605  "Error evaluating branch");
1606 
1607  ExplodedNodeSet CheckersOutSet;
1608  getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
1609  Pred, *this);
1610  // We generated only sinks.
1611  if (CheckersOutSet.empty())
1612  return;
1613 
1614  BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
1615  for (NodeBuilder::iterator I = CheckersOutSet.begin(),
1616  E = CheckersOutSet.end(); E != I; ++I) {
1617  ExplodedNode *PredI = *I;
1618 
1619  if (PredI->isSink())
1620  continue;
1621 
1622  ProgramStateRef PrevState = PredI->getState();
1623  SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
1624 
1625  if (X.isUnknownOrUndef()) {
1626  // Give it a chance to recover from unknown.
1627  if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
1628  if (Ex->getType()->isIntegralOrEnumerationType()) {
1629  // Try to recover some path-sensitivity. Right now casts of symbolic
1630  // integers that promote their values are currently not tracked well.
1631  // If 'Condition' is such an expression, try and recover the
1632  // underlying value and use that instead.
1634  PrevState, Condition,
1635  PredI->getLocationContext(),
1636  getContext());
1637 
1638  if (!recovered.isUnknown()) {
1639  X = recovered;
1640  }
1641  }
1642  }
1643  }
1644 
1645  // If the condition is still unknown, give up.
1646  if (X.isUnknownOrUndef()) {
1647  builder.generateNode(PrevState, true, PredI);
1648  builder.generateNode(PrevState, false, PredI);
1649  continue;
1650  }
1651 
1652  DefinedSVal V = X.castAs<DefinedSVal>();
1653 
1654  ProgramStateRef StTrue, StFalse;
1655  std::tie(StTrue, StFalse) = PrevState->assume(V);
1656 
1657  // Process the true branch.
1658  if (builder.isFeasible(true)) {
1659  if (StTrue)
1660  builder.generateNode(StTrue, true, PredI);
1661  else
1662  builder.markInfeasible(true);
1663  }
1664 
1665  // Process the false branch.
1666  if (builder.isFeasible(false)) {
1667  if (StFalse)
1668  builder.generateNode(StFalse, false, PredI);
1669  else
1670  builder.markInfeasible(false);
1671  }
1672  }
1673  currBldrCtx = nullptr;
1674 }
1675 
1676 /// The GDM component containing the set of global variables which have been
1677 /// previously initialized with explicit initializers.
1678 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
1680 
1681 void ExprEngine::processStaticInitializer(const DeclStmt *DS,
1682  NodeBuilderContext &BuilderCtx,
1683  ExplodedNode *Pred,
1684  clang::ento::ExplodedNodeSet &Dst,
1685  const CFGBlock *DstT,
1686  const CFGBlock *DstF) {
1687  PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1688  currBldrCtx = &BuilderCtx;
1689 
1690  const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
1691  ProgramStateRef state = Pred->getState();
1692  bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
1693  BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
1694 
1695  if (!initHasRun) {
1696  state = state->add<InitializedGlobalsSet>(VD);
1697  }
1698 
1699  builder.generateNode(state, initHasRun, Pred);
1700  builder.markInfeasible(!initHasRun);
1701 
1702  currBldrCtx = nullptr;
1703 }
1704 
1705 /// processIndirectGoto - Called by CoreEngine. Used to generate successor
1706 /// nodes by processing the 'effects' of a computed goto jump.
1708 
1709  ProgramStateRef state = builder.getState();
1710  SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
1711 
1712  // Three possibilities:
1713  //
1714  // (1) We know the computed label.
1715  // (2) The label is NULL (or some other constant), or Undefined.
1716  // (3) We have no clue about the label. Dispatch to all targets.
1717  //
1718 
1720 
1722  const LabelDecl *L = LV->getLabel();
1723 
1724  for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
1725  if (I.getLabel() == L) {
1726  builder.generateNode(I, state);
1727  return;
1728  }
1729  }
1730 
1731  llvm_unreachable("No block with label.");
1732  }
1733 
1734  if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
1735  // Dispatch to the first target and mark it as a sink.
1736  //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
1737  // FIXME: add checker visit.
1738  // UndefBranches.insert(N);
1739  return;
1740  }
1741 
1742  // This is really a catch-all. We don't support symbolics yet.
1743  // FIXME: Implement dispatch for symbolic pointers.
1744 
1745  for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
1746  builder.generateNode(I, state);
1747 }
1748 
1749 #if 0
1750 static bool stackFrameDoesNotContainInitializedTemporaries(ExplodedNode &Pred) {
1751  const StackFrameContext* Frame = Pred.getStackFrame();
1753  Pred.getState()->get<InitializedTemporariesSet>();
1754  return std::find_if(Set.begin(), Set.end(),
1755  [&](const CXXBindTemporaryContext &Ctx) {
1756  if (Ctx.second == Frame) {
1757  Ctx.first->dump();
1758  llvm::errs() << "\n";
1759  }
1760  return Ctx.second == Frame;
1761  }) == Set.end();
1762 }
1763 #endif
1764 
1766  ExplodedNode *Pred,
1767  ExplodedNodeSet &Dst,
1768  const BlockEdge &L) {
1769  SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
1770  getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
1771 }
1772 
1773 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
1774 /// nodes when the control reaches the end of a function.
1776  ExplodedNode *Pred) {
1777  // FIXME: Assert that stackFrameDoesNotContainInitializedTemporaries(*Pred)).
1778  // We currently cannot enable this assert, as lifetime extended temporaries
1779  // are not modelled correctly.
1781  StateMgr.EndPath(Pred->getState());
1782 
1783  ExplodedNodeSet Dst;
1784  if (Pred->getLocationContext()->inTopFrame()) {
1785  // Remove dead symbols.
1786  ExplodedNodeSet AfterRemovedDead;
1787  removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
1788 
1789  // Notify checkers.
1790  for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(),
1791  E = AfterRemovedDead.end(); I != E; ++I) {
1792  getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this);
1793  }
1794  } else {
1795  getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
1796  }
1797 
1798  Engine.enqueueEndOfFunction(Dst);
1799 }
1800 
1801 /// ProcessSwitch - Called by CoreEngine. Used to generate successor
1802 /// nodes by processing the 'effects' of a switch statement.
1805  ProgramStateRef state = builder.getState();
1806  const Expr *CondE = builder.getCondition();
1807  SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
1808 
1809  if (CondV_untested.isUndef()) {
1810  //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
1811  // FIXME: add checker
1812  //UndefBranches.insert(N);
1813 
1814  return;
1815  }
1816  DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
1817 
1818  ProgramStateRef DefaultSt = state;
1819 
1820  iterator I = builder.begin(), EI = builder.end();
1821  bool defaultIsFeasible = I == EI;
1822 
1823  for ( ; I != EI; ++I) {
1824  // Successor may be pruned out during CFG construction.
1825  if (!I.getBlock())
1826  continue;
1827 
1828  const CaseStmt *Case = I.getCase();
1829 
1830  // Evaluate the LHS of the case value.
1831  llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
1832  assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType()));
1833 
1834  // Get the RHS of the case, if it exists.
1835  llvm::APSInt V2;
1836  if (const Expr *E = Case->getRHS())
1837  V2 = E->EvaluateKnownConstInt(getContext());
1838  else
1839  V2 = V1;
1840 
1841  ProgramStateRef StateCase;
1842  if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
1843  std::tie(StateCase, DefaultSt) =
1844  DefaultSt->assumeWithinInclusiveRange(*NL, V1, V2);
1845  else // UnknownVal
1846  StateCase = DefaultSt;
1847 
1848  if (StateCase)
1849  builder.generateCaseStmtNode(I, StateCase);
1850 
1851  // Now "assume" that the case doesn't match. Add this state
1852  // to the default state (if it is feasible).
1853  if (DefaultSt)
1854  defaultIsFeasible = true;
1855  else {
1856  defaultIsFeasible = false;
1857  break;
1858  }
1859  }
1860 
1861  if (!defaultIsFeasible)
1862  return;
1863 
1864  // If we have switch(enum value), the default branch is not
1865  // feasible if all of the enum constants not covered by 'case:' statements
1866  // are not feasible values for the switch condition.
1867  //
1868  // Note that this isn't as accurate as it could be. Even if there isn't
1869  // a case for a particular enum value as long as that enum value isn't
1870  // feasible then it shouldn't be considered for making 'default:' reachable.
1871  const SwitchStmt *SS = builder.getSwitch();
1872  const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
1873  if (CondExpr->getType()->getAs<EnumType>()) {
1874  if (SS->isAllEnumCasesCovered())
1875  return;
1876  }
1877 
1878  builder.generateDefaultCaseNode(DefaultSt);
1879 }
1880 
1881 //===----------------------------------------------------------------------===//
1882 // Transfer functions: Loads and stores.
1883 //===----------------------------------------------------------------------===//
1884 
1886  ExplodedNode *Pred,
1887  ExplodedNodeSet &Dst) {
1888  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1889 
1890  ProgramStateRef state = Pred->getState();
1891  const LocationContext *LCtx = Pred->getLocationContext();
1892 
1893  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1894  // C permits "extern void v", and if you cast the address to a valid type,
1895  // you can even do things with it. We simply pretend
1896  assert(Ex->isGLValue() || VD->getType()->isVoidType());
1897  const LocationContext *LocCtxt = Pred->getLocationContext();
1898  const Decl *D = LocCtxt->getDecl();
1899  const auto *MD = D ? dyn_cast<CXXMethodDecl>(D) : nullptr;
1900  const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
1901  SVal V;
1902  bool IsReference;
1903  if (AMgr.options.shouldInlineLambdas() && DeclRefEx &&
1904  DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
1905  MD->getParent()->isLambda()) {
1906  // Lookup the field of the lambda.
1907  const CXXRecordDecl *CXXRec = MD->getParent();
1908  llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
1909  FieldDecl *LambdaThisCaptureField;
1910  CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
1911  const FieldDecl *FD = LambdaCaptureFields[VD];
1912  if (!FD) {
1913  // When a constant is captured, sometimes no corresponding field is
1914  // created in the lambda object.
1915  assert(VD->getType().isConstQualified());
1916  V = state->getLValue(VD, LocCtxt);
1917  IsReference = false;
1918  } else {
1919  Loc CXXThis =
1920  svalBuilder.getCXXThis(MD, LocCtxt->getCurrentStackFrame());
1921  SVal CXXThisVal = state->getSVal(CXXThis);
1922  V = state->getLValue(FD, CXXThisVal);
1923  IsReference = FD->getType()->isReferenceType();
1924  }
1925  } else {
1926  V = state->getLValue(VD, LocCtxt);
1927  IsReference = VD->getType()->isReferenceType();
1928  }
1929 
1930  // For references, the 'lvalue' is the pointer address stored in the
1931  // reference region.
1932  if (IsReference) {
1933  if (const MemRegion *R = V.getAsRegion())
1934  V = state->getSVal(R);
1935  else
1936  V = UnknownVal();
1937  }
1938 
1939  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1941  return;
1942  }
1943  if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
1944  assert(!Ex->isGLValue());
1945  SVal V = svalBuilder.makeIntVal(ED->getInitVal());
1946  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
1947  return;
1948  }
1949  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1950  SVal V = svalBuilder.getFunctionPointer(FD);
1951  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1953  return;
1954  }
1955  if (isa<FieldDecl>(D)) {
1956  // FIXME: Compute lvalue of field pointers-to-member.
1957  // Right now we just use a non-null void pointer, so that it gives proper
1958  // results in boolean contexts.
1959  SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
1960  currBldrCtx->blockCount());
1961  state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
1962  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
1964  return;
1965  }
1966 
1967  llvm_unreachable("Support for this Decl not implemented.");
1968 }
1969 
1970 /// VisitArraySubscriptExpr - Transfer function for array accesses
1972  ExplodedNode *Pred,
1973  ExplodedNodeSet &Dst){
1974 
1975  const Expr *Base = A->getBase()->IgnoreParens();
1976  const Expr *Idx = A->getIdx()->IgnoreParens();
1977 
1978  ExplodedNodeSet checkerPreStmt;
1979  getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this);
1980 
1981  StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currBldrCtx);
1982  assert(A->isGLValue() ||
1983  (!AMgr.getLangOpts().CPlusPlus &&
1985 
1986  for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(),
1987  ei = checkerPreStmt.end(); it != ei; ++it) {
1988  const LocationContext *LCtx = (*it)->getLocationContext();
1989  ProgramStateRef state = (*it)->getState();
1990  SVal V = state->getLValue(A->getType(),
1991  state->getSVal(Idx, LCtx),
1992  state->getSVal(Base, LCtx));
1993  Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), nullptr,
1995  }
1996 }
1997 
1998 /// VisitMemberExpr - Transfer function for member expressions.
2000  ExplodedNodeSet &Dst) {
2001 
2002  // FIXME: Prechecks eventually go in ::Visit().
2003  ExplodedNodeSet CheckedSet;
2004  getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
2005 
2006  ExplodedNodeSet EvalSet;
2007  ValueDecl *Member = M->getMemberDecl();
2008 
2009  // Handle static member variables and enum constants accessed via
2010  // member syntax.
2011  if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
2012  ExplodedNodeSet Dst;
2013  for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2014  I != E; ++I) {
2015  VisitCommonDeclRefExpr(M, Member, Pred, EvalSet);
2016  }
2017  } else {
2018  StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
2019  ExplodedNodeSet Tmp;
2020 
2021  for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2022  I != E; ++I) {
2023  ProgramStateRef state = (*I)->getState();
2024  const LocationContext *LCtx = (*I)->getLocationContext();
2025  Expr *BaseExpr = M->getBase();
2026 
2027  // Handle C++ method calls.
2028  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
2029  if (MD->isInstance())
2030  state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2031 
2032  SVal MDVal = svalBuilder.getFunctionPointer(MD);
2033  state = state->BindExpr(M, LCtx, MDVal);
2034 
2035  Bldr.generateNode(M, *I, state);
2036  continue;
2037  }
2038 
2039  // Handle regular struct fields / member variables.
2040  state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2041  SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
2042 
2043  FieldDecl *field = cast<FieldDecl>(Member);
2044  SVal L = state->getLValue(field, baseExprVal);
2045 
2046  if (M->isGLValue() || M->getType()->isArrayType()) {
2047  // We special-case rvalues of array type because the analyzer cannot
2048  // reason about them, since we expect all regions to be wrapped in Locs.
2049  // We instead treat these as lvalues and assume that they will decay to
2050  // pointers as soon as they are used.
2051  if (!M->isGLValue()) {
2052  assert(M->getType()->isArrayType());
2053  const ImplicitCastExpr *PE =
2054  dyn_cast<ImplicitCastExpr>((*I)->getParentMap().getParent(M));
2055  if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
2056  llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
2057  }
2058  }
2059 
2060  if (field->getType()->isReferenceType()) {
2061  if (const MemRegion *R = L.getAsRegion())
2062  L = state->getSVal(R);
2063  else
2064  L = UnknownVal();
2065  }
2066 
2067  Bldr.generateNode(M, *I, state->BindExpr(M, LCtx, L), nullptr,
2069  } else {
2070  Bldr.takeNodes(*I);
2071  evalLoad(Tmp, M, M, *I, state, L);
2072  Bldr.addNodes(Tmp);
2073  }
2074  }
2075  }
2076 
2077  getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
2078 }
2079 
2081  ExplodedNodeSet &Dst) {
2082  ExplodedNodeSet AfterPreSet;
2083  getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this);
2084 
2085  // For now, treat all the arguments to C11 atomics as escaping.
2086  // FIXME: Ideally we should model the behavior of the atomics precisely here.
2087 
2088  ExplodedNodeSet AfterInvalidateSet;
2089  StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx);
2090 
2091  for (ExplodedNodeSet::iterator I = AfterPreSet.begin(), E = AfterPreSet.end();
2092  I != E; ++I) {
2093  ProgramStateRef State = (*I)->getState();
2094  const LocationContext *LCtx = (*I)->getLocationContext();
2095 
2096  SmallVector<SVal, 8> ValuesToInvalidate;
2097  for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) {
2098  const Expr *SubExpr = AE->getSubExprs()[SI];
2099  SVal SubExprVal = State->getSVal(SubExpr, LCtx);
2100  ValuesToInvalidate.push_back(SubExprVal);
2101  }
2102 
2103  State = State->invalidateRegions(ValuesToInvalidate, AE,
2104  currBldrCtx->blockCount(),
2105  LCtx,
2106  /*CausedByPointerEscape*/true,
2107  /*Symbols=*/nullptr);
2108 
2109  SVal ResultVal = UnknownVal();
2110  State = State->BindExpr(AE, LCtx, ResultVal);
2111  Bldr.generateNode(AE, *I, State, nullptr,
2113  }
2114 
2115  getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this);
2116 }
2117 
2118 namespace {
2119 class CollectReachableSymbolsCallback final : public SymbolVisitor {
2120  InvalidatedSymbols Symbols;
2121 
2122 public:
2123  CollectReachableSymbolsCallback(ProgramStateRef State) {}
2124  const InvalidatedSymbols &getSymbols() const { return Symbols; }
2125 
2126  bool VisitSymbol(SymbolRef Sym) override {
2127  Symbols.insert(Sym);
2128  return true;
2129  }
2130 };
2131 } // end anonymous namespace
2132 
2133 // A value escapes in three possible cases:
2134 // (1) We are binding to something that is not a memory region.
2135 // (2) We are binding to a MemrRegion that does not have stack storage.
2136 // (3) We are binding to a MemRegion with stack storage that the store
2137 // does not understand.
2139  SVal Loc, SVal Val) {
2140  // Are we storing to something that causes the value to "escape"?
2141  bool escapes = true;
2142 
2143  // TODO: Move to StoreManager.
2144  if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
2145  escapes = !regionLoc->getRegion()->hasStackStorage();
2146 
2147  if (!escapes) {
2148  // To test (3), generate a new state with the binding added. If it is
2149  // the same state, then it escapes (since the store cannot represent
2150  // the binding).
2151  // Do this only if we know that the store is not supposed to generate the
2152  // same state.
2153  SVal StoredVal = State->getSVal(regionLoc->getRegion());
2154  if (StoredVal != Val)
2155  escapes = (State == (State->bindLoc(*regionLoc, Val)));
2156  }
2157  }
2158 
2159  // If our store can represent the binding and we aren't storing to something
2160  // that doesn't have local storage then just return and have the simulation
2161  // state continue as is.
2162  if (!escapes)
2163  return State;
2164 
2165  // Otherwise, find all symbols referenced by 'val' that we are tracking
2166  // and stop tracking them.
2167  CollectReachableSymbolsCallback Scanner =
2168  State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val);
2169  const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
2171  EscapedSymbols,
2172  /*CallEvent*/ nullptr,
2174  nullptr);
2175 
2176  return State;
2177 }
2178 
2181  const InvalidatedSymbols *Invalidated,
2182  ArrayRef<const MemRegion *> ExplicitRegions,
2184  const CallEvent *Call,
2186 
2187  if (!Invalidated || Invalidated->empty())
2188  return State;
2189 
2190  if (!Call)
2192  *Invalidated,
2193  nullptr,
2195  &ITraits);
2196 
2197  // If the symbols were invalidated by a call, we want to find out which ones
2198  // were invalidated directly due to being arguments to the call.
2199  InvalidatedSymbols SymbolsDirectlyInvalidated;
2200  for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
2201  E = ExplicitRegions.end(); I != E; ++I) {
2202  if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
2203  SymbolsDirectlyInvalidated.insert(R->getSymbol());
2204  }
2205 
2206  InvalidatedSymbols SymbolsIndirectlyInvalidated;
2207  for (InvalidatedSymbols::const_iterator I=Invalidated->begin(),
2208  E = Invalidated->end(); I!=E; ++I) {
2209  SymbolRef sym = *I;
2210  if (SymbolsDirectlyInvalidated.count(sym))
2211  continue;
2212  SymbolsIndirectlyInvalidated.insert(sym);
2213  }
2214 
2215  if (!SymbolsDirectlyInvalidated.empty())
2217  SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
2218 
2219  // Notify about the symbols that get indirectly invalidated by the call.
2220  if (!SymbolsIndirectlyInvalidated.empty())
2222  SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
2223 
2224  return State;
2225 }
2226 
2227 /// evalBind - Handle the semantics of binding a value to a specific location.
2228 /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
2229 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
2230  ExplodedNode *Pred,
2231  SVal location, SVal Val,
2232  bool atDeclInit, const ProgramPoint *PP) {
2233 
2234  const LocationContext *LC = Pred->getLocationContext();
2235  PostStmt PS(StoreE, LC);
2236  if (!PP)
2237  PP = &PS;
2238 
2239  // Do a previsit of the bind.
2240  ExplodedNodeSet CheckedSet;
2241  getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
2242  StoreE, *this, *PP);
2243 
2244  StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
2245 
2246  // If the location is not a 'Loc', it will already be handled by
2247  // the checkers. There is nothing left to do.
2248  if (!location.getAs<Loc>()) {
2249  const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
2250  /*tag*/nullptr);
2251  ProgramStateRef state = Pred->getState();
2252  state = processPointerEscapedOnBind(state, location, Val);
2253  Bldr.generateNode(L, state, Pred);
2254  return;
2255  }
2256 
2257  for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2258  I!=E; ++I) {
2259  ExplodedNode *PredI = *I;
2260  ProgramStateRef state = PredI->getState();
2261 
2262  state = processPointerEscapedOnBind(state, location, Val);
2263 
2264  // When binding the value, pass on the hint that this is a initialization.
2265  // For initializations, we do not need to inform clients of region
2266  // changes.
2267  state = state->bindLoc(location.castAs<Loc>(),
2268  Val, /* notifyChanges = */ !atDeclInit);
2269 
2270  const MemRegion *LocReg = nullptr;
2271  if (Optional<loc::MemRegionVal> LocRegVal =
2272  location.getAs<loc::MemRegionVal>()) {
2273  LocReg = LocRegVal->getRegion();
2274  }
2275 
2276  const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
2277  Bldr.generateNode(L, state, PredI);
2278  }
2279 }
2280 
2281 /// evalStore - Handle the semantics of a store via an assignment.
2282 /// @param Dst The node set to store generated state nodes
2283 /// @param AssignE The assignment expression if the store happens in an
2284 /// assignment.
2285 /// @param LocationE The location expression that is stored to.
2286 /// @param state The current simulation state
2287 /// @param location The location to store the value
2288 /// @param Val The value to be stored
2289 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
2290  const Expr *LocationE,
2291  ExplodedNode *Pred,
2292  ProgramStateRef state, SVal location, SVal Val,
2293  const ProgramPointTag *tag) {
2294  // Proceed with the store. We use AssignE as the anchor for the PostStore
2295  // ProgramPoint if it is non-NULL, and LocationE otherwise.
2296  const Expr *StoreE = AssignE ? AssignE : LocationE;
2297 
2298  // Evaluate the location (checks for bad dereferences).
2299  ExplodedNodeSet Tmp;
2300  evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
2301 
2302  if (Tmp.empty())
2303  return;
2304 
2305  if (location.isUndef())
2306  return;
2307 
2308  for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
2309  evalBind(Dst, StoreE, *NI, location, Val, false);
2310 }
2311 
2313  const Expr *NodeEx,
2314  const Expr *BoundEx,
2315  ExplodedNode *Pred,
2317  SVal location,
2318  const ProgramPointTag *tag,
2319  QualType LoadTy)
2320 {
2321  assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2322 
2323  // Are we loading from a region? This actually results in two loads; one
2324  // to fetch the address of the referenced value and one to fetch the
2325  // referenced value.
2326  if (const TypedValueRegion *TR =
2327  dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
2328 
2329  QualType ValTy = TR->getValueType();
2330  if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
2331  static SimpleProgramPointTag
2332  loadReferenceTag(TagProviderName, "Load Reference");
2333  ExplodedNodeSet Tmp;
2334  evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
2335  location, &loadReferenceTag,
2336  getContext().getPointerType(RT->getPointeeType()));
2337 
2338  // Perform the load from the referenced value.
2339  for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
2340  state = (*I)->getState();
2341  location = state->getSVal(BoundEx, (*I)->getLocationContext());
2342  evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
2343  }
2344  return;
2345  }
2346  }
2347 
2348  evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
2349 }
2350 
2351 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
2352  const Expr *NodeEx,
2353  const Expr *BoundEx,
2354  ExplodedNode *Pred,
2356  SVal location,
2357  const ProgramPointTag *tag,
2358  QualType LoadTy) {
2359  assert(NodeEx);
2360  assert(BoundEx);
2361  // Evaluate the location (checks for bad dereferences).
2362  ExplodedNodeSet Tmp;
2363  evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
2364  if (Tmp.empty())
2365  return;
2366 
2367  StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2368  if (location.isUndef())
2369  return;
2370 
2371  // Proceed with the load.
2372  for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
2373  state = (*NI)->getState();
2374  const LocationContext *LCtx = (*NI)->getLocationContext();
2375 
2376  SVal V = UnknownVal();
2377  if (location.isValid()) {
2378  if (LoadTy.isNull())
2379  LoadTy = BoundEx->getType();
2380  V = state->getSVal(location.castAs<Loc>(), LoadTy);
2381  }
2382 
2383  Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
2385  }
2386 }
2387 
2388 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2389  const Stmt *NodeEx,
2390  const Stmt *BoundEx,
2391  ExplodedNode *Pred,
2392  ProgramStateRef state,
2393  SVal location,
2394  const ProgramPointTag *tag,
2395  bool isLoad) {
2396  StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2397  // Early checks for performance reason.
2398  if (location.isUnknown()) {
2399  return;
2400  }
2401 
2402  ExplodedNodeSet Src;
2403  BldrTop.takeNodes(Pred);
2404  StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2405  if (Pred->getState() != state) {
2406  // Associate this new state with an ExplodedNode.
2407  // FIXME: If I pass null tag, the graph is incorrect, e.g for
2408  // int *p;
2409  // p = 0;
2410  // *p = 0xDEADBEEF;
2411  // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2412  // instead "int *p" is noted as
2413  // "Variable 'p' initialized to a null pointer value"
2414 
2415  static SimpleProgramPointTag tag(TagProviderName, "Location");
2416  Bldr.generateNode(NodeEx, Pred, state, &tag);
2417  }
2418  ExplodedNodeSet Tmp;
2419  getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2420  NodeEx, BoundEx, *this);
2421  BldrTop.addNodes(Tmp);
2422 }
2423 
2424 std::pair<const ProgramPointTag *, const ProgramPointTag*>
2426  static SimpleProgramPointTag
2427  eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
2428  "Eagerly Assume True"),
2429  eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
2430  "Eagerly Assume False");
2431  return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2432  &eagerlyAssumeBinOpBifurcationFalse);
2433 }
2434 
2436  ExplodedNodeSet &Src,
2437  const Expr *Ex) {
2438  StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2439 
2440  for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
2441  ExplodedNode *Pred = *I;
2442  // Test if the previous node was as the same expression. This can happen
2443  // when the expression fails to evaluate to anything meaningful and
2444  // (as an optimization) we don't generate a node.
2445  ProgramPoint P = Pred->getLocation();
2446  if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2447  continue;
2448  }
2449 
2450  ProgramStateRef state = Pred->getState();
2451  SVal V = state->getSVal(Ex, Pred->getLocationContext());
2453  if (SEV && SEV->isExpression()) {
2454  const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2456 
2457  ProgramStateRef StateTrue, StateFalse;
2458  std::tie(StateTrue, StateFalse) = state->assume(*SEV);
2459 
2460  // First assume that the condition is true.
2461  if (StateTrue) {
2462  SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2463  StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2464  Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2465  }
2466 
2467  // Next, assume that the condition is false.
2468  if (StateFalse) {
2469  SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2470  StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2471  Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2472  }
2473  }
2474  }
2475 }
2476 
2478  ExplodedNodeSet &Dst) {
2479  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2480  // We have processed both the inputs and the outputs. All of the outputs
2481  // should evaluate to Locs. Nuke all of their values.
2482 
2483  // FIXME: Some day in the future it would be nice to allow a "plug-in"
2484  // which interprets the inline asm and stores proper results in the
2485  // outputs.
2486 
2487  ProgramStateRef state = Pred->getState();
2488 
2489  for (const Expr *O : A->outputs()) {
2490  SVal X = state->getSVal(O, Pred->getLocationContext());
2491  assert (!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
2492 
2493  if (Optional<Loc> LV = X.getAs<Loc>())
2494  state = state->bindLoc(*LV, UnknownVal());
2495  }
2496 
2497  Bldr.generateNode(A, Pred, state);
2498 }
2499 
2501  ExplodedNodeSet &Dst) {
2502  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2503  Bldr.generateNode(A, Pred, Pred->getState());
2504 }
2505 
2506 //===----------------------------------------------------------------------===//
2507 // Visualization.
2508 //===----------------------------------------------------------------------===//
2509 
2510 #ifndef NDEBUG
2513 
2514 namespace llvm {
2515 template<>
2516 struct DOTGraphTraits<ExplodedNode*> :
2517  public DefaultDOTGraphTraits {
2518 
2519  DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2520 
2521  // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
2522  // work.
2523  static std::string getNodeAttributes(const ExplodedNode *N, void*) {
2524 
2525 #if 0
2526  // FIXME: Replace with a general scheme to tell if the node is
2527  // an error node.
2528  if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
2529  GraphPrintCheckerState->isExplicitNullDeref(N) ||
2530  GraphPrintCheckerState->isUndefDeref(N) ||
2531  GraphPrintCheckerState->isUndefStore(N) ||
2532  GraphPrintCheckerState->isUndefControlFlow(N) ||
2533  GraphPrintCheckerState->isUndefResult(N) ||
2534  GraphPrintCheckerState->isBadCall(N) ||
2535  GraphPrintCheckerState->isUndefArg(N))
2536  return "color=\"red\",style=\"filled\"";
2537 
2538  if (GraphPrintCheckerState->isNoReturnCall(N))
2539  return "color=\"blue\",style=\"filled\"";
2540 #endif
2541  return "";
2542  }
2543 
2544  static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
2545  if (SLoc.isFileID()) {
2546  Out << "\\lline="
2548  << " col="
2550  << "\\l";
2551  }
2552  }
2553 
2554  static std::string getNodeLabel(const ExplodedNode *N, void*){
2555 
2556  std::string sbuf;
2557  llvm::raw_string_ostream Out(sbuf);
2558 
2559  // Program Location.
2560  ProgramPoint Loc = N->getLocation();
2561 
2562  switch (Loc.getKind()) {
2564  Out << "Block Entrance: B"
2565  << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
2566  if (const NamedDecl *ND =
2567  dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) {
2568  Out << " (";
2569  ND->printName(Out);
2570  Out << ")";
2571  }
2572  break;
2573  }
2574 
2576  assert (false);
2577  break;
2578 
2580  Out << "CallEnter";
2581  break;
2582 
2584  Out << "CallExitBegin";
2585  break;
2586 
2588  Out << "CallExitEnd";
2589  break;
2590 
2592  Out << "PostStmtPurgeDeadSymbols";
2593  break;
2594 
2596  Out << "PreStmtPurgeDeadSymbols";
2597  break;
2598 
2600  Out << "Epsilon Point";
2601  break;
2602 
2605  Out << "PreCall: ";
2606 
2607  // FIXME: Get proper printing options.
2608  PC.getDecl()->print(Out, LangOptions());
2609  printLocation(Out, PC.getLocation());
2610  break;
2611  }
2612 
2615  Out << "PostCall: ";
2616 
2617  // FIXME: Get proper printing options.
2618  PC.getDecl()->print(Out, LangOptions());
2619  printLocation(Out, PC.getLocation());
2620  break;
2621  }
2622 
2624  Out << "PostInitializer: ";
2625  const CXXCtorInitializer *Init =
2626  Loc.castAs<PostInitializer>().getInitializer();
2627  if (const FieldDecl *FD = Init->getAnyMember())
2628  Out << *FD;
2629  else {
2630  QualType Ty = Init->getTypeSourceInfo()->getType();
2631  Ty = Ty.getLocalUnqualifiedType();
2632  LangOptions LO; // FIXME.
2633  Ty.print(Out, LO);
2634  }
2635  break;
2636  }
2637 
2639  const BlockEdge &E = Loc.castAs<BlockEdge>();
2640  Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
2641  << E.getDst()->getBlockID() << ')';
2642 
2643  if (const Stmt *T = E.getSrc()->getTerminator()) {
2644  SourceLocation SLoc = T->getLocStart();
2645 
2646  Out << "\\|Terminator: ";
2647  LangOptions LO; // FIXME.
2648  E.getSrc()->printTerminator(Out, LO);
2649 
2650  if (SLoc.isFileID()) {
2651  Out << "\\lline="
2653  << " col="
2655  }
2656 
2657  if (isa<SwitchStmt>(T)) {
2658  const Stmt *Label = E.getDst()->getLabel();
2659 
2660  if (Label) {
2661  if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
2662  Out << "\\lcase ";
2663  LangOptions LO; // FIXME.
2664  if (C->getLHS())
2665  C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO));
2666 
2667  if (const Stmt *RHS = C->getRHS()) {
2668  Out << " .. ";
2669  RHS->printPretty(Out, nullptr, PrintingPolicy(LO));
2670  }
2671 
2672  Out << ":";
2673  }
2674  else {
2675  assert (isa<DefaultStmt>(Label));
2676  Out << "\\ldefault:";
2677  }
2678  }
2679  else
2680  Out << "\\l(implicit) default:";
2681  }
2682  else if (isa<IndirectGotoStmt>(T)) {
2683  // FIXME
2684  }
2685  else {
2686  Out << "\\lCondition: ";
2687  if (*E.getSrc()->succ_begin() == E.getDst())
2688  Out << "true";
2689  else
2690  Out << "false";
2691  }
2692 
2693  Out << "\\l";
2694  }
2695 
2696 #if 0
2697  // FIXME: Replace with a general scheme to determine
2698  // the name of the check.
2699  if (GraphPrintCheckerState->isUndefControlFlow(N)) {
2700  Out << "\\|Control-flow based on\\lUndefined value.\\l";
2701  }
2702 #endif
2703  break;
2704  }
2705 
2706  default: {
2707  const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
2708  assert(S != nullptr && "Expecting non-null Stmt");
2709 
2710  Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
2711  LangOptions LO; // FIXME.
2712  S->printPretty(Out, nullptr, PrintingPolicy(LO));
2713  printLocation(Out, S->getLocStart());
2714 
2715  if (Loc.getAs<PreStmt>())
2716  Out << "\\lPreStmt\\l;";
2717  else if (Loc.getAs<PostLoad>())
2718  Out << "\\lPostLoad\\l;";
2719  else if (Loc.getAs<PostStore>())
2720  Out << "\\lPostStore\\l";
2721  else if (Loc.getAs<PostLValue>())
2722  Out << "\\lPostLValue\\l";
2723 
2724 #if 0
2725  // FIXME: Replace with a general scheme to determine
2726  // the name of the check.
2727  if (GraphPrintCheckerState->isImplicitNullDeref(N))
2728  Out << "\\|Implicit-Null Dereference.\\l";
2729  else if (GraphPrintCheckerState->isExplicitNullDeref(N))
2730  Out << "\\|Explicit-Null Dereference.\\l";
2731  else if (GraphPrintCheckerState->isUndefDeref(N))
2732  Out << "\\|Dereference of undefialied value.\\l";
2733  else if (GraphPrintCheckerState->isUndefStore(N))
2734  Out << "\\|Store to Undefined Loc.";
2735  else if (GraphPrintCheckerState->isUndefResult(N))
2736  Out << "\\|Result of operation is undefined.";
2737  else if (GraphPrintCheckerState->isNoReturnCall(N))
2738  Out << "\\|Call to function marked \"noreturn\".";
2739  else if (GraphPrintCheckerState->isBadCall(N))
2740  Out << "\\|Call to NULL/Undefined.";
2741  else if (GraphPrintCheckerState->isUndefArg(N))
2742  Out << "\\|Argument in call is undefined";
2743 #endif
2744 
2745  break;
2746  }
2747  }
2748 
2749  ProgramStateRef state = N->getState();
2750  Out << "\\|StateID: " << (const void*) state.get()
2751  << " NodeID: " << (const void*) N << "\\|";
2752  state->printDOT(Out);
2753 
2754  Out << "\\l";
2755 
2756  if (const ProgramPointTag *tag = Loc.getTag()) {
2757  Out << "\\|Tag: " << tag->getTagDescription();
2758  Out << "\\l";
2759  }
2760  return Out.str();
2761  }
2762 };
2763 } // end llvm namespace
2764 #endif
2765 
2766 void ExprEngine::ViewGraph(bool trim) {
2767 #ifndef NDEBUG
2768  if (trim) {
2769  std::vector<const ExplodedNode*> Src;
2770 
2771  // Flush any outstanding reports to make sure we cover all the nodes.
2772  // This does not cause them to get displayed.
2773  for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
2774  const_cast<BugType*>(*I)->FlushReports(BR);
2775 
2776  // Iterate through the reports and get their nodes.
2778  EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
2779  ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
2780  if (N) Src.push_back(N);
2781  }
2782 
2783  ViewGraph(Src);
2784  }
2785  else {
2786  GraphPrintCheckerState = this;
2788 
2789  llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
2790 
2791  GraphPrintCheckerState = nullptr;
2792  GraphPrintSourceManager = nullptr;
2793  }
2794 #endif
2795 }
2796 
2798 #ifndef NDEBUG
2799  GraphPrintCheckerState = this;
2801 
2802  std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
2803 
2804  if (!TrimmedG.get())
2805  llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
2806  else
2807  llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
2808 
2809  GraphPrintCheckerState = nullptr;
2810  GraphPrintSourceManager = nullptr;
2811 #endif
2812 }
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:52
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2411
unsigned getNumArrayIndices() const
Determine the number of implicit array indices used while described an array member initialization...
Definition: DeclCXX.h:2131
CFGNewAllocator - Represents C++ allocator call.
Definition: CFG.h:151
This represents a GCC inline-assembly statement extension.
Definition: Stmt.h:1565
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1561
TypedValueRegion - An abstract class representing regions having a typed value.
Definition: MemRegion.h:494
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
Definition: SValBuilder.h:237
void ProcessInitializer(const CFGInitializer I, ExplodedNode *Pred)
Definition: ExprEngine.cpp:456
STATISTIC(NumRemoveDeadBindings,"The # of times RemoveDeadBindings is called")
ProgramStateRef getState() const
Definition: CoreEngine.h:487
SVal evalDerivedToBase(SVal Derived, const CastExpr *Cast)
Evaluates a chain of derived-to-base casts through the path specified in Cast.
Definition: Store.cpp:235
const CXXNewExpr * getAllocatorExpr() const
Definition: CFG.h:157
A (possibly-)qualified type.
Definition: Type.h:598
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:79
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:208
Static storage duration.
Definition: Specifiers.h:273
void markInfeasible(bool branch)
Definition: CoreEngine.h:435
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2217
bool hasDeadSymbols() const
bool isMemberPointerType() const
Definition: Type.h:5506
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:254
succ_iterator succ_begin()
Definition: CFG.h:541
CompoundStmt * getSubStmt()
Definition: Expr.h:3396
void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitCall - Transfer function for function calls.
Information about invalidation for a particular region/symbol.
Definition: MemRegion.h:1316
const Expr * getCondition() const
Definition: CoreEngine.h:538
This builder class is useful for generating nodes that resulted from visiting a statement.
Definition: CoreEngine.h:348
void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE, ExplodedNodeSet &PreVisit, ExplodedNodeSet &Dst)
Definition: ExprEngine.cpp:718
EnumConstantDecl - An instance of this object exists for each enum constant that is defined...
Definition: Decl.h:2481
bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2)
Definition: ProgramState.h:549
Defines the SourceManager interface.
virtual bool inTopFrame() const
Return true if the current LocationContext has no caller context.
const LocationContext * getLocationContext() const
Definition: CoreEngine.h:489
static const Stmt * getRightmostLeaf(const Stmt *Condition)
ProgramPoint getLocation() const
getLocation - Returns the edge associated with the given node.
bool isInteger() const
Definition: Type.h:2072
void VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitMSAsmStmt - Transfer function logic for MS inline asm.
virtual QualType getValueType() const =0
Represents a point when we begin processing an inlined call.
Definition: ProgramPoint.h:584
SourceLocation getLocStart() const LLVM_READONLY
Definition: ExprCXX.h:1993
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
void runCheckersForEndFunction(NodeBuilderContext &BC, ExplodedNodeSet &Dst, ExplodedNode *Pred, ExprEngine &Eng)
Run checkers on end of function.
void printState(raw_ostream &Out, ProgramStateRef State, const char *NL, const char *Sep) override
printState - Called by ProgramStateManager to print checker-specific data.
Definition: ExprEngine.cpp:280
StringRef P
const RegionTy * getAs() const
Definition: MemRegion.h:1106
SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc L, NonLoc R, QualType T)
Definition: ExprEngine.h:487
static ExprEngine * GraphPrintCheckerState
The pointer has been passed to a function indirectly.
void processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE, NodeBuilderContext &BldCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF) override
Called by CoreEngine.
Definition: ExprEngine.cpp:701
CFGDeleteDtor - Represents C++ object destructor generated from a call to delete. ...
Definition: CFG.h:218
Represents a program point just before an implicit call event.
Definition: ProgramPoint.h:551
const CXXDeleteExpr * getDeleteExpr() const
Definition: CFG.h:228
void ProcessMemberDtor(const CFGMemberDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Definition: ExprEngine.cpp:657
StorageDuration
The storage duration for an object (per C++ [basic.stc]).
Definition: Specifiers.h:269
static std::string getNodeLabel(const ExplodedNode *N, void *)
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C...
Definition: Type.h:5439
bool shouldWidenLoops()
Returns true if the analysis should try to widen loops.
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2187
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:3962
void processCFGBlockEntrance(const BlockEdge &L, NodeBuilderWithSinks &nodeBuilder, ExplodedNode *Pred) override
Called by CoreEngine when processing the entrance of a CFGBlock.
bool haveEqualEnvironments(ProgramStateRef S1, ProgramStateRef S2)
Definition: ProgramState.h:545
const FieldDecl * getFieldDecl() const
Definition: CFG.h:266
ProgramStateRef getInitialState(const LocationContext *InitLoc) override
getInitialState - Return the initial state used for the root vertex in the ExplodedGraph.
Definition: ExprEngine.cpp:105
Represents an implicit call event.
Definition: ProgramPoint.h:527
ImplTy::const_iterator const_iterator
void VisitUnaryOperator(const UnaryOperator *B, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitUnaryOperator - Transfer function logic for unary operators.
void takeNodes(const ExplodedNodeSet &S)
Definition: CoreEngine.h:301
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:768
void markReachedMaxBlockCount(const Decl *D)
Expr * getInit() const
Get the initializer.
Definition: DeclCXX.h:2155
void printTerminator(raw_ostream &OS, const LangOptions &LO) const
printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Definition: CFG.cpp:4573
void ProcessDeleteDtor(const CFGDeleteDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Definition: ExprEngine.cpp:609
loc::MemRegionVal getCXXThis(const CXXMethodDecl *D, const StackFrameContext *SFC)
Return a memory region for the 'this' object reference.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1813
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:113
Expr * IgnoreImplicit() LLVM_READONLY
IgnoreImplicit - Skip past any implicit AST nodes which might surround this expression.
Definition: Expr.h:724
const internal::VariadicDynCastAllOfMatcher< Decl, VarDecl > varDecl
Matches variable declarations.
Definition: ASTMatchers.h:937
void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE, ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SVal Val, const ProgramPointTag *tag=nullptr)
evalStore - Handle the semantics of a store via an assignment.
void enqueue(ExplodedNodeSet &Set)
Enqueue the given set of nodes onto the work list.
Definition: CoreEngine.cpp:608
roots_iterator roots_begin()
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:38
Defines the Objective-C statement AST node classes.
void removeDead(ExplodedNode *Node, ExplodedNodeSet &Out, const Stmt *ReferenceStmt, const LocationContext *LC, const Stmt *DiagnosticStmt=nullptr, ProgramPoint::Kind K=ProgramPoint::PreStmtPurgeDeadSymbolsKind)
Run the analyzer's garbage collection - remove dead symbols and bindings from the state...
Definition: ExprEngine.cpp:343
ProgramStateRef removeDeadBindings(ProgramStateRef St, const StackFrameContext *LCtx, SymbolReaper &SymReaper)
bool body_empty() const
Definition: Stmt.h:575
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1377
void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
BoundNodesTreeBuilder Nodes
void ProcessTemporaryDtor(const CFGTemporaryDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Definition: ExprEngine.cpp:674
bool isBaseInitializer() const
Determine whether this initializer is initializing a base class.
Definition: DeclCXX.h:2002
const Expr * getTarget() const
Definition: CoreEngine.h:485
void runCheckersForLocation(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, SVal location, bool isLoad, const Stmt *NodeEx, const Stmt *BoundEx, ExprEngine &Eng)
Run checkers for load/store of a location.
Symbolic value.
Definition: SymExpr.h:29
const SwitchStmt * getSwitch() const
Definition: CoreEngine.h:528
ProgramStateRef runCheckersForPointerEscape(ProgramStateRef State, const InvalidatedSymbols &Escaped, const CallEvent *Call, PointerEscapeKind Kind, RegionAndSymbolInvalidationTraits *ITraits)
Run checkers when pointers escape.
One of these records is kept for each identifier that is lexed.
A pointer escapes due to binding its value to a location that the analyzer cannot track...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:92
LineState State
void runCheckersForLiveSymbols(ProgramStateRef state, SymbolReaper &SymReaper)
Run checkers for live symbols.
bool isReferenceType() const
Definition: Type.h:5491
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
Definition: Decl.h:2293
Represents a program point after a store evaluation.
Definition: ProgramPoint.h:399
CFGAutomaticObjDtor - Represents C++ object destructor implicitly generated for automatic object or t...
Definition: CFG.h:194
void VisitCXXDestructor(QualType ObjectType, const MemRegion *Dest, const Stmt *S, bool IsBaseDtor, ExplodedNode *Pred, ExplodedNodeSet &Dst)
bool isFileID() const
MemRegionManager & getRegionManager()
Definition: ProgramState.h:508
AnalysisDeclContext * getAnalysisDeclContext() const
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
Definition: ASTMatchers.h:283
T castAs() const
Convert to the specified CFGElement type, asserting that this CFGElement is of the desired type...
Definition: CFG.h:87
ASTContext & getContext() const
getContext - Return the ASTContext associated with this analysis.
Definition: ExprEngine.h:123
void ProcessImplicitDtor(const CFGImplicitDtor D, ExplodedNode *Pred)
Definition: ExprEngine.cpp:544
Expr * getSubExpr()
Definition: Expr.h:2684
void addPredecessor(ExplodedNode *V, ExplodedGraph &G)
addPredeccessor - Adds a predecessor to the current node, and in tandem add this node as a successor ...
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
void EndPath(ProgramStateRef St)
Definition: ProgramState.h:623
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
unsigned eagerlyAssumeBinOpBifurcation
The flag regulates if we should eagerly assume evaluations of conditionals, thus, bifurcating the pat...
const CXXBindTemporaryExpr * getBindTemporaryExpr() const
Definition: CFG.h:285
unsigned getExpansionColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
static std::string getNodeAttributes(const ExplodedNode *N, void *)
static bool isRelationalOp(Opcode Opc)
Definition: Expr.h:2983
static bool isLocType(QualType T)
Definition: SVals.h:291
void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitOffsetOfExpr - Transfer function for offsetof.
void processEndOfFunction(NodeBuilderContext &BC, ExplodedNode *Pred) override
Called by CoreEngine.
ExplodedNodeSet::iterator iterator
Definition: CoreEngine.h:286
This is a meta program point, which should be skipped by all the diagnostic reasoning etc...
Definition: ProgramPoint.h:659
static bool isEqualityOp(Opcode Opc)
Definition: Expr.h:2986
ExplodedNode * generateSink(const Stmt *S, ExplodedNode *Pred, ProgramStateRef St, const ProgramPointTag *tag=nullptr, ProgramPoint::Kind K=ProgramPoint::PostStmtKind)
Definition: CoreEngine.h:388
Expr * getTrueExpr() const
Definition: Expr.h:3326
IndirectFieldDecl * getIndirectMember() const
Definition: DeclCXX.h:2082
unsigned getIndex() const
const VarDecl * getVarDecl() const
Definition: CFG.h:199
const CFGBlock * getCallSiteBlock() const
ExplodedNode * generateCaseStmtNode(const iterator &I, ProgramStateRef State)
Definition: CoreEngine.cpp:706
bool isUnknownOrUndef() const
Definition: SVals.h:125
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2897
const Stmt * getCallSite() const
llvm::FoldingSet< BugReportEquivClass >::iterator EQClasses_iterator
Iterator over the set of BugReports tracked by the BugReporter.
Definition: BugReporter.h:442
If a crash happens while one of these objects are live, the message is printed out along with the spe...
bool wantsRegionChangeUpdate(ProgramStateRef state)
True if at least one checker wants to check region changes.
void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitReturnStmt - Transfer function logic for return statements.
DefinedSVal getFunctionPointer(const FunctionDecl *func)
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
Definition: Type.h:934
bool isDelegatingInitializer() const
Determine whether this initializer is creating a delegating constructor.
Definition: DeclCXX.h:2030
void ProcessStmt(const CFGStmt S, ExplodedNode *Pred)
Definition: ExprEngine.cpp:425
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2632
NonLoc makeIntValWithPtrWidth(uint64_t integer, bool isUnsigned)
Definition: SValBuilder.h:272
void ProcessNewAllocator(const CXXNewExpr *NE, ExplodedNode *Pred)
Definition: ExprEngine.cpp:571
void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Definition: ExprEngine.cpp:590
QualType getDestroyedType() const
Retrieve the type being destroyed.
Definition: ExprCXX.cpp:144
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1119
ProgramStateRef getState() const
Definition: CoreEngine.h:540
void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitDeclStmt - Transfer function logic for DeclStmts.
bool isValid() const
Definition: SVals.h:129
detail::InMemoryDirectory::const_iterator I
const Stmt * getTriggerStmt() const
Definition: CFG.h:204
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:967
QualType getType() const
Definition: Decl.h:599
reverse_iterator rend()
Definition: CFG.h:511
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.
void VisitLogicalExpr(const BinaryOperator *B, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitLogicalExpr - Transfer function logic for '&&', '||'.
const LocationContext * getLocationContext() const
const CFGBlock * getSrc() const
Definition: ProgramPoint.h:479
void runCheckersForPrintState(raw_ostream &Out, ProgramStateRef State, const char *NL, const char *Sep)
Run checkers for debug-printing a ProgramState.
void removeDeadOnEndOfFunction(NodeBuilderContext &BC, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Remove dead bindings/symbols before exiting a function.
void runCheckersForBind(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, SVal location, SVal val, const Stmt *S, ExprEngine &Eng, const ProgramPoint &PP)
Run checkers for binding of a value to a location.
Expr * getLHS() const
Definition: Expr.h:3594
static SourceManager * GraphPrintSourceManager
Expr ** getSubExprs()
Definition: Expr.h:4864
void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, ExplodedNodeSet &Dst)
CFGBlock - Represents a single basic block in a source-level CFG.
Definition: CFG.h:353
void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
unsigned blockCount() const
Returns the number of times the current basic block has been visited on the exploded graph path...
Definition: CoreEngine.h:194
const MemRegion * StripCasts(bool StripBaseCasts=true) const
Definition: MemRegion.cpp:1155
CheckerManager & getCheckerManager() const
Definition: ExprEngine.h:127
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:415
InliningModes
The modes of inlining, which override the default analysis-wide settings.
Definition: ExprEngine.h:51
SymbolicRegion - A special, "non-concrete" region.
Definition: MemRegion.h:707
void runCheckersForPostStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng, bool wasInlined=false)
Run checkers for post-visiting Stmts.
static unsigned getNumSubExprs(AtomicOp Op)
Determine the number of arguments the specified atomic builtin should have.
Definition: Expr.cpp:3841
const CFGBlock * getDst() const
Definition: ProgramPoint.h:483
void ProcessBaseDtor(const CFGBaseDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Definition: ExprEngine.cpp:638
DefinedOrUnknownSVal makeZeroVal(QualType type)
Construct an SVal representing '0' for the specified type.
Definition: SValBuilder.cpp:32
void processSwitch(SwitchNodeBuilder &builder) override
ProcessSwitch - Called by CoreEngine.
void processBeginOfFunction(NodeBuilderContext &BC, ExplodedNode *Pred, ExplodedNodeSet &Dst, const BlockEdge &L) override
Called by CoreEngine.
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:590
Expr - This represents one expression.
Definition: Expr.h:105
const ProgramStateRef & getState() const
void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Transfer function logic for computing the lvalue of an Objective-C ivar.
StringRef getName() const
Return the actual identifier string.
void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXNewAllocatorCall(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
const Stmt * getStmt() const
Definition: ProgramPoint.h:270
void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitCast - Transfer function logic for all casts (implicit and explicit).
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2414
This is the simplest builder which generates nodes in the ExplodedGraph.
Definition: CoreEngine.h:210
CXXCtorInitializer * getInitializer() const
Definition: CFG.h:138
Optional< T > getAs() const
Convert to the specified SVal type, returning None if this SVal is not of the desired type...
Definition: SVals.h:86
The pointer has been passed to a function call directly.
std::pair< const CXXBindTemporaryExpr *, const StackFrameContext * > CXXBindTemporaryContext
Definition: ExprEngine.cpp:57
Expr * getRHS()
Definition: Stmt.h:715
virtual StringRef getTagDescription() const =0
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Visit - Transfer function logic for all statements.
Definition: ExprEngine.cpp:744
void FlushReports()
Generate and flush diagnostics for all bug reports.
std::pair< const ProgramPointTag *, const ProgramPointTag * > geteagerlyAssumeBinOpBifurcationTags()
void enqueueStmtNode(ExplodedNode *N, const CFGBlock *Block, unsigned Idx)
Enqueue a single node created as a result of statement processing.
Definition: CoreEngine.cpp:544
The reason for pointer escape is unknown.
bool isIndirectMemberInitializer() const
Definition: DeclCXX.h:2014
T castAs() const
Convert to the specified ProgramPoint type, asserting that this ProgramPoint is of the desired type...
Definition: ProgramPoint.h:139
Traits for storing the call processing policy inside GDM.
Definition: ExprEngine.h:646
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1214
const LocationContext * getLocationContext() const
Definition: CoreEngine.h:542
unsigned getBlockID() const
Definition: CFG.h:638
void VisitAtomicExpr(const AtomicExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitMemberExpr - Transfer function for builtin atomic expressions.
This represents a Microsoft inline-assembly statement extension.
Definition: Stmt.h:1744
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1668
ExplodedNode * getNode(const ProgramPoint &L, ProgramStateRef State, bool IsSink=false, bool *IsNew=nullptr)
Retrieve the node associated with a (Location,State) pair, where the 'Location' is a ProgramPoint in ...
Kind getKind() const
Definition: ProgramPoint.h:159
void evalLoad(ExplodedNodeSet &Dst, const Expr *NodeEx, const Expr *BoundExpr, ExplodedNode *Pred, ProgramStateRef St, SVal location, const ProgramPointTag *tag=nullptr, QualType LoadTy=QualType())
Simulate a read of the result of Ex.
ValueDecl * getDecl()
Definition: Expr.h:1017
CFGBaseDtor - Represents C++ object destructor implicitly generated for base object in destructor...
Definition: CFG.h:242
bool isGLValue() const
Definition: Expr.h:250
QualType getConditionType() const
Definition: SValBuilder.h:131
reverse_iterator rbegin()
Definition: CFG.h:510
virtual ProgramStateRef removeDeadBindings(ProgramStateRef state, SymbolReaper &SymReaper)=0
ExplodedNode * generateNode(const iterator &I, ProgramStateRef State, bool isSink=false)
Definition: CoreEngine.cpp:686
While alive, includes the current analysis stack in a crash trace.
void VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitArraySubscriptExpr - Transfer function for array accesses.
Stmt * getBody(const FunctionDecl *&Definition) const
getBody - Retrieve the body (definition) of the function.
Definition: Decl.cpp:2491
Thread storage duration.
Definition: Specifiers.h:272
Expr * getArgument()
Definition: ExprCXX.h:2055
static const Stmt * ResolveCondition(const Stmt *Condition, const CFGBlock *B)
void enqueueEndOfFunction(ExplodedNodeSet &Set)
enqueue the nodes corresponding to the end of function onto the end of path / work list...
Definition: CoreEngine.cpp:623
bool isConsumedExpr(Expr *E) const
Definition: ParentMap.cpp:159
CFGTerminator getTerminator()
Definition: CFG.h:622
bool wantsRegionChangeUpdate(ProgramStateRef state) override
wantsRegionChangeUpdate - Called by ProgramStateManager to determine if a region change should trigge...
Definition: ExprEngine.cpp:266
void processCFGElement(const CFGElement E, ExplodedNode *Pred, unsigned StmtIdx, NodeBuilderContext *Ctx) override
processCFGElement - Called by CoreEngine.
Definition: ExprEngine.cpp:289
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:5730
ProgramStateRef getInitialState(const LocationContext *InitLoc)
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:4679
ProgramStateRef processPointerEscapedOnBind(ProgramStateRef State, SVal Loc, SVal Val) override
Call PointerEscape callback when a value escapes as a result of bind.
void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitGuardedExpr - Transfer function logic for ?, __builtin_choose.
SmallVectorImpl< AnnotatedLine * >::const_iterator Next
EQClasses_iterator EQClasses_begin()
Definition: BugReporter.h:443
ProgramStateRef getWidenedLoopState(ProgramStateRef PrevState, const LocationContext *LCtx, unsigned BlockCount, const Stmt *LoopStmt)
Get the states that result from widening the loop.
Encodes a location in the source.
DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag, const Expr *expr, const LocationContext *LCtx, unsigned count)
Create a new symbol with a unique 'name'.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:3733
const TemplateArgument * iterator
Definition: Type.h:4233
Stmt * getLabel()
Definition: CFG.h:633
const StackFrameContext * getCurrentStackFrame() const
void runCheckersForBranchCondition(const Stmt *condition, ExplodedNodeSet &Dst, ExplodedNode *Pred, ExprEngine &Eng)
Run checkers for branch condition.
FieldDecl * getAnyMember() const
Definition: DeclCXX.h:2074
static bool isCallStmt(const Stmt *S)
Returns true if this is a statement is a function or method call of some kind.
Definition: CallEvent.cpp:265
ProgramPoints can be "tagged" as representing points specific to a given analysis entity...
Definition: ProgramPoint.h:40
AnalysisManager & getAnalysisManager() override
Definition: ExprEngine.h:125
void evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, const Expr *Ex)
evalEagerlyAssumeBinOpBifurcation - Given the nodes in 'Src', eagerly assume symbolic expressions of ...
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
Definition: ExprCXX.h:1804
Expr * getLHS()
Definition: Stmt.h:714
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
Definition: Stmt.h:443
void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitCompoundLiteralExpr - Transfer function logic for compound literals.
LabelDecl - Represents the declaration of a label.
Definition: Decl.h:424
ExplodedNode * generateNode(ProgramStateRef State, ExplodedNode *Pred, const ProgramPointTag *Tag=nullptr)
Definition: CoreEngine.h:323
const Expr * getCond() const
Definition: Stmt.h:994
bool isTemporaryDtorsBranch() const
Definition: CFG.h:313
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
static void printLocation(raw_ostream &Out, SourceLocation SLoc)
void processIndirectGoto(IndirectGotoNodeBuilder &builder) override
processIndirectGoto - Called by CoreEngine.
const CXXTempObjectRegion * getCXXTempObjectRegion(Expr const *Ex, LocationContext const *LC)
Definition: MemRegion.cpp:1016
SourceLocation getLocStart() const LLVM_READONLY
Definition: ExprCXX.h:2064
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1736
BugTypesTy::iterator iterator
Iterator over the set of BugTypes tracked by the BugReporter.
Definition: BugReporter.h:437
const Stmt * getStmt() const
Definition: CFG.h:119
void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition: DeclCXX.cpp:1795
void processBranch(const Stmt *Condition, const Stmt *Term, NodeBuilderContext &BuilderCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF) override
ProcessBranch - Called by CoreEngine.
SVal - This represents a symbolic expression, which can be either an L-value or an R-value...
Definition: SVals.h:46
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>.
Definition: Expr.h:4804
CanQualType VoidTy
Definition: ASTContext.h:893
void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof.
ProgramStateRef runCheckersForEvalAssume(ProgramStateRef state, SVal Cond, bool Assumption)
Run checkers for handling assumptions on symbolic values.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2734
void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitObjCForCollectionStmt - Transfer function logic for ObjCForCollectionStmt.
const Decl * getDecl() const
A class responsible for cleaning up unused symbols.
bool isUndef() const
Definition: SVals.h:121
bool isAllEnumCasesCovered() const
Returns true if the SwitchStmt is a switch of an enum value and all cases have been explicitly covere...
Definition: Stmt.h:1027
void getCaptureFields(llvm::DenseMap< const VarDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition: DeclCXX.cpp:1083
static bool isLogicalOp(Opcode Opc)
Definition: Expr.h:3019
void runCheckersForPreStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng)
Run checkers for pre-visiting Stmts.
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:3380
ProgramStateRef getPersistentStateWithGDM(ProgramStateRef FromState, ProgramStateRef GDMState)
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:70
Opcode getOpcode() const
Definition: Expr.h:1692
void insert(const ExplodedNodeSet &S)
unsigned maxBlockVisitOnPath
The maximum number of times the analyzer visits a block.
std::unique_ptr< ExplodedGraph > trim(ArrayRef< const NodeTy * > Nodes, InterExplodedGraphMap *ForwardMap=nullptr, InterExplodedGraphMap *InverseMap=nullptr) const
Creates a trimmed version of the graph that only contains paths leading to the given nodes...
ast_type_traits::DynTypedNode Node
QualType getType() const
Definition: Expr.h:126
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition: Expr.h:4734
TypeSourceInfo * getTypeSourceInfo() const
Returns the declarator information for a base class or delegating initializer.
Definition: DeclCXX.h:2063
void runCheckersForDeadSymbols(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, SymbolReaper &SymReaper, const Stmt *S, ExprEngine &Eng, ProgramPoint::Kind K)
Run checkers for dead symbols.
const LocationContext * getParent() const
ExplodedNode * generateDefaultCaseNode(ProgramStateRef State, bool isSink=false)
Definition: CoreEngine.cpp:723
SValBuilder & getSValBuilder()
Definition: ExprEngine.h:131
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
Definition: ExprCXX.h:2008
void addNodes(const ExplodedNodeSet &S)
Definition: CoreEngine.h:306
StoreManager & getStoreManager()
Definition: ExprEngine.h:307
Represents a program point just after an implicit call event.
Definition: ProgramPoint.h:568
const LocationContext * getLocationContext() const
Definition: ProgramPoint.h:178
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1375
const NodeBuilderContext & getContext()
Definition: CoreEngine.h:298
This node builder keeps track of the generated sink nodes.
Definition: CoreEngine.h:312
bool isPurgeKind()
Is this a program point corresponding to purge/removal of dead symbols and bindings.
Definition: ProgramPoint.h:170
void reclaimRecentlyAllocatedNodes()
Reclaim "uninteresting" nodes created since the last time this method was called. ...
SourceLocation getLocation() const
Definition: ProgramPoint.h:534
void VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitLambdaExpr - Transfer function logic for LambdaExprs.
Represents symbolic expression.
Definition: SVals.h:315
ProgramStateRef notifyCheckersOfPointerEscape(ProgramStateRef State, const InvalidatedSymbols *Invalidated, ArrayRef< const MemRegion * > ExplicitRegions, ArrayRef< const MemRegion * > Regions, const CallEvent *Call, RegionAndSymbolInvalidationTraits &ITraits) override
Call PointerEscape callback when a value escapes as a result of region invalidation.
detail::InMemoryDirectory::const_iterator E
const MemRegion * getAsRegion() const
Definition: SVals.cpp:135
BranchNodeBuilder is responsible for constructing the nodes corresponding to the two branches of the ...
Definition: CoreEngine.h:401
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition: DeclCXX.h:2069
Represents an abstract call to a function or method along a particular path.
Definition: CallEvent.h:138
Optional< T > getAs() const
Convert to the specified ProgramPoint type, returning None if this ProgramPoint is not of the desired...
Definition: ProgramPoint.h:150
ProgramStateManager & getStateManager() override
Definition: ExprEngine.h:305
const CFGBlock * getBlock() const
Return the CFGBlock associated with this builder.
Definition: CoreEngine.h:190
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2413
const CXXTempObjectRegion * getCXXStaticTempObjectRegion(const Expr *Ex)
Create a CXXTempObjectRegion for temporaries which are lifetime-extended by static references...
Definition: MemRegion.cpp:939
Decl * getCalleeDecl()
Definition: Expr.cpp:1185
SwitchStmt - This represents a 'switch' stmt.
Definition: Stmt.h:957
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:831
const Decl * getDecl() const
Definition: ProgramPoint.h:533
Expr * getRHS() const
Definition: Expr.h:3596
void runCheckersForEndAnalysis(ExplodedGraph &G, BugReporter &BR, ExprEngine &Eng)
Run checkers for end of analysis.
FunctionDecl * getOperatorNew() const
Definition: ExprCXX.h:1889
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:5818
Expr * getFalseExpr() const
Definition: Expr.h:3332
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2063
ExplodedNode * generateSink(ProgramStateRef State, ExplodedNode *Pred, const ProgramPointTag *Tag=nullptr)
Definition: CoreEngine.h:330
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition: Expr.h:3128
Represents a C++ base or member initializer.
Definition: DeclCXX.h:1922
void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Transfer function logic for ObjCAtSynchronizedStmts.
bool isUnknown() const
Definition: SVals.h:117
void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred, ExplodedNodeSet &Dst)
EQClasses_iterator EQClasses_end()
Definition: BugReporter.h:444
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2319
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1528
Represents a base class of a C++ class.
Definition: DeclCXX.h:159
bool isAnyMemberInitializer() const
Definition: DeclCXX.h:2010
SourceManager & getSourceManager()
Definition: ASTContext.h:561
void addAbortedBlock(const ExplodedNode *node, const CFGBlock *block)
Inform the CoreEngine that a basic block was aborted because it could not be completely analyzed...
Definition: CoreEngine.h:147
const StackFrameContext * getStackFrame() const
outputs_range outputs()
Definition: Stmt.h:1544
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1037
Expr * getBase() const
Definition: Expr.h:2405
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:12171
ExplodedNode * generateNode(const ProgramPoint &PP, ProgramStateRef State, ExplodedNode *Pred)
Generates a node in the ExplodedGraph.
Definition: CoreEngine.h:263
void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitBlockExpr - Transfer function logic for BlockExprs.
REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedTemporariesSet, llvm::ImmutableSet< CXXBindTemporaryContext >) static const char *TagProviderName
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2315
const ProgramPointTag * getTag() const
Definition: ProgramPoint.h:176
unsigned NoRetryExhausted
Do not re-analyze paths leading to exhausted nodes with a different strategy.
ProgramStateRef runCheckersForRegionChanges(ProgramStateRef state, const InvalidatedSymbols *invalidated, ArrayRef< const MemRegion * > ExplicitRegions, ArrayRef< const MemRegion * > Regions, const CallEvent *Call)
Run checkers for region changes.
Represents a C++ struct/union/class.
Definition: DeclCXX.h:263
reverse_body_iterator body_rbegin()
Definition: Stmt.h:608
Opcode getOpcode() const
Definition: Expr.h:2940
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:3547
CFGImplicitDtor - Represents C++ object destructor implicitly generated by compiler on various occasi...
Definition: CFG.h:171
Kind getKind() const
Definition: CFG.h:107
Optional< SVal > getConstantVal(const Expr *E)
Returns the value of E, if it can be determined in a non-path-sensitive manner.
pred_iterator pred_begin()
ExplodedNode * generateNode(ProgramStateRef State, bool branch, ExplodedNode *Pred)
Definition: CoreEngine.cpp:672
CFGElement - Represents a top-level expression in a basic block.
Definition: CFG.h:53
This class is used for builtin types like 'int'.
Definition: Type.h:2039
ProgramStateRef processAssume(ProgramStateRef state, SVal cond, bool assumption) override
evalAssume - Callback function invoked by the ConstraintManager when making assumptions about state v...
Definition: ExprEngine.cpp:261
CFGMemberDtor - Represents C++ object destructor implicitly generated for member object in destructor...
Definition: CFG.h:261
bool isArrayType() const
Definition: Type.h:5521
Expr * getRHS() const
Definition: Expr.h:2945
ExplodedNode * generateNode(const Stmt *S, ExplodedNode *Pred, ProgramStateRef St, const ProgramPointTag *tag=nullptr, ProgramPoint::Kind K=ProgramPoint::PostStmtKind)
Definition: CoreEngine.h:378
void processEndWorklist(bool hasWorkRemaining) override
Called by CoreEngine when the analysis worklist has terminated.
Definition: ExprEngine.cpp:285
void runCheckersForBeginFunction(ExplodedNodeSet &Dst, const BlockEdge &L, ExplodedNode *Pred, ExprEngine &Eng)
Run checkers on begining of function.
void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Transfer function logic for DeclRefExprs and BlockDeclRefExprs.
const LangOptions & getLangOpts() const
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:932
static bool shouldRemoveDeadBindings(AnalysisManager &AMgr, const CFGStmt S, const ExplodedNode *Pred, const LocationContext *LC)
Definition: ExprEngine.cpp:316
CFGInitializer - Represents C++ base or member initializer from constructor's initialization list...
Definition: CFG.h:133
const Expr * getSubExpr() const
Definition: ExprCXX.h:1143
void VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitGCCAsmStmt - Transfer function logic for inline asm.
bool mayInlineCXXAllocator()
Returns whether or not allocator call may be considered for inlining.
void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitMemberExpr - Transfer function for member expressions.
AnalysisPurgeMode AnalysisPurgeOpt
NamedDecl - This represents a decl with a name.
Definition: Decl.h:213
void ViewGraph(bool trim=false)
Visualize the ExplodedGraph created by executing the simulation.
ConstraintManager & getConstraintManager()
Definition: ExprEngine.h:309
void VisitBinaryOperator(const BinaryOperator *B, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitBinaryOperator - Transfer function logic for binary operators.
Definition: ExprEngineC.cpp:22
const CXXBaseSpecifier * getBaseSpecifier() const
Definition: CFG.h:247
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:665
bool isFeasible(bool branch)
Definition: CoreEngine.h:442
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition: SVals.h:75
static SVal RecoverCastedSymbol(ProgramStateManager &StateMgr, ProgramStateRef state, const Stmt *Condition, const LocationContext *LCtx, ASTContext &Ctx)
RecoverCastedSymbol - A helper function for ProcessBranch that is used to try to recover some path-se...
void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Create a C++ temporary object for an rvalue.
const MemRegion * getRegion() const
Get the underlining region.
Definition: SVals.h:501
bool shouldInlineLambdas()
Returns true if lambdas should be inlined.
This class handles loading and caching of source files into memory.
CFGTemporaryDtor - Represents C++ object destructor implicitly generated at the end of full expressio...
Definition: CFG.h:280
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
Defines enum values for all the target-independent builtin functions.
Optional< T > getAs() const
Convert to the specified CFGElement type, returning None if this CFGElement is not of the desired typ...
Definition: CFG.h:98
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2295
ProgramStateRef processRegionChanges(ProgramStateRef state, const InvalidatedSymbols *invalidated, ArrayRef< const MemRegion * > ExplicitRegions, ArrayRef< const MemRegion * > Regions, const CallEvent *Call) override
processRegionChanges - Called by ProgramStateManager whenever a change is made to the store...
Definition: ExprEngine.cpp:271