ExprEngineCallAndReturn.cpp revision 056c4b46335a3bd2612414735d5749ee159c0165
1//=-- ExprEngineCallAndReturn.cpp - Support for call/return -----*- 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 ExprEngine's support for calls and returns.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/StaticAnalyzer/Core/CheckerManager.h"
15#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
16#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/Analysis/Support/SaveAndRestore.h"
19
20using namespace clang;
21using namespace ento;
22
23namespace {
24  // Trait class for recording returned expression in the state.
25  struct ReturnExpr {
26    static int TagInt;
27    typedef const Stmt *data_type;
28  };
29  int ReturnExpr::TagInt;
30}
31
32void ExprEngine::processCallEnter(CallEnterNodeBuilder &B) {
33  const ProgramState *state =
34    B.getState()->enterStackFrame(B.getCalleeContext());
35  B.generateNode(state);
36}
37
38void ExprEngine::processCallExit(CallExitNodeBuilder &B) {
39  const ProgramState *state = B.getState();
40  const ExplodedNode *Pred = B.getPredecessor();
41  const StackFrameContext *calleeCtx =
42    cast<StackFrameContext>(Pred->getLocationContext());
43  const Stmt *CE = calleeCtx->getCallSite();
44
45  // If the callee returns an expression, bind its value to CallExpr.
46  const Stmt *ReturnedExpr = state->get<ReturnExpr>();
47  if (ReturnedExpr) {
48    SVal RetVal = state->getSVal(ReturnedExpr);
49    state = state->BindExpr(CE, RetVal);
50    // Clear the return expr GDM.
51    state = state->remove<ReturnExpr>();
52  }
53
54  // Bind the constructed object value to CXXConstructExpr.
55  if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(CE)) {
56    const CXXThisRegion *ThisR =
57    getCXXThisRegion(CCE->getConstructor()->getParent(), calleeCtx);
58
59    SVal ThisV = state->getSVal(ThisR);
60    // Always bind the region to the CXXConstructExpr.
61    state = state->BindExpr(CCE, ThisV);
62  }
63
64  B.generateNode(state);
65}
66
67const ProgramState *
68ExprEngine::invalidateArguments(const ProgramState *State,
69                                const CallOrObjCMessage &Call,
70                                const LocationContext *LC) {
71  SmallVector<const MemRegion *, 8> RegionsToInvalidate;
72
73  if (Call.isObjCMessage()) {
74    // Invalidate all instance variables of the receiver of an ObjC message.
75    // FIXME: We should be able to do better with inter-procedural analysis.
76    if (const MemRegion *MR = Call.getInstanceMessageReceiver(LC).getAsRegion())
77      RegionsToInvalidate.push_back(MR);
78
79  } else if (Call.isCXXCall()) {
80    // Invalidate all instance variables for the callee of a C++ method call.
81    // FIXME: We should be able to do better with inter-procedural analysis.
82    // FIXME: We can probably do better for const versus non-const methods.
83    if (const MemRegion *Callee = Call.getCXXCallee().getAsRegion())
84      RegionsToInvalidate.push_back(Callee);
85
86  } else if (Call.isFunctionCall()) {
87    // Block calls invalidate all captured-by-reference values.
88    if (const MemRegion *Callee = Call.getFunctionCallee().getAsRegion()) {
89      if (isa<BlockDataRegion>(Callee))
90        RegionsToInvalidate.push_back(Callee);
91    }
92  }
93
94  for (unsigned idx = 0, e = Call.getNumArgs(); idx != e; ++idx) {
95    SVal V = Call.getArgSVal(idx);
96
97    // If we are passing a location wrapped as an integer, unwrap it and
98    // invalidate the values referred by the location.
99    if (nonloc::LocAsInteger *Wrapped = dyn_cast<nonloc::LocAsInteger>(&V))
100      V = Wrapped->getLoc();
101    else if (!isa<Loc>(V))
102      continue;
103
104    if (const MemRegion *R = V.getAsRegion()) {
105      // Invalidate the value of the variable passed by reference.
106
107      // Are we dealing with an ElementRegion?  If the element type is
108      // a basic integer type (e.g., char, int) and the underying region
109      // is a variable region then strip off the ElementRegion.
110      // FIXME: We really need to think about this for the general case
111      //   as sometimes we are reasoning about arrays and other times
112      //   about (char*), etc., is just a form of passing raw bytes.
113      //   e.g., void *p = alloca(); foo((char*)p);
114      if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
115        // Checking for 'integral type' is probably too promiscuous, but
116        // we'll leave it in for now until we have a systematic way of
117        // handling all of these cases.  Eventually we need to come up
118        // with an interface to StoreManager so that this logic can be
119        // approriately delegated to the respective StoreManagers while
120        // still allowing us to do checker-specific logic (e.g.,
121        // invalidating reference counts), probably via callbacks.
122        if (ER->getElementType()->isIntegralOrEnumerationType()) {
123          const MemRegion *superReg = ER->getSuperRegion();
124          if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
125              isa<ObjCIvarRegion>(superReg))
126            R = cast<TypedRegion>(superReg);
127        }
128        // FIXME: What about layers of ElementRegions?
129      }
130
131      // Mark this region for invalidation.  We batch invalidate regions
132      // below for efficiency.
133      RegionsToInvalidate.push_back(R);
134    } else {
135      // Nuke all other arguments passed by reference.
136      // FIXME: is this necessary or correct? This handles the non-Region
137      //  cases.  Is it ever valid to store to these?
138      State = State->unbindLoc(cast<Loc>(V));
139    }
140  }
141
142  // Invalidate designated regions using the batch invalidation API.
143
144  // FIXME: We can have collisions on the conjured symbol if the
145  //  expression *I also creates conjured symbols.  We probably want
146  //  to identify conjured symbols by an expression pair: the enclosing
147  //  expression (the context) and the expression itself.  This should
148  //  disambiguate conjured symbols.
149  unsigned Count = currentBuilderContext->getCurrentBlockCount();
150  StoreManager::InvalidatedSymbols IS;
151
152  // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
153  //  global variables.
154  return State->invalidateRegions(RegionsToInvalidate,
155                                  Call.getOriginExpr(), Count,
156                                  &IS, doesInvalidateGlobals(Call));
157
158}
159
160void ExprEngine::VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
161                               ExplodedNodeSet &dst) {
162  // Perform the previsit of the CallExpr.
163  ExplodedNodeSet dstPreVisit;
164  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, CE, *this);
165
166  // Now evaluate the call itself.
167  class DefaultEval : public GraphExpander {
168    ExprEngine &Eng;
169    const CallExpr *CE;
170  public:
171
172    DefaultEval(ExprEngine &eng, const CallExpr *ce)
173    : Eng(eng), CE(ce) {}
174    virtual void expandGraph(ExplodedNodeSet &Dst, ExplodedNode *Pred) {
175      // Should we inline the call?
176      if (Eng.getAnalysisManager().shouldInlineCall() &&
177          Eng.InlineCall(Dst, CE, Pred)) {
178        return;
179      }
180
181      // First handle the return value.
182      PureStmtNodeBuilder Bldr(Pred, Dst, *Eng.currentBuilderContext);
183
184      // Get the callee.
185      const Expr *Callee = CE->getCallee()->IgnoreParens();
186      const ProgramState *state = Pred->getState();
187      SVal L = state->getSVal(Callee);
188
189      // Figure out the result type. We do this dance to handle references.
190      QualType ResultTy;
191      if (const FunctionDecl *FD = L.getAsFunctionDecl())
192        ResultTy = FD->getResultType();
193      else
194        ResultTy = CE->getType();
195
196      if (CE->isLValue())
197        ResultTy = Eng.getContext().getPointerType(ResultTy);
198
199      // Conjure a symbol value to use as the result.
200      SValBuilder &SVB = Eng.getSValBuilder();
201      unsigned Count = Eng.currentBuilderContext->getCurrentBlockCount();
202      SVal RetVal = SVB.getConjuredSymbolVal(0, CE, ResultTy, Count);
203
204      // Generate a new state with the return value set.
205      state = state->BindExpr(CE, RetVal);
206
207      // Invalidate the arguments.
208      const LocationContext *LC = Pred->getLocationContext();
209      state = Eng.invalidateArguments(state, CallOrObjCMessage(CE, state), LC);
210
211      // And make the result node.
212      Bldr.generateNode(CE, Pred, state);
213    }
214  };
215
216  // Finally, evaluate the function call.  We try each of the checkers
217  // to see if the can evaluate the function call.
218  ExplodedNodeSet dstCallEvaluated;
219  DefaultEval defEval(*this, CE);
220  getCheckerManager().runCheckersForEvalCall(dstCallEvaluated,
221                                             dstPreVisit,
222                                             CE, *this, &defEval);
223
224  // Finally, perform the post-condition check of the CallExpr and store
225  // the created nodes in 'Dst'.
226  getCheckerManager().runCheckersForPostStmt(dst, dstCallEvaluated, CE,
227                                             *this);
228}
229
230void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred,
231                                 ExplodedNodeSet &Dst) {
232  ExplodedNodeSet Src;
233  {
234    PureStmtNodeBuilder Bldr(Pred, Src, *currentBuilderContext);
235    if (const Expr *RetE = RS->getRetValue()) {
236      // Record the returned expression in the state. It will be used in
237      // processCallExit to bind the return value to the call expr.
238      {
239        static SimpleProgramPointTag tag("ExprEngine: ReturnStmt");
240        const ProgramState *state = Pred->getState();
241        state = state->set<ReturnExpr>(RetE);
242        Pred = Bldr.generateNode(RetE, Pred, state, false, &tag);
243      }
244      // We may get a NULL Pred because we generated a cached node.
245      if (Pred) {
246        Bldr.takeNodes(Pred);
247        ExplodedNodeSet Tmp;
248        Visit(RetE, Pred, Tmp);
249        Bldr.addNodes(Tmp);
250      }
251    }
252  }
253
254  getCheckerManager().runCheckersForPreStmt(Dst, Src, RS, *this);
255}
256