ExprEngineCallAndReturn.cpp revision 183ba8e19d49ab1ae25d3cdd0a19591369c5ab9f
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  ProgramStateRef state = Pred->getState();
59
60  // Construct a new node and add it to the worklist.
61  bool isNew;
62  ExplodedNode *Node = G.getNode(Loc, state, false, &isNew);
63  Node->addPredecessor(Pred, G);
64  if (isNew)
65    Engine.getWorkList()->enqueue(Node);
66}
67
68// Find the last statement on the path to the exploded node and the
69// corresponding Block.
70static std::pair<const Stmt*,
71                 const CFGBlock*> getLastStmt(const ExplodedNode *Node) {
72  const Stmt *S = 0;
73  const CFGBlock *Blk = 0;
74  const StackFrameContext *SF =
75          Node->getLocation().getLocationContext()->getCurrentStackFrame();
76  while (Node) {
77    const ProgramPoint &PP = Node->getLocation();
78    // Skip any BlockEdges, empty blocks, and the CallExitBegin node.
79    if (isa<BlockEdge>(PP) || isa<CallExitBegin>(PP) || isa<BlockEntrance>(PP)){
80      assert(Node->pred_size() == 1);
81      Node = *Node->pred_begin();
82      continue;
83    }
84    // If we reached the CallEnter, the function has no statements.
85    if (isa<CallEnter>(PP))
86      break;
87    if (const StmtPoint *SP = dyn_cast<StmtPoint>(&PP)) {
88      S = SP->getStmt();
89      // Now, get the enclosing basic block.
90      while (Node && Node->pred_size() >=1 ) {
91        const ProgramPoint &PP = Node->getLocation();
92        if (isa<BlockEdge>(PP) &&
93            (PP.getLocationContext()->getCurrentStackFrame() == SF)) {
94          BlockEdge &EPP = cast<BlockEdge>(PP);
95          Blk = EPP.getDst();
96          break;
97        }
98        Node = *Node->pred_begin();
99      }
100      break;
101    }
102    break;
103  }
104  return std::pair<const Stmt*, const CFGBlock*>(S, Blk);
105}
106
107/// The call exit is simulated with a sequence of nodes, which occur between
108/// CallExitBegin and CallExitEnd. The following operations occur between the
109/// two program points:
110/// 1. CallExitBegin (triggers the start of call exit sequence)
111/// 2. Bind the return value
112/// 3. Run Remove dead bindings to clean up the dead symbols from the callee.
113/// 4. CallExitEnd (switch to the caller context)
114/// 5. PostStmt<CallExpr>
115void ExprEngine::processCallExit(ExplodedNode *CEBNode) {
116  // Step 1 CEBNode was generated before the call.
117
118  const StackFrameContext *calleeCtx =
119      CEBNode->getLocationContext()->getCurrentStackFrame();
120
121  // The parent context might not be a stack frame, so make sure we
122  // look up the first enclosing stack frame.
123  const StackFrameContext *callerCtx =
124    calleeCtx->getParent()->getCurrentStackFrame();
125
126  const Stmt *CE = calleeCtx->getCallSite();
127  ProgramStateRef state = CEBNode->getState();
128  // Find the last statement in the function and the corresponding basic block.
129  const Stmt *LastSt = 0;
130  const CFGBlock *Blk = 0;
131  llvm::tie(LastSt, Blk) = getLastStmt(CEBNode);
132
133  // Step 2: generate node with bound return value: CEBNode -> BindedRetNode.
134
135  // If the callee returns an expression, bind its value to CallExpr.
136  if (CE) {
137    if (const ReturnStmt *RS = dyn_cast_or_null<ReturnStmt>(LastSt)) {
138      const LocationContext *LCtx = CEBNode->getLocationContext();
139      SVal V = state->getSVal(RS, LCtx);
140      state = state->BindExpr(CE, calleeCtx->getParent(), V);
141    }
142
143    // Bind the constructed object value to CXXConstructExpr.
144    if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(CE)) {
145      loc::MemRegionVal This =
146        svalBuilder.getCXXThis(CCE->getConstructor()->getParent(), calleeCtx);
147      SVal ThisV = state->getSVal(This);
148
149      // Always bind the region to the CXXConstructExpr.
150      state = state->BindExpr(CCE, calleeCtx->getParent(), ThisV);
151    }
152  }
153
154  // Step 3: BindedRetNode -> CleanedNodes
155  // If we can find a statement and a block in the inlined function, run remove
156  // dead bindings before returning from the call. This is important to ensure
157  // that we report the issues such as leaks in the stack contexts in which
158  // they occurred.
159  ExplodedNodeSet CleanedNodes;
160  if (LastSt && Blk) {
161    static SimpleProgramPointTag retValBind("ExprEngine : Bind Return Value");
162    PostStmt Loc(LastSt, calleeCtx, &retValBind);
163    bool isNew;
164    ExplodedNode *BindedRetNode = G.getNode(Loc, state, false, &isNew);
165    BindedRetNode->addPredecessor(CEBNode, G);
166    if (!isNew)
167      return;
168
169    NodeBuilderContext Ctx(getCoreEngine(), Blk, BindedRetNode);
170    currentBuilderContext = &Ctx;
171    // Here, we call the Symbol Reaper with 0 statement and caller location
172    // context, telling it to clean up everything in the callee's context
173    // (and it's children). We use LastStmt as a diagnostic statement, which
174    // which the PreStmtPurge Dead point will be associated.
175    removeDead(BindedRetNode, CleanedNodes, 0, callerCtx, LastSt,
176               ProgramPoint::PostStmtPurgeDeadSymbolsKind);
177    currentBuilderContext = 0;
178  } else {
179    CleanedNodes.Add(CEBNode);
180  }
181
182  for (ExplodedNodeSet::iterator I = CleanedNodes.begin(),
183                                 E = CleanedNodes.end(); I != E; ++I) {
184
185    // Step 4: Generate the CallExit and leave the callee's context.
186    // CleanedNodes -> CEENode
187    CallExitEnd Loc(calleeCtx, callerCtx);
188    bool isNew;
189    ProgramStateRef CEEState = (*I == CEBNode) ? state : (*I)->getState();
190    ExplodedNode *CEENode = G.getNode(Loc, CEEState, false, &isNew);
191    CEENode->addPredecessor(*I, G);
192    if (!isNew)
193      return;
194
195    // Step 5: Perform the post-condition check of the CallExpr and enqueue the
196    // result onto the work list.
197    // CEENode -> Dst -> WorkList
198    ExplodedNodeSet Dst;
199    NodeBuilderContext Ctx(Engine, calleeCtx->getCallSiteBlock(), CEENode);
200    SaveAndRestore<const NodeBuilderContext*> NBCSave(currentBuilderContext,
201        &Ctx);
202    SaveAndRestore<unsigned> CBISave(currentStmtIdx, calleeCtx->getIndex());
203
204    // FIXME: This needs to call PostCall.
205    // FIXME: If/when we inline Objective-C messages, this also needs to call
206    // PostObjCMessage.
207    if (CE)
208      getCheckerManager().runCheckersForPostStmt(Dst, CEENode, CE, *this, true);
209    else
210      Dst.Add(CEENode);
211
212    // Enqueue the next element in the block.
213    for (ExplodedNodeSet::iterator PSI = Dst.begin(), PSE = Dst.end();
214                                   PSI != PSE; ++PSI) {
215      Engine.getWorkList()->enqueue(*PSI, calleeCtx->getCallSiteBlock(),
216                                    calleeCtx->getIndex()+1);
217    }
218  }
219}
220
221static unsigned getNumberStackFrames(const LocationContext *LCtx) {
222  unsigned count = 0;
223  while (LCtx) {
224    if (isa<StackFrameContext>(LCtx))
225      ++count;
226    LCtx = LCtx->getParent();
227  }
228  return count;
229}
230
231// Determine if we should inline the call.
232bool ExprEngine::shouldInlineDecl(const Decl *D, ExplodedNode *Pred) {
233  AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(D);
234  const CFG *CalleeCFG = CalleeADC->getCFG();
235
236  // It is possible that the CFG cannot be constructed.
237  // Be safe, and check if the CalleeCFG is valid.
238  if (!CalleeCFG)
239    return false;
240
241  if (getNumberStackFrames(Pred->getLocationContext())
242        == AMgr.InlineMaxStackDepth)
243    return false;
244
245  if (Engine.FunctionSummaries->hasReachedMaxBlockCount(D))
246    return false;
247
248  if (CalleeCFG->getNumBlockIDs() > AMgr.InlineMaxFunctionSize)
249    return false;
250
251  // Do not inline variadic calls (for now).
252  if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
253    if (BD->isVariadic())
254      return false;
255  }
256  else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
257    if (FD->isVariadic())
258      return false;
259  }
260
261  // It is possible that the live variables analysis cannot be
262  // run.  If so, bail out.
263  if (!CalleeADC->getAnalysis<RelaxedLiveVariables>())
264    return false;
265
266  return true;
267}
268
269bool ExprEngine::inlineCall(const CallEvent &Call,
270                            ExplodedNode *Pred) {
271  if (!getAnalysisManager().shouldInlineCall())
272    return false;
273
274  const Decl *D = Call.getRuntimeDefinition();
275  if (!D)
276    return false;
277
278  const LocationContext *CurLC = Pred->getLocationContext();
279  const StackFrameContext *CallerSFC = CurLC->getCurrentStackFrame();
280  const LocationContext *ParentOfCallee = 0;
281
282  switch (Call.getKind()) {
283  case CE_Function:
284  case CE_CXXMember:
285  case CE_CXXMemberOperator:
286    // These are always at least possible to inline.
287    break;
288  case CE_CXXConstructor:
289  case CE_CXXDestructor: {
290    // Only inline constructors and destructors if we built the CFGs for them
291    // properly.
292    const AnalysisDeclContext *ADC = CallerSFC->getAnalysisDeclContext();
293    if (!ADC->getCFGBuildOptions().AddImplicitDtors ||
294        !ADC->getCFGBuildOptions().AddInitializers)
295      return false;
296    // FIXME: This is a hack. We only process VarDecl destructors right now,
297    // so we should only inline VarDecl constructors.
298    if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call))
299      if (!isa<VarRegion>(Ctor->getCXXThisVal().getAsRegion()))
300        return false;
301    break;
302  }
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    break;
318  }
319
320  if (!shouldInlineDecl(D, Pred))
321    return false;
322
323  if (!ParentOfCallee)
324    ParentOfCallee = CallerSFC;
325
326  // This may be NULL, but that's fine.
327  const Expr *CallE = Call.getOriginExpr();
328
329  // Construct a new stack frame for the callee.
330  AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(D);
331  const StackFrameContext *CalleeSFC =
332    CalleeADC->getStackFrame(ParentOfCallee, CallE,
333                             currentBuilderContext->getBlock(),
334                             currentStmtIdx);
335
336  CallEnter Loc(CallE, CalleeSFC, CurLC);
337
338  // Construct a new state which contains the mapping from actual to
339  // formal arguments.
340  ProgramStateRef State = Pred->getState()->enterStackFrame(Call, CalleeSFC);
341
342  bool isNew;
343  if (ExplodedNode *N = G.getNode(Loc, State, false, &isNew)) {
344    N->addPredecessor(Pred, G);
345    if (isNew)
346      Engine.getWorkList()->enqueue(N);
347  }
348  return true;
349}
350
351static ProgramStateRef getInlineFailedState(ProgramStateRef State,
352                                            const Stmt *CallE) {
353  void *ReplayState = State->get<ReplayWithoutInlining>();
354  if (!ReplayState)
355    return 0;
356
357  assert(ReplayState == (const void*)CallE && "Backtracked to the wrong call.");
358  (void)CallE;
359
360  return State->remove<ReplayWithoutInlining>();
361}
362
363void ExprEngine::VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
364                               ExplodedNodeSet &dst) {
365  // Perform the previsit of the CallExpr.
366  ExplodedNodeSet dstPreVisit;
367  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, CE, *this);
368
369  // Get the callee kind.
370  CallEventKind K = classifyCallExpr(CE);
371
372  // Evaluate the function call.  We try each of the checkers
373  // to see if the can evaluate the function call.
374  ExplodedNodeSet dstCallEvaluated;
375  for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
376       I != E; ++I) {
377    ProgramStateRef State = (*I)->getState();
378    const LocationContext *LCtx = (*I)->getLocationContext();
379
380    // Evaluate the call.
381    switch (K) {
382    case CE_Function:
383      evalCall(dstCallEvaluated, *I, FunctionCall(CE, State, LCtx));
384      break;
385    case CE_CXXMember:
386      evalCall(dstCallEvaluated, *I, CXXMemberCall(cast<CXXMemberCallExpr>(CE),
387                                                   State, LCtx));
388      break;
389    case CE_CXXMemberOperator:
390      evalCall(dstCallEvaluated, *I,
391               CXXMemberOperatorCall(cast<CXXOperatorCallExpr>(CE),
392                                     State, LCtx));
393      break;
394    case CE_Block:
395      evalCall(dstCallEvaluated, *I, BlockCall(CE, State, LCtx));
396      break;
397    default:
398      llvm_unreachable("Non-CallExpr CallEventKind");
399    }
400  }
401
402  // Finally, perform the post-condition check of the CallExpr and store
403  // the created nodes in 'Dst'.
404  // Note that if the call was inlined, dstCallEvaluated will be empty.
405  // The post-CallExpr check will occur in processCallExit.
406  getCheckerManager().runCheckersForPostStmt(dst, dstCallEvaluated, CE,
407                                             *this);
408}
409
410void ExprEngine::evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred,
411                          const SimpleCall &Call) {
412  // Run any pre-call checks using the generic call interface.
413  ExplodedNodeSet dstPreVisit;
414  getCheckerManager().runCheckersForPreCall(dstPreVisit, Pred, Call, *this);
415
416  // Actually evaluate the function call.  We try each of the checkers
417  // to see if the can evaluate the function call, and get a callback at
418  // defaultEvalCall if all of them fail.
419  ExplodedNodeSet dstCallEvaluated;
420  getCheckerManager().runCheckersForEvalCall(dstCallEvaluated, dstPreVisit,
421                                             Call, *this);
422
423  // Finally, run any post-call checks.
424  getCheckerManager().runCheckersForPostCall(Dst, dstCallEvaluated,
425                                             Call, *this);
426}
427
428ProgramStateRef ExprEngine::bindReturnValue(const CallEvent &Call,
429                                            const LocationContext *LCtx,
430                                            ProgramStateRef State) {
431  const Expr *E = Call.getOriginExpr();
432  if (!E)
433    return State;
434
435  // Some method families have known return values.
436  if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(&Call)) {
437    switch (Msg->getMethodFamily()) {
438    default:
439      break;
440    case OMF_autorelease:
441    case OMF_retain:
442    case OMF_self: {
443      // These methods return their receivers.
444      return State->BindExpr(E, LCtx, Msg->getReceiverSVal());
445    }
446    }
447  }
448
449  // Conjure a symbol if the return value is unknown.
450  QualType ResultTy = Call.getResultType();
451  SValBuilder &SVB = getSValBuilder();
452  unsigned Count = currentBuilderContext->getCurrentBlockCount();
453  SVal R = SVB.getConjuredSymbolVal(0, E, LCtx, ResultTy, Count);
454  return State->BindExpr(E, LCtx, R);
455}
456
457void ExprEngine::defaultEvalCall(NodeBuilder &Bldr, ExplodedNode *Pred,
458                                 const CallEvent &Call) {
459  ProgramStateRef State = 0;
460  const Expr *E = Call.getOriginExpr();
461
462  // Try to inline the call.
463  // The origin expression here is just used as a kind of checksum;
464  // for CallEvents that do not have origin expressions, this should still be
465  // safe.
466  State = getInlineFailedState(Pred->getState(), E);
467  if (State == 0 && inlineCall(Call, Pred)) {
468    // If we inlined the call, the successor has been manually added onto
469    // the work list and we should not consider it for subsequent call
470    // handling steps.
471    Bldr.takeNodes(Pred);
472    return;
473  }
474
475  // If we can't inline it, handle the return value and invalidate the regions.
476  if (State == 0)
477    State = Pred->getState();
478
479  // Invalidate any regions touched by the call.
480  unsigned Count = currentBuilderContext->getCurrentBlockCount();
481  State = Call.invalidateRegions(Count, State);
482
483  // Construct and bind the return value.
484  State = bindReturnValue(Call, Pred->getLocationContext(), State);
485
486  // And make the result node.
487  Bldr.generateNode(Call.getProgramPoint(), State, Pred);
488}
489
490void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred,
491                                 ExplodedNodeSet &Dst) {
492
493  ExplodedNodeSet dstPreVisit;
494  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, RS, *this);
495
496  StmtNodeBuilder B(dstPreVisit, Dst, *currentBuilderContext);
497
498  if (RS->getRetValue()) {
499    for (ExplodedNodeSet::iterator it = dstPreVisit.begin(),
500                                  ei = dstPreVisit.end(); it != ei; ++it) {
501      B.generateNode(RS, *it, (*it)->getState());
502    }
503  }
504}
505