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