clang  8.0.0svn
ExprEngine.h
Go to the documentation of this file.
1 //===- ExprEngine.h - Path-Sensitive Expression-Level Dataflow --*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a meta-engine for path-sensitive dataflow analysis that
11 // is built on CoreEngine, but provides the boilerplate to execute transfer
12 // functions and build the ExplodedGraph at the expression level.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H
17 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H
18 
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/Type.h"
21 #include "clang/Analysis/CFG.h"
24 #include "clang/Basic/LLVM.h"
36 #include "llvm/ADT/ArrayRef.h"
37 #include <cassert>
38 #include <utility>
39 
40 namespace clang {
41 
42 class AnalysisDeclContextManager;
43 class AnalyzerOptions;
44 class ASTContext;
45 class ConstructionContext;
46 class CXXBindTemporaryExpr;
47 class CXXCatchStmt;
48 class CXXConstructExpr;
49 class CXXDeleteExpr;
50 class CXXNewExpr;
51 class CXXThisExpr;
52 class Decl;
53 class DeclStmt;
54 class GCCAsmStmt;
55 class LambdaExpr;
56 class LocationContext;
57 class MaterializeTemporaryExpr;
58 class MSAsmStmt;
59 class NamedDecl;
60 class ObjCAtSynchronizedStmt;
61 class ObjCForCollectionStmt;
62 class ObjCIvarRefExpr;
63 class ObjCMessageExpr;
64 class ReturnStmt;
65 class Stmt;
66 
67 namespace cross_tu {
68 
69 class CrossTranslationUnitContext;
70 
71 } // namespace cross_tu
72 
73 namespace ento {
74 
75 class BasicValueFactory;
76 class CallEvent;
77 class CheckerManager;
78 class ConstraintManager;
79 class CXXTempObjectRegion;
80 class MemRegion;
81 class RegionAndSymbolInvalidationTraits;
82 class SymbolManager;
83 
84 class ExprEngine : public SubEngine {
85 public:
86  /// The modes of inlining, which override the default analysis-wide settings.
88  /// Follow the default settings for inlining callees.
89  Inline_Regular = 0,
90 
91  /// Do minimal inlining of callees.
92  Inline_Minimal = 0x1
93  };
94 
95  /// Hints for figuring out of a call should be inlined during evalCall().
96  struct EvalCallOptions {
97  /// This call is a constructor or a destructor for which we do not currently
98  /// compute the this-region correctly.
99  bool IsCtorOrDtorWithImproperlyModeledTargetRegion = false;
100 
101  /// This call is a constructor or a destructor for a single element within
102  /// an array, a part of array construction or destruction.
103  bool IsArrayCtorOrDtor = false;
104 
105  /// This call is a constructor or a destructor of a temporary value.
106  bool IsTemporaryCtorOrDtor = false;
107 
108  /// This call is a constructor for a temporary that is lifetime-extended
109  /// by binding it to a reference-type field within an aggregate,
110  /// for example 'A { const C &c; }; A a = { C() };'
111  bool IsTemporaryLifetimeExtendedViaAggregate = false;
112 
114  };
115 
116 private:
118 
119  AnalysisManager &AMgr;
120 
121  AnalysisDeclContextManager &AnalysisDeclContexts;
122 
123  CoreEngine Engine;
124 
125  /// G - the simulation graph.
126  ExplodedGraph &G;
127 
128  /// StateMgr - Object that manages the data for all created states.
129  ProgramStateManager StateMgr;
130 
131  /// SymMgr - Object that manages the symbol information.
132  SymbolManager &SymMgr;
133 
134  /// svalBuilder - SValBuilder object that creates SVals from expressions.
135  SValBuilder &svalBuilder;
136 
137  unsigned int currStmtIdx = 0;
138  const NodeBuilderContext *currBldrCtx = nullptr;
139 
140  /// Helper object to determine if an Objective-C message expression
141  /// implicitly never returns.
142  ObjCNoReturn ObjCNoRet;
143 
144  /// The BugReporter associated with this engine. It is important that
145  /// this object be placed at the very end of member variables so that its
146  /// destructor is called before the rest of the ExprEngine is destroyed.
147  GRBugReporter BR;
148 
149  /// The functions which have been analyzed through inlining. This is owned by
150  /// AnalysisConsumer. It can be null.
151  SetOfConstDecls *VisitedCallees;
152 
153  /// The flag, which specifies the mode of inlining for the engine.
154  InliningModes HowToInline;
155 
156 public:
158  SetOfConstDecls *VisitedCalleesIn,
159  FunctionSummariesTy *FS, InliningModes HowToInlineIn);
160 
161  ~ExprEngine() override;
162 
163  /// Returns true if there is still simulation state on the worklist.
164  bool ExecuteWorkList(const LocationContext *L, unsigned Steps = 150000) {
165  return Engine.ExecuteWorkList(L, Steps, nullptr);
166  }
167 
168  /// Execute the work list with an initial state. Nodes that reaches the exit
169  /// of the function are added into the Dst set, which represent the exit
170  /// state of the function call. Returns true if there is still simulation
171  /// state on the worklist.
172  bool ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps,
173  ProgramStateRef InitState,
174  ExplodedNodeSet &Dst) {
175  return Engine.ExecuteWorkListWithInitialState(L, Steps, InitState, Dst);
176  }
177 
178  /// getContext - Return the ASTContext associated with this analysis.
179  ASTContext &getContext() const { return AMgr.getASTContext(); }
180 
181  AnalysisManager &getAnalysisManager() override { return AMgr; }
182 
184  return *AMgr.getCheckerManager();
185  }
186 
187  SValBuilder &getSValBuilder() { return svalBuilder; }
188 
189  BugReporter &getBugReporter() { return BR; }
190 
193  return &CTU;
194  }
195 
197  assert(currBldrCtx);
198  return *currBldrCtx;
199  }
200 
201  const Stmt *getStmt() const;
202 
203  void GenerateAutoTransition(ExplodedNode *N);
204  void enqueueEndOfPath(ExplodedNodeSet &S);
205  void GenerateCallExitNode(ExplodedNode *N);
206 
207 
208  /// Dump graph to the specified filename.
209  /// If filename is empty, generate a temporary one.
210  /// \return The filename the graph is written into.
211  std::string DumpGraph(bool trim = false, StringRef Filename="");
212 
213  /// Dump the graph consisting of the given nodes to a specified filename.
214  /// Generate a temporary filename if it's not provided.
215  /// \return The filename the graph is written into.
216  std::string DumpGraph(ArrayRef<const ExplodedNode *> Nodes,
217  StringRef Filename = "");
218 
219  /// Visualize the ExplodedGraph created by executing the simulation.
220  void ViewGraph(bool trim = false);
221 
222  /// Visualize a trimmed ExplodedGraph that only contains paths to the given
223  /// nodes.
224  void ViewGraph(ArrayRef<const ExplodedNode *> Nodes);
225 
226  /// getInitialState - Return the initial state used for the root vertex
227  /// in the ExplodedGraph.
228  ProgramStateRef getInitialState(const LocationContext *InitLoc) override;
229 
230  ExplodedGraph &getGraph() { return G; }
231  const ExplodedGraph &getGraph() const { return G; }
232 
233  /// Run the analyzer's garbage collection - remove dead symbols and
234  /// bindings from the state.
235  ///
236  /// Checkers can participate in this process with two callbacks:
237  /// \c checkLiveSymbols and \c checkDeadSymbols. See the CheckerDocumentation
238  /// class for more information.
239  ///
240  /// \param Node The predecessor node, from which the processing should start.
241  /// \param Out The returned set of output nodes.
242  /// \param ReferenceStmt The statement which is about to be processed.
243  /// Everything needed for this statement should be considered live.
244  /// A null statement means that everything in child LocationContexts
245  /// is dead.
246  /// \param LC The location context of the \p ReferenceStmt. A null location
247  /// context means that we have reached the end of analysis and that
248  /// all statements and local variables should be considered dead.
249  /// \param DiagnosticStmt Used as a location for any warnings that should
250  /// occur while removing the dead (e.g. leaks). By default, the
251  /// \p ReferenceStmt is used.
252  /// \param K Denotes whether this is a pre- or post-statement purge. This
253  /// must only be ProgramPoint::PostStmtPurgeDeadSymbolsKind if an
254  /// entire location context is being cleared, in which case the
255  /// \p ReferenceStmt must either be a ReturnStmt or \c NULL. Otherwise,
256  /// it must be ProgramPoint::PreStmtPurgeDeadSymbolsKind (the default)
257  /// and \p ReferenceStmt must be valid (non-null).
258  void removeDead(ExplodedNode *Node, ExplodedNodeSet &Out,
259  const Stmt *ReferenceStmt, const LocationContext *LC,
260  const Stmt *DiagnosticStmt = nullptr,
262 
263  /// processCFGElement - Called by CoreEngine. Used to generate new successor
264  /// nodes by processing the 'effects' of a CFG element.
265  void processCFGElement(const CFGElement E, ExplodedNode *Pred,
266  unsigned StmtIdx, NodeBuilderContext *Ctx) override;
267 
268  void ProcessStmt(const Stmt *S, ExplodedNode *Pred);
269 
270  void ProcessLoopExit(const Stmt* S, ExplodedNode *Pred);
271 
272  void ProcessInitializer(const CFGInitializer I, ExplodedNode *Pred);
273 
274  void ProcessImplicitDtor(const CFGImplicitDtor D, ExplodedNode *Pred);
275 
276  void ProcessNewAllocator(const CXXNewExpr *NE, ExplodedNode *Pred);
277 
278  void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D,
279  ExplodedNode *Pred, ExplodedNodeSet &Dst);
280  void ProcessDeleteDtor(const CFGDeleteDtor D,
281  ExplodedNode *Pred, ExplodedNodeSet &Dst);
282  void ProcessBaseDtor(const CFGBaseDtor D,
283  ExplodedNode *Pred, ExplodedNodeSet &Dst);
284  void ProcessMemberDtor(const CFGMemberDtor D,
285  ExplodedNode *Pred, ExplodedNodeSet &Dst);
286  void ProcessTemporaryDtor(const CFGTemporaryDtor D,
287  ExplodedNode *Pred, ExplodedNodeSet &Dst);
288 
289  /// Called by CoreEngine when processing the entrance of a CFGBlock.
290  void processCFGBlockEntrance(const BlockEdge &L,
291  NodeBuilderWithSinks &nodeBuilder,
292  ExplodedNode *Pred) override;
293 
294  /// ProcessBranch - Called by CoreEngine. Used to generate successor
295  /// nodes by processing the 'effects' of a branch condition.
296  void processBranch(const Stmt *Condition,
297  NodeBuilderContext& BuilderCtx,
298  ExplodedNode *Pred,
299  ExplodedNodeSet &Dst,
300  const CFGBlock *DstT,
301  const CFGBlock *DstF) override;
302 
303  /// Called by CoreEngine.
304  /// Used to generate successor nodes for temporary destructors depending
305  /// on whether the corresponding constructor was visited.
306  void processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
307  NodeBuilderContext &BldCtx,
308  ExplodedNode *Pred, ExplodedNodeSet &Dst,
309  const CFGBlock *DstT,
310  const CFGBlock *DstF) override;
311 
312  /// Called by CoreEngine. Used to processing branching behavior
313  /// at static initializers.
314  void processStaticInitializer(const DeclStmt *DS,
315  NodeBuilderContext& BuilderCtx,
316  ExplodedNode *Pred,
317  ExplodedNodeSet &Dst,
318  const CFGBlock *DstT,
319  const CFGBlock *DstF) override;
320 
321  /// processIndirectGoto - Called by CoreEngine. Used to generate successor
322  /// nodes by processing the 'effects' of a computed goto jump.
323  void processIndirectGoto(IndirectGotoNodeBuilder& builder) override;
324 
325  /// ProcessSwitch - Called by CoreEngine. Used to generate successor
326  /// nodes by processing the 'effects' of a switch statement.
327  void processSwitch(SwitchNodeBuilder& builder) override;
328 
329  /// Called by CoreEngine. Used to notify checkers that processing a
330  /// function has begun. Called for both inlined and and top-level functions.
331  void processBeginOfFunction(NodeBuilderContext &BC,
332  ExplodedNode *Pred, ExplodedNodeSet &Dst,
333  const BlockEdge &L) override;
334 
335  /// Called by CoreEngine. Used to notify checkers that processing a
336  /// function has ended. Called for both inlined and and top-level functions.
337  void processEndOfFunction(NodeBuilderContext& BC,
338  ExplodedNode *Pred,
339  const ReturnStmt *RS = nullptr) override;
340 
341  /// Remove dead bindings/symbols before exiting a function.
342  void removeDeadOnEndOfFunction(NodeBuilderContext& BC,
343  ExplodedNode *Pred,
344  ExplodedNodeSet &Dst);
345 
346  /// Generate the entry node of the callee.
347  void processCallEnter(NodeBuilderContext& BC, CallEnter CE,
348  ExplodedNode *Pred) override;
349 
350  /// Generate the sequence of nodes that simulate the call exit and the post
351  /// visit for CallExpr.
352  void processCallExit(ExplodedNode *Pred) override;
353 
354  /// Called by CoreEngine when the analysis worklist has terminated.
355  void processEndWorklist() override;
356 
357  /// evalAssume - Callback function invoked by the ConstraintManager when
358  /// making assumptions about state values.
359  ProgramStateRef processAssume(ProgramStateRef state, SVal cond,
360  bool assumption) override;
361 
362  /// processRegionChanges - Called by ProgramStateManager whenever a change is made
363  /// to the store. Used to update checkers that track region values.
365  processRegionChanges(ProgramStateRef state,
366  const InvalidatedSymbols *invalidated,
367  ArrayRef<const MemRegion *> ExplicitRegions,
369  const LocationContext *LCtx,
370  const CallEvent *Call) override;
371 
372  /// printState - Called by ProgramStateManager to print checker-specific data.
373  void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
374  const char *Sep,
375  const LocationContext *LCtx = nullptr) override;
376 
377  ProgramStateManager &getStateManager() override { return StateMgr; }
378 
379  StoreManager &getStoreManager() { return StateMgr.getStoreManager(); }
380 
382  return StateMgr.getConstraintManager();
383  }
384 
385  // FIXME: Remove when we migrate over to just using SValBuilder.
387  return StateMgr.getBasicVals();
388  }
389 
390  // FIXME: Remove when we migrate over to just using ValueManager.
391  SymbolManager &getSymbolManager() { return SymMgr; }
392  const SymbolManager &getSymbolManager() const { return SymMgr; }
393 
394  // Functions for external checking of whether we have unfinished work
395  bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); }
396  bool hasEmptyWorkList() const { return !Engine.getWorkList()->hasWork(); }
397  bool hasWorkRemaining() const { return Engine.hasWorkRemaining(); }
398 
399  const CoreEngine &getCoreEngine() const { return Engine; }
400 
401 public:
402  /// Visit - Transfer function logic for all statements. Dispatches to
403  /// other functions that handle specific kinds of statements.
404  void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst);
405 
406  /// VisitArraySubscriptExpr - Transfer function for array accesses.
407  void VisitArraySubscriptExpr(const ArraySubscriptExpr *Ex,
408  ExplodedNode *Pred,
409  ExplodedNodeSet &Dst);
410 
411  /// VisitGCCAsmStmt - Transfer function logic for inline asm.
412  void VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
413  ExplodedNodeSet &Dst);
414 
415  /// VisitMSAsmStmt - Transfer function logic for MS inline asm.
416  void VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
417  ExplodedNodeSet &Dst);
418 
419  /// VisitBlockExpr - Transfer function logic for BlockExprs.
420  void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
421  ExplodedNodeSet &Dst);
422 
423  /// VisitLambdaExpr - Transfer function logic for LambdaExprs.
424  void VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred,
425  ExplodedNodeSet &Dst);
426 
427  /// VisitBinaryOperator - Transfer function logic for binary operators.
428  void VisitBinaryOperator(const BinaryOperator* B, ExplodedNode *Pred,
429  ExplodedNodeSet &Dst);
430 
431 
432  /// VisitCall - Transfer function for function calls.
433  void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
434  ExplodedNodeSet &Dst);
435 
436  /// VisitCast - Transfer function logic for all casts (implicit and explicit).
437  void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred,
438  ExplodedNodeSet &Dst);
439 
440  /// VisitCompoundLiteralExpr - Transfer function logic for compound literals.
441  void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
442  ExplodedNode *Pred, ExplodedNodeSet &Dst);
443 
444  /// Transfer function logic for DeclRefExprs and BlockDeclRefExprs.
445  void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D,
446  ExplodedNode *Pred, ExplodedNodeSet &Dst);
447 
448  /// VisitDeclStmt - Transfer function logic for DeclStmts.
449  void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
450  ExplodedNodeSet &Dst);
451 
452  /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose
453  void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R,
454  ExplodedNode *Pred, ExplodedNodeSet &Dst);
455 
456  void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred,
457  ExplodedNodeSet &Dst);
458 
459  /// VisitLogicalExpr - Transfer function logic for '&&', '||'
460  void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
461  ExplodedNodeSet &Dst);
462 
463  /// VisitMemberExpr - Transfer function for member expressions.
464  void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
465  ExplodedNodeSet &Dst);
466 
467  /// VisitAtomicExpr - Transfer function for builtin atomic expressions
468  void VisitAtomicExpr(const AtomicExpr *E, ExplodedNode *Pred,
469  ExplodedNodeSet &Dst);
470 
471  /// Transfer function logic for ObjCAtSynchronizedStmts.
472  void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
473  ExplodedNode *Pred, ExplodedNodeSet &Dst);
474 
475  /// Transfer function logic for computing the lvalue of an Objective-C ivar.
476  void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred,
477  ExplodedNodeSet &Dst);
478 
479  /// VisitObjCForCollectionStmt - Transfer function logic for
480  /// ObjCForCollectionStmt.
481  void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S,
482  ExplodedNode *Pred, ExplodedNodeSet &Dst);
483 
484  void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred,
485  ExplodedNodeSet &Dst);
486 
487  /// VisitReturnStmt - Transfer function logic for return statements.
488  void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred,
489  ExplodedNodeSet &Dst);
490 
491  /// VisitOffsetOfExpr - Transfer function for offsetof.
492  void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred,
493  ExplodedNodeSet &Dst);
494 
495  /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof.
496  void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
497  ExplodedNode *Pred, ExplodedNodeSet &Dst);
498 
499  /// VisitUnaryOperator - Transfer function logic for unary operators.
500  void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode *Pred,
501  ExplodedNodeSet &Dst);
502 
503  /// Handle ++ and -- (both pre- and post-increment).
504  void VisitIncrementDecrementOperator(const UnaryOperator* U,
505  ExplodedNode *Pred,
506  ExplodedNodeSet &Dst);
507 
508  void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE,
509  ExplodedNodeSet &PreVisit,
510  ExplodedNodeSet &Dst);
511 
512  void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred,
513  ExplodedNodeSet &Dst);
514 
515  void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
516  ExplodedNodeSet & Dst);
517 
518  void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred,
519  ExplodedNodeSet &Dst);
520 
521  void VisitCXXDestructor(QualType ObjectType, const MemRegion *Dest,
522  const Stmt *S, bool IsBaseDtor,
523  ExplodedNode *Pred, ExplodedNodeSet &Dst,
524  const EvalCallOptions &Options);
525 
526  void VisitCXXNewAllocatorCall(const CXXNewExpr *CNE,
527  ExplodedNode *Pred,
528  ExplodedNodeSet &Dst);
529 
530  void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
531  ExplodedNodeSet &Dst);
532 
533  void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred,
534  ExplodedNodeSet &Dst);
535 
536  /// Create a C++ temporary object for an rvalue.
537  void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
538  ExplodedNode *Pred,
539  ExplodedNodeSet &Dst);
540 
541  /// evalEagerlyAssumeBinOpBifurcation - Given the nodes in 'Src', eagerly assume symbolic
542  /// expressions of the form 'x != 0' and generate new nodes (stored in Dst)
543  /// with those assumptions.
544  void evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, ExplodedNodeSet &Src,
545  const Expr *Ex);
546 
547  static std::pair<const ProgramPointTag *, const ProgramPointTag *>
548  geteagerlyAssumeBinOpBifurcationTags();
549 
551  return X.isValid() ? svalBuilder.evalMinus(X.castAs<NonLoc>()) : X;
552  }
553 
555  return X.isValid() ? svalBuilder.evalComplement(X.castAs<NonLoc>()) : X;
556  }
557 
558  ProgramStateRef handleLValueBitCast(ProgramStateRef state, const Expr *Ex,
559  const LocationContext *LCtx, QualType T,
560  QualType ExTy, const CastExpr *CastE,
561  StmtNodeBuilder &Bldr,
562  ExplodedNode *Pred);
563 
564  ProgramStateRef handleLVectorSplat(ProgramStateRef state,
565  const LocationContext *LCtx,
566  const CastExpr *CastE,
567  StmtNodeBuilder &Bldr,
568  ExplodedNode *Pred);
569 
570  void handleUOExtension(ExplodedNodeSet::iterator I,
571  const UnaryOperator* U,
572  StmtNodeBuilder &Bldr);
573 
574 public:
576  NonLoc L, NonLoc R, QualType T) {
577  return svalBuilder.evalBinOpNN(state, op, L, R, T);
578  }
579 
581  NonLoc L, SVal R, QualType T) {
582  return R.isValid() ? svalBuilder.evalBinOpNN(state, op, L,
583  R.castAs<NonLoc>(), T) : R;
584  }
585 
587  SVal LHS, SVal RHS, QualType T) {
588  return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T);
589  }
590 
591  /// By looking at a certain item that may be potentially part of an object's
592  /// ConstructionContext, retrieve such object's location. A particular
593  /// statement can be transparently passed as \p Item in most cases.
594  static Optional<SVal>
595  getObjectUnderConstruction(ProgramStateRef State,
596  const ConstructionContextItem &Item,
597  const LocationContext *LC);
598 
599 protected:
600  /// evalBind - Handle the semantics of binding a value to a specific location.
601  /// This method is used by evalStore, VisitDeclStmt, and others.
602  void evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, ExplodedNode *Pred,
603  SVal location, SVal Val, bool atDeclInit = false,
604  const ProgramPoint *PP = nullptr);
605 
606  /// Call PointerEscape callback when a value escapes as a result of bind.
607  ProgramStateRef processPointerEscapedOnBind(ProgramStateRef State,
608  SVal Loc,
609  SVal Val,
610  const LocationContext *LCtx) override;
611  /// Call PointerEscape callback when a value escapes as a result of
612  /// region invalidation.
613  /// \param[in] ITraits Specifies invalidation traits for regions/symbols.
614  ProgramStateRef notifyCheckersOfPointerEscape(
615  ProgramStateRef State,
616  const InvalidatedSymbols *Invalidated,
617  ArrayRef<const MemRegion *> ExplicitRegions,
618  const CallEvent *Call,
619  RegionAndSymbolInvalidationTraits &ITraits) override;
620 
621  /// A simple wrapper when you only need to notify checkers of pointer-escape
622  /// of a single value.
623  ProgramStateRef escapeValue(ProgramStateRef State, SVal V,
624  PointerEscapeKind K) const;
625 
626 public:
627  // FIXME: 'tag' should be removed, and a LocationContext should be used
628  // instead.
629  // FIXME: Comment on the meaning of the arguments, when 'St' may not
630  // be the same as Pred->state, and when 'location' may not be the
631  // same as state->getLValue(Ex).
632  /// Simulate a read of the result of Ex.
633  void evalLoad(ExplodedNodeSet &Dst,
634  const Expr *NodeEx, /* Eventually will be a CFGStmt */
635  const Expr *BoundExpr,
636  ExplodedNode *Pred,
637  ProgramStateRef St,
638  SVal location,
639  const ProgramPointTag *tag = nullptr,
640  QualType LoadTy = QualType());
641 
642  // FIXME: 'tag' should be removed, and a LocationContext should be used
643  // instead.
644  void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE,
645  ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SVal Val,
646  const ProgramPointTag *tag = nullptr);
647 
648  /// Return the CFG element corresponding to the worklist element
649  /// that is currently being processed by ExprEngine.
651  return (*currBldrCtx->getBlock())[currStmtIdx];
652  }
653 
654  /// Create a new state in which the call return value is binded to the
655  /// call origin expression.
656  ProgramStateRef bindReturnValue(const CallEvent &Call,
657  const LocationContext *LCtx,
658  ProgramStateRef State);
659 
660  /// Evaluate a call, running pre- and post-call checks and allowing checkers
661  /// to be responsible for handling the evaluation of the call itself.
662  void evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred,
663  const CallEvent &Call);
664 
665  /// Default implementation of call evaluation.
666  void defaultEvalCall(NodeBuilder &B, ExplodedNode *Pred,
667  const CallEvent &Call,
668  const EvalCallOptions &CallOpts = {});
669 
670 private:
671  ProgramStateRef finishArgumentConstruction(ProgramStateRef State,
672  const CallEvent &Call);
673  void finishArgumentConstruction(ExplodedNodeSet &Dst, ExplodedNode *Pred,
674  const CallEvent &Call);
675 
676  void evalLoadCommon(ExplodedNodeSet &Dst,
677  const Expr *NodeEx, /* Eventually will be a CFGStmt */
678  const Expr *BoundEx,
679  ExplodedNode *Pred,
680  ProgramStateRef St,
681  SVal location,
682  const ProgramPointTag *tag,
683  QualType LoadTy);
684 
685  void evalLocation(ExplodedNodeSet &Dst,
686  const Stmt *NodeEx, /* This will eventually be a CFGStmt */
687  const Stmt *BoundEx,
688  ExplodedNode *Pred,
689  ProgramStateRef St,
690  SVal location,
691  bool isLoad);
692 
693  /// Count the stack depth and determine if the call is recursive.
694  void examineStackFrames(const Decl *D, const LocationContext *LCtx,
695  bool &IsRecursive, unsigned &StackDepth);
696 
697  enum CallInlinePolicy {
698  CIP_Allowed,
699  CIP_DisallowedOnce,
700  CIP_DisallowedAlways
701  };
702 
703  /// See if a particular call should be inlined, by only looking
704  /// at the call event and the current state of analysis.
705  CallInlinePolicy mayInlineCallKind(const CallEvent &Call,
706  const ExplodedNode *Pred,
707  AnalyzerOptions &Opts,
708  const EvalCallOptions &CallOpts);
709 
710  /// Checks our policies and decides weither the given call should be inlined.
711  bool shouldInlineCall(const CallEvent &Call, const Decl *D,
712  const ExplodedNode *Pred,
713  const EvalCallOptions &CallOpts = {});
714 
715  bool inlineCall(const CallEvent &Call, const Decl *D, NodeBuilder &Bldr,
716  ExplodedNode *Pred, ProgramStateRef State);
717 
718  /// Conservatively evaluate call by invalidating regions and binding
719  /// a conjured return value.
720  void conservativeEvalCall(const CallEvent &Call, NodeBuilder &Bldr,
721  ExplodedNode *Pred, ProgramStateRef State);
722 
723  /// Either inline or process the call conservatively (or both), based
724  /// on DynamicDispatchBifurcation data.
725  void BifurcateCall(const MemRegion *BifurReg,
726  const CallEvent &Call, const Decl *D, NodeBuilder &Bldr,
727  ExplodedNode *Pred);
728 
729  bool replayWithoutInlining(ExplodedNode *P, const LocationContext *CalleeLC);
730 
731  /// Models a trivial copy or move constructor or trivial assignment operator
732  /// call with a simple bind.
733  void performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred,
734  const CallEvent &Call);
735 
736  /// If the value of the given expression \p InitWithAdjustments is a NonLoc,
737  /// copy it into a new temporary object region, and replace the value of the
738  /// expression with that.
739  ///
740  /// If \p Result is provided, the new region will be bound to this expression
741  /// instead of \p InitWithAdjustments.
742  ///
743  /// Returns the temporary region with adjustments into the optional
744  /// OutRegionWithAdjustments out-parameter if a new region was indeed needed,
745  /// otherwise sets it to nullptr.
746  ProgramStateRef createTemporaryRegionIfNeeded(
747  ProgramStateRef State, const LocationContext *LC,
748  const Expr *InitWithAdjustments, const Expr *Result = nullptr,
749  const SubRegion **OutRegionWithAdjustments = nullptr);
750 
751  /// Returns a region representing the first element of a (possibly
752  /// multi-dimensional) array, for the purposes of element construction or
753  /// destruction.
754  ///
755  /// On return, \p Ty will be set to the base type of the array.
756  ///
757  /// If the type is not an array type at all, the original value is returned.
758  /// Otherwise the "IsArray" flag is set.
759  static SVal makeZeroElementRegion(ProgramStateRef State, SVal LValue,
760  QualType &Ty, bool &IsArray);
761 
762  /// For a DeclStmt or CXXInitCtorInitializer, walk backward in the current CFG
763  /// block to find the constructor expression that directly constructed into
764  /// the storage for this statement. Returns null if the constructor for this
765  /// statement created a temporary object region rather than directly
766  /// constructing into an existing region.
767  const CXXConstructExpr *findDirectConstructorForCurrentCFGElement();
768 
769  /// Update the program state with all the path-sensitive information
770  /// that's necessary to perform construction of an object with a given
771  /// syntactic construction context. If the construction context is unavailable
772  /// or unusable for any reason, a dummy temporary region is returned, and the
773  /// IsConstructorWithImproperlyModeledTargetRegion flag is set in \p CallOpts.
774  /// Returns the updated program state and the new object's this-region.
775  std::pair<ProgramStateRef, SVal> prepareForObjectConstruction(
776  const Expr *E, ProgramStateRef State, const LocationContext *LCtx,
777  const ConstructionContext *CC, EvalCallOptions &CallOpts);
778 
779  /// Store the location of a C++ object corresponding to a statement
780  /// until the statement is actually encountered. For example, if a DeclStmt
781  /// has CXXConstructExpr as its initializer, the object would be considered
782  /// to be "under construction" between CXXConstructExpr and DeclStmt.
783  /// This allows, among other things, to keep bindings to variable's fields
784  /// made within the constructor alive until its declaration actually
785  /// goes into scope.
786  static ProgramStateRef
787  addObjectUnderConstruction(ProgramStateRef State,
788  const ConstructionContextItem &Item,
789  const LocationContext *LC, SVal V);
790 
791  /// Mark the object sa fully constructed, cleaning up the state trait
792  /// that tracks objects under construction.
793  static ProgramStateRef
794  finishObjectConstruction(ProgramStateRef State,
795  const ConstructionContextItem &Item,
796  const LocationContext *LC);
797 
798  /// If the given expression corresponds to a temporary that was used for
799  /// passing into an elidable copy/move constructor and that constructor
800  /// was actually elided, track that we also need to elide the destructor.
801  static ProgramStateRef elideDestructor(ProgramStateRef State,
802  const CXXBindTemporaryExpr *BTE,
803  const LocationContext *LC);
804 
805  /// Stop tracking the destructor that corresponds to an elided constructor.
806  static ProgramStateRef
807  cleanupElidedDestructor(ProgramStateRef State,
808  const CXXBindTemporaryExpr *BTE,
809  const LocationContext *LC);
810 
811  /// Returns true if the given expression corresponds to a temporary that
812  /// was constructed for passing into an elidable copy/move constructor
813  /// and that constructor was actually elided.
814  static bool isDestructorElided(ProgramStateRef State,
815  const CXXBindTemporaryExpr *BTE,
816  const LocationContext *LC);
817 
818  /// Check if all objects under construction have been fully constructed
819  /// for the given context range (including FromLC, not including ToLC).
820  /// This is useful for assertions. Also checks if elided destructors
821  /// were cleaned up.
822  static bool areAllObjectsFullyConstructed(ProgramStateRef State,
823  const LocationContext *FromLC,
824  const LocationContext *ToLC);
825 };
826 
827 /// Traits for storing the call processing policy inside GDM.
828 /// The GDM stores the corresponding CallExpr pointer.
829 // FIXME: This does not use the nice trait macros because it must be accessible
830 // from multiple translation units.
832 template <>
834  public ProgramStatePartialTrait<const void*> {
835  static void *GDMIndex();
836 };
837 
838 } // namespace ento
839 
840 } // namespace clang
841 
842 #endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H
This represents a GCC inline-assembly statement extension.
Definition: Stmt.h:2409
A (possibly-)qualified type.
Definition: Type.h:642
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:94
CheckerManager * getCheckerManager() const
bool ExecuteWorkList(const LocationContext *L, unsigned Steps, ProgramStateRef InitState)
ExecuteWorkList - Run the worklist algorithm for a maximum number of steps.
Definition: CoreEngine.cpp:81
Stmt - This represents one statement.
Definition: Stmt.h:66
Information about invalidation for a particular region/symbol.
Definition: MemRegion.h:1438
BasicValueFactory & getBasicVals()
Definition: ProgramState.h:538
This builder class is useful for generating nodes that resulted from visiting a statement.
Definition: CoreEngine.h:370
C Language Family Type Representation.
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
Represents a point when we begin processing an inlined call.
Definition: ProgramPoint.h:632
StringRef P
bool ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps, ProgramStateRef InitState, ExplodedNodeSet &Dst)
Execute the work list with an initial state.
Definition: ExprEngine.h:172
SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc L, NonLoc R, QualType T)
Definition: ExprEngine.h:575
Represents C++ object destructor generated from a call to delete.
Definition: CFG.h:409
Hints for figuring out of a call should be inlined during evalCall().
Definition: ExprEngine.h:96
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1250
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:4056
cross_tu::CrossTranslationUnitContext * getCrossTranslationUnitContext() override
Definition: ExprEngine.h:192
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:2830
const NodeBuilderContext & getBuilderContext()
Definition: ExprEngine.h:196
bool ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps, ProgramStateRef InitState, ExplodedNodeSet &Dst)
Returns true if there is still simulation state on the worklist.
Definition: CoreEngine.cpp:198
BoundNodesTreeBuilder Nodes
bool hasWorkRemaining() const
Definition: CoreEngine.h:155
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
LineState State
Represents C++ object destructor implicitly generated for automatic object or temporary bound to cons...
Definition: CFG.h:384
bool hasEmptyWorkList() const
Definition: ExprEngine.h:396
bool wasBlocksExhausted() const
Definition: ExprEngine.h:395
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
Describes an C or C++ initializer list.
Definition: Expr.h:4117
BinaryOperatorKind
WorkList * getWorkList() const
Definition: CoreEngine.h:165
CFGElement getCurrentCFGElement()
Return the CFG element corresponding to the worklist element that is currently being processed by Exp...
Definition: ExprEngine.h:650
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3219
const CoreEngine & getCoreEngine() const
Definition: ExprEngine.h:399
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2903
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1205
SVal evalComplement(SVal X)
Definition: ExprEngine.h:554
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1599
ASTContext & getASTContext() override
Represents the this expression in C++.
Definition: ExprCXX.h:964
CheckerManager & getCheckerManager() const
Definition: ExprEngine.h:183
StringRef Filename
Definition: Format.cpp:1629
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand...
Definition: Expr.h:2227
SVal evalBinOp(ProgramStateRef ST, BinaryOperator::Opcode Op, SVal LHS, SVal RHS, QualType T)
Definition: ExprEngine.h:586
Represents a single basic block in a source-level CFG.
Definition: CFG.h:552
InliningModes
The modes of inlining, which override the default analysis-wide settings.
Definition: ExprEngine.h:87
This represents one expression.
Definition: Expr.h:106
virtual SVal evalMinus(NonLoc val)=0
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5096
This is the simplest builder which generates nodes in the ExplodedGraph.
Definition: CoreEngine.h:228
bool isValid() const
Definition: SVals.h:149
Represents Objective-C&#39;s @synchronized statement.
Definition: StmtObjC.h:262
ASTContext & getContext() const
getContext - Return the ASTContext associated with this analysis.
Definition: ExprEngine.h:179
Traits for storing the call processing policy inside GDM.
Definition: ExprEngine.h:831
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
Definition: Stmt.h:2177
SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, SVal lhs, SVal rhs, QualType type)
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:904
This represents a Microsoft inline-assembly statement extension.
Definition: Stmt.h:2584
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1901
Represents C++ object destructor implicitly generated for base object in destructor.
Definition: CFG.h:435
SymbolManager & getSymbolManager()
Definition: ExprEngine.h:391
BugReporter is a utility class for generating PathDiagnostics for analysis.
Definition: BugReporter.h:412
ProgramPoints can be "tagged" as representing points specific to a given analysis entity...
Definition: ProgramPoint.h:40
AnalysisManager & getAnalysisManager() override
Definition: ExprEngine.h:181
bool wasBlocksExhausted() const
Definition: CoreEngine.h:154
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
Definition: ExprCXX.h:1861
virtual bool hasWork() const =0
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
Definition: Stmt.h:877
SVal - This represents a symbolic expression, which can be either an L-value or an R-value...
Definition: SVals.h:76
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:5352
BugReporter & getBugReporter()
Definition: ExprEngine.h:189
BasicValueFactory & getBasicVals()
Definition: ExprEngine.h:386
virtual SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc lhs, NonLoc rhs, QualType resultTy)=0
Create a new value which represents a binary expression with two non- location operands.
bool ExecuteWorkList(const LocationContext *L, unsigned Steps=150000)
Returns true if there is still simulation state on the worklist.
Definition: ExprEngine.h:164
ast_type_traits::DynTypedNode Node
CoreEngine - Implements the core logic of the graph-reachability analysis.
Definition: CoreEngine.h:55
const SymbolManager & getSymbolManager() const
Definition: ExprEngine.h:392
Dataflow Directional Tag Classes.
SValBuilder & getSValBuilder()
Definition: ExprEngine.h:187
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
Definition: ExprCXX.h:2088
StoreManager & getStoreManager()
Definition: ExprEngine.h:379
bool hasWorkRemaining() const
Definition: ExprEngine.h:397
This node builder keeps track of the generated sink nodes.
Definition: CoreEngine.h:333
const ExplodedGraph & getGraph() const
Definition: ExprEngine.h:231
Represents an abstract call to a function or method along a particular path.
Definition: CallEvent.h:171
ProgramStateManager & getStateManager() override
Definition: ExprEngine.h:377
This class is used for tools that requires cross translation unit capability.
Represents a single point (AST node) in the program that requires attention during construction of an...
PointerEscapeKind
Describes the different reasons a pointer escapes during analysis.
ConstraintManager & getConstraintManager()
Definition: ProgramState.h:565
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition: SVals.h:104
SVal evalMinus(SVal X)
Definition: ExprEngine.h:550
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2317
SubRegion - A region that subsets another larger region.
Definition: MemRegion.h:431
Represents Objective-C&#39;s collection statement.
Definition: StmtObjC.h:24
Stores options for the analyzer from the command line.
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:513
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:13853
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2587
ConstructionContext&#39;s subclasses describe different ways of constructing an object in C++...
virtual SVal evalComplement(NonLoc val)=0
Represents C++ object destructor implicitly generated by compiler on various occasions.
Definition: CFG.h:359
SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc L, SVal R, QualType T)
Definition: ExprEngine.h:580
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:29
Represents a top-level expression in a basic block.
Definition: CFG.h:56
GRBugReporter is used for generating path-sensitive reports.
Definition: BugReporter.h:513
Represents C++ object destructor implicitly generated for member object in destructor.
Definition: CFG.h:456
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2405
Represents C++ base or member initializer from constructor&#39;s initialization list. ...
Definition: CFG.h:220
ExplodedGraph & getGraph()
Definition: ExprEngine.h:230
This represents a decl that may have a name.
Definition: Decl.h:248
ConstraintManager & getConstraintManager()
Definition: ExprEngine.h:381
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type, member-designator).
Definition: Expr.h:2122
Represents C++ object destructor implicitly generated at the end of full expression for temporary obj...
Definition: CFG.h:477
const CFGBlock * getBlock() const
Return the CFGBlock associated with this builder.
Definition: CoreEngine.h:208