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