clang  9.0.0svn
ExprEngine.cpp
Go to the documentation of this file.
1 //===- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines a meta-engine for path-sensitive dataflow analysis that
10 // is built on GREngine, but provides the boilerplate to execute transfer
11 // functions and build the ExplodedGraph at the expression level.
12 //
13 //===----------------------------------------------------------------------===//
14 
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclBase.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ParentMap.h"
27 #include "clang/AST/Stmt.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/AST/StmtObjC.h"
30 #include "clang/AST/Type.h"
32 #include "clang/Analysis/CFG.h"
37 #include "clang/Basic/LLVM.h"
42 #include "clang/Basic/Specifiers.h"
63 #include "llvm/ADT/APSInt.h"
64 #include "llvm/ADT/DenseMap.h"
65 #include "llvm/ADT/ImmutableMap.h"
66 #include "llvm/ADT/ImmutableSet.h"
67 #include "llvm/ADT/Optional.h"
68 #include "llvm/ADT/SmallVector.h"
69 #include "llvm/ADT/Statistic.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/Compiler.h"
72 #include "llvm/Support/DOTGraphTraits.h"
73 #include "llvm/Support/ErrorHandling.h"
74 #include "llvm/Support/GraphWriter.h"
75 #include "llvm/Support/SaveAndRestore.h"
76 #include "llvm/Support/raw_ostream.h"
77 #include <cassert>
78 #include <cstdint>
79 #include <memory>
80 #include <string>
81 #include <tuple>
82 #include <utility>
83 #include <vector>
84 
85 using namespace clang;
86 using namespace ento;
87 
88 #define DEBUG_TYPE "ExprEngine"
89 
90 STATISTIC(NumRemoveDeadBindings,
91  "The # of times RemoveDeadBindings is called");
92 STATISTIC(NumMaxBlockCountReached,
93  "The # of aborted paths due to reaching the maximum block count in "
94  "a top level function");
95 STATISTIC(NumMaxBlockCountReachedInInlined,
96  "The # of aborted paths due to reaching the maximum block count in "
97  "an inlined function");
98 STATISTIC(NumTimesRetriedWithoutInlining,
99  "The # of times we re-evaluated a call without inlining");
100 
101 //===----------------------------------------------------------------------===//
102 // Internal program state traits.
103 //===----------------------------------------------------------------------===//
104 
105 namespace {
106 
107 // When modeling a C++ constructor, for a variety of reasons we need to track
108 // the location of the object for the duration of its ConstructionContext.
109 // ObjectsUnderConstruction maps statements within the construction context
110 // to the object's location, so that on every such statement the location
111 // could have been retrieved.
112 
113 /// ConstructedObjectKey is used for being able to find the path-sensitive
114 /// memory region of a freshly constructed object while modeling the AST node
115 /// that syntactically represents the object that is being constructed.
116 /// Semantics of such nodes may sometimes require access to the region that's
117 /// not otherwise present in the program state, or to the very fact that
118 /// the construction context was present and contained references to these
119 /// AST nodes.
120 class ConstructedObjectKey {
121  typedef std::pair<ConstructionContextItem, const LocationContext *>
122  ConstructedObjectKeyImpl;
123 
124  const ConstructedObjectKeyImpl Impl;
125 
126  const void *getAnyASTNodePtr() const {
127  if (const Stmt *S = getItem().getStmtOrNull())
128  return S;
129  else
130  return getItem().getCXXCtorInitializer();
131  }
132 
133 public:
134  explicit ConstructedObjectKey(const ConstructionContextItem &Item,
135  const LocationContext *LC)
136  : Impl(Item, LC) {}
137 
138  const ConstructionContextItem &getItem() const { return Impl.first; }
139  const LocationContext *getLocationContext() const { return Impl.second; }
140 
141  ASTContext &getASTContext() const {
142  return getLocationContext()->getDecl()->getASTContext();
143  }
144 
145  void printJson(llvm::raw_ostream &Out, PrinterHelper *Helper,
146  PrintingPolicy &PP) const {
147  const Stmt *S = getItem().getStmtOrNull();
148  const CXXCtorInitializer *I = nullptr;
149  if (!S)
150  I = getItem().getCXXCtorInitializer();
151 
152  if (S)
153  Out << "\"stmt_id\": " << S->getID(getASTContext());
154  else
155  Out << "\"init_id\": " << I->getID(getASTContext());
156 
157  // Kind
158  Out << ", \"kind\": \"" << getItem().getKindAsString()
159  << "\", \"argument_index\": ";
160 
162  Out << getItem().getIndex();
163  else
164  Out << "null";
165 
166  // Pretty-print
167  Out << ", \"pretty\": ";
168 
169  if (S) {
170  S->printJson(Out, Helper, PP, /*AddQuotes=*/true);
171  } else {
172  Out << '\"' << I->getAnyMember()->getNameAsString() << '\"';
173  }
174  }
175 
176  void Profile(llvm::FoldingSetNodeID &ID) const {
177  ID.Add(Impl.first);
178  ID.AddPointer(Impl.second);
179  }
180 
181  bool operator==(const ConstructedObjectKey &RHS) const {
182  return Impl == RHS.Impl;
183  }
184 
185  bool operator<(const ConstructedObjectKey &RHS) const {
186  return Impl < RHS.Impl;
187  }
188 };
189 } // namespace
190 
191 typedef llvm::ImmutableMap<ConstructedObjectKey, SVal>
193 REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction,
195 
196 //===----------------------------------------------------------------------===//
197 // Engine construction and deletion.
198 //===----------------------------------------------------------------------===//
199 
200 static const char* TagProviderName = "ExprEngine";
201 
203  AnalysisManager &mgr,
204  SetOfConstDecls *VisitedCalleesIn,
206  InliningModes HowToInlineIn)
207  : CTU(CTU), AMgr(mgr),
208  AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
209  Engine(*this, FS, mgr.getAnalyzerOptions()), G(Engine.getGraph()),
210  StateMgr(getContext(), mgr.getStoreManagerCreator(),
211  mgr.getConstraintManagerCreator(), G.getAllocator(),
212  this),
213  SymMgr(StateMgr.getSymbolManager()),
214  MRMgr(StateMgr.getRegionManager()),
215  svalBuilder(StateMgr.getSValBuilder()),
216  ObjCNoRet(mgr.getASTContext()),
217  BR(mgr, *this),
218  VisitedCallees(VisitedCalleesIn),
219  HowToInline(HowToInlineIn)
220  {
221  unsigned TrimInterval = mgr.options.GraphTrimInterval;
222  if (TrimInterval != 0) {
223  // Enable eager node reclamation when constructing the ExplodedGraph.
224  G.enableNodeReclamation(TrimInterval);
225  }
226 }
227 
229  BR.FlushReports();
230 }
231 
232 //===----------------------------------------------------------------------===//
233 // Utility methods.
234 //===----------------------------------------------------------------------===//
235 
237  ProgramStateRef state = StateMgr.getInitialState(InitLoc);
238  const Decl *D = InitLoc->getDecl();
239 
240  // Preconditions.
241  // FIXME: It would be nice if we had a more general mechanism to add
242  // such preconditions. Some day.
243  do {
244  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
245  // Precondition: the first argument of 'main' is an integer guaranteed
246  // to be > 0.
247  const IdentifierInfo *II = FD->getIdentifier();
248  if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
249  break;
250 
251  const ParmVarDecl *PD = FD->getParamDecl(0);
252  QualType T = PD->getType();
253  const auto *BT = dyn_cast<BuiltinType>(T);
254  if (!BT || !BT->isInteger())
255  break;
256 
257  const MemRegion *R = state->getRegion(PD, InitLoc);
258  if (!R)
259  break;
260 
261  SVal V = state->getSVal(loc::MemRegionVal(R));
262  SVal Constraint_untested = evalBinOp(state, BO_GT, V,
263  svalBuilder.makeZeroVal(T),
264  svalBuilder.getConditionType());
265 
266  Optional<DefinedOrUnknownSVal> Constraint =
267  Constraint_untested.getAs<DefinedOrUnknownSVal>();
268 
269  if (!Constraint)
270  break;
271 
272  if (ProgramStateRef newState = state->assume(*Constraint, true))
273  state = newState;
274  }
275  break;
276  }
277  while (false);
278 
279  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
280  // Precondition: 'self' is always non-null upon entry to an Objective-C
281  // method.
282  const ImplicitParamDecl *SelfD = MD->getSelfDecl();
283  const MemRegion *R = state->getRegion(SelfD, InitLoc);
284  SVal V = state->getSVal(loc::MemRegionVal(R));
285 
286  if (Optional<Loc> LV = V.getAs<Loc>()) {
287  // Assume that the pointer value in 'self' is non-null.
288  state = state->assume(*LV, true);
289  assert(state && "'self' cannot be null");
290  }
291  }
292 
293  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
294  if (!MD->isStatic()) {
295  // Precondition: 'this' is always non-null upon entry to the
296  // top-level function. This is our starting assumption for
297  // analyzing an "open" program.
298  const StackFrameContext *SFC = InitLoc->getStackFrame();
299  if (SFC->getParent() == nullptr) {
300  loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
301  SVal V = state->getSVal(L);
302  if (Optional<Loc> LV = V.getAs<Loc>()) {
303  state = state->assume(*LV, true);
304  assert(state && "'this' cannot be null");
305  }
306  }
307  }
308  }
309 
310  return state;
311 }
312 
313 ProgramStateRef ExprEngine::createTemporaryRegionIfNeeded(
315  const Expr *InitWithAdjustments, const Expr *Result,
316  const SubRegion **OutRegionWithAdjustments) {
317  // FIXME: This function is a hack that works around the quirky AST
318  // we're often having with respect to C++ temporaries. If only we modelled
319  // the actual execution order of statements properly in the CFG,
320  // all the hassle with adjustments would not be necessary,
321  // and perhaps the whole function would be removed.
322  SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, LC);
323  if (!Result) {
324  // If we don't have an explicit result expression, we're in "if needed"
325  // mode. Only create a region if the current value is a NonLoc.
326  if (!InitValWithAdjustments.getAs<NonLoc>()) {
327  if (OutRegionWithAdjustments)
328  *OutRegionWithAdjustments = nullptr;
329  return State;
330  }
331  Result = InitWithAdjustments;
332  } else {
333  // We need to create a region no matter what. For sanity, make sure we don't
334  // try to stuff a Loc into a non-pointer temporary region.
335  assert(!InitValWithAdjustments.getAs<Loc>() ||
336  Loc::isLocType(Result->getType()) ||
337  Result->getType()->isMemberPointerType());
338  }
339 
340  ProgramStateManager &StateMgr = State->getStateManager();
341  MemRegionManager &MRMgr = StateMgr.getRegionManager();
342  StoreManager &StoreMgr = StateMgr.getStoreManager();
343 
344  // MaterializeTemporaryExpr may appear out of place, after a few field and
345  // base-class accesses have been made to the object, even though semantically
346  // it is the whole object that gets materialized and lifetime-extended.
347  //
348  // For example:
349  //
350  // `-MaterializeTemporaryExpr
351  // `-MemberExpr
352  // `-CXXTemporaryObjectExpr
353  //
354  // instead of the more natural
355  //
356  // `-MemberExpr
357  // `-MaterializeTemporaryExpr
358  // `-CXXTemporaryObjectExpr
359  //
360  // Use the usual methods for obtaining the expression of the base object,
361  // and record the adjustments that we need to make to obtain the sub-object
362  // that the whole expression 'Ex' refers to. This trick is usual,
363  // in the sense that CodeGen takes a similar route.
364 
367 
368  const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments(
369  CommaLHSs, Adjustments);
370 
371  // Take the region for Init, i.e. for the whole object. If we do not remember
372  // the region in which the object originally was constructed, come up with
373  // a new temporary region out of thin air and copy the contents of the object
374  // (which are currently present in the Environment, because Init is an rvalue)
375  // into that region. This is not correct, but it is better than nothing.
376  const TypedValueRegion *TR = nullptr;
377  if (const auto *MT = dyn_cast<MaterializeTemporaryExpr>(Result)) {
378  if (Optional<SVal> V = getObjectUnderConstruction(State, MT, LC)) {
379  State = finishObjectConstruction(State, MT, LC);
380  State = State->BindExpr(Result, LC, *V);
381  return State;
382  } else {
383  StorageDuration SD = MT->getStorageDuration();
384  // If this object is bound to a reference with static storage duration, we
385  // put it in a different region to prevent "address leakage" warnings.
386  if (SD == SD_Static || SD == SD_Thread) {
387  TR = MRMgr.getCXXStaticTempObjectRegion(Init);
388  } else {
389  TR = MRMgr.getCXXTempObjectRegion(Init, LC);
390  }
391  }
392  } else {
393  TR = MRMgr.getCXXTempObjectRegion(Init, LC);
394  }
395 
396  SVal Reg = loc::MemRegionVal(TR);
397  SVal BaseReg = Reg;
398 
399  // Make the necessary adjustments to obtain the sub-object.
400  for (auto I = Adjustments.rbegin(), E = Adjustments.rend(); I != E; ++I) {
401  const SubobjectAdjustment &Adj = *I;
402  switch (Adj.Kind) {
404  Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath);
405  break;
407  Reg = StoreMgr.getLValueField(Adj.Field, Reg);
408  break;
410  // FIXME: Unimplemented.
411  State = State->invalidateRegions(Reg, InitWithAdjustments,
412  currBldrCtx->blockCount(), LC, true,
413  nullptr, nullptr, nullptr);
414  return State;
415  }
416  }
417 
418  // What remains is to copy the value of the object to the new region.
419  // FIXME: In other words, what we should always do is copy value of the
420  // Init expression (which corresponds to the bigger object) to the whole
421  // temporary region TR. However, this value is often no longer present
422  // in the Environment. If it has disappeared, we instead invalidate TR.
423  // Still, what we can do is assign the value of expression Ex (which
424  // corresponds to the sub-object) to the TR's sub-region Reg. At least,
425  // values inside Reg would be correct.
426  SVal InitVal = State->getSVal(Init, LC);
427  if (InitVal.isUnknown()) {
428  InitVal = getSValBuilder().conjureSymbolVal(Result, LC, Init->getType(),
429  currBldrCtx->blockCount());
430  State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
431 
432  // Then we'd need to take the value that certainly exists and bind it
433  // over.
434  if (InitValWithAdjustments.isUnknown()) {
435  // Try to recover some path sensitivity in case we couldn't
436  // compute the value.
437  InitValWithAdjustments = getSValBuilder().conjureSymbolVal(
438  Result, LC, InitWithAdjustments->getType(),
439  currBldrCtx->blockCount());
440  }
441  State =
442  State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false);
443  } else {
444  State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
445  }
446 
447  // The result expression would now point to the correct sub-region of the
448  // newly created temporary region. Do this last in order to getSVal of Init
449  // correctly in case (Result == Init).
450  if (Result->isGLValue()) {
451  State = State->BindExpr(Result, LC, Reg);
452  } else {
453  State = State->BindExpr(Result, LC, InitValWithAdjustments);
454  }
455 
456  // Notify checkers once for two bindLoc()s.
457  State = processRegionChange(State, TR, LC);
458 
459  if (OutRegionWithAdjustments)
460  *OutRegionWithAdjustments = cast<SubRegion>(Reg.getAsRegion());
461  return State;
462 }
463 
465 ExprEngine::addObjectUnderConstruction(ProgramStateRef State,
466  const ConstructionContextItem &Item,
467  const LocationContext *LC, SVal V) {
468  ConstructedObjectKey Key(Item, LC->getStackFrame());
469  // FIXME: Currently the state might already contain the marker due to
470  // incorrect handling of temporaries bound to default parameters.
471  assert(!State->get<ObjectsUnderConstruction>(Key) ||
472  Key.getItem().getKind() ==
474  return State->set<ObjectsUnderConstruction>(Key, V);
475 }
476 
479  const ConstructionContextItem &Item,
480  const LocationContext *LC) {
481  ConstructedObjectKey Key(Item, LC->getStackFrame());
482  return Optional<SVal>::create(State->get<ObjectsUnderConstruction>(Key));
483 }
484 
486 ExprEngine::finishObjectConstruction(ProgramStateRef State,
487  const ConstructionContextItem &Item,
488  const LocationContext *LC) {
489  ConstructedObjectKey Key(Item, LC->getStackFrame());
490  assert(State->contains<ObjectsUnderConstruction>(Key));
491  return State->remove<ObjectsUnderConstruction>(Key);
492 }
493 
494 ProgramStateRef ExprEngine::elideDestructor(ProgramStateRef State,
495  const CXXBindTemporaryExpr *BTE,
496  const LocationContext *LC) {
497  ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
498  // FIXME: Currently the state might already contain the marker due to
499  // incorrect handling of temporaries bound to default parameters.
500  return State->set<ObjectsUnderConstruction>(Key, UnknownVal());
501 }
502 
504 ExprEngine::cleanupElidedDestructor(ProgramStateRef State,
505  const CXXBindTemporaryExpr *BTE,
506  const LocationContext *LC) {
507  ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
508  assert(State->contains<ObjectsUnderConstruction>(Key));
509  return State->remove<ObjectsUnderConstruction>(Key);
510 }
511 
512 bool ExprEngine::isDestructorElided(ProgramStateRef State,
513  const CXXBindTemporaryExpr *BTE,
514  const LocationContext *LC) {
515  ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
516  return State->contains<ObjectsUnderConstruction>(Key);
517 }
518 
519 bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State,
520  const LocationContext *FromLC,
521  const LocationContext *ToLC) {
522  const LocationContext *LC = FromLC;
523  while (LC != ToLC) {
524  assert(LC && "ToLC must be a parent of FromLC!");
525  for (auto I : State->get<ObjectsUnderConstruction>())
526  if (I.first.getLocationContext() == LC)
527  return false;
528 
529  LC = LC->getParent();
530  }
531  return true;
532 }
533 
534 
535 //===----------------------------------------------------------------------===//
536 // Top-level transfer function logic (Dispatcher).
537 //===----------------------------------------------------------------------===//
538 
539 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
540 /// logic for handling assumptions on symbolic values.
542  SVal cond, bool assumption) {
543  return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
544 }
545 
548  const InvalidatedSymbols *invalidated,
549  ArrayRef<const MemRegion *> Explicits,
551  const LocationContext *LCtx,
552  const CallEvent *Call) {
553  return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
554  Explicits, Regions,
555  LCtx, Call);
556 }
557 
558 static void
560  const char *NL, const LocationContext *LCtx,
561  unsigned int Space = 0, bool IsDot = false) {
562  PrintingPolicy PP =
564 
565  ++Space;
566  bool HasItem = false;
567 
568  // Store the last key.
569  const ConstructedObjectKey *LastKey = nullptr;
570  for (const auto &I : State->get<ObjectsUnderConstruction>()) {
571  const ConstructedObjectKey &Key = I.first;
572  if (Key.getLocationContext() != LCtx)
573  continue;
574 
575  if (!HasItem) {
576  Out << "[" << NL;
577  HasItem = true;
578  }
579 
580  LastKey = &Key;
581  }
582 
583  for (const auto &I : State->get<ObjectsUnderConstruction>()) {
584  const ConstructedObjectKey &Key = I.first;
585  SVal Value = I.second;
586  if (Key.getLocationContext() != LCtx)
587  continue;
588 
589  Indent(Out, Space, IsDot) << "{ ";
590  Key.printJson(Out, nullptr, PP);
591  Out << ", \"value\": \"" << Value << "\" }";
592 
593  if (&Key != LastKey)
594  Out << ',';
595  Out << NL;
596  }
597 
598  if (HasItem)
599  Indent(Out, --Space, IsDot) << ']'; // End of "location_context".
600  else {
601  Out << "null ";
602  }
603 }
604 
605 void ExprEngine::printJson(raw_ostream &Out, ProgramStateRef State,
606  const LocationContext *LCtx, const char *NL,
607  unsigned int Space, bool IsDot) const {
608  Indent(Out, Space, IsDot) << "\"constructing_objects\": ";
609 
610  if (LCtx && !State->get<ObjectsUnderConstruction>().isEmpty()) {
611  ++Space;
612  Out << '[' << NL;
613  LCtx->printJson(Out, NL, Space, IsDot, [&](const LocationContext *LC) {
614  printObjectsUnderConstructionJson(Out, State, NL, LC, Space, IsDot);
615  });
616 
617  --Space;
618  Indent(Out, Space, IsDot) << "]," << NL; // End of "constructing_objects".
619  } else {
620  Out << "null," << NL;
621  }
622 
623  getCheckerManager().runCheckersForPrintStateJson(Out, State, NL, Space,
624  IsDot);
625 }
626 
629 }
630 
632  unsigned StmtIdx, NodeBuilderContext *Ctx) {
634  currStmtIdx = StmtIdx;
635  currBldrCtx = Ctx;
636 
637  switch (E.getKind()) {
641  ProcessStmt(E.castAs<CFGStmt>().getStmt(), Pred);
642  return;
645  return;
648  Pred);
649  return;
656  return;
659  return;
663  return;
664  }
665 }
666 
667 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
668  const Stmt *S,
669  const ExplodedNode *Pred,
670  const LocationContext *LC) {
671  // Are we never purging state values?
672  if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
673  return false;
674 
675  // Is this the beginning of a basic block?
676  if (Pred->getLocation().getAs<BlockEntrance>())
677  return true;
678 
679  // Is this on a non-expression?
680  if (!isa<Expr>(S))
681  return true;
682 
683  // Run before processing a call.
684  if (CallEvent::isCallStmt(S))
685  return true;
686 
687  // Is this an expression that is consumed by another expression? If so,
688  // postpone cleaning out the state.
690  return !PM.isConsumedExpr(cast<Expr>(S));
691 }
692 
694  const Stmt *ReferenceStmt,
695  const LocationContext *LC,
696  const Stmt *DiagnosticStmt,
697  ProgramPoint::Kind K) {
699  ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
700  && "PostStmt is not generally supported by the SymbolReaper yet");
701  assert(LC && "Must pass the current (or expiring) LocationContext");
702 
703  if (!DiagnosticStmt) {
704  DiagnosticStmt = ReferenceStmt;
705  assert(DiagnosticStmt && "Required for clearing a LocationContext");
706  }
707 
708  NumRemoveDeadBindings++;
709  ProgramStateRef CleanedState = Pred->getState();
710 
711  // LC is the location context being destroyed, but SymbolReaper wants a
712  // location context that is still live. (If this is the top-level stack
713  // frame, this will be null.)
714  if (!ReferenceStmt) {
716  "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
717  LC = LC->getParent();
718  }
719 
720  const StackFrameContext *SFC = LC ? LC->getStackFrame() : nullptr;
721  SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
722 
723  for (auto I : CleanedState->get<ObjectsUnderConstruction>()) {
724  if (SymbolRef Sym = I.second.getAsSymbol())
725  SymReaper.markLive(Sym);
726  if (const MemRegion *MR = I.second.getAsRegion())
727  SymReaper.markLive(MR);
728  }
729 
730  getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
731 
732  // Create a state in which dead bindings are removed from the environment
733  // and the store. TODO: The function should just return new env and store,
734  // not a new state.
735  CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
736 
737  // Process any special transfer function for dead symbols.
738  // A tag to track convenience transitions, which can be removed at cleanup.
739  static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
740  // Call checkers with the non-cleaned state so that they could query the
741  // values of the soon to be dead symbols.
742  ExplodedNodeSet CheckedSet;
743  getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
744  DiagnosticStmt, *this, K);
745 
746  // For each node in CheckedSet, generate CleanedNodes that have the
747  // environment, the store, and the constraints cleaned up but have the
748  // user-supplied states as the predecessors.
749  StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
750  for (const auto I : CheckedSet) {
751  ProgramStateRef CheckerState = I->getState();
752 
753  // The constraint manager has not been cleaned up yet, so clean up now.
754  CheckerState =
755  getConstraintManager().removeDeadBindings(CheckerState, SymReaper);
756 
757  assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
758  "Checkers are not allowed to modify the Environment as a part of "
759  "checkDeadSymbols processing.");
760  assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
761  "Checkers are not allowed to modify the Store as a part of "
762  "checkDeadSymbols processing.");
763 
764  // Create a state based on CleanedState with CheckerState GDM and
765  // generate a transition to that state.
766  ProgramStateRef CleanedCheckerSt =
767  StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
768  Bldr.generateNode(DiagnosticStmt, I, CleanedCheckerSt, &cleanupTag, K);
769  }
770 }
771 
772 void ExprEngine::ProcessStmt(const Stmt *currStmt, ExplodedNode *Pred) {
773  // Reclaim any unnecessary nodes in the ExplodedGraph.
775 
776  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
777  currStmt->getBeginLoc(),
778  "Error evaluating statement");
779 
780  // Remove dead bindings and symbols.
781  ExplodedNodeSet CleanedStates;
782  if (shouldRemoveDeadBindings(AMgr, currStmt, Pred,
783  Pred->getLocationContext())) {
784  removeDead(Pred, CleanedStates, currStmt,
785  Pred->getLocationContext());
786  } else
787  CleanedStates.Add(Pred);
788 
789  // Visit the statement.
790  ExplodedNodeSet Dst;
791  for (const auto I : CleanedStates) {
792  ExplodedNodeSet DstI;
793  // Visit the statement.
794  Visit(currStmt, I, DstI);
795  Dst.insert(DstI);
796  }
797 
798  // Enqueue the new nodes onto the work list.
799  Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
800 }
801 
803  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
804  S->getBeginLoc(),
805  "Error evaluating end of the loop");
806  ExplodedNodeSet Dst;
807  Dst.Add(Pred);
808  NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
809  ProgramStateRef NewState = Pred->getState();
810 
811  if(AMgr.options.ShouldUnrollLoops)
812  NewState = processLoopEnd(S, NewState);
813 
814  LoopExit PP(S, Pred->getLocationContext());
815  Bldr.generateNode(PP, NewState, Pred);
816  // Enqueue the new nodes onto the work list.
817  Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
818 }
819 
821  ExplodedNode *Pred) {
822  const CXXCtorInitializer *BMI = CFGInit.getInitializer();
823  const Expr *Init = BMI->getInit()->IgnoreImplicit();
824  const LocationContext *LC = Pred->getLocationContext();
825 
826  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
827  BMI->getSourceLocation(),
828  "Error evaluating initializer");
829 
830  // We don't clean up dead bindings here.
831  const auto *stackFrame = cast<StackFrameContext>(Pred->getLocationContext());
832  const auto *decl = cast<CXXConstructorDecl>(stackFrame->getDecl());
833 
834  ProgramStateRef State = Pred->getState();
835  SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
836 
837  ExplodedNodeSet Tmp;
838  SVal FieldLoc;
839 
840  // Evaluate the initializer, if necessary
841  if (BMI->isAnyMemberInitializer()) {
842  // Constructors build the object directly in the field,
843  // but non-objects must be copied in from the initializer.
844  if (getObjectUnderConstruction(State, BMI, LC)) {
845  // The field was directly constructed, so there is no need to bind.
846  // But we still need to stop tracking the object under construction.
847  State = finishObjectConstruction(State, BMI, LC);
848  NodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
849  PostStore PS(Init, LC, /*Loc*/ nullptr, /*tag*/ nullptr);
850  Bldr.generateNode(PS, State, Pred);
851  } else {
852  const ValueDecl *Field;
853  if (BMI->isIndirectMemberInitializer()) {
854  Field = BMI->getIndirectMember();
855  FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
856  } else {
857  Field = BMI->getMember();
858  FieldLoc = State->getLValue(BMI->getMember(), thisVal);
859  }
860 
861  SVal InitVal;
862  if (Init->getType()->isArrayType()) {
863  // Handle arrays of trivial type. We can represent this with a
864  // primitive load/copy from the base array region.
865  const ArraySubscriptExpr *ASE;
866  while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
867  Init = ASE->getBase()->IgnoreImplicit();
868 
869  SVal LValue = State->getSVal(Init, stackFrame);
870  if (!Field->getType()->isReferenceType())
871  if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
872  InitVal = State->getSVal(*LValueLoc);
873 
874  // If we fail to get the value for some reason, use a symbolic value.
875  if (InitVal.isUnknownOrUndef()) {
876  SValBuilder &SVB = getSValBuilder();
877  InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
878  Field->getType(),
879  currBldrCtx->blockCount());
880  }
881  } else {
882  InitVal = State->getSVal(BMI->getInit(), stackFrame);
883  }
884 
885  PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
886  evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
887  }
888  } else {
889  assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
890  Tmp.insert(Pred);
891  // We already did all the work when visiting the CXXConstructExpr.
892  }
893 
894  // Construct PostInitializer nodes whether the state changed or not,
895  // so that the diagnostics don't get confused.
896  PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
897  ExplodedNodeSet Dst;
898  NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
899  for (const auto I : Tmp) {
900  ProgramStateRef State = I->getState();
901  Bldr.generateNode(PP, State, I);
902  }
903 
904  // Enqueue the new nodes onto the work list.
905  Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
906 }
907 
909  ExplodedNode *Pred) {
910  ExplodedNodeSet Dst;
911  switch (D.getKind()) {
914  break;
916  ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
917  break;
919  ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
920  break;
923  break;
925  ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
926  break;
927  default:
928  llvm_unreachable("Unexpected dtor kind.");
929  }
930 
931  // Enqueue the new nodes onto the work list.
932  Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
933 }
934 
936  ExplodedNode *Pred) {
937  ExplodedNodeSet Dst;
939  AnalyzerOptions &Opts = AMgr.options;
940  // TODO: We're not evaluating allocators for all cases just yet as
941  // we're not handling the return value correctly, which causes false
942  // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
943  if (Opts.MayInlineCXXAllocator)
944  VisitCXXNewAllocatorCall(NE, Pred, Dst);
945  else {
946  NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
947  const LocationContext *LCtx = Pred->getLocationContext();
948  PostImplicitCall PP(NE->getOperatorNew(), NE->getBeginLoc(), LCtx);
949  Bldr.generateNode(PP, Pred->getState(), Pred);
950  }
951  Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
952 }
953 
955  ExplodedNode *Pred,
956  ExplodedNodeSet &Dst) {
957  const VarDecl *varDecl = Dtor.getVarDecl();
958  QualType varType = varDecl->getType();
959 
960  ProgramStateRef state = Pred->getState();
961  SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
962  const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
963 
964  if (varType->isReferenceType()) {
965  const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion();
966  if (!ValueRegion) {
967  // FIXME: This should not happen. The language guarantees a presence
968  // of a valid initializer here, so the reference shall not be undefined.
969  // It seems that we're calling destructors over variables that
970  // were not initialized yet.
971  return;
972  }
973  Region = ValueRegion->getBaseRegion();
974  varType = cast<TypedValueRegion>(Region)->getValueType();
975  }
976 
977  // FIXME: We need to run the same destructor on every element of the array.
978  // This workaround will just run the first destructor (which will still
979  // invalidate the entire array).
980  EvalCallOptions CallOpts;
981  Region = makeZeroElementRegion(state, loc::MemRegionVal(Region), varType,
982  CallOpts.IsArrayCtorOrDtor).getAsRegion();
983 
984  VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
985  Pred, Dst, CallOpts);
986 }
987 
989  ExplodedNode *Pred,
990  ExplodedNodeSet &Dst) {
991  ProgramStateRef State = Pred->getState();
992  const LocationContext *LCtx = Pred->getLocationContext();
993  const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
994  const Stmt *Arg = DE->getArgument();
995  QualType DTy = DE->getDestroyedType();
996  SVal ArgVal = State->getSVal(Arg, LCtx);
997 
998  // If the argument to delete is known to be a null value,
999  // don't run destructor.
1000  if (State->isNull(ArgVal).isConstrainedTrue()) {
1001  QualType BTy = getContext().getBaseElementType(DTy);
1002  const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
1003  const CXXDestructorDecl *Dtor = RD->getDestructor();
1004 
1005  PostImplicitCall PP(Dtor, DE->getBeginLoc(), LCtx);
1006  NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1007  Bldr.generateNode(PP, Pred->getState(), Pred);
1008  return;
1009  }
1010 
1011  EvalCallOptions CallOpts;
1012  const MemRegion *ArgR = ArgVal.getAsRegion();
1013  if (DE->isArrayForm()) {
1014  // FIXME: We need to run the same destructor on every element of the array.
1015  // This workaround will just run the first destructor (which will still
1016  // invalidate the entire array).
1017  CallOpts.IsArrayCtorOrDtor = true;
1018  // Yes, it may even be a multi-dimensional array.
1019  while (const auto *AT = getContext().getAsArrayType(DTy))
1020  DTy = AT->getElementType();
1021  if (ArgR)
1022  ArgR = getStoreManager().GetElementZeroRegion(cast<SubRegion>(ArgR), DTy);
1023  }
1024 
1025  VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts);
1026 }
1027 
1029  ExplodedNode *Pred, ExplodedNodeSet &Dst) {
1030  const LocationContext *LCtx = Pred->getLocationContext();
1031 
1032  const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
1033  Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
1034  LCtx->getStackFrame());
1035  SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
1036 
1037  // Create the base object region.
1038  const CXXBaseSpecifier *Base = D.getBaseSpecifier();
1039  QualType BaseTy = Base->getType();
1040  SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
1041  Base->isVirtual());
1042 
1044  CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst, {});
1045 }
1046 
1048  ExplodedNode *Pred, ExplodedNodeSet &Dst) {
1049  const FieldDecl *Member = D.getFieldDecl();
1050  QualType T = Member->getType();
1051  ProgramStateRef State = Pred->getState();
1052  const LocationContext *LCtx = Pred->getLocationContext();
1053 
1054  const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
1055  Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
1056  LCtx->getStackFrame());
1057  SVal FieldVal =
1058  State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
1059 
1060  // FIXME: We need to run the same destructor on every element of the array.
1061  // This workaround will just run the first destructor (which will still
1062  // invalidate the entire array).
1063  EvalCallOptions CallOpts;
1064  FieldVal = makeZeroElementRegion(State, FieldVal, T,
1065  CallOpts.IsArrayCtorOrDtor);
1066 
1068  CurDtor->getBody(), /*IsBase=*/false, Pred, Dst, CallOpts);
1069 }
1070 
1072  ExplodedNode *Pred,
1073  ExplodedNodeSet &Dst) {
1074  const CXXBindTemporaryExpr *BTE = D.getBindTemporaryExpr();
1075  ProgramStateRef State = Pred->getState();
1076  const LocationContext *LC = Pred->getLocationContext();
1077  const MemRegion *MR = nullptr;
1078 
1079  if (Optional<SVal> V =
1081  Pred->getLocationContext())) {
1082  // FIXME: Currently we insert temporary destructors for default parameters,
1083  // but we don't insert the constructors, so the entry in
1084  // ObjectsUnderConstruction may be missing.
1085  State = finishObjectConstruction(State, D.getBindTemporaryExpr(),
1086  Pred->getLocationContext());
1087  MR = V->getAsRegion();
1088  }
1089 
1090  // If copy elision has occurred, and the constructor corresponding to the
1091  // destructor was elided, we need to skip the destructor as well.
1092  if (isDestructorElided(State, BTE, LC)) {
1093  State = cleanupElidedDestructor(State, BTE, LC);
1094  NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1097  Pred->getLocationContext());
1098  Bldr.generateNode(PP, State, Pred);
1099  return;
1100  }
1101 
1102  ExplodedNodeSet CleanDtorState;
1103  StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx);
1104  StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
1105 
1107  // FIXME: Currently CleanDtorState can be empty here due to temporaries being
1108  // bound to default parameters.
1109  assert(CleanDtorState.size() <= 1);
1110  ExplodedNode *CleanPred =
1111  CleanDtorState.empty() ? Pred : *CleanDtorState.begin();
1112 
1113  EvalCallOptions CallOpts;
1114  CallOpts.IsTemporaryCtorOrDtor = true;
1115  if (!MR) {
1117 
1118  // If we have no MR, we still need to unwrap the array to avoid destroying
1119  // the whole array at once. Regardless, we'd eventually need to model array
1120  // destructors properly, element-by-element.
1121  while (const ArrayType *AT = getContext().getAsArrayType(T)) {
1122  T = AT->getElementType();
1123  CallOpts.IsArrayCtorOrDtor = true;
1124  }
1125  } else {
1126  // We'd eventually need to makeZeroElementRegion() trick here,
1127  // but for now we don't have the respective construction contexts,
1128  // so MR would always be null in this case. Do nothing for now.
1129  }
1131  /*IsBase=*/false, CleanPred, Dst, CallOpts);
1132 }
1133 
1135  NodeBuilderContext &BldCtx,
1136  ExplodedNode *Pred,
1137  ExplodedNodeSet &Dst,
1138  const CFGBlock *DstT,
1139  const CFGBlock *DstF) {
1140  BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF);
1141  ProgramStateRef State = Pred->getState();
1142  const LocationContext *LC = Pred->getLocationContext();
1143  if (getObjectUnderConstruction(State, BTE, LC)) {
1144  TempDtorBuilder.markInfeasible(false);
1145  TempDtorBuilder.generateNode(State, true, Pred);
1146  } else {
1147  TempDtorBuilder.markInfeasible(true);
1148  TempDtorBuilder.generateNode(State, false, Pred);
1149  }
1150 }
1151 
1153  ExplodedNodeSet &PreVisit,
1154  ExplodedNodeSet &Dst) {
1155  // This is a fallback solution in case we didn't have a construction
1156  // context when we were constructing the temporary. Otherwise the map should
1157  // have been populated there.
1158  if (!getAnalysisManager().options.ShouldIncludeTemporaryDtorsInCFG) {
1159  // In case we don't have temporary destructors in the CFG, do not mark
1160  // the initialization - we would otherwise never clean it up.
1161  Dst = PreVisit;
1162  return;
1163  }
1164  StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
1165  for (ExplodedNode *Node : PreVisit) {
1166  ProgramStateRef State = Node->getState();
1167  const LocationContext *LC = Node->getLocationContext();
1168  if (!getObjectUnderConstruction(State, BTE, LC)) {
1169  // FIXME: Currently the state might also already contain the marker due to
1170  // incorrect handling of temporaries bound to default parameters; for
1171  // those, we currently skip the CXXBindTemporaryExpr but rely on adding
1172  // temporary destructor nodes.
1173  State = addObjectUnderConstruction(State, BTE, LC, UnknownVal());
1174  }
1175  StmtBldr.generateNode(BTE, Node, State);
1176  }
1177 }
1178 
1180  PointerEscapeKind K) const {
1181  class CollectReachableSymbolsCallback final : public SymbolVisitor {
1182  InvalidatedSymbols Symbols;
1183 
1184  public:
1185  explicit CollectReachableSymbolsCallback(ProgramStateRef) {}
1186 
1187  const InvalidatedSymbols &getSymbols() const { return Symbols; }
1188 
1189  bool VisitSymbol(SymbolRef Sym) override {
1190  Symbols.insert(Sym);
1191  return true;
1192  }
1193  };
1194 
1195  const CollectReachableSymbolsCallback &Scanner =
1196  State->scanReachableSymbols<CollectReachableSymbolsCallback>(V);
1198  State, Scanner.getSymbols(), /*CallEvent*/ nullptr, K, nullptr);
1199 }
1200 
1201 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
1202  ExplodedNodeSet &DstTop) {
1203  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1204  S->getBeginLoc(), "Error evaluating statement");
1205  ExplodedNodeSet Dst;
1206  StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
1207 
1208  assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
1209 
1210  switch (S->getStmtClass()) {
1211  // C++, OpenMP and ARC stuff we don't support yet.
1212  case Expr::ObjCIndirectCopyRestoreExprClass:
1213  case Stmt::CXXDependentScopeMemberExprClass:
1214  case Stmt::CXXInheritedCtorInitExprClass:
1215  case Stmt::CXXTryStmtClass:
1216  case Stmt::CXXTypeidExprClass:
1217  case Stmt::CXXUuidofExprClass:
1218  case Stmt::CXXFoldExprClass:
1219  case Stmt::MSPropertyRefExprClass:
1220  case Stmt::MSPropertySubscriptExprClass:
1221  case Stmt::CXXUnresolvedConstructExprClass:
1222  case Stmt::DependentScopeDeclRefExprClass:
1223  case Stmt::ArrayTypeTraitExprClass:
1224  case Stmt::ExpressionTraitExprClass:
1225  case Stmt::UnresolvedLookupExprClass:
1226  case Stmt::UnresolvedMemberExprClass:
1227  case Stmt::TypoExprClass:
1228  case Stmt::CXXNoexceptExprClass:
1229  case Stmt::PackExpansionExprClass:
1230  case Stmt::SubstNonTypeTemplateParmPackExprClass:
1231  case Stmt::FunctionParmPackExprClass:
1232  case Stmt::CoroutineBodyStmtClass:
1233  case Stmt::CoawaitExprClass:
1234  case Stmt::DependentCoawaitExprClass:
1235  case Stmt::CoreturnStmtClass:
1236  case Stmt::CoyieldExprClass:
1237  case Stmt::SEHTryStmtClass:
1238  case Stmt::SEHExceptStmtClass:
1239  case Stmt::SEHLeaveStmtClass:
1240  case Stmt::SEHFinallyStmtClass:
1241  case Stmt::OMPParallelDirectiveClass:
1242  case Stmt::OMPSimdDirectiveClass:
1243  case Stmt::OMPForDirectiveClass:
1244  case Stmt::OMPForSimdDirectiveClass:
1245  case Stmt::OMPSectionsDirectiveClass:
1246  case Stmt::OMPSectionDirectiveClass:
1247  case Stmt::OMPSingleDirectiveClass:
1248  case Stmt::OMPMasterDirectiveClass:
1249  case Stmt::OMPCriticalDirectiveClass:
1250  case Stmt::OMPParallelForDirectiveClass:
1251  case Stmt::OMPParallelForSimdDirectiveClass:
1252  case Stmt::OMPParallelSectionsDirectiveClass:
1253  case Stmt::OMPTaskDirectiveClass:
1254  case Stmt::OMPTaskyieldDirectiveClass:
1255  case Stmt::OMPBarrierDirectiveClass:
1256  case Stmt::OMPTaskwaitDirectiveClass:
1257  case Stmt::OMPTaskgroupDirectiveClass:
1258  case Stmt::OMPFlushDirectiveClass:
1259  case Stmt::OMPOrderedDirectiveClass:
1260  case Stmt::OMPAtomicDirectiveClass:
1261  case Stmt::OMPTargetDirectiveClass:
1262  case Stmt::OMPTargetDataDirectiveClass:
1263  case Stmt::OMPTargetEnterDataDirectiveClass:
1264  case Stmt::OMPTargetExitDataDirectiveClass:
1265  case Stmt::OMPTargetParallelDirectiveClass:
1266  case Stmt::OMPTargetParallelForDirectiveClass:
1267  case Stmt::OMPTargetUpdateDirectiveClass:
1268  case Stmt::OMPTeamsDirectiveClass:
1269  case Stmt::OMPCancellationPointDirectiveClass:
1270  case Stmt::OMPCancelDirectiveClass:
1271  case Stmt::OMPTaskLoopDirectiveClass:
1272  case Stmt::OMPTaskLoopSimdDirectiveClass:
1273  case Stmt::OMPDistributeDirectiveClass:
1274  case Stmt::OMPDistributeParallelForDirectiveClass:
1275  case Stmt::OMPDistributeParallelForSimdDirectiveClass:
1276  case Stmt::OMPDistributeSimdDirectiveClass:
1277  case Stmt::OMPTargetParallelForSimdDirectiveClass:
1278  case Stmt::OMPTargetSimdDirectiveClass:
1279  case Stmt::OMPTeamsDistributeDirectiveClass:
1280  case Stmt::OMPTeamsDistributeSimdDirectiveClass:
1281  case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
1282  case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
1283  case Stmt::OMPTargetTeamsDirectiveClass:
1284  case Stmt::OMPTargetTeamsDistributeDirectiveClass:
1285  case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
1286  case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
1287  case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
1288  case Stmt::CapturedStmtClass: {
1289  const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1290  Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1291  break;
1292  }
1293 
1294  case Stmt::ParenExprClass:
1295  llvm_unreachable("ParenExprs already handled.");
1296  case Stmt::GenericSelectionExprClass:
1297  llvm_unreachable("GenericSelectionExprs already handled.");
1298  // Cases that should never be evaluated simply because they shouldn't
1299  // appear in the CFG.
1300  case Stmt::BreakStmtClass:
1301  case Stmt::CaseStmtClass:
1302  case Stmt::CompoundStmtClass:
1303  case Stmt::ContinueStmtClass:
1304  case Stmt::CXXForRangeStmtClass:
1305  case Stmt::DefaultStmtClass:
1306  case Stmt::DoStmtClass:
1307  case Stmt::ForStmtClass:
1308  case Stmt::GotoStmtClass:
1309  case Stmt::IfStmtClass:
1310  case Stmt::IndirectGotoStmtClass:
1311  case Stmt::LabelStmtClass:
1312  case Stmt::NoStmtClass:
1313  case Stmt::NullStmtClass:
1314  case Stmt::SwitchStmtClass:
1315  case Stmt::WhileStmtClass:
1316  case Expr::MSDependentExistsStmtClass:
1317  llvm_unreachable("Stmt should not be in analyzer evaluation loop");
1318 
1319  case Stmt::ObjCSubscriptRefExprClass:
1320  case Stmt::ObjCPropertyRefExprClass:
1321  llvm_unreachable("These are handled by PseudoObjectExpr");
1322 
1323  case Stmt::GNUNullExprClass: {
1324  // GNU __null is a pointer-width integer, not an actual pointer.
1325  ProgramStateRef state = Pred->getState();
1326  state = state->BindExpr(S, Pred->getLocationContext(),
1327  svalBuilder.makeIntValWithPtrWidth(0, false));
1328  Bldr.generateNode(S, Pred, state);
1329  break;
1330  }
1331 
1332  case Stmt::ObjCAtSynchronizedStmtClass:
1333  Bldr.takeNodes(Pred);
1334  VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
1335  Bldr.addNodes(Dst);
1336  break;
1337 
1338  case Expr::ConstantExprClass:
1339  case Stmt::ExprWithCleanupsClass:
1340  // Handled due to fully linearised CFG.
1341  break;
1342 
1343  case Stmt::CXXBindTemporaryExprClass: {
1344  Bldr.takeNodes(Pred);
1345  ExplodedNodeSet PreVisit;
1346  getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1347  ExplodedNodeSet Next;
1348  VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
1349  getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
1350  Bldr.addNodes(Dst);
1351  break;
1352  }
1353 
1354  // Cases not handled yet; but will handle some day.
1355  case Stmt::DesignatedInitExprClass:
1356  case Stmt::DesignatedInitUpdateExprClass:
1357  case Stmt::ArrayInitLoopExprClass:
1358  case Stmt::ArrayInitIndexExprClass:
1359  case Stmt::ExtVectorElementExprClass:
1360  case Stmt::ImaginaryLiteralClass:
1361  case Stmt::ObjCAtCatchStmtClass:
1362  case Stmt::ObjCAtFinallyStmtClass:
1363  case Stmt::ObjCAtTryStmtClass:
1364  case Stmt::ObjCAutoreleasePoolStmtClass:
1365  case Stmt::ObjCEncodeExprClass:
1366  case Stmt::ObjCIsaExprClass:
1367  case Stmt::ObjCProtocolExprClass:
1368  case Stmt::ObjCSelectorExprClass:
1369  case Stmt::ParenListExprClass:
1370  case Stmt::ShuffleVectorExprClass:
1371  case Stmt::ConvertVectorExprClass:
1372  case Stmt::VAArgExprClass:
1373  case Stmt::CUDAKernelCallExprClass:
1374  case Stmt::OpaqueValueExprClass:
1375  case Stmt::AsTypeExprClass:
1376  // Fall through.
1377 
1378  // Cases we intentionally don't evaluate, since they don't need
1379  // to be explicitly evaluated.
1380  case Stmt::PredefinedExprClass:
1381  case Stmt::AddrLabelExprClass:
1382  case Stmt::AttributedStmtClass:
1383  case Stmt::IntegerLiteralClass:
1384  case Stmt::FixedPointLiteralClass:
1385  case Stmt::CharacterLiteralClass:
1386  case Stmt::ImplicitValueInitExprClass:
1387  case Stmt::CXXScalarValueInitExprClass:
1388  case Stmt::CXXBoolLiteralExprClass:
1389  case Stmt::ObjCBoolLiteralExprClass:
1390  case Stmt::ObjCAvailabilityCheckExprClass:
1391  case Stmt::FloatingLiteralClass:
1392  case Stmt::NoInitExprClass:
1393  case Stmt::SizeOfPackExprClass:
1394  case Stmt::StringLiteralClass:
1395  case Stmt::SourceLocExprClass:
1396  case Stmt::ObjCStringLiteralClass:
1397  case Stmt::CXXPseudoDestructorExprClass:
1398  case Stmt::SubstNonTypeTemplateParmExprClass:
1399  case Stmt::CXXNullPtrLiteralExprClass:
1400  case Stmt::OMPArraySectionExprClass:
1401  case Stmt::TypeTraitExprClass: {
1402  Bldr.takeNodes(Pred);
1403  ExplodedNodeSet preVisit;
1404  getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1405  getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
1406  Bldr.addNodes(Dst);
1407  break;
1408  }
1409 
1410  case Stmt::CXXDefaultArgExprClass:
1411  case Stmt::CXXDefaultInitExprClass: {
1412  Bldr.takeNodes(Pred);
1413  ExplodedNodeSet PreVisit;
1414  getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1415 
1416  ExplodedNodeSet Tmp;
1417  StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
1418 
1419  const Expr *ArgE;
1420  if (const auto *DefE = dyn_cast<CXXDefaultArgExpr>(S))
1421  ArgE = DefE->getExpr();
1422  else if (const auto *DefE = dyn_cast<CXXDefaultInitExpr>(S))
1423  ArgE = DefE->getExpr();
1424  else
1425  llvm_unreachable("unknown constant wrapper kind");
1426 
1427  bool IsTemporary = false;
1428  if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
1429  ArgE = MTE->GetTemporaryExpr();
1430  IsTemporary = true;
1431  }
1432 
1433  Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
1434  if (!ConstantVal)
1435  ConstantVal = UnknownVal();
1436 
1437  const LocationContext *LCtx = Pred->getLocationContext();
1438  for (const auto I : PreVisit) {
1439  ProgramStateRef State = I->getState();
1440  State = State->BindExpr(S, LCtx, *ConstantVal);
1441  if (IsTemporary)
1442  State = createTemporaryRegionIfNeeded(State, LCtx,
1443  cast<Expr>(S),
1444  cast<Expr>(S));
1445  Bldr2.generateNode(S, I, State);
1446  }
1447 
1448  getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1449  Bldr.addNodes(Dst);
1450  break;
1451  }
1452 
1453  // Cases we evaluate as opaque expressions, conjuring a symbol.
1454  case Stmt::CXXStdInitializerListExprClass:
1455  case Expr::ObjCArrayLiteralClass:
1456  case Expr::ObjCDictionaryLiteralClass:
1457  case Expr::ObjCBoxedExprClass: {
1458  Bldr.takeNodes(Pred);
1459 
1460  ExplodedNodeSet preVisit;
1461  getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1462 
1463  ExplodedNodeSet Tmp;
1464  StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
1465 
1466  const auto *Ex = cast<Expr>(S);
1467  QualType resultType = Ex->getType();
1468 
1469  for (const auto N : preVisit) {
1470  const LocationContext *LCtx = N->getLocationContext();
1471  SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
1472  resultType,
1473  currBldrCtx->blockCount());
1474  ProgramStateRef State = N->getState()->BindExpr(Ex, LCtx, result);
1475 
1476  // Escape pointers passed into the list, unless it's an ObjC boxed
1477  // expression which is not a boxable C structure.
1478  if (!(isa<ObjCBoxedExpr>(Ex) &&
1479  !cast<ObjCBoxedExpr>(Ex)->getSubExpr()
1480  ->getType()->isRecordType()))
1481  for (auto Child : Ex->children()) {
1482  assert(Child);
1483  SVal Val = State->getSVal(Child, LCtx);
1484  State = escapeValue(State, Val, PSK_EscapeOther);
1485  }
1486 
1487  Bldr2.generateNode(S, N, State);
1488  }
1489 
1490  getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1491  Bldr.addNodes(Dst);
1492  break;
1493  }
1494 
1495  case Stmt::ArraySubscriptExprClass:
1496  Bldr.takeNodes(Pred);
1497  VisitArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
1498  Bldr.addNodes(Dst);
1499  break;
1500 
1501  case Stmt::GCCAsmStmtClass:
1502  Bldr.takeNodes(Pred);
1503  VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
1504  Bldr.addNodes(Dst);
1505  break;
1506 
1507  case Stmt::MSAsmStmtClass:
1508  Bldr.takeNodes(Pred);
1509  VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
1510  Bldr.addNodes(Dst);
1511  break;
1512 
1513  case Stmt::BlockExprClass:
1514  Bldr.takeNodes(Pred);
1515  VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
1516  Bldr.addNodes(Dst);
1517  break;
1518 
1519  case Stmt::LambdaExprClass:
1520  if (AMgr.options.ShouldInlineLambdas) {
1521  Bldr.takeNodes(Pred);
1522  VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
1523  Bldr.addNodes(Dst);
1524  } else {
1525  const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1526  Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1527  }
1528  break;
1529 
1530  case Stmt::BinaryOperatorClass: {
1531  const auto *B = cast<BinaryOperator>(S);
1532  if (B->isLogicalOp()) {
1533  Bldr.takeNodes(Pred);
1534  VisitLogicalExpr(B, Pred, Dst);
1535  Bldr.addNodes(Dst);
1536  break;
1537  }
1538  else if (B->getOpcode() == BO_Comma) {
1539  ProgramStateRef state = Pred->getState();
1540  Bldr.generateNode(B, Pred,
1541  state->BindExpr(B, Pred->getLocationContext(),
1542  state->getSVal(B->getRHS(),
1543  Pred->getLocationContext())));
1544  break;
1545  }
1546 
1547  Bldr.takeNodes(Pred);
1548 
1549  if (AMgr.options.ShouldEagerlyAssume &&
1550  (B->isRelationalOp() || B->isEqualityOp())) {
1551  ExplodedNodeSet Tmp;
1552  VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
1553  evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
1554  }
1555  else
1556  VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1557 
1558  Bldr.addNodes(Dst);
1559  break;
1560  }
1561 
1562  case Stmt::CXXOperatorCallExprClass: {
1563  const auto *OCE = cast<CXXOperatorCallExpr>(S);
1564 
1565  // For instance method operators, make sure the 'this' argument has a
1566  // valid region.
1567  const Decl *Callee = OCE->getCalleeDecl();
1568  if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
1569  if (MD->isInstance()) {
1570  ProgramStateRef State = Pred->getState();
1571  const LocationContext *LCtx = Pred->getLocationContext();
1572  ProgramStateRef NewState =
1573  createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
1574  if (NewState != State) {
1575  Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
1577  // Did we cache out?
1578  if (!Pred)
1579  break;
1580  }
1581  }
1582  }
1583  // FALLTHROUGH
1584  LLVM_FALLTHROUGH;
1585  }
1586 
1587  case Stmt::CallExprClass:
1588  case Stmt::CXXMemberCallExprClass:
1589  case Stmt::UserDefinedLiteralClass:
1590  Bldr.takeNodes(Pred);
1591  VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
1592  Bldr.addNodes(Dst);
1593  break;
1594 
1595  case Stmt::CXXCatchStmtClass:
1596  Bldr.takeNodes(Pred);
1597  VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
1598  Bldr.addNodes(Dst);
1599  break;
1600 
1601  case Stmt::CXXTemporaryObjectExprClass:
1602  case Stmt::CXXConstructExprClass:
1603  Bldr.takeNodes(Pred);
1604  VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
1605  Bldr.addNodes(Dst);
1606  break;
1607 
1608  case Stmt::CXXNewExprClass: {
1609  Bldr.takeNodes(Pred);
1610 
1611  ExplodedNodeSet PreVisit;
1612  getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1613 
1614  ExplodedNodeSet PostVisit;
1615  for (const auto i : PreVisit)
1616  VisitCXXNewExpr(cast<CXXNewExpr>(S), i, PostVisit);
1617 
1618  getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1619  Bldr.addNodes(Dst);
1620  break;
1621  }
1622 
1623  case Stmt::CXXDeleteExprClass: {
1624  Bldr.takeNodes(Pred);
1625  ExplodedNodeSet PreVisit;
1626  const auto *CDE = cast<CXXDeleteExpr>(S);
1627  getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1628 
1629  for (const auto i : PreVisit)
1630  VisitCXXDeleteExpr(CDE, i, Dst);
1631 
1632  Bldr.addNodes(Dst);
1633  break;
1634  }
1635  // FIXME: ChooseExpr is really a constant. We need to fix
1636  // the CFG do not model them as explicit control-flow.
1637 
1638  case Stmt::ChooseExprClass: { // __builtin_choose_expr
1639  Bldr.takeNodes(Pred);
1640  const auto *C = cast<ChooseExpr>(S);
1641  VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
1642  Bldr.addNodes(Dst);
1643  break;
1644  }
1645 
1646  case Stmt::CompoundAssignOperatorClass:
1647  Bldr.takeNodes(Pred);
1648  VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1649  Bldr.addNodes(Dst);
1650  break;
1651 
1652  case Stmt::CompoundLiteralExprClass:
1653  Bldr.takeNodes(Pred);
1654  VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
1655  Bldr.addNodes(Dst);
1656  break;
1657 
1658  case Stmt::BinaryConditionalOperatorClass:
1659  case Stmt::ConditionalOperatorClass: { // '?' operator
1660  Bldr.takeNodes(Pred);
1661  const auto *C = cast<AbstractConditionalOperator>(S);
1662  VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
1663  Bldr.addNodes(Dst);
1664  break;
1665  }
1666 
1667  case Stmt::CXXThisExprClass:
1668  Bldr.takeNodes(Pred);
1669  VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
1670  Bldr.addNodes(Dst);
1671  break;
1672 
1673  case Stmt::DeclRefExprClass: {
1674  Bldr.takeNodes(Pred);
1675  const auto *DE = cast<DeclRefExpr>(S);
1676  VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
1677  Bldr.addNodes(Dst);
1678  break;
1679  }
1680 
1681  case Stmt::DeclStmtClass:
1682  Bldr.takeNodes(Pred);
1683  VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
1684  Bldr.addNodes(Dst);
1685  break;
1686 
1687  case Stmt::ImplicitCastExprClass:
1688  case Stmt::CStyleCastExprClass:
1689  case Stmt::CXXStaticCastExprClass:
1690  case Stmt::CXXDynamicCastExprClass:
1691  case Stmt::CXXReinterpretCastExprClass:
1692  case Stmt::CXXConstCastExprClass:
1693  case Stmt::CXXFunctionalCastExprClass:
1694  case Stmt::ObjCBridgedCastExprClass: {
1695  Bldr.takeNodes(Pred);
1696  const auto *C = cast<CastExpr>(S);
1697  ExplodedNodeSet dstExpr;
1698  VisitCast(C, C->getSubExpr(), Pred, dstExpr);
1699 
1700  // Handle the postvisit checks.
1701  getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1702  Bldr.addNodes(Dst);
1703  break;
1704  }
1705 
1706  case Expr::MaterializeTemporaryExprClass: {
1707  Bldr.takeNodes(Pred);
1708  const auto *MTE = cast<MaterializeTemporaryExpr>(S);
1709  ExplodedNodeSet dstPrevisit;
1710  getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this);
1711  ExplodedNodeSet dstExpr;
1712  for (const auto i : dstPrevisit)
1713  CreateCXXTemporaryObject(MTE, i, dstExpr);
1714  getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this);
1715  Bldr.addNodes(Dst);
1716  break;
1717  }
1718 
1719  case Stmt::InitListExprClass:
1720  Bldr.takeNodes(Pred);
1721  VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1722  Bldr.addNodes(Dst);
1723  break;
1724 
1725  case Stmt::MemberExprClass:
1726  Bldr.takeNodes(Pred);
1727  VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1728  Bldr.addNodes(Dst);
1729  break;
1730 
1731  case Stmt::AtomicExprClass:
1732  Bldr.takeNodes(Pred);
1733  VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
1734  Bldr.addNodes(Dst);
1735  break;
1736 
1737  case Stmt::ObjCIvarRefExprClass:
1738  Bldr.takeNodes(Pred);
1739  VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1740  Bldr.addNodes(Dst);
1741  break;
1742 
1743  case Stmt::ObjCForCollectionStmtClass:
1744  Bldr.takeNodes(Pred);
1745  VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1746  Bldr.addNodes(Dst);
1747  break;
1748 
1749  case Stmt::ObjCMessageExprClass:
1750  Bldr.takeNodes(Pred);
1751  VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1752  Bldr.addNodes(Dst);
1753  break;
1754 
1755  case Stmt::ObjCAtThrowStmtClass:
1756  case Stmt::CXXThrowExprClass:
1757  // FIXME: This is not complete. We basically treat @throw as
1758  // an abort.
1759  Bldr.generateSink(S, Pred, Pred->getState());
1760  break;
1761 
1762  case Stmt::ReturnStmtClass:
1763  Bldr.takeNodes(Pred);
1764  VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1765  Bldr.addNodes(Dst);
1766  break;
1767 
1768  case Stmt::OffsetOfExprClass: {
1769  Bldr.takeNodes(Pred);
1770  ExplodedNodeSet PreVisit;
1771  getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1772 
1773  ExplodedNodeSet PostVisit;
1774  for (const auto Node : PreVisit)
1775  VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Node, PostVisit);
1776 
1777  getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1778  Bldr.addNodes(Dst);
1779  break;
1780  }
1781 
1782  case Stmt::UnaryExprOrTypeTraitExprClass:
1783  Bldr.takeNodes(Pred);
1784  VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1785  Pred, Dst);
1786  Bldr.addNodes(Dst);
1787  break;
1788 
1789  case Stmt::StmtExprClass: {
1790  const auto *SE = cast<StmtExpr>(S);
1791 
1792  if (SE->getSubStmt()->body_empty()) {
1793  // Empty statement expression.
1794  assert(SE->getType() == getContext().VoidTy
1795  && "Empty statement expression must have void type.");
1796  break;
1797  }
1798 
1799  if (const auto *LastExpr =
1800  dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1801  ProgramStateRef state = Pred->getState();
1802  Bldr.generateNode(SE, Pred,
1803  state->BindExpr(SE, Pred->getLocationContext(),
1804  state->getSVal(LastExpr,
1805  Pred->getLocationContext())));
1806  }
1807  break;
1808  }
1809 
1810  case Stmt::UnaryOperatorClass: {
1811  Bldr.takeNodes(Pred);
1812  const auto *U = cast<UnaryOperator>(S);
1813  if (AMgr.options.ShouldEagerlyAssume && (U->getOpcode() == UO_LNot)) {
1814  ExplodedNodeSet Tmp;
1815  VisitUnaryOperator(U, Pred, Tmp);
1816  evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1817  }
1818  else
1819  VisitUnaryOperator(U, Pred, Dst);
1820  Bldr.addNodes(Dst);
1821  break;
1822  }
1823 
1824  case Stmt::PseudoObjectExprClass: {
1825  Bldr.takeNodes(Pred);
1826  ProgramStateRef state = Pred->getState();
1827  const auto *PE = cast<PseudoObjectExpr>(S);
1828  if (const Expr *Result = PE->getResultExpr()) {
1829  SVal V = state->getSVal(Result, Pred->getLocationContext());
1830  Bldr.generateNode(S, Pred,
1831  state->BindExpr(S, Pred->getLocationContext(), V));
1832  }
1833  else
1834  Bldr.generateNode(S, Pred,
1835  state->BindExpr(S, Pred->getLocationContext(),
1836  UnknownVal()));
1837 
1838  Bldr.addNodes(Dst);
1839  break;
1840  }
1841  }
1842 }
1843 
1844 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1845  const LocationContext *CalleeLC) {
1846  const StackFrameContext *CalleeSF = CalleeLC->getStackFrame();
1847  const StackFrameContext *CallerSF = CalleeSF->getParent()->getStackFrame();
1848  assert(CalleeSF && CallerSF);
1849  ExplodedNode *BeforeProcessingCall = nullptr;
1850  const Stmt *CE = CalleeSF->getCallSite();
1851 
1852  // Find the first node before we started processing the call expression.
1853  while (N) {
1854  ProgramPoint L = N->getLocation();
1855  BeforeProcessingCall = N;
1856  N = N->pred_empty() ? nullptr : *(N->pred_begin());
1857 
1858  // Skip the nodes corresponding to the inlined code.
1859  if (L.getStackFrame() != CallerSF)
1860  continue;
1861  // We reached the caller. Find the node right before we started
1862  // processing the call.
1863  if (L.isPurgeKind())
1864  continue;
1865  if (L.getAs<PreImplicitCall>())
1866  continue;
1867  if (L.getAs<CallEnter>())
1868  continue;
1869  if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1870  if (SP->getStmt() == CE)
1871  continue;
1872  break;
1873  }
1874 
1875  if (!BeforeProcessingCall)
1876  return false;
1877 
1878  // TODO: Clean up the unneeded nodes.
1879 
1880  // Build an Epsilon node from which we will restart the analyzes.
1881  // Note that CE is permitted to be NULL!
1882  ProgramPoint NewNodeLoc =
1883  EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1884  // Add the special flag to GDM to signal retrying with no inlining.
1885  // Note, changing the state ensures that we are not going to cache out.
1886  ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1887  NewNodeState =
1888  NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1889 
1890  // Make the new node a successor of BeforeProcessingCall.
1891  bool IsNew = false;
1892  ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1893  // We cached out at this point. Caching out is common due to us backtracking
1894  // from the inlined function, which might spawn several paths.
1895  if (!IsNew)
1896  return true;
1897 
1898  NewNode->addPredecessor(BeforeProcessingCall, G);
1899 
1900  // Add the new node to the work list.
1901  Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1902  CalleeSF->getIndex());
1903  NumTimesRetriedWithoutInlining++;
1904  return true;
1905 }
1906 
1907 /// Block entrance. (Update counters).
1909  NodeBuilderWithSinks &nodeBuilder,
1910  ExplodedNode *Pred) {
1912  // If we reach a loop which has a known bound (and meets
1913  // other constraints) then consider completely unrolling it.
1914  if(AMgr.options.ShouldUnrollLoops) {
1915  unsigned maxBlockVisitOnPath = AMgr.options.maxBlockVisitOnPath;
1916  const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminatorStmt();
1917  if (Term) {
1918  ProgramStateRef NewState = updateLoopStack(Term, AMgr.getASTContext(),
1919  Pred, maxBlockVisitOnPath);
1920  if (NewState != Pred->getState()) {
1921  ExplodedNode *UpdatedNode = nodeBuilder.generateNode(NewState, Pred);
1922  if (!UpdatedNode)
1923  return;
1924  Pred = UpdatedNode;
1925  }
1926  }
1927  // Is we are inside an unrolled loop then no need the check the counters.
1928  if(isUnrolledState(Pred->getState()))
1929  return;
1930  }
1931 
1932  // If this block is terminated by a loop and it has already been visited the
1933  // maximum number of times, widen the loop.
1934  unsigned int BlockCount = nodeBuilder.getContext().blockCount();
1935  if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
1936  AMgr.options.ShouldWidenLoops) {
1937  const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminatorStmt();
1938  if (!(Term &&
1939  (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
1940  return;
1941  // Widen.
1942  const LocationContext *LCtx = Pred->getLocationContext();
1943  ProgramStateRef WidenedState =
1944  getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
1945  nodeBuilder.generateNode(WidenedState, Pred);
1946  return;
1947  }
1948 
1949  // FIXME: Refactor this into a checker.
1950  if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
1951  static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
1952  const ExplodedNode *Sink =
1953  nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1954 
1955  // Check if we stopped at the top level function or not.
1956  // Root node should have the location context of the top most function.
1957  const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1958  const LocationContext *CalleeSF = CalleeLC->getStackFrame();
1959  const LocationContext *RootLC =
1960  (*G.roots_begin())->getLocation().getLocationContext();
1961  if (RootLC->getStackFrame() != CalleeSF) {
1962  Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1963 
1964  // Re-run the call evaluation without inlining it, by storing the
1965  // no-inlining policy in the state and enqueuing the new work item on
1966  // the list. Replay should almost never fail. Use the stats to catch it
1967  // if it does.
1968  if ((!AMgr.options.NoRetryExhausted &&
1969  replayWithoutInlining(Pred, CalleeLC)))
1970  return;
1971  NumMaxBlockCountReachedInInlined++;
1972  } else
1973  NumMaxBlockCountReached++;
1974 
1975  // Make sink nodes as exhausted(for stats) only if retry failed.
1976  Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1977  }
1978 }
1979 
1980 //===----------------------------------------------------------------------===//
1981 // Branch processing.
1982 //===----------------------------------------------------------------------===//
1983 
1984 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1985 /// to try to recover some path-sensitivity for casts of symbolic
1986 /// integers that promote their values (which are currently not tracked well).
1987 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1988 // cast(s) did was sign-extend the original value.
1990  const Stmt *Condition,
1991  const LocationContext *LCtx,
1992  ASTContext &Ctx) {
1993 
1994  const auto *Ex = dyn_cast<Expr>(Condition);
1995  if (!Ex)
1996  return UnknownVal();
1997 
1998  uint64_t bits = 0;
1999  bool bitsInit = false;
2000 
2001  while (const auto *CE = dyn_cast<CastExpr>(Ex)) {
2002  QualType T = CE->getType();
2003 
2004  if (!T->isIntegralOrEnumerationType())
2005  return UnknownVal();
2006 
2007  uint64_t newBits = Ctx.getTypeSize(T);
2008  if (!bitsInit || newBits < bits) {
2009  bitsInit = true;
2010  bits = newBits;
2011  }
2012 
2013  Ex = CE->getSubExpr();
2014  }
2015 
2016  // We reached a non-cast. Is it a symbolic value?
2017  QualType T = Ex->getType();
2018 
2019  if (!bitsInit || !T->isIntegralOrEnumerationType() ||
2020  Ctx.getTypeSize(T) > bits)
2021  return UnknownVal();
2022 
2023  return state->getSVal(Ex, LCtx);
2024 }
2025 
2026 #ifndef NDEBUG
2027 static const Stmt *getRightmostLeaf(const Stmt *Condition) {
2028  while (Condition) {
2029  const auto *BO = dyn_cast<BinaryOperator>(Condition);
2030  if (!BO || !BO->isLogicalOp()) {
2031  return Condition;
2032  }
2033  Condition = BO->getRHS()->IgnoreParens();
2034  }
2035  return nullptr;
2036 }
2037 #endif
2038 
2039 // Returns the condition the branch at the end of 'B' depends on and whose value
2040 // has been evaluated within 'B'.
2041 // In most cases, the terminator condition of 'B' will be evaluated fully in
2042 // the last statement of 'B'; in those cases, the resolved condition is the
2043 // given 'Condition'.
2044 // If the condition of the branch is a logical binary operator tree, the CFG is
2045 // optimized: in that case, we know that the expression formed by all but the
2046 // rightmost leaf of the logical binary operator tree must be true, and thus
2047 // the branch condition is at this point equivalent to the truth value of that
2048 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
2049 // expression in its final statement. As the full condition in that case was
2050 // not evaluated, and is thus not in the SVal cache, we need to use that leaf
2051 // expression to evaluate the truth value of the condition in the current state
2052 // space.
2053 static const Stmt *ResolveCondition(const Stmt *Condition,
2054  const CFGBlock *B) {
2055  if (const auto *Ex = dyn_cast<Expr>(Condition))
2056  Condition = Ex->IgnoreParens();
2057 
2058  const auto *BO = dyn_cast<BinaryOperator>(Condition);
2059  if (!BO || !BO->isLogicalOp())
2060  return Condition;
2061 
2062  assert(B->getTerminator().isStmtBranch() &&
2063  "Other kinds of branches are handled separately!");
2064 
2065  // For logical operations, we still have the case where some branches
2066  // use the traditional "merge" approach and others sink the branch
2067  // directly into the basic blocks representing the logical operation.
2068  // We need to distinguish between those two cases here.
2069 
2070  // The invariants are still shifting, but it is possible that the
2071  // last element in a CFGBlock is not a CFGStmt. Look for the last
2072  // CFGStmt as the value of the condition.
2073  CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
2074  for (; I != E; ++I) {
2075  CFGElement Elem = *I;
2076  Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
2077  if (!CS)
2078  continue;
2079  const Stmt *LastStmt = CS->getStmt();
2080  assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
2081  return LastStmt;
2082  }
2083  llvm_unreachable("could not resolve condition");
2084 }
2085 
2086 void ExprEngine::processBranch(const Stmt *Condition,
2087  NodeBuilderContext& BldCtx,
2088  ExplodedNode *Pred,
2089  ExplodedNodeSet &Dst,
2090  const CFGBlock *DstT,
2091  const CFGBlock *DstF) {
2092  assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
2093  "CXXBindTemporaryExprs are handled by processBindTemporary.");
2094  const LocationContext *LCtx = Pred->getLocationContext();
2095  PrettyStackTraceLocationContext StackCrashInfo(LCtx);
2096  currBldrCtx = &BldCtx;
2097 
2098  // Check for NULL conditions; e.g. "for(;;)"
2099  if (!Condition) {
2100  BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
2101  NullCondBldr.markInfeasible(false);
2102  NullCondBldr.generateNode(Pred->getState(), true, Pred);
2103  return;
2104  }
2105 
2106  if (const auto *Ex = dyn_cast<Expr>(Condition))
2107  Condition = Ex->IgnoreParens();
2108 
2109  Condition = ResolveCondition(Condition, BldCtx.getBlock());
2110  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
2111  Condition->getBeginLoc(),
2112  "Error evaluating branch");
2113 
2114  ExplodedNodeSet CheckersOutSet;
2115  getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
2116  Pred, *this);
2117  // We generated only sinks.
2118  if (CheckersOutSet.empty())
2119  return;
2120 
2121  BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
2122  for (const auto PredI : CheckersOutSet) {
2123  if (PredI->isSink())
2124  continue;
2125 
2126  ProgramStateRef PrevState = PredI->getState();
2127  SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
2128 
2129  if (X.isUnknownOrUndef()) {
2130  // Give it a chance to recover from unknown.
2131  if (const auto *Ex = dyn_cast<Expr>(Condition)) {
2132  if (Ex->getType()->isIntegralOrEnumerationType()) {
2133  // Try to recover some path-sensitivity. Right now casts of symbolic
2134  // integers that promote their values are currently not tracked well.
2135  // If 'Condition' is such an expression, try and recover the
2136  // underlying value and use that instead.
2137  SVal recovered = RecoverCastedSymbol(PrevState, Condition,
2138  PredI->getLocationContext(),
2139  getContext());
2140 
2141  if (!recovered.isUnknown()) {
2142  X = recovered;
2143  }
2144  }
2145  }
2146  }
2147 
2148  // If the condition is still unknown, give up.
2149  if (X.isUnknownOrUndef()) {
2150  builder.generateNode(PrevState, true, PredI);
2151  builder.generateNode(PrevState, false, PredI);
2152  continue;
2153  }
2154 
2155  DefinedSVal V = X.castAs<DefinedSVal>();
2156 
2157  ProgramStateRef StTrue, StFalse;
2158  std::tie(StTrue, StFalse) = PrevState->assume(V);
2159 
2160  // Process the true branch.
2161  if (builder.isFeasible(true)) {
2162  if (StTrue)
2163  builder.generateNode(StTrue, true, PredI);
2164  else
2165  builder.markInfeasible(true);
2166  }
2167 
2168  // Process the false branch.
2169  if (builder.isFeasible(false)) {
2170  if (StFalse)
2171  builder.generateNode(StFalse, false, PredI);
2172  else
2173  builder.markInfeasible(false);
2174  }
2175  }
2176  currBldrCtx = nullptr;
2177 }
2178 
2179 /// The GDM component containing the set of global variables which have been
2180 /// previously initialized with explicit initializers.
2181 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
2182  llvm::ImmutableSet<const VarDecl *>)
2183 
2185  NodeBuilderContext &BuilderCtx,
2186  ExplodedNode *Pred,
2187  ExplodedNodeSet &Dst,
2188  const CFGBlock *DstT,
2189  const CFGBlock *DstF) {
2190  PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
2191  currBldrCtx = &BuilderCtx;
2192 
2193  const auto *VD = cast<VarDecl>(DS->getSingleDecl());
2194  ProgramStateRef state = Pred->getState();
2195  bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
2196  BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
2197 
2198  if (!initHasRun) {
2199  state = state->add<InitializedGlobalsSet>(VD);
2200  }
2201 
2202  builder.generateNode(state, initHasRun, Pred);
2203  builder.markInfeasible(!initHasRun);
2204 
2205  currBldrCtx = nullptr;
2206 }
2207 
2208 /// processIndirectGoto - Called by CoreEngine. Used to generate successor
2209 /// nodes by processing the 'effects' of a computed goto jump.
2211  ProgramStateRef state = builder.getState();
2212  SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
2213 
2214  // Three possibilities:
2215  //
2216  // (1) We know the computed label.
2217  // (2) The label is NULL (or some other constant), or Undefined.
2218  // (3) We have no clue about the label. Dispatch to all targets.
2219  //
2220 
2221  using iterator = IndirectGotoNodeBuilder::iterator;
2222 
2224  const LabelDecl *L = LV->getLabel();
2225 
2226  for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
2227  if (I.getLabel() == L) {
2228  builder.generateNode(I, state);
2229  return;
2230  }
2231  }
2232 
2233  llvm_unreachable("No block with label.");
2234  }
2235 
2236  if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
2237  // Dispatch to the first target and mark it as a sink.
2238  //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
2239  // FIXME: add checker visit.
2240  // UndefBranches.insert(N);
2241  return;
2242  }
2243 
2244  // This is really a catch-all. We don't support symbolics yet.
2245  // FIXME: Implement dispatch for symbolic pointers.
2246 
2247  for (iterator I = builder.begin(), E = builder.end(); I != E; ++I)
2248  builder.generateNode(I, state);
2249 }
2250 
2252  ExplodedNode *Pred,
2253  ExplodedNodeSet &Dst,
2254  const BlockEdge &L) {
2255  SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
2256  getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
2257 }
2258 
2259 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
2260 /// nodes when the control reaches the end of a function.
2262  ExplodedNode *Pred,
2263  const ReturnStmt *RS) {
2264  ProgramStateRef State = Pred->getState();
2265 
2266  if (!Pred->getStackFrame()->inTopFrame())
2267  State = finishArgumentConstruction(
2269  Pred->getStackFrame(), Pred->getState()));
2270 
2271  // FIXME: We currently cannot assert that temporaries are clear, because
2272  // lifetime extended temporaries are not always modelled correctly. In some
2273  // cases when we materialize the temporary, we do
2274  // createTemporaryRegionIfNeeded(), and the region changes, and also the
2275  // respective destructor becomes automatic from temporary. So for now clean up
2276  // the state manually before asserting. Ideally, this braced block of code
2277  // should go away.
2278  {
2279  const LocationContext *FromLC = Pred->getLocationContext();
2280  const LocationContext *ToLC = FromLC->getStackFrame()->getParent();
2281  const LocationContext *LC = FromLC;
2282  while (LC != ToLC) {
2283  assert(LC && "ToLC must be a parent of FromLC!");
2284  for (auto I : State->get<ObjectsUnderConstruction>())
2285  if (I.first.getLocationContext() == LC) {
2286  // The comment above only pardons us for not cleaning up a
2287  // temporary destructor. If any other statements are found here,
2288  // it must be a separate problem.
2289  assert(I.first.getItem().getKind() ==
2291  I.first.getItem().getKind() ==
2293  State = State->remove<ObjectsUnderConstruction>(I.first);
2294  }
2295  LC = LC->getParent();
2296  }
2297  }
2298 
2299  // Perform the transition with cleanups.
2300  if (State != Pred->getState()) {
2301  ExplodedNodeSet PostCleanup;
2302  NodeBuilder Bldr(Pred, PostCleanup, BC);
2303  Pred = Bldr.generateNode(Pred->getLocation(), State, Pred);
2304  if (!Pred) {
2305  // The node with clean temporaries already exists. We might have reached
2306  // it on a path on which we initialize different temporaries.
2307  return;
2308  }
2309  }
2310 
2311  assert(areAllObjectsFullyConstructed(Pred->getState(),
2312  Pred->getLocationContext(),
2313  Pred->getStackFrame()->getParent()));
2314 
2316 
2317  ExplodedNodeSet Dst;
2318  if (Pred->getLocationContext()->inTopFrame()) {
2319  // Remove dead symbols.
2320  ExplodedNodeSet AfterRemovedDead;
2321  removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
2322 
2323  // Notify checkers.
2324  for (const auto I : AfterRemovedDead)
2325  getCheckerManager().runCheckersForEndFunction(BC, Dst, I, *this, RS);
2326  } else {
2327  getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this, RS);
2328  }
2329 
2330  Engine.enqueueEndOfFunction(Dst, RS);
2331 }
2332 
2333 /// ProcessSwitch - Called by CoreEngine. Used to generate successor
2334 /// nodes by processing the 'effects' of a switch statement.
2336  using iterator = SwitchNodeBuilder::iterator;
2337 
2338  ProgramStateRef state = builder.getState();
2339  const Expr *CondE = builder.getCondition();
2340  SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
2341 
2342  if (CondV_untested.isUndef()) {
2343  //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
2344  // FIXME: add checker
2345  //UndefBranches.insert(N);
2346 
2347  return;
2348  }
2349  DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
2350 
2351  ProgramStateRef DefaultSt = state;
2352 
2353  iterator I = builder.begin(), EI = builder.end();
2354  bool defaultIsFeasible = I == EI;
2355 
2356  for ( ; I != EI; ++I) {
2357  // Successor may be pruned out during CFG construction.
2358  if (!I.getBlock())
2359  continue;
2360 
2361  const CaseStmt *Case = I.getCase();
2362 
2363  // Evaluate the LHS of the case value.
2364  llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
2365  assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType()));
2366 
2367  // Get the RHS of the case, if it exists.
2368  llvm::APSInt V2;
2369  if (const Expr *E = Case->getRHS())
2370  V2 = E->EvaluateKnownConstInt(getContext());
2371  else
2372  V2 = V1;
2373 
2374  ProgramStateRef StateCase;
2375  if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
2376  std::tie(StateCase, DefaultSt) =
2377  DefaultSt->assumeInclusiveRange(*NL, V1, V2);
2378  else // UnknownVal
2379  StateCase = DefaultSt;
2380 
2381  if (StateCase)
2382  builder.generateCaseStmtNode(I, StateCase);
2383 
2384  // Now "assume" that the case doesn't match. Add this state
2385  // to the default state (if it is feasible).
2386  if (DefaultSt)
2387  defaultIsFeasible = true;
2388  else {
2389  defaultIsFeasible = false;
2390  break;
2391  }
2392  }
2393 
2394  if (!defaultIsFeasible)
2395  return;
2396 
2397  // If we have switch(enum value), the default branch is not
2398  // feasible if all of the enum constants not covered by 'case:' statements
2399  // are not feasible values for the switch condition.
2400  //
2401  // Note that this isn't as accurate as it could be. Even if there isn't
2402  // a case for a particular enum value as long as that enum value isn't
2403  // feasible then it shouldn't be considered for making 'default:' reachable.
2404  const SwitchStmt *SS = builder.getSwitch();
2405  const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
2406  if (CondExpr->getType()->getAs<EnumType>()) {
2407  if (SS->isAllEnumCasesCovered())
2408  return;
2409  }
2410 
2411  builder.generateDefaultCaseNode(DefaultSt);
2412 }
2413 
2414 //===----------------------------------------------------------------------===//
2415 // Transfer functions: Loads and stores.
2416 //===----------------------------------------------------------------------===//
2417 
2419  ExplodedNode *Pred,
2420  ExplodedNodeSet &Dst) {
2421  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2422 
2423  ProgramStateRef state = Pred->getState();
2424  const LocationContext *LCtx = Pred->getLocationContext();
2425 
2426  if (const auto *VD = dyn_cast<VarDecl>(D)) {
2427  // C permits "extern void v", and if you cast the address to a valid type,
2428  // you can even do things with it. We simply pretend
2429  assert(Ex->isGLValue() || VD->getType()->isVoidType());
2430  const LocationContext *LocCtxt = Pred->getLocationContext();
2431  const Decl *D = LocCtxt->getDecl();
2432  const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
2433  const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
2435 
2436  if (AMgr.options.ShouldInlineLambdas && DeclRefEx &&
2437  DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
2438  MD->getParent()->isLambda()) {
2439  // Lookup the field of the lambda.
2440  const CXXRecordDecl *CXXRec = MD->getParent();
2441  llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
2442  FieldDecl *LambdaThisCaptureField;
2443  CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
2444 
2445  // Sema follows a sequence of complex rules to determine whether the
2446  // variable should be captured.
2447  if (const FieldDecl *FD = LambdaCaptureFields[VD]) {
2448  Loc CXXThis =
2449  svalBuilder.getCXXThis(MD, LocCtxt->getStackFrame());
2450  SVal CXXThisVal = state->getSVal(CXXThis);
2451  VInfo = std::make_pair(state->getLValue(FD, CXXThisVal), FD->getType());
2452  }
2453  }
2454 
2455  if (!VInfo)
2456  VInfo = std::make_pair(state->getLValue(VD, LocCtxt), VD->getType());
2457 
2458  SVal V = VInfo->first;
2459  bool IsReference = VInfo->second->isReferenceType();
2460 
2461  // For references, the 'lvalue' is the pointer address stored in the
2462  // reference region.
2463  if (IsReference) {
2464  if (const MemRegion *R = V.getAsRegion())
2465  V = state->getSVal(R);
2466  else
2467  V = UnknownVal();
2468  }
2469 
2470  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2472  return;
2473  }
2474  if (const auto *ED = dyn_cast<EnumConstantDecl>(D)) {
2475  assert(!Ex->isGLValue());
2476  SVal V = svalBuilder.makeIntVal(ED->getInitVal());
2477  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
2478  return;
2479  }
2480  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2481  SVal V = svalBuilder.getFunctionPointer(FD);
2482  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2484  return;
2485  }
2486  if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
2487  // FIXME: Compute lvalue of field pointers-to-member.
2488  // Right now we just use a non-null void pointer, so that it gives proper
2489  // results in boolean contexts.
2490  // FIXME: Maybe delegate this to the surrounding operator&.
2491  // Note how this expression is lvalue, however pointer-to-member is NonLoc.
2492  SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
2493  currBldrCtx->blockCount());
2494  state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
2495  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2497  return;
2498  }
2499  if (isa<BindingDecl>(D)) {
2500  // FIXME: proper support for bound declarations.
2501  // For now, let's just prevent crashing.
2502  return;
2503  }
2504 
2505  llvm_unreachable("Support for this Decl not implemented.");
2506 }
2507 
2508 /// VisitArraySubscriptExpr - Transfer function for array accesses
2510  ExplodedNode *Pred,
2511  ExplodedNodeSet &Dst){
2512  const Expr *Base = A->getBase()->IgnoreParens();
2513  const Expr *Idx = A->getIdx()->IgnoreParens();
2514 
2515  ExplodedNodeSet CheckerPreStmt;
2516  getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this);
2517 
2518  ExplodedNodeSet EvalSet;
2519  StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx);
2520 
2521  bool IsVectorType = A->getBase()->getType()->isVectorType();
2522 
2523  // The "like" case is for situations where C standard prohibits the type to
2524  // be an lvalue, e.g. taking the address of a subscript of an expression of
2525  // type "void *".
2526  bool IsGLValueLike = A->isGLValue() ||
2527  (A->getType().isCForbiddenLValueType() && !AMgr.getLangOpts().CPlusPlus);
2528 
2529  for (auto *Node : CheckerPreStmt) {
2530  const LocationContext *LCtx = Node->getLocationContext();
2531  ProgramStateRef state = Node->getState();
2532 
2533  if (IsGLValueLike) {
2534  QualType T = A->getType();
2535 
2536  // One of the forbidden LValue types! We still need to have sensible
2537  // symbolic locations to represent this stuff. Note that arithmetic on
2538  // void pointers is a GCC extension.
2539  if (T->isVoidType())
2540  T = getContext().CharTy;
2541 
2542  SVal V = state->getLValue(T,
2543  state->getSVal(Idx, LCtx),
2544  state->getSVal(Base, LCtx));
2545  Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr,
2547  } else if (IsVectorType) {
2548  // FIXME: non-glvalue vector reads are not modelled.
2549  Bldr.generateNode(A, Node, state, nullptr);
2550  } else {
2551  llvm_unreachable("Array subscript should be an lValue when not \
2552 a vector and not a forbidden lvalue type");
2553  }
2554  }
2555 
2556  getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
2557 }
2558 
2559 /// VisitMemberExpr - Transfer function for member expressions.
2561  ExplodedNodeSet &Dst) {
2562  // FIXME: Prechecks eventually go in ::Visit().
2563  ExplodedNodeSet CheckedSet;
2564  getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
2565 
2566  ExplodedNodeSet EvalSet;
2567  ValueDecl *Member = M->getMemberDecl();
2568 
2569  // Handle static member variables and enum constants accessed via
2570  // member syntax.
2571  if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
2572  for (const auto I : CheckedSet)
2573  VisitCommonDeclRefExpr(M, Member, I, EvalSet);
2574  } else {
2575  StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
2576  ExplodedNodeSet Tmp;
2577 
2578  for (const auto I : CheckedSet) {
2579  ProgramStateRef state = I->getState();
2580  const LocationContext *LCtx = I->getLocationContext();
2581  Expr *BaseExpr = M->getBase();
2582 
2583  // Handle C++ method calls.
2584  if (const auto *MD = dyn_cast<CXXMethodDecl>(Member)) {
2585  if (MD->isInstance())
2586  state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2587 
2588  SVal MDVal = svalBuilder.getFunctionPointer(MD);
2589  state = state->BindExpr(M, LCtx, MDVal);
2590 
2591  Bldr.generateNode(M, I, state);
2592  continue;
2593  }
2594 
2595  // Handle regular struct fields / member variables.
2596  const SubRegion *MR = nullptr;
2597  state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr,
2598  /*Result=*/nullptr,
2599  /*OutRegionWithAdjustments=*/&MR);
2600  SVal baseExprVal =
2601  MR ? loc::MemRegionVal(MR) : state->getSVal(BaseExpr, LCtx);
2602 
2603  const auto *field = cast<FieldDecl>(Member);
2604  SVal L = state->getLValue(field, baseExprVal);
2605 
2606  if (M->isGLValue() || M->getType()->isArrayType()) {
2607  // We special-case rvalues of array type because the analyzer cannot
2608  // reason about them, since we expect all regions to be wrapped in Locs.
2609  // We instead treat these as lvalues and assume that they will decay to
2610  // pointers as soon as they are used.
2611  if (!M->isGLValue()) {
2612  assert(M->getType()->isArrayType());
2613  const auto *PE =
2614  dyn_cast<ImplicitCastExpr>(I->getParentMap().getParentIgnoreParens(M));
2615  if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
2616  llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
2617  }
2618  }
2619 
2620  if (field->getType()->isReferenceType()) {
2621  if (const MemRegion *R = L.getAsRegion())
2622  L = state->getSVal(R);
2623  else
2624  L = UnknownVal();
2625  }
2626 
2627  Bldr.generateNode(M, I, state->BindExpr(M, LCtx, L), nullptr,
2629  } else {
2630  Bldr.takeNodes(I);
2631  evalLoad(Tmp, M, M, I, state, L);
2632  Bldr.addNodes(Tmp);
2633  }
2634  }
2635  }
2636 
2637  getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
2638 }
2639 
2641  ExplodedNodeSet &Dst) {
2642  ExplodedNodeSet AfterPreSet;
2643  getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this);
2644 
2645  // For now, treat all the arguments to C11 atomics as escaping.
2646  // FIXME: Ideally we should model the behavior of the atomics precisely here.
2647 
2648  ExplodedNodeSet AfterInvalidateSet;
2649  StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx);
2650 
2651  for (const auto I : AfterPreSet) {
2652  ProgramStateRef State = I->getState();
2653  const LocationContext *LCtx = I->getLocationContext();
2654 
2655  SmallVector<SVal, 8> ValuesToInvalidate;
2656  for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) {
2657  const Expr *SubExpr = AE->getSubExprs()[SI];
2658  SVal SubExprVal = State->getSVal(SubExpr, LCtx);
2659  ValuesToInvalidate.push_back(SubExprVal);
2660  }
2661 
2662  State = State->invalidateRegions(ValuesToInvalidate, AE,
2663  currBldrCtx->blockCount(),
2664  LCtx,
2665  /*CausedByPointerEscape*/true,
2666  /*Symbols=*/nullptr);
2667 
2668  SVal ResultVal = UnknownVal();
2669  State = State->BindExpr(AE, LCtx, ResultVal);
2670  Bldr.generateNode(AE, I, State, nullptr,
2672  }
2673 
2674  getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this);
2675 }
2676 
2677 // A value escapes in four possible cases:
2678 // (1) We are binding to something that is not a memory region.
2679 // (2) We are binding to a MemRegion that does not have stack storage.
2680 // (3) We are binding to a top-level parameter region with a non-trivial
2681 // destructor. We won't see the destructor during analysis, but it's there.
2682 // (4) We are binding to a MemRegion with stack storage that the store
2683 // does not understand.
2686  SVal Val, const LocationContext *LCtx) {
2687 
2688  // Cases (1) and (2).
2689  const MemRegion *MR = Loc.getAsRegion();
2690  if (!MR || !MR->hasStackStorage())
2691  return escapeValue(State, Val, PSK_EscapeOnBind);
2692 
2693  // Case (3).
2694  if (const auto *VR = dyn_cast<VarRegion>(MR->getBaseRegion()))
2695  if (VR->hasStackParametersStorage() && VR->getStackFrame()->inTopFrame())
2696  if (const auto *RD = VR->getValueType()->getAsCXXRecordDecl())
2697  if (!RD->hasTrivialDestructor())
2698  return escapeValue(State, Val, PSK_EscapeOnBind);
2699 
2700  // Case (4): in order to test that, generate a new state with the binding
2701  // added. If it is the same state, then it escapes (since the store cannot
2702  // represent the binding).
2703  // Do this only if we know that the store is not supposed to generate the
2704  // same state.
2705  SVal StoredVal = State->getSVal(MR);
2706  if (StoredVal != Val)
2707  if (State == (State->bindLoc(loc::MemRegionVal(MR), Val, LCtx)))
2708  return escapeValue(State, Val, PSK_EscapeOnBind);
2709 
2710  return State;
2711 }
2712 
2715  const InvalidatedSymbols *Invalidated,
2716  ArrayRef<const MemRegion *> ExplicitRegions,
2717  const CallEvent *Call,
2719  if (!Invalidated || Invalidated->empty())
2720  return State;
2721 
2722  if (!Call)
2724  *Invalidated,
2725  nullptr,
2727  &ITraits);
2728 
2729  // If the symbols were invalidated by a call, we want to find out which ones
2730  // were invalidated directly due to being arguments to the call.
2731  InvalidatedSymbols SymbolsDirectlyInvalidated;
2732  for (const auto I : ExplicitRegions) {
2733  if (const SymbolicRegion *R = I->StripCasts()->getAs<SymbolicRegion>())
2734  SymbolsDirectlyInvalidated.insert(R->getSymbol());
2735  }
2736 
2737  InvalidatedSymbols SymbolsIndirectlyInvalidated;
2738  for (const auto &sym : *Invalidated) {
2739  if (SymbolsDirectlyInvalidated.count(sym))
2740  continue;
2741  SymbolsIndirectlyInvalidated.insert(sym);
2742  }
2743 
2744  if (!SymbolsDirectlyInvalidated.empty())
2746  SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
2747 
2748  // Notify about the symbols that get indirectly invalidated by the call.
2749  if (!SymbolsIndirectlyInvalidated.empty())
2751  SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
2752 
2753  return State;
2754 }
2755 
2756 /// evalBind - Handle the semantics of binding a value to a specific location.
2757 /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
2758 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
2759  ExplodedNode *Pred,
2760  SVal location, SVal Val,
2761  bool atDeclInit, const ProgramPoint *PP) {
2762  const LocationContext *LC = Pred->getLocationContext();
2763  PostStmt PS(StoreE, LC);
2764  if (!PP)
2765  PP = &PS;
2766 
2767  // Do a previsit of the bind.
2768  ExplodedNodeSet CheckedSet;
2769  getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
2770  StoreE, *this, *PP);
2771 
2772  StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
2773 
2774  // If the location is not a 'Loc', it will already be handled by
2775  // the checkers. There is nothing left to do.
2776  if (!location.getAs<Loc>()) {
2777  const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
2778  /*tag*/nullptr);
2779  ProgramStateRef state = Pred->getState();
2780  state = processPointerEscapedOnBind(state, location, Val, LC);
2781  Bldr.generateNode(L, state, Pred);
2782  return;
2783  }
2784 
2785  for (const auto PredI : CheckedSet) {
2786  ProgramStateRef state = PredI->getState();
2787 
2788  state = processPointerEscapedOnBind(state, location, Val, LC);
2789 
2790  // When binding the value, pass on the hint that this is a initialization.
2791  // For initializations, we do not need to inform clients of region
2792  // changes.
2793  state = state->bindLoc(location.castAs<Loc>(),
2794  Val, LC, /* notifyChanges = */ !atDeclInit);
2795 
2796  const MemRegion *LocReg = nullptr;
2797  if (Optional<loc::MemRegionVal> LocRegVal =
2798  location.getAs<loc::MemRegionVal>()) {
2799  LocReg = LocRegVal->getRegion();
2800  }
2801 
2802  const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
2803  Bldr.generateNode(L, state, PredI);
2804  }
2805 }
2806 
2807 /// evalStore - Handle the semantics of a store via an assignment.
2808 /// @param Dst The node set to store generated state nodes
2809 /// @param AssignE The assignment expression if the store happens in an
2810 /// assignment.
2811 /// @param LocationE The location expression that is stored to.
2812 /// @param state The current simulation state
2813 /// @param location The location to store the value
2814 /// @param Val The value to be stored
2815 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
2816  const Expr *LocationE,
2817  ExplodedNode *Pred,
2818  ProgramStateRef state, SVal location, SVal Val,
2819  const ProgramPointTag *tag) {
2820  // Proceed with the store. We use AssignE as the anchor for the PostStore
2821  // ProgramPoint if it is non-NULL, and LocationE otherwise.
2822  const Expr *StoreE = AssignE ? AssignE : LocationE;
2823 
2824  // Evaluate the location (checks for bad dereferences).
2825  ExplodedNodeSet Tmp;
2826  evalLocation(Tmp, AssignE, LocationE, Pred, state, location, false);
2827 
2828  if (Tmp.empty())
2829  return;
2830 
2831  if (location.isUndef())
2832  return;
2833 
2834  for (const auto I : Tmp)
2835  evalBind(Dst, StoreE, I, location, Val, false);
2836 }
2837 
2839  const Expr *NodeEx,
2840  const Expr *BoundEx,
2841  ExplodedNode *Pred,
2843  SVal location,
2844  const ProgramPointTag *tag,
2845  QualType LoadTy) {
2846  assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2847  assert(NodeEx);
2848  assert(BoundEx);
2849  // Evaluate the location (checks for bad dereferences).
2850  ExplodedNodeSet Tmp;
2851  evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, true);
2852  if (Tmp.empty())
2853  return;
2854 
2855  StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2856  if (location.isUndef())
2857  return;
2858 
2859  // Proceed with the load.
2860  for (const auto I : Tmp) {
2861  state = I->getState();
2862  const LocationContext *LCtx = I->getLocationContext();
2863 
2864  SVal V = UnknownVal();
2865  if (location.isValid()) {
2866  if (LoadTy.isNull())
2867  LoadTy = BoundEx->getType();
2868  V = state->getSVal(location.castAs<Loc>(), LoadTy);
2869  }
2870 
2871  Bldr.generateNode(NodeEx, I, state->BindExpr(BoundEx, LCtx, V), tag,
2873  }
2874 }
2875 
2876 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2877  const Stmt *NodeEx,
2878  const Stmt *BoundEx,
2879  ExplodedNode *Pred,
2881  SVal location,
2882  bool isLoad) {
2883  StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2884  // Early checks for performance reason.
2885  if (location.isUnknown()) {
2886  return;
2887  }
2888 
2889  ExplodedNodeSet Src;
2890  BldrTop.takeNodes(Pred);
2891  StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2892  if (Pred->getState() != state) {
2893  // Associate this new state with an ExplodedNode.
2894  // FIXME: If I pass null tag, the graph is incorrect, e.g for
2895  // int *p;
2896  // p = 0;
2897  // *p = 0xDEADBEEF;
2898  // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2899  // instead "int *p" is noted as
2900  // "Variable 'p' initialized to a null pointer value"
2901 
2902  static SimpleProgramPointTag tag(TagProviderName, "Location");
2903  Bldr.generateNode(NodeEx, Pred, state, &tag);
2904  }
2905  ExplodedNodeSet Tmp;
2906  getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2907  NodeEx, BoundEx, *this);
2908  BldrTop.addNodes(Tmp);
2909 }
2910 
2911 std::pair<const ProgramPointTag *, const ProgramPointTag*>
2913  static SimpleProgramPointTag
2914  eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
2915  "Eagerly Assume True"),
2916  eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
2917  "Eagerly Assume False");
2918  return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2919  &eagerlyAssumeBinOpBifurcationFalse);
2920 }
2921 
2923  ExplodedNodeSet &Src,
2924  const Expr *Ex) {
2925  StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2926 
2927  for (const auto Pred : Src) {
2928  // Test if the previous node was as the same expression. This can happen
2929  // when the expression fails to evaluate to anything meaningful and
2930  // (as an optimization) we don't generate a node.
2931  ProgramPoint P = Pred->getLocation();
2932  if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2933  continue;
2934  }
2935 
2936  ProgramStateRef state = Pred->getState();
2937  SVal V = state->getSVal(Ex, Pred->getLocationContext());
2939  if (SEV && SEV->isExpression()) {
2940  const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2942 
2943  ProgramStateRef StateTrue, StateFalse;
2944  std::tie(StateTrue, StateFalse) = state->assume(*SEV);
2945 
2946  // First assume that the condition is true.
2947  if (StateTrue) {
2948  SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2949  StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2950  Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2951  }
2952 
2953  // Next, assume that the condition is false.
2954  if (StateFalse) {
2955  SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2956  StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2957  Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2958  }
2959  }
2960  }
2961 }
2962 
2964  ExplodedNodeSet &Dst) {
2965  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2966  // We have processed both the inputs and the outputs. All of the outputs
2967  // should evaluate to Locs. Nuke all of their values.
2968 
2969  // FIXME: Some day in the future it would be nice to allow a "plug-in"
2970  // which interprets the inline asm and stores proper results in the
2971  // outputs.
2972 
2973  ProgramStateRef state = Pred->getState();
2974 
2975  for (const Expr *O : A->outputs()) {
2976  SVal X = state->getSVal(O, Pred->getLocationContext());
2977  assert(!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
2978 
2979  if (Optional<Loc> LV = X.getAs<Loc>())
2980  state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext());
2981  }
2982 
2983  Bldr.generateNode(A, Pred, state);
2984 }
2985 
2987  ExplodedNodeSet &Dst) {
2988  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2989  Bldr.generateNode(A, Pred, Pred->getState());
2990 }
2991 
2992 //===----------------------------------------------------------------------===//
2993 // Visualization.
2994 //===----------------------------------------------------------------------===//
2995 
2996 #ifndef NDEBUG
2997 namespace llvm {
2998 
2999 template<>
3000 struct DOTGraphTraits<ExplodedGraph*> : public DefaultDOTGraphTraits {
3001  DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3002 
3003  static bool nodeHasBugReport(const ExplodedNode *N) {
3004  BugReporter &BR = static_cast<ExprEngine &>(
3005  N->getState()->getStateManager().getOwningEngine()).getBugReporter();
3006 
3007  const auto EQClasses =
3008  llvm::make_range(BR.EQClasses_begin(), BR.EQClasses_end());
3009 
3010  for (const auto &EQ : EQClasses) {
3011  for (const BugReport &Report : EQ) {
3012  if (Report.getErrorNode() == N)
3013  return true;
3014  }
3015  }
3016  return false;
3017  }
3018 
3019  /// \p PreCallback: callback before break.
3020  /// \p PostCallback: callback after break.
3021  /// \p Stop: stop iteration if returns {@code true}
3022  /// \return Whether {@code Stop} ever returned {@code true}.
3023  static bool traverseHiddenNodes(
3024  const ExplodedNode *N,
3025  llvm::function_ref<void(const ExplodedNode *)> PreCallback,
3026  llvm::function_ref<void(const ExplodedNode *)> PostCallback,
3027  llvm::function_ref<bool(const ExplodedNode *)> Stop) {
3028  const ExplodedNode *FirstHiddenNode = N;
3029  while (FirstHiddenNode->pred_size() == 1 &&
3030  isNodeHidden(*FirstHiddenNode->pred_begin())) {
3031  FirstHiddenNode = *FirstHiddenNode->pred_begin();
3032  }
3033  const ExplodedNode *OtherNode = FirstHiddenNode;
3034  while (true) {
3035  PreCallback(OtherNode);
3036  if (Stop(OtherNode))
3037  return true;
3038 
3039  if (OtherNode == N)
3040  break;
3041  PostCallback(OtherNode);
3042 
3043  OtherNode = *OtherNode->succ_begin();
3044  }
3045  return false;
3046  }
3047 
3048  static std::string getNodeAttributes(const ExplodedNode *N,
3049  ExplodedGraph *) {
3051  auto Noop = [](const ExplodedNode*){};
3052  if (traverseHiddenNodes(N, Noop, Noop, &nodeHasBugReport)) {
3053  Out.push_back("style=filled");
3054  Out.push_back("fillcolor=red");
3055  }
3056 
3057  if (traverseHiddenNodes(N, Noop, Noop,
3058  [](const ExplodedNode *C) { return C->isSink(); }))
3059  Out.push_back("color=blue");
3060  return llvm::join(Out, ",");
3061  }
3062 
3063  static bool isNodeHidden(const ExplodedNode *N) {
3064  return N->isTrivial();
3065  }
3066 
3067  static std::string getNodeLabel(const ExplodedNode *N, ExplodedGraph *G){
3068  std::string Buf;
3069  llvm::raw_string_ostream Out(Buf);
3070 
3071  const bool IsDot = true;
3072  const unsigned int Space = 1;
3073  ProgramStateRef State = N->getState();
3074 
3075  Out << "{ \"node_id\": " << N->getID(G) << ", \"pointer\": \""
3076  << (const void *)N << "\", \"state_id\": " << State->getID()
3077  << ", \"has_report\": " << (nodeHasBugReport(N) ? "true" : "false")
3078  << ",\\l";
3079 
3080  Indent(Out, Space, IsDot) << "\"program_points\": [\\l";
3081 
3082  // Dump program point for all the previously skipped nodes.
3083  traverseHiddenNodes(
3084  N,
3085  [&](const ExplodedNode *OtherNode) {
3086  Indent(Out, Space + 1, IsDot) << "{ ";
3087  OtherNode->getLocation().printJson(Out, /*NL=*/"\\l");
3088  Out << ", \"tag\": ";
3089  if (const ProgramPointTag *Tag = OtherNode->getLocation().getTag())
3090  Out << '\"' << Tag->getTagDescription() << "\" }";
3091  else
3092  Out << "null }";
3093  },
3094  // Adds a comma and a new-line between each program point.
3095  [&](const ExplodedNode *) { Out << ",\\l"; },
3096  [&](const ExplodedNode *) { return false; });
3097 
3098  Out << "\\l"; // Adds a new-line to the last program point.
3099  Indent(Out, Space, IsDot) << "],\\l";
3100 
3101  bool SameAsAllPredecessors =
3102  std::all_of(N->pred_begin(), N->pred_end(), [&](const ExplodedNode *P) {
3103  return P->getState() == State;
3104  });
3105 
3106  if (!SameAsAllPredecessors) {
3107  State->printDOT(Out, N->getLocationContext(), Space);
3108  } else {
3109  Indent(Out, Space, IsDot) << "\"program_state\": null";
3110  }
3111 
3112  Out << "\\l}";
3113  if (!N->succ_empty())
3114  Out << ',';
3115  Out << "\\l";
3116 
3117  return Out.str();
3118  }
3119 };
3120 
3121 } // namespace llvm
3122 #endif
3123 
3124 void ExprEngine::ViewGraph(bool trim) {
3125 #ifndef NDEBUG
3126  std::string Filename = DumpGraph(trim);
3127  llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
3128 #endif
3129  llvm::errs() << "Warning: viewing graph requires assertions" << "\n";
3130 }
3131 
3132 
3134 #ifndef NDEBUG
3135  std::string Filename = DumpGraph(Nodes);
3136  llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
3137 #endif
3138  llvm::errs() << "Warning: viewing graph requires assertions" << "\n";
3139 }
3140 
3141 std::string ExprEngine::DumpGraph(bool trim, StringRef Filename) {
3142 #ifndef NDEBUG
3143  if (trim) {
3144  std::vector<const ExplodedNode *> Src;
3145 
3146  // Iterate through the reports and get their nodes.
3148  EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
3149  const auto *N = const_cast<ExplodedNode *>(EI->begin()->getErrorNode());
3150  if (N) Src.push_back(N);
3151  }
3152  return DumpGraph(Src, Filename);
3153  } else {
3154  return llvm::WriteGraph(&G, "ExprEngine", /*ShortNames=*/false,
3155  /*Title=*/"Exploded Graph", /*Filename=*/Filename);
3156  }
3157 #endif
3158  llvm::errs() << "Warning: dumping graph requires assertions" << "\n";
3159  return "";
3160 }
3161 
3163  StringRef Filename) {
3164 #ifndef NDEBUG
3165  std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
3166 
3167  if (!TrimmedG.get()) {
3168  llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
3169  } else {
3170  return llvm::WriteGraph(TrimmedG.get(), "TrimmedExprEngine",
3171  /*ShortNames=*/false,
3172  /*Title=*/"Trimmed Exploded Graph",
3173  /*Filename=*/Filename);
3174  }
3175 #endif
3176  llvm::errs() << "Warning: dumping graph requires assertions" << "\n";
3177  return "";
3178 }
3179 
3181  static int index = 0;
3182  return &index;
3183 }
void processEndWorklist() override
Called by CoreEngine when the analysis worklist has terminated.
Definition: ExprEngine.cpp:627
bool isBaseInitializer() const
Determine whether this initializer is initializing a base class.
Definition: DeclCXX.h:2407
Defines the clang::ASTContext interface.
Represents C++ allocator call.
Definition: CFG.h:239
This represents a GCC inline-assembly statement extension.
Definition: Stmt.h:2837
TypedValueRegion - An abstract class representing regions having a typed value.
Definition: MemRegion.h:529
ProgramStateRef processRegionChange(ProgramStateRef state, const MemRegion *MR, const LocationContext *LCtx)
Definition: SubEngine.h:145
Expr * getInit() const
Get the initializer.
Definition: DeclCXX.h:2536
void VisitArraySubscriptExpr(const ArraySubscriptExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitArraySubscriptExpr - Transfer function for array accesses.
void ProcessInitializer(const CFGInitializer I, ExplodedNode *Pred)
Definition: ExprEngine.cpp:820
SVal evalDerivedToBase(SVal Derived, const CastExpr *Cast)
Evaluates a chain of derived-to-base casts through the path specified in Cast.
Definition: Store.cpp:248
A (possibly-)qualified type.
Definition: Type.h:643
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:94
Static storage duration.
Definition: Specifiers.h:309
bool isArrayType() const
Definition: Type.h:6407
void markLive(SymbolRef sym)
Unconditionally marks a symbol as live.
bool isMemberPointerType() const
Definition: Type.h:6389
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2890
void markInfeasible(bool branch)
Definition: CoreEngine.h:465
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:76
const Stmt * getStmt() const
Definition: CFG.h:132
bool IsTemporaryCtorOrDtor
This call is a constructor or a destructor of a temporary value.
Definition: ExprEngine.h:106
bool operator==(CanQual< T > x, CanQual< U > y)
static bool nodeHasBugReport(const ExplodedNode *N)
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C...
Definition: Type.h:6307
unsigned blockCount() const
Returns the number of times the current basic block has been visited on the exploded graph path...
Definition: CoreEngine.h:220
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
Definition: Dominators.h:29
void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitCall - Transfer function for function calls.
Stmt - This represents one statement.
Definition: Stmt.h:66
Information about invalidation for a particular region/symbol.
Definition: MemRegion.h:1439
This builder class is useful for generating nodes that resulted from visiting a statement.
Definition: CoreEngine.h:378
void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE, ExplodedNodeSet &PreVisit, ExplodedNodeSet &Dst)
C Language Family Type Representation.
Defines the SourceManager interface.
static bool nodeHasBugReport(const ExplodedNode *N)
static const Stmt * getRightmostLeaf(const Stmt *Condition)
Expr * getBase() const
Definition: Expr.h:2884
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:88
Represents a point when we begin processing an inlined call.
Definition: ProgramPoint.h:630
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
FunctionDecl * getOperatorNew() const
Definition: ExprCXX.h:2119
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:245
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
ExprEngine(cross_tu::CrossTranslationUnitContext &CTU, AnalysisManager &mgr, SetOfConstDecls *VisitedCalleesIn, FunctionSummariesTy *FS, InliningModes HowToInlineIn)
Definition: ExprEngine.cpp:202
StringRef P
const CastExpr * BasePath
Definition: Expr.h:71
SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc L, NonLoc R, QualType T)
Definition: ExprEngine.h:584
void processBranch(const Stmt *Condition, NodeBuilderContext &BuilderCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF) override
ProcessBranch - Called by CoreEngine.
The pointer has been passed to a function indirectly.
void ViewGraph(bool trim=false)
Visualize the ExplodedGraph created by executing the simulation.
void processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE, NodeBuilderContext &BldCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF) override
Called by CoreEngine.
Represents C++ object destructor generated from a call to delete.
Definition: CFG.h:408
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2829
Hints for figuring out of a call should be inlined during evalCall().
Definition: ExprEngine.h:96
Represents a program point just before an implicit call event.
Definition: ProgramPoint.h:583
bool IsArrayCtorOrDtor
This call is a constructor or a destructor for a single element within an array, a part of array cons...
Definition: ExprEngine.h:103
void ProcessMemberDtor(const CFGMemberDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
StorageDuration
The storage duration for an object (per C++ [basic.stc]).
Definition: Specifiers.h:305
void runCheckersForPrintStateJson(raw_ostream &Out, ProgramStateRef State, const char *NL="\, unsigned int Space=0, bool IsDot=false) const
Run checkers for debug-printing a ProgramState.
T castAs() const
Convert to the specified CFGElement type, asserting that this CFGElement is of the desired type...
Definition: CFG.h:98
const ProgramStateRef & getState() const
DOTGraphTraits(bool isSimple=false)
void processCFGBlockEntrance(const BlockEdge &L, NodeBuilderWithSinks &nodeBuilder, ExplodedNode *Pred) override
Called by CoreEngine when processing the entrance of a CFGBlock.
Represents a point when we exit a loop.
Definition: ProgramPoint.h:713
ProgramStateRef getInitialState(const LocationContext *InitLoc) override
getInitialState - Return the initial state used for the root vertex in the ExplodedGraph.
Definition: ExprEngine.cpp:236
const CXXDestructorDecl * getDestructorDecl(ASTContext &astContext) const
Definition: CFG.cpp:4803
static void printObjectsUnderConstructionJson(raw_ostream &Out, ProgramStateRef State, const char *NL, const LocationContext *LCtx, unsigned int Space=0, bool IsDot=false)
Definition: ExprEngine.cpp:559
bool isIndirectMemberInitializer() const
Definition: DeclCXX.h:2419
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:329
Represents a variable declaration or definition.
Definition: Decl.h:812
ProgramStateRef notifyCheckersOfPointerEscape(ProgramStateRef State, const InvalidatedSymbols *Invalidated, ArrayRef< const MemRegion *> ExplicitRegions, const CallEvent *Call, RegionAndSymbolInvalidationTraits &ITraits) override
Call PointerEscape callback when a value escapes as a result of region invalidation.
ASTContext & getASTContext() const
REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction, ObjectsUnderConstructionMap) static const char *TagProviderName
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6818
void ProcessDeleteDtor(const CFGDeleteDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Definition: ExprEngine.cpp:988
loc::MemRegionVal getCXXThis(const CXXMethodDecl *D, const StackFrameContext *SFC)
Return a memory region for the &#39;this&#39; object reference.
static Optional< SVal > getObjectUnderConstruction(ProgramStateRef State, const ConstructionContextItem &Item, const LocationContext *LC)
By looking at a certain item that may be potentially part of an object&#39;s ConstructionContext, retrieve such object&#39;s location.
Definition: ExprEngine.cpp:478
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.
const ElementRegion * GetElementZeroRegion(const SubRegion *R, QualType T)
Definition: Store.cpp:67
void enqueue(ExplodedNodeSet &Set)
Enqueue the given set of nodes onto the work list.
Definition: CoreEngine.cpp:572
const internal::VariadicDynCastAllOfMatcher< Decl, VarDecl > varDecl
Matches variable declarations.
const Stmt * getTriggerStmt() const
Definition: CFG.h:393
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:37
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:693
ProgramStateRef removeDeadBindings(ProgramStateRef St, const StackFrameContext *LCtx, SymbolReaper &SymReaper)
Represents a parameter to a function.
Definition: Decl.h:1564
Defines the clang::Expr interface and subclasses for C++ expressions.
long i
Definition: xmmintrin.h:1456
void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
BoundNodesTreeBuilder Nodes
static bool shouldRemoveDeadBindings(AnalysisManager &AMgr, const Stmt *S, const ExplodedNode *Pred, const LocationContext *LC)
Definition: ExprEngine.cpp:667
void ProcessTemporaryDtor(const CFGTemporaryDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void ProcessLoopExit(const Stmt *S, ExplodedNode *Pred)
Definition: ExprEngine.cpp:802
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
bool haveEqualEnvironments(ProgramStateRef S1, ProgramStateRef S2) const
Definition: ProgramState.h:560
ProgramStateRef runCheckersForPointerEscape(ProgramStateRef State, const InvalidatedSymbols &Escaped, const CallEvent *Call, PointerEscapeKind Kind, RegionAndSymbolInvalidationTraits *ITraits)
Run checkers when pointers escape.
One of these records is kept for each identifier that is lexed.
A pointer escapes due to binding its value to a location that the analyzer cannot track...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
LineState State
void runCheckersForLiveSymbols(ProgramStateRef state, SymbolReaper &SymReaper)
Run checkers for live symbols.
void printJson(raw_ostream &Out, PrinterHelper *Helper, const PrintingPolicy &Policy, bool AddQuotes) const
Pretty-prints in JSON format.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:263
Represents a member of a struct/union/class.
Definition: Decl.h:2605
Represents a program point after a store evaluation.
Definition: ProgramPoint.h:431
Represents C++ object destructor implicitly generated for automatic object or temporary bound to cons...
Definition: CFG.h:383
bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2) const
Definition: ProgramState.h:564
ProgramStateRef processLoopEnd(const Stmt *LoopStmt, ProgramStateRef State)
Updates the given ProgramState.
bool isReferenceType() const
Definition: Type.h:6363
void ProcessImplicitDtor(const CFGImplicitDtor D, ExplodedNode *Pred)
Definition: ExprEngine.cpp:908
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:2156
void addPredecessor(ExplodedNode *V, ExplodedGraph &G)
addPredeccessor - Adds a predecessor to the current node, and in tandem add this node as a successor ...
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
const StackFrameContext * getStackFrame() const
Definition: ProgramPoint.h:183
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6714
void enableNodeReclamation(unsigned Interval)
Enable tracking of recently allocated nodes for potential reclamation when calling reclaimRecentlyAll...
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:261
static bool isLocType(QualType T)
Definition: SVals.h:329
void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitOffsetOfExpr - Transfer function for offsetof.
This is a meta program point, which should be skipped by all the diagnostic reasoning etc...
Definition: ProgramPoint.h:732
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:417
enum clang::SubobjectAdjustment::@47 Kind
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:1304
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
STATISTIC(NumRemoveDeadBindings, "The # of times RemoveDeadBindings is called")
const LocationContext * getLocationContext() const
ExplodedNode * generateCaseStmtNode(const iterator &I, ProgramStateRef State)
Definition: CoreEngine.cpp:662
virtual bool inTopFrame() const
Return true if the current LocationContext has no caller context.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:657
static bool isRecordType(QualType T)
const LocationContext * getParent() const
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3405
bool isUnknown() const
Definition: SVals.h:136
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.
const VarDecl * getVarDecl() const
Definition: CFG.h:388
CaseStmt - Represent a case statement.
Definition: Stmt.h:1463
const CXXBaseSpecifier * getBaseSpecifier() const
Definition: CFG.h:439
bool isAnyMemberInitializer() const
Definition: DeclCXX.h:2415
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:63
void ProcessNewAllocator(const CXXNewExpr *NE, ExplodedNode *Pred)
Definition: ExprEngine.cpp:935
void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Definition: ExprEngine.cpp:954
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1277
virtual SVal getLValueField(const FieldDecl *D, SVal Base)
Definition: Store.h:145
FieldDecl * getAnyMember() const
Definition: DeclCXX.h:2480
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:1736
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition: DeclCXX.h:2474
RangeSelector node(std::string ID)
Selects a node, including trailing semicolon (for non-expression statements).
void runCheckersForEndFunction(NodeBuilderContext &BC, ExplodedNodeSet &Dst, ExplodedNode *Pred, ExprEngine &Eng, const ReturnStmt *RS)
Run checkers on end of function.
reverse_iterator rend()
Definition: CFG.h:727
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:190
void VisitLogicalExpr(const BinaryOperator *B, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitLogicalExpr - Transfer function logic for &#39;&&&#39;, &#39;||&#39;.
bool isArrayForm() const
Definition: ExprCXX.h:2287
CXXCtorInitializer * getInitializer() const
Definition: CFG.h:224
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.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1636
const FieldDecl * getFieldDecl() const
Definition: CFG.h:460
const Stmt * getCallSite() const
Expr ** getSubExprs()
Definition: Expr.h:5864
void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, ExplodedNodeSet &Dst)
bool isDelegatingInitializer() const
Determine whether this initializer is creating a delegating constructor.
Definition: DeclCXX.h:2435
StringRef Filename
Definition: Format.cpp:1709
const CXXBindTemporaryExpr * getBindTemporaryExpr() const
Definition: CFG.h:481
Represents a single basic block in a source-level CFG.
Definition: CFG.h:570
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:87
SymbolicRegion - A special, "non-concrete" region.
Definition: MemRegion.h:763
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:4447
void ProcessBaseDtor(const CFGBaseDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
DefinedOrUnknownSVal makeZeroVal(QualType type)
Construct an SVal representing &#39;0&#39; for the specified type.
Definition: SValBuilder.cpp:52
void processSwitch(SwitchNodeBuilder &builder) override
ProcessSwitch - Called by CoreEngine.
void processBeginOfFunction(NodeBuilderContext &BC, ExplodedNode *Pred, ExplodedNodeSet &Dst, const BlockEdge &L) override
Called by CoreEngine.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:636
This represents one expression.
Definition: Expr.h:108
Defines the clang::LangOptions interface.
void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Transfer function logic for computing the lvalue of an Objective-C ivar.
void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXNewAllocatorCall(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
const Expr * getCondition() const
Definition: CoreEngine.h:570
CallEventRef getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State)
Gets an outside caller given a callee context.
Definition: CallEvent.cpp:1362
void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitCast - Transfer function logic for all casts (implicit and explicit).
#define V(N, I)
Definition: ASTContext.h:2907
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2830
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
This is the simplest builder which generates nodes in the ExplodedGraph.
Definition: CoreEngine.h:236
void Add(ExplodedNode *N)
The pointer has been passed to a function call directly.
struct DTB DerivedToBase
Definition: Expr.h:81
Expr * getRHS()
Definition: Stmt.h:1564
QualType getConditionType() const
Definition: SValBuilder.h:160
bool isValid() const
Definition: SVals.h:148
const LocationContext * getLocationContext() const
Definition: CoreEngine.h:574
bool inTopFrame() const override
Return true if the current LocationContext has no caller context.
void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Visit - Transfer function logic for all statements.
void FlushReports()
Generate and flush diagnostics for all bug reports.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static std::pair< const ProgramPointTag *, const ProgramPointTag * > geteagerlyAssumeBinOpBifurcationTags()
QualType getType() const
Definition: Expr.h:137
The reason for pointer escape is unknown.
ASTContext & getContext() const
getContext - Return the ASTContext associated with this analysis.
Definition: ExprEngine.h:182
Traits for storing the call processing policy inside GDM.
Definition: ExprEngine.h:859
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1772
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
Definition: Stmt.h:2595
void VisitAtomicExpr(const AtomicExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitAtomicExpr - Transfer function for builtin atomic expressions.
This represents a Microsoft inline-assembly statement extension.
Definition: Stmt.h:3060
const SwitchStmt * getSwitch() const
Definition: CoreEngine.h:560
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.
Represents C++ object destructor implicitly generated for base object in destructor.
Definition: CFG.h:434
QualType getDestroyedType() const
Retrieve the type being destroyed.
Definition: ExprCXX.cpp:224
const Expr * getSubExpr() const
Definition: ExprCXX.h:1300
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:708
reverse_iterator rbegin()
Definition: CFG.h:726
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:111
const MemRegion * getRegion() const
Get the underlining region.
Definition: SVals.h:605
ExplodedNode * generateNode(const iterator &I, ProgramStateRef State, bool isSink=false)
Definition: CoreEngine.cpp:643
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.
Thread storage duration.
Definition: Specifiers.h:308
Expr * getArgument()
Definition: ExprCXX.h:2302
static const Stmt * ResolveCondition(const Stmt *Condition, const CFGBlock *B)
Kind getKind() const
Definition: CFG.h:118
void processCFGElement(const CFGElement E, ExplodedNode *Pred, unsigned StmtIdx, NodeBuilderContext *Ctx) override
processCFGElement - Called by CoreEngine.
Definition: ExprEngine.cpp:631
ProgramStateRef getInitialState(const LocationContext *InitLoc)
const LocationContext * getLocationContext() const
Definition: CoreEngine.h:520
const Stmt * getStmt() const
Definition: ProgramPoint.h:279
void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitGuardedExpr - Transfer function logic for ?, __builtin_choose.
void printJson(raw_ostream &Out, ProgramStateRef State, const LocationContext *LCtx, const char *NL, unsigned int Space, bool IsDot) const override
printJson - Called by ProgramStateManager to print checker-specific data.
Definition: ExprEngine.cpp:605
DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag, const Expr *expr, const LocationContext *LCtx, unsigned count)
Create a new symbol with a unique &#39;name&#39;.
ProgramStateRef getWidenedLoopState(ProgramStateRef PrevState, const LocationContext *LCtx, unsigned BlockCount, const Stmt *LoopStmt)
Get the states that result from widening the loop.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4449
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:441
ProgramPoints can be "tagged" as representing points specific to a given analysis entity...
Definition: ProgramPoint.h:39
AnalysisManager & getAnalysisManager() override
Definition: ExprEngine.h:184
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:291
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:151
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
Definition: ExprCXX.h:2000
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2240
Expr * getLHS()
Definition: Stmt.h:1552
CallEventManager & getCallEventManager()
Definition: ProgramState.h:526
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
Definition: Stmt.h:1203
void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitCompoundLiteralExpr - Transfer function logic for compound literals.
Represents the declaration of a label.
Definition: Decl.h:468
ExplodedNode * generateNode(ProgramStateRef State, ExplodedNode *Pred, const ProgramPointTag *Tag=nullptr)
Definition: CoreEngine.h:353
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:1044
Expr * getCond()
Definition: Stmt.h:2062
void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
bool IsCtorOrDtorWithImproperlyModeledTargetRegion
This call is a constructor or a destructor for which we do not currently compute the this-region corr...
Definition: ExprEngine.h:99
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:75
int64_t getID(const ASTContext &Context) const
Definition: Stmt.cpp:288
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
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:5797
CanQualType VoidTy
Definition: ASTContext.h:1014
void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof.
ProgramStateRef runCheckersForEvalAssume(ProgramStateRef state, SVal Cond, bool Assumption)
Run checkers for handling assumptions on symbolic values.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3245
BugReporter & getBugReporter()
Definition: ExprEngine.h:196
void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitObjCForCollectionStmt - Transfer function logic for ObjCForCollectionStmt.
A class responsible for cleaning up unused symbols.
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
void runCheckersForPreStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng)
Run checkers for pre-visiting Stmts.
bool isVectorType() const
Definition: Type.h:6443
bool isStmtBranch() const
Definition: CFG.h:533
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:109
Defines various enumerations that describe declaration and type specifiers.
StringRef getName() const
Return the actual identifier string.
ast_type_traits::DynTypedNode Node
CanQualType CharTy
Definition: ASTContext.h:1016
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.
void ProcessStmt(const Stmt *S, ExplodedNode *Pred)
Definition: ExprEngine.cpp:772
ExplodedNode * generateDefaultCaseNode(ProgramStateRef State, bool isSink=false)
Definition: CoreEngine.cpp:677
SValBuilder & getSValBuilder()
Definition: ExprEngine.h:194
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
Definition: ExprCXX.h:2260
void addNodes(const ExplodedNodeSet &S)
Definition: CoreEngine.h:335
StoreManager & getStoreManager()
Definition: ExprEngine.h:386
Represents a program point just after an implicit call event.
Definition: ProgramPoint.h:600
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:547
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition: DeclCXX.cpp:2354
void VisitCXXDestructor(QualType ObjectType, const MemRegion *Dest, const Stmt *S, bool IsBaseDtor, ExplodedNode *Pred, ExplodedNodeSet &Dst, const EvalCallOptions &Options)
const NodeBuilderContext & getContext()
Definition: CoreEngine.h:326
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
This node builder keeps track of the generated sink nodes.
Definition: CoreEngine.h:341
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:1087
void reclaimRecentlyAllocatedNodes()
Reclaim "uninteresting" nodes created since the last time this method was called. ...
void VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitLambdaExpr - Transfer function logic for LambdaExprs.
const Decl * getSingleDecl() const
Definition: Stmt.h:1218
Represents symbolic expression that isn&#39;t a location.
Definition: SVals.h:349
Stmt * getTerminatorStmt()
Definition: CFG.h:860
BranchNodeBuilder is responsible for constructing the nodes corresponding to the two branches of the ...
Definition: CoreEngine.h:430
Represents an abstract call to a function or method along a particular path.
Definition: CallEvent.h:170
ProgramStateRef getState() const
Definition: CoreEngine.h:572
const Stmt * getLoopStmt() const
Definition: CFG.h:269
ProgramStateManager & getStateManager() override
Definition: ExprEngine.h:384
This class is used for tools that requires cross translation unit capability.
const Decl * getDecl() const
const CXXDeleteExpr * getDeleteExpr() const
Definition: CFG.h:418
Represents a single point (AST node) in the program that requires attention during construction of an...
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:2941
const CXXTempObjectRegion * getCXXStaticTempObjectRegion(const Expr *Ex)
Create a CXXTempObjectRegion for temporaries which are lifetime-extended by static references...
Definition: MemRegion.cpp:967
PointerEscapeKind
Describes the different reasons a pointer escapes during analysis.
SwitchStmt - This represents a &#39;switch&#39; stmt.
Definition: Stmt.h:2002
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2311
unsigned getIntWidth(QualType T) const
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2933
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:103
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2432
ExplodedNode * generateSink(ProgramStateRef State, ExplodedNode *Pred, const ProgramPointTag *Tag=nullptr)
Definition: CoreEngine.h:360
SubRegion - A region that subsets another larger region.
Definition: MemRegion.h:435
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2338
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:2488
const LocationContext * getLocationContext() const
Definition: ProgramPoint.h:179
void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred, ExplodedNodeSet &Dst)
bool hasStackStorage() const
Definition: MemRegion.cpp:1140
const StackFrameContext * getStackFrame() const
void printJson(raw_ostream &Out, const char *NL="\, unsigned int Space=0, bool IsDot=false, std::function< void(const LocationContext *)> printMoreInfoPerContext=[](const LocationContext *) {}) const
llvm::FoldingSet< BugReportEquivClass >::iterator EQClasses_iterator
Iterator over the set of BugReports tracked by the BugReporter.
Definition: BugReporter.h:467
Represents a base class of a C++ class.
Definition: DeclCXX.h:192
Stores options for the analyzer from the command line.
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:1416
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2079
outputs_range outputs()
Definition: Stmt.h:2811
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:14134
ExplodedNode * generateNode(const ProgramPoint &PP, ProgramStateRef State, ExplodedNode *Pred)
Generates a node in the ExplodedGraph.
Definition: CoreEngine.h:289
const CXXNewExpr * getAllocatorExpr() const
Definition: CFG.h:245
void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitBlockExpr - Transfer function logic for BlockExprs.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2807
Defines the clang::SourceLocation class and associated facilities.
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
bool isVoidType() const
Definition: Type.h:6610
Represents C++ object destructor implicitly generated by compiler on various occasions.
Definition: CFG.h:358
ProgramStateRef getState() const
Definition: CoreEngine.h:518
pred_iterator pred_begin()
ExplodedNode * generateNode(ProgramStateRef State, bool branch, ExplodedNode *Pred)
Definition: CoreEngine.cpp:629
Represents a top-level expression in a basic block.
Definition: CFG.h:55
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2408
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:541
Represents C++ object destructor implicitly generated for member object in destructor.
Definition: CFG.h:455
const MemRegion * getBaseRegion() const
Definition: MemRegion.cpp:1160
FieldDecl * Field
Definition: Expr.h:82
ExplodedNode * generateNode(const Stmt *S, ExplodedNode *Pred, ProgramStateRef St, const ProgramPointTag *tag=nullptr, ProgramPoint::Kind K=ProgramPoint::PostStmtKind)
Definition: CoreEngine.h:407
bool isUndef() const
Definition: SVals.h:140
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:943
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.
std::string DumpGraph(bool trim=false, StringRef Filename="")
Dump graph to the specified filename.
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.
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition: JsonSupport.h:19
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1141
result[0]
Definition: emmintrin.h:120
Represents C++ base or member initializer from constructor&#39;s initialization list. ...
Definition: CFG.h:219
void VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitGCCAsmStmt - Transfer function logic for inline asm.
const StackFrameContext * getStackFrame() const
void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitMemberExpr - Transfer function for member expressions.
QualType getType() const
Definition: Decl.h:647
ProgramStateRef escapeValue(ProgramStateRef State, SVal V, PointerEscapeKind K) const
A simple wrapper when you only need to notify checkers of pointer-escape of a single value...
llvm::ImmutableMap< ConstructedObjectKey, SVal > ObjectsUnderConstructionMap
Definition: ExprEngine.cpp:192
This represents a decl that may have a name.
Definition: Decl.h:248
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:388
void VisitBinaryOperator(const BinaryOperator *B, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitBinaryOperator - Transfer function logic for binary operators.
Definition: ExprEngineC.cpp:40
CFGTerminator getTerminator() const
Definition: CFG.h:858
AnalysisDeclContext * getAnalysisDeclContext() const
bool isFeasible(bool branch)
Definition: CoreEngine.h:472
void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Create a C++ temporary object for an rvalue.
static SVal RecoverCastedSymbol(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...
const Expr * getTarget() const
Definition: CoreEngine.h:516
Represents C++ object destructor implicitly generated at the end of full expression for temporary obj...
Definition: CFG.h:476
const CFGBlock * getBlock() const
Return the CFGBlock associated with this builder.
Definition: CoreEngine.h:216
int64_t getID(const ASTContext &Context) const
Definition: DeclCXX.cpp:2335
bool isUnknownOrUndef() const
Definition: SVals.h:144
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2937
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:291
Represents the point where a loop ends.
Definition: CFG.h:265