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