ExprEngineCallAndReturn.cpp revision 852aa0d2c5d2d1faf2d77b5aa3c0848068a342c5
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/Analysis/Analyses/LiveVariables.h"
15#include "clang/StaticAnalyzer/Core/CheckerManager.h"
16#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
17#include "clang/StaticAnalyzer/Core/PathSensitive/Calls.h"
18#include "clang/AST/DeclCXX.h"
19#include "llvm/ADT/SmallSet.h"
20#include "llvm/Support/SaveAndRestore.h"
21
22using namespace clang;
23using namespace ento;
24
25static CallEventKind classifyCallExpr(const CallExpr *CE) {
26  if (isa<CXXMemberCallExpr>(CE))
27    return CE_CXXMember;
28
29  const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE);
30  if (OpCE) {
31    const FunctionDecl *DirectCallee = CE->getDirectCallee();
32    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
33      if (MD->isInstance())
34        return CE_CXXMemberOperator;
35  } else if (CE->getCallee()->getType()->isBlockPointerType()) {
36    return CE_Block;
37  }
38
39  return CE_Function;
40}
41
42void ExprEngine::processCallEnter(CallEnter CE, ExplodedNode *Pred) {
43  // Get the entry block in the CFG of the callee.
44  const StackFrameContext *calleeCtx = CE.getCalleeContext();
45  const CFG *CalleeCFG = calleeCtx->getCFG();
46  const CFGBlock *Entry = &(CalleeCFG->getEntry());
47
48  // Validate the CFG.
49  assert(Entry->empty());
50  assert(Entry->succ_size() == 1);
51
52  // Get the solitary sucessor.
53  const CFGBlock *Succ = *(Entry->succ_begin());
54
55  // Construct an edge representing the starting location in the callee.
56  BlockEdge Loc(Entry, Succ, calleeCtx);
57
58  // Construct a new state which contains the mapping from actual to
59  // formal arguments.
60  const LocationContext *callerCtx = Pred->getLocationContext();
61  ProgramStateRef state = Pred->getState()->enterStackFrame(callerCtx,
62                                                            calleeCtx);
63
64  // Construct a new node and add it to the worklist.
65  bool isNew;
66  ExplodedNode *Node = G.getNode(Loc, state, false, &isNew);
67  Node->addPredecessor(Pred, G);
68  if (isNew)
69    Engine.getWorkList()->enqueue(Node);
70}
71
72// Find the last statement on the path to the exploded node and the
73// corresponding Block.
74static std::pair<const Stmt*,
75                 const CFGBlock*> getLastStmt(const ExplodedNode *Node) {
76  const Stmt *S = 0;
77  const CFGBlock *Blk = 0;
78  const StackFrameContext *SF =
79          Node->getLocation().getLocationContext()->getCurrentStackFrame();
80  while (Node) {
81    const ProgramPoint &PP = Node->getLocation();
82    // Skip any BlockEdges, empty blocks, and the CallExitBegin node.
83    if (isa<BlockEdge>(PP) || isa<CallExitBegin>(PP) || isa<BlockEntrance>(PP)){
84      assert(Node->pred_size() == 1);
85      Node = *Node->pred_begin();
86      continue;
87    }
88    // If we reached the CallEnter, the function has no statements.
89    if (isa<CallEnter>(PP))
90      break;
91    if (const StmtPoint *SP = dyn_cast<StmtPoint>(&PP)) {
92      S = SP->getStmt();
93      // Now, get the enclosing basic block.
94      while (Node && Node->pred_size() >=1 ) {
95        const ProgramPoint &PP = Node->getLocation();
96        if (isa<BlockEdge>(PP) &&
97            (PP.getLocationContext()->getCurrentStackFrame() == SF)) {
98          BlockEdge &EPP = cast<BlockEdge>(PP);
99          Blk = EPP.getDst();
100          break;
101        }
102        Node = *Node->pred_begin();
103      }
104      break;
105    }
106    break;
107  }
108  return std::pair<const Stmt*, const CFGBlock*>(S, Blk);
109}
110
111/// The call exit is simulated with a sequence of nodes, which occur between
112/// CallExitBegin and CallExitEnd. The following operations occur between the
113/// two program points:
114/// 1. CallExitBegin (triggers the start of call exit sequence)
115/// 2. Bind the return value
116/// 3. Run Remove dead bindings to clean up the dead symbols from the callee.
117/// 4. CallExitEnd (switch to the caller context)
118/// 5. PostStmt<CallExpr>
119void ExprEngine::processCallExit(ExplodedNode *CEBNode) {
120  // Step 1 CEBNode was generated before the call.
121
122  const StackFrameContext *calleeCtx =
123      CEBNode->getLocationContext()->getCurrentStackFrame();
124
125  // The parent context might not be a stack frame, so make sure we
126  // look up the first enclosing stack frame.
127  const StackFrameContext *callerCtx =
128    calleeCtx->getParent()->getCurrentStackFrame();
129
130  const Stmt *CE = calleeCtx->getCallSite();
131  ProgramStateRef state = CEBNode->getState();
132  // Find the last statement in the function and the corresponding basic block.
133  const Stmt *LastSt = 0;
134  const CFGBlock *Blk = 0;
135  llvm::tie(LastSt, Blk) = getLastStmt(CEBNode);
136
137  // Step 2: generate node with bound return value: CEBNode -> BindedRetNode.
138
139  // If the callee returns an expression, bind its value to CallExpr.
140  if (CE) {
141    if (const ReturnStmt *RS = dyn_cast_or_null<ReturnStmt>(LastSt)) {
142      const LocationContext *LCtx = CEBNode->getLocationContext();
143      SVal V = state->getSVal(RS, LCtx);
144      state = state->BindExpr(CE, callerCtx, V);
145    }
146
147    // Bind the constructed object value to CXXConstructExpr.
148    if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(CE)) {
149      loc::MemRegionVal This =
150        svalBuilder.getCXXThis(CCE->getConstructor()->getParent(), calleeCtx);
151      SVal ThisV = state->getSVal(This);
152
153      // Always bind the region to the CXXConstructExpr.
154      state = state->BindExpr(CCE, CEBNode->getLocationContext(), ThisV);
155    }
156  }
157
158  static SimpleProgramPointTag retValBindTag("ExprEngine : Bind Return Value");
159  PostStmt Loc(LastSt, calleeCtx, &retValBindTag);
160  bool isNew;
161  ExplodedNode *BindedRetNode = G.getNode(Loc, state, false, &isNew);
162  BindedRetNode->addPredecessor(CEBNode, G);
163  if (!isNew)
164    return;
165
166  // Step 3: BindedRetNode -> CleanedNodes
167  // If we can find a statement and a block in the inlined function, run remove
168  // dead bindings before returning from the call. This is important to ensure
169  // that we report the issues such as leaks in the stack contexts in which
170  // they occurred.
171  ExplodedNodeSet CleanedNodes;
172  if (LastSt && Blk) {
173    NodeBuilderContext Ctx(getCoreEngine(), Blk, BindedRetNode);
174    currentBuilderContext = &Ctx;
175    // Here, we call the Symbol Reaper with 0 statement and caller location
176    // context, telling it to clean up everything in the callee's context
177    // (and it's children). We use LastStmt as a diagnostic statement, which
178    // which the PreStmtPurge Dead point will be associated.
179    removeDead(BindedRetNode, CleanedNodes, 0, callerCtx, LastSt,
180               ProgramPoint::PostStmtPurgeDeadSymbolsKind);
181    currentBuilderContext = 0;
182  } else {
183    CleanedNodes.Add(CEBNode);
184  }
185
186  for (ExplodedNodeSet::iterator I = CleanedNodes.begin(),
187                                 E = CleanedNodes.end(); I != E; ++I) {
188
189    // Step 4: Generate the CallExit and leave the callee's context.
190    // CleanedNodes -> CEENode
191    CallExitEnd Loc(calleeCtx, callerCtx);
192    bool isNew;
193    ExplodedNode *CEENode = G.getNode(Loc, (*I)->getState(), false, &isNew);
194    CEENode->addPredecessor(*I, G);
195    if (!isNew)
196      return;
197
198    // Step 5: Perform the post-condition check of the CallExpr and enqueue the
199    // result onto the work list.
200    // CEENode -> Dst -> WorkList
201    ExplodedNodeSet Dst;
202    NodeBuilderContext Ctx(Engine, calleeCtx->getCallSiteBlock(), CEENode);
203    SaveAndRestore<const NodeBuilderContext*> NBCSave(currentBuilderContext,
204        &Ctx);
205    SaveAndRestore<unsigned> CBISave(currentStmtIdx, calleeCtx->getIndex());
206
207    // FIXME: This needs to call PostCall.
208    if (CE)
209      getCheckerManager().runCheckersForPostStmt(Dst, CEENode, CE, *this, true);
210
211    // Enqueue the next element in the block.
212    for (ExplodedNodeSet::iterator PSI = Dst.begin(), PSE = Dst.end();
213                                   PSI != PSE; ++PSI) {
214      Engine.getWorkList()->enqueue(*PSI, calleeCtx->getCallSiteBlock(),
215                                    calleeCtx->getIndex()+1);
216    }
217  }
218}
219
220static unsigned getNumberStackFrames(const LocationContext *LCtx) {
221  unsigned count = 0;
222  while (LCtx) {
223    if (isa<StackFrameContext>(LCtx))
224      ++count;
225    LCtx = LCtx->getParent();
226  }
227  return count;
228}
229
230// Determine if we should inline the call.
231bool ExprEngine::shouldInlineDecl(const Decl *D, ExplodedNode *Pred) {
232  // FIXME: default constructors don't have bodies.
233  if (!D->hasBody())
234    return false;
235
236  AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(D);
237  const CFG *CalleeCFG = CalleeADC->getCFG();
238
239  // It is possible that the CFG cannot be constructed.
240  // Be safe, and check if the CalleeCFG is valid.
241  if (!CalleeCFG)
242    return false;
243
244  if (getNumberStackFrames(Pred->getLocationContext())
245        == AMgr.InlineMaxStackDepth)
246    return false;
247
248  if (Engine.FunctionSummaries->hasReachedMaxBlockCount(D))
249    return false;
250
251  if (CalleeCFG->getNumBlockIDs() > AMgr.InlineMaxFunctionSize)
252    return false;
253
254  // Do not inline variadic calls (for now).
255  if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
256    if (BD->isVariadic())
257      return false;
258  }
259  else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
260    if (FD->isVariadic())
261      return false;
262  }
263
264  // It is possible that the live variables analysis cannot be
265  // run.  If so, bail out.
266  if (!CalleeADC->getAnalysis<RelaxedLiveVariables>())
267    return false;
268
269  return true;
270}
271
272bool ExprEngine::inlineCall(ExplodedNodeSet &Dst,
273                            const CallEvent &Call,
274                            ExplodedNode *Pred) {
275  if (!getAnalysisManager().shouldInlineCall())
276    return false;
277
278  const StackFrameContext *CallerSFC =
279    Pred->getLocationContext()->getCurrentStackFrame();
280
281  const Decl *D = Call.getDefinition();
282  if (!D)
283    return false;
284
285  const LocationContext *ParentOfCallee = 0;
286
287  switch (Call.getKind()) {
288  case CE_Function:
289  case CE_CXXMember:
290    // These are always at least possible to inline.
291    break;
292  case CE_CXXMemberOperator:
293    // FIXME: This should be possible to inline, but
294    // RegionStore::enterStackFrame isn't smart enough to handle the first
295    // argument being 'this'. The correct solution is to use CallEvent in
296    // enterStackFrame as well.
297    return false;
298  case CE_CXXConstructor:
299  case CE_CXXDestructor:
300    // Do not inline constructors until we can really model destructors.
301    // This is unfortunate, but basically necessary for smart pointers and such.
302    return false;
303  case CE_CXXAllocator:
304    // Do not inline allocators until we model deallocators.
305    // This is unfortunate, but basically necessary for smart pointers and such.
306    return false;
307  case CE_Block: {
308    const BlockDataRegion *BR = cast<BlockCall>(Call).getBlockRegion();
309    assert(BR && "If we have the block definition we should have its region");
310    AnalysisDeclContext *BlockCtx = AMgr.getAnalysisDeclContext(D);
311    ParentOfCallee = BlockCtx->getBlockInvocationContext(CallerSFC,
312                                                         cast<BlockDecl>(D),
313                                                         BR);
314    break;
315  }
316  case CE_ObjCMessage:
317  case CE_ObjCPropertyAccess:
318    // These always use dynamic dispatch; enabling inlining means assuming
319    // that a particular method will be called at runtime.
320    return false;
321  }
322
323  if (!shouldInlineDecl(D, Pred))
324    return false;
325
326  if (!ParentOfCallee)
327    ParentOfCallee = CallerSFC;
328
329  // This may be NULL, but that's fine.
330  const Expr *CallE = Call.getOriginExpr();
331
332  // Construct a new stack frame for the callee.
333  AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(D);
334  const StackFrameContext *CalleeSFC =
335    CalleeADC->getStackFrame(ParentOfCallee, CallE,
336                             currentBuilderContext->getBlock(),
337                             currentStmtIdx);
338
339  CallEnter Loc(CallE, CalleeSFC, Pred->getLocationContext());
340  bool isNew;
341  if (ExplodedNode *N = G.getNode(Loc, Pred->getState(), false, &isNew)) {
342    N->addPredecessor(Pred, G);
343    if (isNew)
344      Engine.getWorkList()->enqueue(N);
345  }
346  return true;
347}
348
349static ProgramStateRef getInlineFailedState(ExplodedNode *&N,
350                                            const Stmt *CallE) {
351  void *ReplayState = N->getState()->get<ReplayWithoutInlining>();
352  if (!ReplayState)
353    return 0;
354
355  assert(ReplayState == (const void*)CallE && "Backtracked to the wrong call.");
356  (void)CallE;
357
358  return N->getState()->remove<ReplayWithoutInlining>();
359}
360
361void ExprEngine::VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
362                               ExplodedNodeSet &dst) {
363  // Perform the previsit of the CallExpr.
364  ExplodedNodeSet dstPreVisit;
365  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, CE, *this);
366
367  // Get the callee kind.
368  CallEventKind K = classifyCallExpr(CE);
369
370  // Evaluate the function call.  We try each of the checkers
371  // to see if the can evaluate the function call.
372  ExplodedNodeSet dstCallEvaluated;
373  for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
374       I != E; ++I) {
375    ProgramStateRef State = (*I)->getState();
376    const LocationContext *LCtx = (*I)->getLocationContext();
377
378    // Evaluate the call.
379    switch (K) {
380    case CE_Function:
381      evalCall(dstCallEvaluated, *I, FunctionCall(CE, State, LCtx));
382      break;
383    case CE_CXXMember:
384      evalCall(dstCallEvaluated, *I, CXXMemberCall(cast<CXXMemberCallExpr>(CE),
385                                                   State, LCtx));
386      break;
387    case CE_CXXMemberOperator:
388      evalCall(dstCallEvaluated, *I,
389               CXXMemberOperatorCall(cast<CXXOperatorCallExpr>(CE),
390                                     State, LCtx));
391      break;
392    case CE_Block:
393      evalCall(dstCallEvaluated, *I, BlockCall(CE, State, LCtx));
394      break;
395    default:
396      llvm_unreachable("Non-CallExpr CallEventKind");
397    }
398  }
399
400  // Finally, perform the post-condition check of the CallExpr and store
401  // the created nodes in 'Dst'.
402  // Note that if the call was inlined, dstCallEvaluated will be empty.
403  // The post-CallExpr check will occur in processCallExit.
404  getCheckerManager().runCheckersForPostStmt(dst, dstCallEvaluated, CE,
405                                             *this);
406}
407
408void ExprEngine::evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred,
409                          const SimpleCall &Call) {
410  // Run any pre-call checks using the generic call interface.
411  ExplodedNodeSet dstPreVisit;
412  getCheckerManager().runCheckersForPreCall(dstPreVisit, Pred, Call, *this);
413
414  // Actually evaluate the function call.  We try each of the checkers
415  // to see if the can evaluate the function call, and get a callback at
416  // defaultEvalCall if all of them fail.
417  ExplodedNodeSet dstCallEvaluated;
418  getCheckerManager().runCheckersForEvalCall(dstCallEvaluated, dstPreVisit,
419                                             Call, *this);
420
421  // Finally, run any post-call checks.
422  getCheckerManager().runCheckersForPostCall(Dst, dstCallEvaluated,
423                                             Call, *this);
424}
425
426void ExprEngine::defaultEvalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred,
427                                 const CallEvent &Call) {
428  // Try to inline the call.
429  // The origin expression here is just used as a kind of checksum;
430  // for CallEvents that do not have origin expressions, this should still be
431  // safe.
432  const Expr *E = Call.getOriginExpr();
433  ProgramStateRef state = getInlineFailedState(Pred, E);
434  if (state == 0 && inlineCall(Dst, Call, Pred))
435    return;
436
437  // If we can't inline it, handle the return value and invalidate the regions.
438  NodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
439
440  // Invalidate any regions touched by the call.
441  unsigned Count = currentBuilderContext->getCurrentBlockCount();
442  if (state == 0)
443    state = Pred->getState();
444  state = Call.invalidateRegions(Count, state);
445
446  // Conjure a symbol value to use as the result.
447  if (E) {
448    QualType ResultTy = Call.getResultType();
449    SValBuilder &SVB = getSValBuilder();
450    const LocationContext *LCtx = Pred->getLocationContext();
451    SVal RetVal = SVB.getConjuredSymbolVal(0, E, LCtx, ResultTy, Count);
452
453    state = state->BindExpr(E, LCtx, RetVal);
454  }
455
456  // And make the result node.
457  Bldr.generateNode(Call.getProgramPoint(), state, Pred);
458}
459
460void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred,
461                                 ExplodedNodeSet &Dst) {
462
463  ExplodedNodeSet dstPreVisit;
464  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, RS, *this);
465
466  StmtNodeBuilder B(dstPreVisit, Dst, *currentBuilderContext);
467
468  if (RS->getRetValue()) {
469    for (ExplodedNodeSet::iterator it = dstPreVisit.begin(),
470                                  ei = dstPreVisit.end(); it != ei; ++it) {
471      B.generateNode(RS, *it, (*it)->getState());
472    }
473  }
474}
475