ExprEngine.h revision 69f87c956b3ac2b80124fd9604af012e1061473a
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_GR_EXPRENGINE
17#define LLVM_CLANG_GR_EXPRENGINE
18
19#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
20#include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
22#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
23#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
24#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/Type.h"
27
28namespace clang {
29
30class AnalysisDeclContextManager;
31class CXXCatchStmt;
32class CXXConstructExpr;
33class CXXDeleteExpr;
34class CXXNewExpr;
35class CXXTemporaryObjectExpr;
36class CXXThisExpr;
37class MaterializeTemporaryExpr;
38class ObjCAtSynchronizedStmt;
39class ObjCForCollectionStmt;
40
41namespace ento {
42
43class AnalysisManager;
44class CallEvent;
45class SimpleCall;
46class ObjCMethodCall;
47
48class ExprEngine : public SubEngine {
49  AnalysisManager &AMgr;
50
51  AnalysisDeclContextManager &AnalysisDeclContexts;
52
53  CoreEngine Engine;
54
55  /// G - the simulation graph.
56  ExplodedGraph& G;
57
58  /// StateMgr - Object that manages the data for all created states.
59  ProgramStateManager StateMgr;
60
61  /// SymMgr - Object that manages the symbol information.
62  SymbolManager& SymMgr;
63
64  /// svalBuilder - SValBuilder object that creates SVals from expressions.
65  SValBuilder &svalBuilder;
66
67  /// EntryNode - The immediate predecessor node.
68  ExplodedNode *EntryNode;
69
70  /// CleanedState - The state for EntryNode "cleaned" of all dead
71  ///  variables and symbols (as determined by a liveness analysis).
72  ProgramStateRef CleanedState;
73
74  /// currentStmt - The current block-level statement.
75  const Stmt *currentStmt;
76  unsigned int currentStmtIdx;
77  const NodeBuilderContext *currentBuilderContext;
78
79  /// Obj-C Class Identifiers.
80  IdentifierInfo* NSExceptionII;
81
82  /// Obj-C Selectors.
83  Selector* NSExceptionInstanceRaiseSelectors;
84  Selector RaiseSel;
85
86  /// Whether or not GC is enabled in this analysis.
87  bool ObjCGCEnabled;
88
89  /// The BugReporter associated with this engine.  It is important that
90  ///  this object be placed at the very end of member variables so that its
91  ///  destructor is called before the rest of the ExprEngine is destroyed.
92  GRBugReporter BR;
93
94public:
95  ExprEngine(AnalysisManager &mgr, bool gcEnabled,
96             SetOfConstDecls *VisitedCallees,
97             FunctionSummariesTy *FS);
98
99  ~ExprEngine();
100
101  /// Returns true if there is still simulation state on the worklist.
102  bool ExecuteWorkList(const LocationContext *L, unsigned Steps = 150000) {
103    return Engine.ExecuteWorkList(L, Steps, 0);
104  }
105
106  /// Execute the work list with an initial state. Nodes that reaches the exit
107  /// of the function are added into the Dst set, which represent the exit
108  /// state of the function call. Returns true if there is still simulation
109  /// state on the worklist.
110  bool ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps,
111                                       ProgramStateRef InitState,
112                                       ExplodedNodeSet &Dst) {
113    return Engine.ExecuteWorkListWithInitialState(L, Steps, InitState, Dst);
114  }
115
116  /// getContext - Return the ASTContext associated with this analysis.
117  ASTContext &getContext() const { return AMgr.getASTContext(); }
118
119  virtual AnalysisManager &getAnalysisManager() { return AMgr; }
120
121  CheckerManager &getCheckerManager() const {
122    return *AMgr.getCheckerManager();
123  }
124
125  SValBuilder &getSValBuilder() { return svalBuilder; }
126
127  BugReporter& getBugReporter() { return BR; }
128
129  const NodeBuilderContext &getBuilderContext() {
130    assert(currentBuilderContext);
131    return *currentBuilderContext;
132  }
133
134  bool isObjCGCEnabled() { return ObjCGCEnabled; }
135
136  const Stmt *getStmt() const;
137
138  void GenerateAutoTransition(ExplodedNode *N);
139  void enqueueEndOfPath(ExplodedNodeSet &S);
140  void GenerateCallExitNode(ExplodedNode *N);
141
142  /// ViewGraph - Visualize the ExplodedGraph created by executing the
143  ///  simulation.
144  void ViewGraph(bool trim = false);
145
146  void ViewGraph(ExplodedNode** Beg, ExplodedNode** End);
147
148  /// getInitialState - Return the initial state used for the root vertex
149  ///  in the ExplodedGraph.
150  ProgramStateRef getInitialState(const LocationContext *InitLoc);
151
152  ExplodedGraph& getGraph() { return G; }
153  const ExplodedGraph& getGraph() const { return G; }
154
155  /// \brief Run the analyzer's garbage collection - remove dead symbols and
156  /// bindings.
157  ///
158  /// \param Node - The predecessor node, from which the processing should
159  /// start.
160  /// \param Out - The returned set of output nodes.
161  /// \param ReferenceStmt - Run garbage collection using the symbols,
162  /// which are live before the given statement.
163  /// \param LC - The location context of the ReferenceStmt.
164  /// \param DiagnosticStmt - the statement used to associate the diagnostic
165  /// message, if any warnings should occur while removing the dead (leaks
166  /// are usually reported here).
167  /// \param K - In some cases it is possible to use PreStmt kind. (Do
168  /// not use it unless you know what you are doing.)
169  void removeDead(ExplodedNode *Node, ExplodedNodeSet &Out,
170            const Stmt *ReferenceStmt, const LocationContext *LC,
171            const Stmt *DiagnosticStmt,
172            ProgramPoint::Kind K = ProgramPoint::PreStmtPurgeDeadSymbolsKind);
173
174  /// processCFGElement - Called by CoreEngine. Used to generate new successor
175  ///  nodes by processing the 'effects' of a CFG element.
176  void processCFGElement(const CFGElement E, ExplodedNode *Pred,
177                         unsigned StmtIdx, NodeBuilderContext *Ctx);
178
179  void ProcessStmt(const CFGStmt S, ExplodedNode *Pred);
180
181  void ProcessInitializer(const CFGInitializer I, ExplodedNode *Pred);
182
183  void ProcessImplicitDtor(const CFGImplicitDtor D, ExplodedNode *Pred);
184
185  void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D,
186                               ExplodedNode *Pred, ExplodedNodeSet &Dst);
187  void ProcessBaseDtor(const CFGBaseDtor D,
188                       ExplodedNode *Pred, ExplodedNodeSet &Dst);
189  void ProcessMemberDtor(const CFGMemberDtor D,
190                         ExplodedNode *Pred, ExplodedNodeSet &Dst);
191  void ProcessTemporaryDtor(const CFGTemporaryDtor D,
192                            ExplodedNode *Pred, ExplodedNodeSet &Dst);
193
194  /// Called by CoreEngine when processing the entrance of a CFGBlock.
195  virtual void processCFGBlockEntrance(const BlockEdge &L,
196                                       NodeBuilderWithSinks &nodeBuilder);
197
198  /// ProcessBranch - Called by CoreEngine.  Used to generate successor
199  ///  nodes by processing the 'effects' of a branch condition.
200  void processBranch(const Stmt *Condition, const Stmt *Term,
201                     NodeBuilderContext& BuilderCtx,
202                     ExplodedNode *Pred,
203                     ExplodedNodeSet &Dst,
204                     const CFGBlock *DstT,
205                     const CFGBlock *DstF);
206
207  /// processIndirectGoto - Called by CoreEngine.  Used to generate successor
208  ///  nodes by processing the 'effects' of a computed goto jump.
209  void processIndirectGoto(IndirectGotoNodeBuilder& builder);
210
211  /// ProcessSwitch - Called by CoreEngine.  Used to generate successor
212  ///  nodes by processing the 'effects' of a switch statement.
213  void processSwitch(SwitchNodeBuilder& builder);
214
215  /// ProcessEndPath - Called by CoreEngine.  Used to generate end-of-path
216  ///  nodes when the control reaches the end of a function.
217  void processEndOfFunction(NodeBuilderContext& BC);
218
219  /// Generate the entry node of the callee.
220  void processCallEnter(CallEnter CE, ExplodedNode *Pred);
221
222  /// Generate the sequence of nodes that simulate the call exit and the post
223  /// visit for CallExpr.
224  void processCallExit(ExplodedNode *Pred);
225
226  /// Called by CoreEngine when the analysis worklist has terminated.
227  void processEndWorklist(bool hasWorkRemaining);
228
229  /// evalAssume - Callback function invoked by the ConstraintManager when
230  ///  making assumptions about state values.
231  ProgramStateRef processAssume(ProgramStateRef state, SVal cond,bool assumption);
232
233  /// wantsRegionChangeUpdate - Called by ProgramStateManager to determine if a
234  ///  region change should trigger a processRegionChanges update.
235  bool wantsRegionChangeUpdate(ProgramStateRef state);
236
237  /// processRegionChanges - Called by ProgramStateManager whenever a change is made
238  ///  to the store. Used to update checkers that track region values.
239  ProgramStateRef
240  processRegionChanges(ProgramStateRef state,
241                       const StoreManager::InvalidatedSymbols *invalidated,
242                       ArrayRef<const MemRegion *> ExplicitRegions,
243                       ArrayRef<const MemRegion *> Regions,
244                       const CallEvent *Call);
245
246  /// printState - Called by ProgramStateManager to print checker-specific data.
247  void printState(raw_ostream &Out, ProgramStateRef State,
248                  const char *NL, const char *Sep);
249
250  virtual ProgramStateManager& getStateManager() { return StateMgr; }
251
252  StoreManager& getStoreManager() { return StateMgr.getStoreManager(); }
253
254  ConstraintManager& getConstraintManager() {
255    return StateMgr.getConstraintManager();
256  }
257
258  // FIXME: Remove when we migrate over to just using SValBuilder.
259  BasicValueFactory& getBasicVals() {
260    return StateMgr.getBasicVals();
261  }
262  const BasicValueFactory& getBasicVals() const {
263    return StateMgr.getBasicVals();
264  }
265
266  // FIXME: Remove when we migrate over to just using ValueManager.
267  SymbolManager& getSymbolManager() { return SymMgr; }
268  const SymbolManager& getSymbolManager() const { return SymMgr; }
269
270  // Functions for external checking of whether we have unfinished work
271  bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); }
272  bool hasEmptyWorkList() const { return !Engine.getWorkList()->hasWork(); }
273  bool hasWorkRemaining() const { return Engine.hasWorkRemaining(); }
274
275  const CoreEngine &getCoreEngine() const { return Engine; }
276
277public:
278  /// Visit - Transfer function logic for all statements.  Dispatches to
279  ///  other functions that handle specific kinds of statements.
280  void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst);
281
282  /// VisitArraySubscriptExpr - Transfer function for array accesses.
283  void VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *Ex,
284                                   ExplodedNode *Pred,
285                                   ExplodedNodeSet &Dst);
286
287  /// VisitAsmStmt - Transfer function logic for inline asm.
288  void VisitAsmStmt(const AsmStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst);
289
290  /// VisitMSAsmStmt - Transfer function logic for MS inline asm.
291  void VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
292                      ExplodedNodeSet &Dst);
293
294  /// VisitBlockExpr - Transfer function logic for BlockExprs.
295  void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
296                      ExplodedNodeSet &Dst);
297
298  /// VisitBinaryOperator - Transfer function logic for binary operators.
299  void VisitBinaryOperator(const BinaryOperator* B, ExplodedNode *Pred,
300                           ExplodedNodeSet &Dst);
301
302
303  /// VisitCall - Transfer function for function calls.
304  void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
305                     ExplodedNodeSet &Dst);
306
307  /// VisitCast - Transfer function logic for all casts (implicit and explicit).
308  void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred,
309                ExplodedNodeSet &Dst);
310
311  /// VisitCompoundLiteralExpr - Transfer function logic for compound literals.
312  void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
313                                ExplodedNode *Pred, ExplodedNodeSet &Dst);
314
315  /// Transfer function logic for DeclRefExprs and BlockDeclRefExprs.
316  void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D,
317                              ExplodedNode *Pred, ExplodedNodeSet &Dst);
318
319  /// VisitDeclStmt - Transfer function logic for DeclStmts.
320  void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
321                     ExplodedNodeSet &Dst);
322
323  /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose
324  void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R,
325                        ExplodedNode *Pred, ExplodedNodeSet &Dst);
326
327  void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred,
328                         ExplodedNodeSet &Dst);
329
330  /// VisitLogicalExpr - Transfer function logic for '&&', '||'
331  void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
332                        ExplodedNodeSet &Dst);
333
334  /// VisitMemberExpr - Transfer function for member expressions.
335  void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
336                           ExplodedNodeSet &Dst);
337
338  /// Transfer function logic for ObjCAtSynchronizedStmts.
339  void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
340                                   ExplodedNode *Pred, ExplodedNodeSet &Dst);
341
342  /// Transfer function logic for computing the lvalue of an Objective-C ivar.
343  void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred,
344                                ExplodedNodeSet &Dst);
345
346  /// VisitObjCForCollectionStmt - Transfer function logic for
347  ///  ObjCForCollectionStmt.
348  void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S,
349                                  ExplodedNode *Pred, ExplodedNodeSet &Dst);
350
351  void VisitObjCMessage(const ObjCMethodCall &Msg, ExplodedNode *Pred,
352                        ExplodedNodeSet &Dst);
353
354  /// VisitReturnStmt - Transfer function logic for return statements.
355  void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred,
356                       ExplodedNodeSet &Dst);
357
358  /// VisitOffsetOfExpr - Transfer function for offsetof.
359  void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred,
360                         ExplodedNodeSet &Dst);
361
362  /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof.
363  void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
364                              ExplodedNode *Pred, ExplodedNodeSet &Dst);
365
366  /// VisitUnaryOperator - Transfer function logic for unary operators.
367  void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode *Pred,
368                          ExplodedNodeSet &Dst);
369
370  /// Handle ++ and -- (both pre- and post-increment).
371  void VisitIncrementDecrementOperator(const UnaryOperator* U,
372                                       ExplodedNode *Pred,
373                                       ExplodedNodeSet &Dst);
374
375  void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred,
376                         ExplodedNodeSet &Dst);
377
378  void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
379                        ExplodedNodeSet & Dst);
380
381  void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *expr,
382                                   ExplodedNode *Pred, ExplodedNodeSet &Dst);
383
384  void VisitCXXConstructExpr(const CXXConstructExpr *E, const MemRegion *Dest,
385                             ExplodedNode *Pred, ExplodedNodeSet &Dst);
386
387  void VisitCXXDestructor(const CXXDestructorDecl *DD,
388                          const MemRegion *Dest, const Stmt *S,
389                          ExplodedNode *Pred, ExplodedNodeSet &Dst);
390
391  void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
392                       ExplodedNodeSet &Dst);
393
394  void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred,
395                          ExplodedNodeSet &Dst);
396
397  /// Create a C++ temporary object for an rvalue.
398  void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
399                                ExplodedNode *Pred,
400                                ExplodedNodeSet &Dst);
401
402  /// evalEagerlyAssume - Given the nodes in 'Src', eagerly assume symbolic
403  ///  expressions of the form 'x != 0' and generate new nodes (stored in Dst)
404  ///  with those assumptions.
405  void evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src,
406                         const Expr *Ex);
407
408  std::pair<const ProgramPointTag *, const ProgramPointTag*>
409    getEagerlyAssumeTags();
410
411  SVal evalMinus(SVal X) {
412    return X.isValid() ? svalBuilder.evalMinus(cast<NonLoc>(X)) : X;
413  }
414
415  SVal evalComplement(SVal X) {
416    return X.isValid() ? svalBuilder.evalComplement(cast<NonLoc>(X)) : X;
417  }
418
419public:
420
421  SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
422                 NonLoc L, NonLoc R, QualType T) {
423    return svalBuilder.evalBinOpNN(state, op, L, R, T);
424  }
425
426  SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
427                 NonLoc L, SVal R, QualType T) {
428    return R.isValid() ? svalBuilder.evalBinOpNN(state,op,L, cast<NonLoc>(R), T) : R;
429  }
430
431  SVal evalBinOp(ProgramStateRef ST, BinaryOperator::Opcode Op,
432                 SVal LHS, SVal RHS, QualType T) {
433    return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T);
434  }
435
436protected:
437  void evalObjCMessage(StmtNodeBuilder &Bldr, const ObjCMethodCall &Msg,
438                       ExplodedNode *Pred, ProgramStateRef state,
439                       bool GenSink);
440
441  ProgramStateRef MarkBranch(ProgramStateRef state,
442                                 const Stmt *Terminator,
443                                 const LocationContext *LCtx,
444                                 bool branchTaken);
445
446  /// evalBind - Handle the semantics of binding a value to a specific location.
447  ///  This method is used by evalStore, VisitDeclStmt, and others.
448  void evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, ExplodedNode *Pred,
449                SVal location, SVal Val, bool atDeclInit = false);
450
451public:
452  // FIXME: 'tag' should be removed, and a LocationContext should be used
453  // instead.
454  // FIXME: Comment on the meaning of the arguments, when 'St' may not
455  // be the same as Pred->state, and when 'location' may not be the
456  // same as state->getLValue(Ex).
457  /// Simulate a read of the result of Ex.
458  void evalLoad(ExplodedNodeSet &Dst,
459                const Expr *NodeEx,  /* Eventually will be a CFGStmt */
460                const Expr *BoundExpr,
461                ExplodedNode *Pred,
462                ProgramStateRef St,
463                SVal location,
464                const ProgramPointTag *tag = 0,
465                QualType LoadTy = QualType());
466
467  // FIXME: 'tag' should be removed, and a LocationContext should be used
468  // instead.
469  void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE,
470                 ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SVal Val,
471                 const ProgramPointTag *tag = 0);
472
473  void evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred,
474                const SimpleCall &Call);
475  void defaultEvalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred,
476                       const CallEvent &Call);
477private:
478  void evalLoadCommon(ExplodedNodeSet &Dst,
479                      const Expr *NodeEx,  /* Eventually will be a CFGStmt */
480                      const Expr *BoundEx,
481                      ExplodedNode *Pred,
482                      ProgramStateRef St,
483                      SVal location,
484                      const ProgramPointTag *tag,
485                      QualType LoadTy);
486
487  // FIXME: 'tag' should be removed, and a LocationContext should be used
488  // instead.
489  void evalLocation(ExplodedNodeSet &Dst,
490                    const Stmt *NodeEx, /* This will eventually be a CFGStmt */
491                    const Stmt *BoundEx,
492                    ExplodedNode *Pred,
493                    ProgramStateRef St, SVal location,
494                    const ProgramPointTag *tag, bool isLoad);
495
496  bool shouldInlineDecl(const Decl *D, ExplodedNode *Pred);
497  bool inlineCall(ExplodedNodeSet &Dst, const CallEvent &Call,
498                  ExplodedNode *Pred);
499
500  bool replayWithoutInlining(ExplodedNode *P, const LocationContext *CalleeLC);
501};
502
503/// Traits for storing the call processing policy inside GDM.
504/// The GDM stores the corresponding CallExpr pointer.
505struct ReplayWithoutInlining{};
506template <>
507struct ProgramStateTrait<ReplayWithoutInlining> :
508  public ProgramStatePartialTrait<void*> {
509  static void *GDMIndex() { static int index = 0; return &index; }
510};
511
512} // end ento namespace
513
514} // end clang namespace
515
516#endif
517