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