ExprEngine.h revision 35bdbf40624beba3fc00cb72ab444659939c1a6b
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/GRState.h"
23#include "clang/StaticAnalyzer/Core/PathSensitive/TransferFuncs.h"
24#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
25#include "clang/AST/Type.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang/AST/ExprCXX.h"
28#include "clang/AST/StmtObjC.h"
29
30namespace clang {
31
32class ObjCForCollectionStmt;
33
34namespace ento {
35
36class AnalysisManager;
37
38class ExprEngine : public SubEngine {
39  AnalysisManager &AMgr;
40
41  CoreEngine Engine;
42
43  /// G - the simulation graph.
44  ExplodedGraph& G;
45
46  /// Builder - The current StmtNodeBuilder which is used when building the
47  ///  nodes for a given statement.
48  StmtNodeBuilder* Builder;
49
50  /// StateMgr - Object that manages the data for all created states.
51  GRStateManager StateMgr;
52
53  /// SymMgr - Object that manages the symbol information.
54  SymbolManager& SymMgr;
55
56  /// svalBuilder - SValBuilder object that creates SVals from expressions.
57  SValBuilder &svalBuilder;
58
59  /// EntryNode - The immediate predecessor node.
60  ExplodedNode* EntryNode;
61
62  /// CleanedState - The state for EntryNode "cleaned" of all dead
63  ///  variables and symbols (as determined by a liveness analysis).
64  const GRState* CleanedState;
65
66  /// currentStmt - The current block-level statement.
67  const Stmt* currentStmt;
68
69  // Obj-C Class Identifiers.
70  IdentifierInfo* NSExceptionII;
71
72  // Obj-C Selectors.
73  Selector* NSExceptionInstanceRaiseSelectors;
74  Selector RaiseSel;
75
76  /// The BugReporter associated with this engine.  It is important that
77  ///  this object be placed at the very end of member variables so that its
78  ///  destructor is called before the rest of the ExprEngine is destroyed.
79  GRBugReporter BR;
80
81  llvm::OwningPtr<TransferFuncs> TF;
82
83public:
84  ExprEngine(AnalysisManager &mgr, TransferFuncs *tf);
85
86  ~ExprEngine();
87
88  void ExecuteWorkList(const LocationContext *L, unsigned Steps = 150000) {
89    Engine.ExecuteWorkList(L, Steps, 0);
90  }
91
92  /// Execute the work list with an initial state. Nodes that reaches the exit
93  /// of the function are added into the Dst set, which represent the exit
94  /// state of the function call.
95  void ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps,
96                                       const GRState *InitState,
97                                       ExplodedNodeSet &Dst) {
98    Engine.ExecuteWorkListWithInitialState(L, Steps, InitState, Dst);
99  }
100
101  /// getContext - Return the ASTContext associated with this analysis.
102  ASTContext& getContext() const { return AMgr.getASTContext(); }
103
104  virtual AnalysisManager &getAnalysisManager() { return AMgr; }
105
106  CheckerManager &getCheckerManager() const {
107    return *AMgr.getCheckerManager();
108  }
109
110  SValBuilder &getSValBuilder() { return svalBuilder; }
111
112  TransferFuncs& getTF() { return *TF; }
113
114  BugReporter& getBugReporter() { return BR; }
115
116  StmtNodeBuilder &getBuilder() { assert(Builder); return *Builder; }
117
118  // FIXME: Remove once TransferFuncs is no longer referenced.
119  void setTransferFunction(TransferFuncs* tf);
120
121  /// ViewGraph - Visualize the ExplodedGraph created by executing the
122  ///  simulation.
123  void ViewGraph(bool trim = false);
124
125  void ViewGraph(ExplodedNode** Beg, ExplodedNode** End);
126
127  /// getInitialState - Return the initial state used for the root vertex
128  ///  in the ExplodedGraph.
129  const GRState* getInitialState(const LocationContext *InitLoc);
130
131  ExplodedGraph& getGraph() { return G; }
132  const ExplodedGraph& getGraph() const { return G; }
133
134  /// processCFGElement - Called by CoreEngine. Used to generate new successor
135  ///  nodes by processing the 'effects' of a CFG element.
136  void processCFGElement(const CFGElement E, StmtNodeBuilder& builder);
137
138  void ProcessStmt(const CFGStmt S, StmtNodeBuilder &builder);
139
140  void ProcessInitializer(const CFGInitializer I, StmtNodeBuilder &builder);
141
142  void ProcessImplicitDtor(const CFGImplicitDtor D, StmtNodeBuilder &builder);
143
144  void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D,
145                            StmtNodeBuilder &builder);
146  void ProcessBaseDtor(const CFGBaseDtor D, StmtNodeBuilder &builder);
147  void ProcessMemberDtor(const CFGMemberDtor D, StmtNodeBuilder &builder);
148  void ProcessTemporaryDtor(const CFGTemporaryDtor D,
149                            StmtNodeBuilder &builder);
150
151  /// Called by CoreEngine when processing the entrance of a CFGBlock.
152  virtual void processCFGBlockEntrance(ExplodedNodeSet &dstNodes,
153                                GenericNodeBuilder<BlockEntrance> &nodeBuilder);
154
155  /// ProcessBranch - Called by CoreEngine.  Used to generate successor
156  ///  nodes by processing the 'effects' of a branch condition.
157  void processBranch(const Stmt* Condition, const Stmt* Term,
158                     BranchNodeBuilder& builder);
159
160  /// processIndirectGoto - Called by CoreEngine.  Used to generate successor
161  ///  nodes by processing the 'effects' of a computed goto jump.
162  void processIndirectGoto(IndirectGotoNodeBuilder& builder);
163
164  /// ProcessSwitch - Called by CoreEngine.  Used to generate successor
165  ///  nodes by processing the 'effects' of a switch statement.
166  void processSwitch(SwitchNodeBuilder& builder);
167
168  /// ProcessEndPath - Called by CoreEngine.  Used to generate end-of-path
169  ///  nodes when the control reaches the end of a function.
170  void processEndOfFunction(EndOfFunctionNodeBuilder& builder);
171
172  /// Generate the entry node of the callee.
173  void processCallEnter(CallEnterNodeBuilder &builder);
174
175  /// Generate the first post callsite node.
176  void processCallExit(CallExitNodeBuilder &builder);
177
178  /// Called by CoreEngine when the analysis worklist has terminated.
179  void processEndWorklist(bool hasWorkRemaining);
180
181  /// evalAssume - Callback function invoked by the ConstraintManager when
182  ///  making assumptions about state values.
183  const GRState *processAssume(const GRState *state, SVal cond,bool assumption);
184
185  /// wantsRegionChangeUpdate - Called by GRStateManager to determine if a
186  ///  region change should trigger a processRegionChanges update.
187  bool wantsRegionChangeUpdate(const GRState* state);
188
189  /// processRegionChanges - Called by GRStateManager whenever a change is made
190  ///  to the store. Used to update checkers that track region values.
191  const GRState *
192  processRegionChanges(const GRState *state,
193                       const StoreManager::InvalidatedSymbols *invalidated,
194                       const MemRegion * const *Begin,
195                       const MemRegion * const *End);
196
197  virtual GRStateManager& getStateManager() { return StateMgr; }
198
199  StoreManager& getStoreManager() { return StateMgr.getStoreManager(); }
200
201  ConstraintManager& getConstraintManager() {
202    return StateMgr.getConstraintManager();
203  }
204
205  // FIXME: Remove when we migrate over to just using SValBuilder.
206  BasicValueFactory& getBasicVals() {
207    return StateMgr.getBasicVals();
208  }
209  const BasicValueFactory& getBasicVals() const {
210    return StateMgr.getBasicVals();
211  }
212
213  // FIXME: Remove when we migrate over to just using ValueManager.
214  SymbolManager& getSymbolManager() { return SymMgr; }
215  const SymbolManager& getSymbolManager() const { return SymMgr; }
216
217  // Functions for external checking of whether we have unfinished work
218  bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); }
219  bool hasEmptyWorkList() const { return !Engine.getWorkList()->hasWork(); }
220  bool hasWorkRemaining() const { return Engine.hasWorkRemaining(); }
221
222  const CoreEngine &getCoreEngine() const { return Engine; }
223
224protected:
225  const GRState* GetState(ExplodedNode* N) {
226    return N == EntryNode ? CleanedState : N->getState();
227  }
228
229public:
230  ExplodedNode* MakeNode(ExplodedNodeSet& Dst, const Stmt* S,
231                         ExplodedNode* Pred, const GRState* St,
232                         ProgramPoint::Kind K = ProgramPoint::PostStmtKind,
233                         const void *tag = 0);
234
235  /// Visit - Transfer function logic for all statements.  Dispatches to
236  ///  other functions that handle specific kinds of statements.
237  void Visit(const Stmt* S, ExplodedNode* Pred, ExplodedNodeSet& Dst);
238
239  /// VisitArraySubscriptExpr - Transfer function for array accesses.
240  void VisitLvalArraySubscriptExpr(const ArraySubscriptExpr* Ex,
241                                   ExplodedNode* Pred,
242                                   ExplodedNodeSet& Dst);
243
244  /// VisitAsmStmt - Transfer function logic for inline asm.
245  void VisitAsmStmt(const AsmStmt* A, ExplodedNode* Pred, ExplodedNodeSet& Dst);
246
247  void VisitAsmStmtHelperOutputs(const AsmStmt* A,
248                                 AsmStmt::const_outputs_iterator I,
249                                 AsmStmt::const_outputs_iterator E,
250                                 ExplodedNode* Pred, ExplodedNodeSet& Dst);
251
252  void VisitAsmStmtHelperInputs(const AsmStmt* A,
253                                AsmStmt::const_inputs_iterator I,
254                                AsmStmt::const_inputs_iterator E,
255                                ExplodedNode* Pred, ExplodedNodeSet& Dst);
256
257  /// VisitBlockExpr - Transfer function logic for BlockExprs.
258  void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
259                      ExplodedNodeSet &Dst);
260
261  /// VisitBinaryOperator - Transfer function logic for binary operators.
262  void VisitBinaryOperator(const BinaryOperator* B, ExplodedNode* Pred,
263                           ExplodedNodeSet& Dst);
264
265
266  /// VisitCall - Transfer function for function calls.
267  void VisitCallExpr(const CallExpr* CE, ExplodedNode* Pred,
268                     ExplodedNodeSet& Dst);
269
270  /// VisitCast - Transfer function logic for all casts (implicit and explicit).
271  void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred,
272                ExplodedNodeSet &Dst);
273
274  /// VisitCompoundLiteralExpr - Transfer function logic for compound literals.
275  void VisitCompoundLiteralExpr(const CompoundLiteralExpr* CL,
276                                ExplodedNode* Pred, ExplodedNodeSet& Dst);
277
278  /// Transfer function logic for DeclRefExprs and BlockDeclRefExprs.
279  void VisitCommonDeclRefExpr(const Expr* DR, const NamedDecl *D,
280                              ExplodedNode* Pred, ExplodedNodeSet& Dst);
281
282  /// VisitDeclStmt - Transfer function logic for DeclStmts.
283  void VisitDeclStmt(const DeclStmt* DS, ExplodedNode* Pred,
284                     ExplodedNodeSet& Dst);
285
286  /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose
287  void VisitGuardedExpr(const Expr* Ex, const Expr* L, const Expr* R,
288                        ExplodedNode* Pred, ExplodedNodeSet& Dst);
289
290  void VisitInitListExpr(const InitListExpr* E, ExplodedNode* Pred,
291                         ExplodedNodeSet& Dst);
292
293  /// VisitLogicalExpr - Transfer function logic for '&&', '||'
294  void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode* Pred,
295                        ExplodedNodeSet& Dst);
296
297  /// VisitMemberExpr - Transfer function for member expressions.
298  void VisitMemberExpr(const MemberExpr* M, ExplodedNode* Pred,
299                           ExplodedNodeSet& Dst);
300
301  /// Transfer function logic for ObjCAtSynchronizedStmts.
302  void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
303                                   ExplodedNode *Pred, ExplodedNodeSet &Dst);
304
305  void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *E,
306                                ExplodedNode *Pred, ExplodedNodeSet &Dst);
307
308  /// Transfer function logic for computing the lvalue of an Objective-C ivar.
309  void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr* DR, ExplodedNode* Pred,
310                                ExplodedNodeSet& Dst);
311
312  /// VisitObjCForCollectionStmt - Transfer function logic for
313  ///  ObjCForCollectionStmt.
314  void VisitObjCForCollectionStmt(const ObjCForCollectionStmt* S,
315                                  ExplodedNode* Pred, ExplodedNodeSet& Dst);
316
317  void VisitObjCForCollectionStmtAux(const ObjCForCollectionStmt* S,
318                                     ExplodedNode* Pred,
319                                     ExplodedNodeSet& Dst, SVal ElementV);
320
321  /// VisitObjCMessageExpr - Transfer function for ObjC message expressions.
322  void VisitObjCMessageExpr(const ObjCMessageExpr* ME, ExplodedNode* Pred,
323                            ExplodedNodeSet& Dst);
324  void VisitObjCMessage(const ObjCMessage &msg, ExplodedNodeSet &Src,
325                        ExplodedNodeSet& Dst);
326
327  /// VisitReturnStmt - Transfer function logic for return statements.
328  void VisitReturnStmt(const ReturnStmt* R, ExplodedNode* Pred,
329                       ExplodedNodeSet& Dst);
330
331  /// VisitOffsetOfExpr - Transfer function for offsetof.
332  void VisitOffsetOfExpr(const OffsetOfExpr* Ex, ExplodedNode* Pred,
333                         ExplodedNodeSet& Dst);
334
335  /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof.
336  void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr* Ex,
337                              ExplodedNode* Pred, ExplodedNodeSet& Dst);
338
339  /// VisitUnaryOperator - Transfer function logic for unary operators.
340  void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode* Pred,
341                          ExplodedNodeSet& Dst);
342
343  void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
344                        ExplodedNodeSet & Dst);
345
346  void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *expr,
347                                   ExplodedNode *Pred, ExplodedNodeSet &Dst) {
348    VisitCXXConstructExpr(expr, 0, Pred, Dst);
349  }
350
351  void VisitCXXConstructExpr(const CXXConstructExpr *E, const MemRegion *Dest,
352                             ExplodedNode *Pred, ExplodedNodeSet &Dst);
353
354  void VisitCXXDestructor(const CXXDestructorDecl *DD,
355                          const MemRegion *Dest, const Stmt *S,
356                          ExplodedNode *Pred, ExplodedNodeSet &Dst);
357
358  void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
359                       ExplodedNodeSet &Dst);
360
361  void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred,
362                          ExplodedNodeSet &Dst);
363
364  void VisitAggExpr(const Expr *E, const MemRegion *Dest, ExplodedNode *Pred,
365                    ExplodedNodeSet &Dst);
366
367  /// Create a C++ temporary object for an rvalue.
368  void CreateCXXTemporaryObject(const Expr *Ex, ExplodedNode *Pred,
369                                ExplodedNodeSet &Dst);
370
371  /// Synthesize CXXThisRegion.
372  const CXXThisRegion *getCXXThisRegion(const CXXRecordDecl *RD,
373                                        const StackFrameContext *SFC);
374
375  const CXXThisRegion *getCXXThisRegion(const CXXMethodDecl *decl,
376                                        const StackFrameContext *frameCtx);
377
378  /// Evaluate arguments with a work list algorithm.
379  void evalArguments(ConstExprIterator AI, ConstExprIterator AE,
380                     const FunctionProtoType *FnType,
381                     ExplodedNode *Pred, ExplodedNodeSet &Dst,
382                     bool FstArgAsLValue = false);
383
384  /// Evaluate callee expression (for a function call).
385  void evalCallee(const CallExpr *callExpr, const ExplodedNodeSet &src,
386                  ExplodedNodeSet &dest);
387
388  /// evalEagerlyAssume - Given the nodes in 'Src', eagerly assume symbolic
389  ///  expressions of the form 'x != 0' and generate new nodes (stored in Dst)
390  ///  with those assumptions.
391  void evalEagerlyAssume(ExplodedNodeSet& Dst, ExplodedNodeSet& Src,
392                         const Expr *Ex);
393
394  SVal evalMinus(SVal X) {
395    return X.isValid() ? svalBuilder.evalMinus(cast<NonLoc>(X)) : X;
396  }
397
398  SVal evalComplement(SVal X) {
399    return X.isValid() ? svalBuilder.evalComplement(cast<NonLoc>(X)) : X;
400  }
401
402public:
403
404  SVal evalBinOp(const GRState *state, BinaryOperator::Opcode op,
405                 NonLoc L, NonLoc R, QualType T) {
406    return svalBuilder.evalBinOpNN(state, op, L, R, T);
407  }
408
409  SVal evalBinOp(const GRState *state, BinaryOperator::Opcode op,
410                 NonLoc L, SVal R, QualType T) {
411    return R.isValid() ? svalBuilder.evalBinOpNN(state,op,L, cast<NonLoc>(R), T) : R;
412  }
413
414  SVal evalBinOp(const GRState *ST, BinaryOperator::Opcode Op,
415                 SVal LHS, SVal RHS, QualType T) {
416    return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T);
417  }
418
419protected:
420  void evalObjCMessage(ExplodedNodeSet& Dst, const ObjCMessage &msg,
421                       ExplodedNode* Pred, const GRState *state) {
422    assert (Builder && "StmtNodeBuilder must be defined.");
423    getTF().evalObjCMessage(Dst, *this, *Builder, msg, Pred, state);
424  }
425
426  const GRState* MarkBranch(const GRState* St, const Stmt* Terminator,
427                            bool branchTaken);
428
429  /// evalBind - Handle the semantics of binding a value to a specific location.
430  ///  This method is used by evalStore, VisitDeclStmt, and others.
431  void evalBind(ExplodedNodeSet& Dst, const Stmt* StoreE, ExplodedNode* Pred,
432                const GRState* St, SVal location, SVal Val,
433                bool atDeclInit = false);
434
435public:
436  // FIXME: 'tag' should be removed, and a LocationContext should be used
437  // instead.
438  // FIXME: Comment on the meaning of the arguments, when 'St' may not
439  // be the same as Pred->state, and when 'location' may not be the
440  // same as state->getLValue(Ex).
441  /// Simulate a read of the result of Ex.
442  void evalLoad(ExplodedNodeSet& Dst, const Expr* Ex, ExplodedNode* Pred,
443                const GRState* St, SVal location, const void *tag = 0,
444                QualType LoadTy = QualType());
445
446  // FIXME: 'tag' should be removed, and a LocationContext should be used
447  // instead.
448  void evalStore(ExplodedNodeSet& Dst, const Expr* AssignE, const Expr* StoreE,
449                 ExplodedNode* Pred, const GRState* St, SVal TargetLV, SVal Val,
450                 const void *tag = 0);
451private:
452  void evalLoadCommon(ExplodedNodeSet& Dst, const Expr* Ex, ExplodedNode* Pred,
453                      const GRState* St, SVal location, const void *tag,
454                      QualType LoadTy);
455
456  // FIXME: 'tag' should be removed, and a LocationContext should be used
457  // instead.
458  void evalLocation(ExplodedNodeSet &Dst, const Stmt *S, ExplodedNode* Pred,
459                    const GRState* St, SVal location,
460                    const void *tag, bool isLoad);
461
462  bool InlineCall(ExplodedNodeSet &Dst, const CallExpr *CE, ExplodedNode *Pred);
463};
464
465} // end ento namespace
466
467} // end clang namespace
468
469#endif
470