ExprEngineCallAndReturn.cpp revision 6fe4dfbc9e5a7018763b1d898876d9b2b8ec3425
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#define DEBUG_TYPE "ExprEngine"
15
16#include "clang/Analysis/Analyses/LiveVariables.h"
17#include "clang/StaticAnalyzer/Core/CheckerManager.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/ParentMap.h"
22#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/Support/SaveAndRestore.h"
25
26using namespace clang;
27using namespace ento;
28
29STATISTIC(NumOfDynamicDispatchPathSplits,
30  "The # of times we split the path due to imprecise dynamic dispatch info");
31
32STATISTIC(NumInlinedCalls,
33  "The # of times we inlined a call");
34
35void ExprEngine::processCallEnter(CallEnter CE, ExplodedNode *Pred) {
36  // Get the entry block in the CFG of the callee.
37  const StackFrameContext *calleeCtx = CE.getCalleeContext();
38  const CFG *CalleeCFG = calleeCtx->getCFG();
39  const CFGBlock *Entry = &(CalleeCFG->getEntry());
40
41  // Validate the CFG.
42  assert(Entry->empty());
43  assert(Entry->succ_size() == 1);
44
45  // Get the solitary sucessor.
46  const CFGBlock *Succ = *(Entry->succ_begin());
47
48  // Construct an edge representing the starting location in the callee.
49  BlockEdge Loc(Entry, Succ, calleeCtx);
50
51  ProgramStateRef state = Pred->getState();
52
53  // Construct a new node and add it to the worklist.
54  bool isNew;
55  ExplodedNode *Node = G.getNode(Loc, state, false, &isNew);
56  Node->addPredecessor(Pred, G);
57  if (isNew)
58    Engine.getWorkList()->enqueue(Node);
59}
60
61// Find the last statement on the path to the exploded node and the
62// corresponding Block.
63static std::pair<const Stmt*,
64                 const CFGBlock*> getLastStmt(const ExplodedNode *Node) {
65  const Stmt *S = 0;
66  const StackFrameContext *SF =
67          Node->getLocation().getLocationContext()->getCurrentStackFrame();
68
69  // Back up through the ExplodedGraph until we reach a statement node.
70  while (Node) {
71    const ProgramPoint &PP = Node->getLocation();
72
73    if (const StmtPoint *SP = dyn_cast<StmtPoint>(&PP)) {
74      S = SP->getStmt();
75      break;
76    } else if (const CallExitEnd *CEE = dyn_cast<CallExitEnd>(&PP)) {
77      S = CEE->getCalleeContext()->getCallSite();
78      if (S)
79        break;
80      // If we have an implicit call, we'll probably end up with a
81      // StmtPoint inside the callee, which is acceptable.
82      // (It's possible a function ONLY contains implicit calls -- such as an
83      // implicitly-generated destructor -- so we shouldn't just skip back to
84      // the CallEnter node and keep going.)
85    } else if (const CallEnter *CE = dyn_cast<CallEnter>(&PP)) {
86      // If we reached the CallEnter for this function, it has no statements.
87      if (CE->getCalleeContext() == SF)
88        break;
89    }
90
91    Node = *Node->pred_begin();
92  }
93
94  const CFGBlock *Blk = 0;
95  if (S) {
96    // Now, get the enclosing basic block.
97    while (Node && Node->pred_size() >=1 ) {
98      const ProgramPoint &PP = Node->getLocation();
99      if (isa<BlockEdge>(PP) &&
100          (PP.getLocationContext()->getCurrentStackFrame() == SF)) {
101        BlockEdge &EPP = cast<BlockEdge>(PP);
102        Blk = EPP.getDst();
103        break;
104      }
105      Node = *Node->pred_begin();
106    }
107  }
108
109  return std::pair<const Stmt*, const CFGBlock*>(S, Blk);
110}
111
112/// The call exit is simulated with a sequence of nodes, which occur between
113/// CallExitBegin and CallExitEnd. The following operations occur between the
114/// two program points:
115/// 1. CallExitBegin (triggers the start of call exit sequence)
116/// 2. Bind the return value
117/// 3. Run Remove dead bindings to clean up the dead symbols from the callee.
118/// 4. CallExitEnd (switch to the caller context)
119/// 5. PostStmt<CallExpr>
120void ExprEngine::processCallExit(ExplodedNode *CEBNode) {
121  // Step 1 CEBNode was generated before the call.
122
123  const StackFrameContext *calleeCtx =
124      CEBNode->getLocationContext()->getCurrentStackFrame();
125
126  // The parent context might not be a stack frame, so make sure we
127  // look up the first enclosing stack frame.
128  const StackFrameContext *callerCtx =
129    calleeCtx->getParent()->getCurrentStackFrame();
130
131  const Stmt *CE = calleeCtx->getCallSite();
132  ProgramStateRef state = CEBNode->getState();
133  // Find the last statement in the function and the corresponding basic block.
134  const Stmt *LastSt = 0;
135  const CFGBlock *Blk = 0;
136  llvm::tie(LastSt, Blk) = getLastStmt(CEBNode);
137
138  // Step 2: generate node with bound return value: CEBNode -> BindedRetNode.
139
140  // If the callee returns an expression, bind its value to CallExpr.
141  if (CE) {
142    if (const ReturnStmt *RS = dyn_cast_or_null<ReturnStmt>(LastSt)) {
143      const LocationContext *LCtx = CEBNode->getLocationContext();
144      SVal V = state->getSVal(RS, LCtx);
145      state = state->BindExpr(CE, callerCtx, V);
146    }
147
148    // Bind the constructed object value to CXXConstructExpr.
149    if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(CE)) {
150      loc::MemRegionVal This =
151        svalBuilder.getCXXThis(CCE->getConstructor()->getParent(), calleeCtx);
152      SVal ThisV = state->getSVal(This);
153
154      // Always bind the region to the CXXConstructExpr.
155      state = state->BindExpr(CCE, callerCtx, ThisV);
156    }
157  }
158
159  // Generate a CallEvent /before/ cleaning the state, so that we can get the
160  // correct value for 'this' (if necessary).
161  CallEventManager &CEMgr = getStateManager().getCallEventManager();
162  CallEventRef<> Call = CEMgr.getCaller(calleeCtx, state);
163
164  // Step 3: BindedRetNode -> CleanedNodes
165  // If we can find a statement and a block in the inlined function, run remove
166  // dead bindings before returning from the call. This is important to ensure
167  // that we report the issues such as leaks in the stack contexts in which
168  // they occurred.
169  ExplodedNodeSet CleanedNodes;
170  if (LastSt && Blk) {
171    static SimpleProgramPointTag retValBind("ExprEngine : Bind Return Value");
172    PostStmt Loc(LastSt, calleeCtx, &retValBind);
173    bool isNew;
174    ExplodedNode *BindedRetNode = G.getNode(Loc, state, false, &isNew);
175    BindedRetNode->addPredecessor(CEBNode, G);
176    if (!isNew)
177      return;
178
179    NodeBuilderContext Ctx(getCoreEngine(), Blk, BindedRetNode);
180    currBldrCtx = &Ctx;
181    // Here, we call the Symbol Reaper with 0 statement and caller location
182    // context, telling it to clean up everything in the callee's context
183    // (and it's children). We use LastStmt as a diagnostic statement, which
184    // which the PreStmtPurge Dead point will be associated.
185    removeDead(BindedRetNode, CleanedNodes, 0, callerCtx, LastSt,
186               ProgramPoint::PostStmtPurgeDeadSymbolsKind);
187    currBldrCtx = 0;
188  } else {
189    CleanedNodes.Add(CEBNode);
190  }
191
192  for (ExplodedNodeSet::iterator I = CleanedNodes.begin(),
193                                 E = CleanedNodes.end(); I != E; ++I) {
194
195    // Step 4: Generate the CallExit and leave the callee's context.
196    // CleanedNodes -> CEENode
197    CallExitEnd Loc(calleeCtx, callerCtx);
198    bool isNew;
199    ProgramStateRef CEEState = (*I == CEBNode) ? state : (*I)->getState();
200    ExplodedNode *CEENode = G.getNode(Loc, CEEState, false, &isNew);
201    CEENode->addPredecessor(*I, G);
202    if (!isNew)
203      return;
204
205    // Step 5: Perform the post-condition check of the CallExpr and enqueue the
206    // result onto the work list.
207    // CEENode -> Dst -> WorkList
208    NodeBuilderContext Ctx(Engine, calleeCtx->getCallSiteBlock(), CEENode);
209    SaveAndRestore<const NodeBuilderContext*> NBCSave(currBldrCtx,
210        &Ctx);
211    SaveAndRestore<unsigned> CBISave(currStmtIdx, calleeCtx->getIndex());
212
213    CallEventRef<> UpdatedCall = Call.cloneWithState(CEEState);
214
215    ExplodedNodeSet DstPostCall;
216    getCheckerManager().runCheckersForPostCall(DstPostCall, CEENode,
217                                               *UpdatedCall, *this,
218                                               /*WasInlined=*/true);
219
220    ExplodedNodeSet Dst;
221    if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
222      getCheckerManager().runCheckersForPostObjCMessage(Dst, DstPostCall, *Msg,
223                                                        *this,
224                                                        /*WasInlined=*/true);
225    } else if (CE) {
226      getCheckerManager().runCheckersForPostStmt(Dst, DstPostCall, CE,
227                                                 *this, /*WasInlined=*/true);
228    } else {
229      Dst.insert(DstPostCall);
230    }
231
232    // Enqueue the next element in the block.
233    for (ExplodedNodeSet::iterator PSI = Dst.begin(), PSE = Dst.end();
234                                   PSI != PSE; ++PSI) {
235      Engine.getWorkList()->enqueue(*PSI, calleeCtx->getCallSiteBlock(),
236                                    calleeCtx->getIndex()+1);
237    }
238  }
239}
240
241static unsigned getNumberStackFrames(const LocationContext *LCtx) {
242  unsigned count = 0;
243  while (LCtx) {
244    if (isa<StackFrameContext>(LCtx))
245      ++count;
246    LCtx = LCtx->getParent();
247  }
248  return count;
249}
250
251// Determine if we should inline the call.
252bool ExprEngine::shouldInlineDecl(const Decl *D, ExplodedNode *Pred) {
253  AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(D);
254  const CFG *CalleeCFG = CalleeADC->getCFG();
255
256  // It is possible that the CFG cannot be constructed.
257  // Be safe, and check if the CalleeCFG is valid.
258  if (!CalleeCFG)
259    return false;
260
261  if (getNumberStackFrames(Pred->getLocationContext())
262        == AMgr.InlineMaxStackDepth)
263    return false;
264
265  if (Engine.FunctionSummaries->hasReachedMaxBlockCount(D))
266    return false;
267
268  if (CalleeCFG->getNumBlockIDs() > AMgr.InlineMaxFunctionSize)
269    return false;
270
271  // Do not inline variadic calls (for now).
272  if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
273    if (BD->isVariadic())
274      return false;
275  }
276  else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
277    if (FD->isVariadic())
278      return false;
279  }
280
281  // It is possible that the live variables analysis cannot be
282  // run.  If so, bail out.
283  if (!CalleeADC->getAnalysis<RelaxedLiveVariables>())
284    return false;
285
286  return true;
287}
288
289/// The GDM component containing the dynamic dispatch bifurcation info. When
290/// the exact type of the receiver is not known, we want to explore both paths -
291/// one on which we do inline it and the other one on which we don't. This is
292/// done to ensure we do not drop coverage.
293/// This is the map from the receiver region to a bool, specifying either we
294/// consider this region's information precise or not along the given path.
295namespace clang {
296namespace ento {
297enum DynamicDispatchMode { DynamicDispatchModeInlined = 1,
298                           DynamicDispatchModeConservative };
299
300struct DynamicDispatchBifurcationMap {};
301typedef llvm::ImmutableMap<const MemRegion*,
302                           unsigned int> DynamicDispatchBifur;
303template<> struct ProgramStateTrait<DynamicDispatchBifurcationMap>
304    :  public ProgramStatePartialTrait<DynamicDispatchBifur> {
305  static void *GDMIndex() { static int index; return &index; }
306};
307
308}}
309
310static bool shouldInlineCXX(AnalysisManager &AMgr) {
311  switch (AMgr.IPAMode) {
312  case None:
313  case BasicInlining:
314    return false;
315  case Inlining:
316  case DynamicDispatch:
317  case DynamicDispatchBifurcate:
318    return true;
319  case NumIPAModes:
320    llvm_unreachable("not actually a valid option");
321  }
322  llvm_unreachable("bogus IPAMode");
323}
324
325bool ExprEngine::inlineCall(const CallEvent &Call, const Decl *D,
326                            NodeBuilder &Bldr, ExplodedNode *Pred,
327                            ProgramStateRef State) {
328  assert(D);
329
330  const LocationContext *CurLC = Pred->getLocationContext();
331  const StackFrameContext *CallerSFC = CurLC->getCurrentStackFrame();
332  const LocationContext *ParentOfCallee = 0;
333
334  // FIXME: Refactor this check into a hypothetical CallEvent::canInline.
335  switch (Call.getKind()) {
336  case CE_Function:
337    break;
338  case CE_CXXMember:
339  case CE_CXXMemberOperator:
340    if (!shouldInlineCXX(getAnalysisManager()))
341      return false;
342    break;
343  case CE_CXXConstructor: {
344    if (!shouldInlineCXX(getAnalysisManager()))
345      return false;
346
347    const CXXConstructorCall &Ctor = cast<CXXConstructorCall>(Call);
348
349    // FIXME: We don't handle constructors or destructors for arrays properly.
350    const MemRegion *Target = Ctor.getCXXThisVal().getAsRegion();
351    if (Target && isa<ElementRegion>(Target))
352      return false;
353
354    // FIXME: This is a hack. We don't use the correct region for a new
355    // expression, so if we inline the constructor its result will just be
356    // thrown away. This short-term hack is tracked in <rdar://problem/12180598>
357    // and the longer-term possible fix is discussed in PR12014.
358    const CXXConstructExpr *CtorExpr = Ctor.getOriginExpr();
359    if (const Stmt *Parent = CurLC->getParentMap().getParent(CtorExpr))
360      if (isa<CXXNewExpr>(Parent))
361        return false;
362
363    // If the destructor is trivial, it's always safe to inline the constructor.
364    if (Ctor.getDecl()->getParent()->hasTrivialDestructor())
365      break;
366
367    // For other types, only inline constructors if we built the CFGs for the
368    // destructor properly.
369    const AnalysisDeclContext *ADC = CallerSFC->getAnalysisDeclContext();
370    assert(ADC->getCFGBuildOptions().AddInitializers && "No CFG initializers");
371    if (!ADC->getCFGBuildOptions().AddImplicitDtors)
372      return false;
373
374    // FIXME: This is a hack. We don't handle temporary destructors
375    // right now, so we shouldn't inline their constructors.
376    if (CtorExpr->getConstructionKind() == CXXConstructExpr::CK_Complete)
377      if (!Target || !isa<DeclRegion>(Target))
378        return false;
379
380    break;
381  }
382  case CE_CXXDestructor: {
383    if (!shouldInlineCXX(getAnalysisManager()))
384      return false;
385
386    // Only inline constructors and destructors if we built the CFGs for them
387    // properly.
388    const AnalysisDeclContext *ADC = CallerSFC->getAnalysisDeclContext();
389    if (!ADC->getCFGBuildOptions().AddImplicitDtors)
390      return false;
391
392    const CXXDestructorCall &Dtor = cast<CXXDestructorCall>(Call);
393
394    // FIXME: We don't handle constructors or destructors for arrays properly.
395    const MemRegion *Target = Dtor.getCXXThisVal().getAsRegion();
396    if (Target && isa<ElementRegion>(Target))
397      return false;
398
399    break;
400  }
401  case CE_CXXAllocator:
402    if (!shouldInlineCXX(getAnalysisManager()))
403      return false;
404
405    // Do not inline allocators until we model deallocators.
406    // This is unfortunate, but basically necessary for smart pointers and such.
407    return false;
408  case CE_Block: {
409    const BlockDataRegion *BR = cast<BlockCall>(Call).getBlockRegion();
410    assert(BR && "If we have the block definition we should have its region");
411    AnalysisDeclContext *BlockCtx = AMgr.getAnalysisDeclContext(D);
412    ParentOfCallee = BlockCtx->getBlockInvocationContext(CallerSFC,
413                                                         cast<BlockDecl>(D),
414                                                         BR);
415    break;
416  }
417  case CE_ObjCMessage:
418    if (!(getAnalysisManager().IPAMode == DynamicDispatch ||
419          getAnalysisManager().IPAMode == DynamicDispatchBifurcate))
420      return false;
421    break;
422  }
423
424  if (!shouldInlineDecl(D, Pred))
425    return false;
426
427  if (!ParentOfCallee)
428    ParentOfCallee = CallerSFC;
429
430  // This may be NULL, but that's fine.
431  const Expr *CallE = Call.getOriginExpr();
432
433  // Construct a new stack frame for the callee.
434  AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(D);
435  const StackFrameContext *CalleeSFC =
436    CalleeADC->getStackFrame(ParentOfCallee, CallE,
437                             currBldrCtx->getBlock(),
438                             currStmtIdx);
439
440  CallEnter Loc(CallE, CalleeSFC, CurLC);
441
442  // Construct a new state which contains the mapping from actual to
443  // formal arguments.
444  State = State->enterStackFrame(Call, CalleeSFC);
445
446  bool isNew;
447  if (ExplodedNode *N = G.getNode(Loc, State, false, &isNew)) {
448    N->addPredecessor(Pred, G);
449    if (isNew)
450      Engine.getWorkList()->enqueue(N);
451  }
452
453  // If we decided to inline the call, the successor has been manually
454  // added onto the work list so remove it from the node builder.
455  Bldr.takeNodes(Pred);
456
457  NumInlinedCalls++;
458
459  return true;
460}
461
462static ProgramStateRef getInlineFailedState(ProgramStateRef State,
463                                            const Stmt *CallE) {
464  void *ReplayState = State->get<ReplayWithoutInlining>();
465  if (!ReplayState)
466    return 0;
467
468  assert(ReplayState == (const void*)CallE && "Backtracked to the wrong call.");
469  (void)CallE;
470
471  return State->remove<ReplayWithoutInlining>();
472}
473
474void ExprEngine::VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
475                               ExplodedNodeSet &dst) {
476  // Perform the previsit of the CallExpr.
477  ExplodedNodeSet dstPreVisit;
478  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, CE, *this);
479
480  // Get the call in its initial state. We use this as a template to perform
481  // all the checks.
482  CallEventManager &CEMgr = getStateManager().getCallEventManager();
483  CallEventRef<> CallTemplate
484    = CEMgr.getSimpleCall(CE, Pred->getState(), Pred->getLocationContext());
485
486  // Evaluate the function call.  We try each of the checkers
487  // to see if the can evaluate the function call.
488  ExplodedNodeSet dstCallEvaluated;
489  for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
490       I != E; ++I) {
491    evalCall(dstCallEvaluated, *I, *CallTemplate);
492  }
493
494  // Finally, perform the post-condition check of the CallExpr and store
495  // the created nodes in 'Dst'.
496  // Note that if the call was inlined, dstCallEvaluated will be empty.
497  // The post-CallExpr check will occur in processCallExit.
498  getCheckerManager().runCheckersForPostStmt(dst, dstCallEvaluated, CE,
499                                             *this);
500}
501
502void ExprEngine::evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred,
503                          const CallEvent &Call) {
504  // WARNING: At this time, the state attached to 'Call' may be older than the
505  // state in 'Pred'. This is a minor optimization since CheckerManager will
506  // use an updated CallEvent instance when calling checkers, but if 'Call' is
507  // ever used directly in this function all callers should be updated to pass
508  // the most recent state. (It is probably not worth doing the work here since
509  // for some callers this will not be necessary.)
510
511  // Run any pre-call checks using the generic call interface.
512  ExplodedNodeSet dstPreVisit;
513  getCheckerManager().runCheckersForPreCall(dstPreVisit, Pred, Call, *this);
514
515  // Actually evaluate the function call.  We try each of the checkers
516  // to see if the can evaluate the function call, and get a callback at
517  // defaultEvalCall if all of them fail.
518  ExplodedNodeSet dstCallEvaluated;
519  getCheckerManager().runCheckersForEvalCall(dstCallEvaluated, dstPreVisit,
520                                             Call, *this);
521
522  // Finally, run any post-call checks.
523  getCheckerManager().runCheckersForPostCall(Dst, dstCallEvaluated,
524                                             Call, *this);
525}
526
527ProgramStateRef ExprEngine::bindReturnValue(const CallEvent &Call,
528                                            const LocationContext *LCtx,
529                                            ProgramStateRef State) {
530  const Expr *E = Call.getOriginExpr();
531  if (!E)
532    return State;
533
534  // Some method families have known return values.
535  if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(&Call)) {
536    switch (Msg->getMethodFamily()) {
537    default:
538      break;
539    case OMF_autorelease:
540    case OMF_retain:
541    case OMF_self: {
542      // These methods return their receivers.
543      return State->BindExpr(E, LCtx, Msg->getReceiverSVal());
544    }
545    }
546  } else if (const CXXConstructorCall *C = dyn_cast<CXXConstructorCall>(&Call)){
547    return State->BindExpr(E, LCtx, C->getCXXThisVal());
548  }
549
550  // Conjure a symbol if the return value is unknown.
551  QualType ResultTy = Call.getResultType();
552  SValBuilder &SVB = getSValBuilder();
553  unsigned Count = currBldrCtx->blockCount();
554  SVal R = SVB.conjureSymbolVal(0, E, LCtx, ResultTy, Count);
555  return State->BindExpr(E, LCtx, R);
556}
557
558// Conservatively evaluate call by invalidating regions and binding
559// a conjured return value.
560void ExprEngine::conservativeEvalCall(const CallEvent &Call, NodeBuilder &Bldr,
561                                      ExplodedNode *Pred, ProgramStateRef State) {
562  State = Call.invalidateRegions(currBldrCtx->blockCount(), State);
563  State = bindReturnValue(Call, Pred->getLocationContext(), State);
564
565  // And make the result node.
566  Bldr.generateNode(Call.getProgramPoint(), State, Pred);
567}
568
569void ExprEngine::defaultEvalCall(NodeBuilder &Bldr, ExplodedNode *Pred,
570                                 const CallEvent &CallTemplate) {
571  // Make sure we have the most recent state attached to the call.
572  ProgramStateRef State = Pred->getState();
573  CallEventRef<> Call = CallTemplate.cloneWithState(State);
574
575  if (!getAnalysisManager().shouldInlineCall()) {
576    conservativeEvalCall(*Call, Bldr, Pred, State);
577    return;
578  }
579  // Try to inline the call.
580  // The origin expression here is just used as a kind of checksum;
581  // this should still be safe even for CallEvents that don't come from exprs.
582  const Expr *E = Call->getOriginExpr();
583  ProgramStateRef InlinedFailedState = getInlineFailedState(State, E);
584
585  if (InlinedFailedState) {
586    // If we already tried once and failed, make sure we don't retry later.
587    State = InlinedFailedState;
588  } else {
589    RuntimeDefinition RD = Call->getRuntimeDefinition();
590    const Decl *D = RD.getDecl();
591    if (D) {
592      if (RD.mayHaveOtherDefinitions()) {
593        // Explore with and without inlining the call.
594        if (getAnalysisManager().IPAMode == DynamicDispatchBifurcate) {
595          BifurcateCall(RD.getDispatchRegion(), *Call, D, Bldr, Pred);
596          return;
597        }
598
599        // Don't inline if we're not in any dynamic dispatch mode.
600        if (getAnalysisManager().IPAMode != DynamicDispatch) {
601          conservativeEvalCall(*Call, Bldr, Pred, State);
602          return;
603        }
604      }
605
606      // We are not bifurcating and we do have a Decl, so just inline.
607      if (inlineCall(*Call, D, Bldr, Pred, State))
608        return;
609    }
610  }
611
612  // If we can't inline it, handle the return value and invalidate the regions.
613  conservativeEvalCall(*Call, Bldr, Pred, State);
614}
615
616void ExprEngine::BifurcateCall(const MemRegion *BifurReg,
617                               const CallEvent &Call, const Decl *D,
618                               NodeBuilder &Bldr, ExplodedNode *Pred) {
619  assert(BifurReg);
620  BifurReg = BifurReg->StripCasts();
621
622  // Check if we've performed the split already - note, we only want
623  // to split the path once per memory region.
624  ProgramStateRef State = Pred->getState();
625  const unsigned int *BState =
626                        State->get<DynamicDispatchBifurcationMap>(BifurReg);
627  if (BState) {
628    // If we are on "inline path", keep inlining if possible.
629    if (*BState == DynamicDispatchModeInlined)
630      if (inlineCall(Call, D, Bldr, Pred, State))
631        return;
632    // If inline failed, or we are on the path where we assume we
633    // don't have enough info about the receiver to inline, conjure the
634    // return value and invalidate the regions.
635    conservativeEvalCall(Call, Bldr, Pred, State);
636    return;
637  }
638
639  // If we got here, this is the first time we process a message to this
640  // region, so split the path.
641  ProgramStateRef IState =
642      State->set<DynamicDispatchBifurcationMap>(BifurReg,
643                                               DynamicDispatchModeInlined);
644  inlineCall(Call, D, Bldr, Pred, IState);
645
646  ProgramStateRef NoIState =
647      State->set<DynamicDispatchBifurcationMap>(BifurReg,
648                                               DynamicDispatchModeConservative);
649  conservativeEvalCall(Call, Bldr, Pred, NoIState);
650
651  NumOfDynamicDispatchPathSplits++;
652  return;
653}
654
655
656void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred,
657                                 ExplodedNodeSet &Dst) {
658
659  ExplodedNodeSet dstPreVisit;
660  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, RS, *this);
661
662  StmtNodeBuilder B(dstPreVisit, Dst, *currBldrCtx);
663
664  if (RS->getRetValue()) {
665    for (ExplodedNodeSet::iterator it = dstPreVisit.begin(),
666                                  ei = dstPreVisit.end(); it != ei; ++it) {
667      B.generateNode(RS, *it, (*it)->getState());
668    }
669  }
670}
671