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