ExprEngineCallAndReturn.cpp revision 55fc873017f10f6f566b182b70f6fc22aefa3464
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/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/ParentMap.h"
20#include "clang/Analysis/Analyses/LiveVariables.h"
21#include "clang/StaticAnalyzer/Core/CheckerManager.h"
22#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
23#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/Support/SaveAndRestore.h"
26
27using namespace clang;
28using namespace ento;
29
30STATISTIC(NumOfDynamicDispatchPathSplits,
31  "The # of times we split the path due to imprecise dynamic dispatch info");
32
33STATISTIC(NumInlinedCalls,
34  "The # of times we inlined a call");
35
36void ExprEngine::processCallEnter(CallEnter CE, ExplodedNode *Pred) {
37  // Get the entry block in the CFG of the callee.
38  const StackFrameContext *calleeCtx = CE.getCalleeContext();
39  const CFG *CalleeCFG = calleeCtx->getCFG();
40  const CFGBlock *Entry = &(CalleeCFG->getEntry());
41
42  // Validate the CFG.
43  assert(Entry->empty());
44  assert(Entry->succ_size() == 1);
45
46  // Get the solitary sucessor.
47  const CFGBlock *Succ = *(Entry->succ_begin());
48
49  // Construct an edge representing the starting location in the callee.
50  BlockEdge Loc(Entry, Succ, calleeCtx);
51
52  ProgramStateRef state = Pred->getState();
53
54  // Construct a new node and add it to the worklist.
55  bool isNew;
56  ExplodedNode *Node = G.getNode(Loc, state, false, &isNew);
57  Node->addPredecessor(Pred, G);
58  if (isNew)
59    Engine.getWorkList()->enqueue(Node);
60}
61
62// Find the last statement on the path to the exploded node and the
63// corresponding Block.
64static std::pair<const Stmt*,
65                 const CFGBlock*> getLastStmt(const ExplodedNode *Node) {
66  const Stmt *S = 0;
67  const StackFrameContext *SF =
68          Node->getLocation().getLocationContext()->getCurrentStackFrame();
69
70  // Back up through the ExplodedGraph until we reach a statement node in this
71  // stack frame.
72  while (Node) {
73    const ProgramPoint &PP = Node->getLocation();
74
75    if (PP.getLocationContext()->getCurrentStackFrame() == SF) {
76      if (const StmtPoint *SP = dyn_cast<StmtPoint>(&PP)) {
77        S = SP->getStmt();
78        break;
79      } else if (const CallExitEnd *CEE = dyn_cast<CallExitEnd>(&PP)) {
80        S = CEE->getCalleeContext()->getCallSite();
81        if (S)
82          break;
83
84        // If there is no statement, this is an implicitly-generated call.
85        // We'll walk backwards over it and then continue the loop to find
86        // an actual statement.
87        const CallEnter *CE;
88        do {
89          Node = Node->getFirstPred();
90          CE = Node->getLocationAs<CallEnter>();
91        } while (!CE || CE->getCalleeContext() != CEE->getCalleeContext());
92
93        // Continue searching the graph.
94      }
95    } else if (const CallEnter *CE = dyn_cast<CallEnter>(&PP)) {
96      // If we reached the CallEnter for this function, it has no statements.
97      if (CE->getCalleeContext() == SF)
98        break;
99    }
100
101    if (Node->pred_empty())
102      return std::pair<const Stmt*, const CFGBlock*>((Stmt*)0, (CFGBlock*)0);
103
104    Node = *Node->pred_begin();
105  }
106
107  const CFGBlock *Blk = 0;
108  if (S) {
109    // Now, get the enclosing basic block.
110    while (Node) {
111      const ProgramPoint &PP = Node->getLocation();
112      if (isa<BlockEdge>(PP) &&
113          (PP.getLocationContext()->getCurrentStackFrame() == SF)) {
114        BlockEdge &EPP = cast<BlockEdge>(PP);
115        Blk = EPP.getDst();
116        break;
117      }
118      if (Node->pred_empty())
119        return std::pair<const Stmt*, const CFGBlock*>(S, (CFGBlock*)0);
120
121      Node = *Node->pred_begin();
122    }
123  }
124
125  return std::pair<const Stmt*, const CFGBlock*>(S, Blk);
126}
127
128/// Adjusts a return value when the called function's return type does not
129/// match the caller's expression type. This can happen when a dynamic call
130/// is devirtualized, and the overridding method has a covariant (more specific)
131/// return type than the parent's method. For C++ objects, this means we need
132/// to add base casts.
133static SVal adjustReturnValue(SVal V, QualType ExpectedTy, QualType ActualTy,
134                              StoreManager &StoreMgr) {
135  // For now, the only adjustments we handle apply only to locations.
136  if (!isa<Loc>(V))
137    return V;
138
139  // If the types already match, don't do any unnecessary work.
140  ExpectedTy = ExpectedTy.getCanonicalType();
141  ActualTy = ActualTy.getCanonicalType();
142  if (ExpectedTy == ActualTy)
143    return V;
144
145  // No adjustment is needed between Objective-C pointer types.
146  if (ExpectedTy->isObjCObjectPointerType() &&
147      ActualTy->isObjCObjectPointerType())
148    return V;
149
150  // C++ object pointers may need "derived-to-base" casts.
151  const CXXRecordDecl *ExpectedClass = ExpectedTy->getPointeeCXXRecordDecl();
152  const CXXRecordDecl *ActualClass = ActualTy->getPointeeCXXRecordDecl();
153  if (ExpectedClass && ActualClass) {
154    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
155                       /*DetectVirtual=*/false);
156    if (ActualClass->isDerivedFrom(ExpectedClass, Paths) &&
157        !Paths.isAmbiguous(ActualTy->getCanonicalTypeUnqualified())) {
158      return StoreMgr.evalDerivedToBase(V, Paths.front());
159    }
160  }
161
162  // Unfortunately, Objective-C does not enforce that overridden methods have
163  // covariant return types, so we can't assert that that never happens.
164  // Be safe and return UnknownVal().
165  return UnknownVal();
166}
167
168void ExprEngine::removeDeadOnEndOfFunction(NodeBuilderContext& BC,
169                                           ExplodedNode *Pred,
170                                           ExplodedNodeSet &Dst) {
171  // Find the last statement in the function and the corresponding basic block.
172  const Stmt *LastSt = 0;
173  const CFGBlock *Blk = 0;
174  llvm::tie(LastSt, Blk) = getLastStmt(Pred);
175  if (!Blk || !LastSt) {
176    Dst.Add(Pred);
177    return;
178  }
179
180  // Here, we destroy the current location context. We use the current
181  // function's entire body as a diagnostic statement, with which the program
182  // point will be associated. However, we only want to use LastStmt as a
183  // reference for what to clean up if it's a ReturnStmt; otherwise, everything
184  // is dead.
185  SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
186  const LocationContext *LCtx = Pred->getLocationContext();
187  removeDead(Pred, Dst, dyn_cast<ReturnStmt>(LastSt), LCtx,
188             LCtx->getAnalysisDeclContext()->getBody(),
189             ProgramPoint::PostStmtPurgeDeadSymbolsKind);
190}
191
192static bool wasDifferentDeclUsedForInlining(CallEventRef<> Call,
193    const StackFrameContext *calleeCtx) {
194  const Decl *RuntimeCallee = calleeCtx->getDecl();
195  const Decl *StaticDecl = Call->getDecl();
196  assert(RuntimeCallee);
197  if (!StaticDecl)
198    return true;
199  return RuntimeCallee->getCanonicalDecl() != StaticDecl->getCanonicalDecl();
200}
201
202/// The call exit is simulated with a sequence of nodes, which occur between
203/// CallExitBegin and CallExitEnd. The following operations occur between the
204/// two program points:
205/// 1. CallExitBegin (triggers the start of call exit sequence)
206/// 2. Bind the return value
207/// 3. Run Remove dead bindings to clean up the dead symbols from the callee.
208/// 4. CallExitEnd (switch to the caller context)
209/// 5. PostStmt<CallExpr>
210void ExprEngine::processCallExit(ExplodedNode *CEBNode) {
211  // Step 1 CEBNode was generated before the call.
212
213  const StackFrameContext *calleeCtx =
214      CEBNode->getLocationContext()->getCurrentStackFrame();
215
216  // The parent context might not be a stack frame, so make sure we
217  // look up the first enclosing stack frame.
218  const StackFrameContext *callerCtx =
219    calleeCtx->getParent()->getCurrentStackFrame();
220
221  const Stmt *CE = calleeCtx->getCallSite();
222  ProgramStateRef state = CEBNode->getState();
223  // Find the last statement in the function and the corresponding basic block.
224  const Stmt *LastSt = 0;
225  const CFGBlock *Blk = 0;
226  llvm::tie(LastSt, Blk) = getLastStmt(CEBNode);
227
228  // Generate a CallEvent /before/ cleaning the state, so that we can get the
229  // correct value for 'this' (if necessary).
230  CallEventManager &CEMgr = getStateManager().getCallEventManager();
231  CallEventRef<> Call = CEMgr.getCaller(calleeCtx, state);
232
233  // Step 2: generate node with bound return value: CEBNode -> BindedRetNode.
234
235  // If the callee returns an expression, bind its value to CallExpr.
236  if (CE) {
237    if (const ReturnStmt *RS = dyn_cast_or_null<ReturnStmt>(LastSt)) {
238      const LocationContext *LCtx = CEBNode->getLocationContext();
239      SVal V = state->getSVal(RS, LCtx);
240
241      // Ensure that the return type matches the type of the returned Expr.
242      if (wasDifferentDeclUsedForInlining(Call, calleeCtx)) {
243        QualType ReturnedTy =
244          CallEvent::getDeclaredResultType(calleeCtx->getDecl());
245        if (!ReturnedTy.isNull()) {
246          if (const Expr *Ex = dyn_cast<Expr>(CE)) {
247            V = adjustReturnValue(V, Ex->getType(), ReturnedTy,
248                                  getStoreManager());
249          }
250        }
251      }
252
253      state = state->BindExpr(CE, callerCtx, V);
254    }
255
256    // Bind the constructed object value to CXXConstructExpr.
257    if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(CE)) {
258      loc::MemRegionVal This =
259        svalBuilder.getCXXThis(CCE->getConstructor()->getParent(), calleeCtx);
260      SVal ThisV = state->getSVal(This);
261
262      // If the constructed object is a prvalue, get its bindings.
263      // Note that we have to be careful here because constructors embedded
264      // in DeclStmts are not marked as lvalues.
265      if (!CCE->isGLValue())
266        if (const MemRegion *MR = ThisV.getAsRegion())
267          if (isa<CXXTempObjectRegion>(MR))
268            ThisV = state->getSVal(cast<Loc>(ThisV));
269
270      state = state->BindExpr(CCE, callerCtx, ThisV);
271    }
272  }
273
274  // Step 3: BindedRetNode -> CleanedNodes
275  // If we can find a statement and a block in the inlined function, run remove
276  // dead bindings before returning from the call. This is important to ensure
277  // that we report the issues such as leaks in the stack contexts in which
278  // they occurred.
279  ExplodedNodeSet CleanedNodes;
280  if (LastSt && Blk && AMgr.options.AnalysisPurgeOpt != PurgeNone) {
281    static SimpleProgramPointTag retValBind("ExprEngine : Bind Return Value");
282    PostStmt Loc(LastSt, calleeCtx, &retValBind);
283    bool isNew;
284    ExplodedNode *BindedRetNode = G.getNode(Loc, state, false, &isNew);
285    BindedRetNode->addPredecessor(CEBNode, G);
286    if (!isNew)
287      return;
288
289    NodeBuilderContext Ctx(getCoreEngine(), Blk, BindedRetNode);
290    currBldrCtx = &Ctx;
291    // Here, we call the Symbol Reaper with 0 statement and callee location
292    // context, telling it to clean up everything in the callee's context
293    // (and its children). We use the callee's function body as a diagnostic
294    // statement, with which the program point will be associated.
295    removeDead(BindedRetNode, CleanedNodes, 0, calleeCtx,
296               calleeCtx->getAnalysisDeclContext()->getBody(),
297               ProgramPoint::PostStmtPurgeDeadSymbolsKind);
298    currBldrCtx = 0;
299  } else {
300    CleanedNodes.Add(CEBNode);
301  }
302
303  for (ExplodedNodeSet::iterator I = CleanedNodes.begin(),
304                                 E = CleanedNodes.end(); I != E; ++I) {
305
306    // Step 4: Generate the CallExit and leave the callee's context.
307    // CleanedNodes -> CEENode
308    CallExitEnd Loc(calleeCtx, callerCtx);
309    bool isNew;
310    ProgramStateRef CEEState = (*I == CEBNode) ? state : (*I)->getState();
311    ExplodedNode *CEENode = G.getNode(Loc, CEEState, false, &isNew);
312    CEENode->addPredecessor(*I, G);
313    if (!isNew)
314      return;
315
316    // Step 5: Perform the post-condition check of the CallExpr and enqueue the
317    // result onto the work list.
318    // CEENode -> Dst -> WorkList
319    NodeBuilderContext Ctx(Engine, calleeCtx->getCallSiteBlock(), CEENode);
320    SaveAndRestore<const NodeBuilderContext*> NBCSave(currBldrCtx,
321        &Ctx);
322    SaveAndRestore<unsigned> CBISave(currStmtIdx, calleeCtx->getIndex());
323
324    CallEventRef<> UpdatedCall = Call.cloneWithState(CEEState);
325
326    ExplodedNodeSet DstPostCall;
327    getCheckerManager().runCheckersForPostCall(DstPostCall, CEENode,
328                                               *UpdatedCall, *this,
329                                               /*WasInlined=*/true);
330
331    ExplodedNodeSet Dst;
332    if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
333      getCheckerManager().runCheckersForPostObjCMessage(Dst, DstPostCall, *Msg,
334                                                        *this,
335                                                        /*WasInlined=*/true);
336    } else if (CE) {
337      getCheckerManager().runCheckersForPostStmt(Dst, DstPostCall, CE,
338                                                 *this, /*WasInlined=*/true);
339    } else {
340      Dst.insert(DstPostCall);
341    }
342
343    // Enqueue the next element in the block.
344    for (ExplodedNodeSet::iterator PSI = Dst.begin(), PSE = Dst.end();
345                                   PSI != PSE; ++PSI) {
346      Engine.getWorkList()->enqueue(*PSI, calleeCtx->getCallSiteBlock(),
347                                    calleeCtx->getIndex()+1);
348    }
349  }
350}
351
352void ExprEngine::examineStackFrames(const Decl *D, const LocationContext *LCtx,
353                               bool &IsRecursive, unsigned &StackDepth) {
354  IsRecursive = false;
355  StackDepth = 0;
356
357  while (LCtx) {
358    if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LCtx)) {
359      const Decl *DI = SFC->getDecl();
360
361      // Mark recursive (and mutually recursive) functions and always count
362      // them when measuring the stack depth.
363      if (DI == D) {
364        IsRecursive = true;
365        ++StackDepth;
366        LCtx = LCtx->getParent();
367        continue;
368      }
369
370      // Do not count the small functions when determining the stack depth.
371      AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(DI);
372      const CFG *CalleeCFG = CalleeADC->getCFG();
373      if (CalleeCFG->getNumBlockIDs() > AMgr.options.getAlwaysInlineSize())
374        ++StackDepth;
375    }
376    LCtx = LCtx->getParent();
377  }
378
379}
380
381static bool IsInStdNamespace(const FunctionDecl *FD) {
382  const DeclContext *DC = FD->getEnclosingNamespaceContext();
383  const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
384  if (!ND)
385    return false;
386
387  while (const DeclContext *Parent = ND->getParent()) {
388    if (!isa<NamespaceDecl>(Parent))
389      break;
390    ND = cast<NamespaceDecl>(Parent);
391  }
392
393  return ND->getName() == "std";
394}
395
396// Determine if we should inline the call.
397bool ExprEngine::shouldInlineDecl(const Decl *D, ExplodedNode *Pred) {
398  AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(D);
399  const CFG *CalleeCFG = CalleeADC->getCFG();
400
401  // It is possible that the CFG cannot be constructed.
402  // Be safe, and check if the CalleeCFG is valid.
403  if (!CalleeCFG)
404    return false;
405
406  bool IsRecursive = false;
407  unsigned StackDepth = 0;
408  examineStackFrames(D, Pred->getLocationContext(), IsRecursive, StackDepth);
409  if ((StackDepth >= AMgr.options.InlineMaxStackDepth) &&
410       ((CalleeCFG->getNumBlockIDs() > AMgr.options.getAlwaysInlineSize())
411         || IsRecursive))
412    return false;
413
414  if (Engine.FunctionSummaries->hasReachedMaxBlockCount(D))
415    return false;
416
417  if (CalleeCFG->getNumBlockIDs() > AMgr.options.InlineMaxFunctionSize)
418    return false;
419
420  // Do not inline variadic calls (for now).
421  if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
422    if (BD->isVariadic())
423      return false;
424  }
425  else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
426    if (FD->isVariadic())
427      return false;
428  }
429
430  if (getContext().getLangOpts().CPlusPlus) {
431    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
432      // Conditionally allow the inlining of template functions.
433      if (!getAnalysisManager().options.mayInlineTemplateFunctions())
434        if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
435          return false;
436
437      // Conditionally allow the inlining of C++ standard library functions.
438      if (!getAnalysisManager().options.mayInlineCXXStandardLibrary())
439        if (getContext().getSourceManager().isInSystemHeader(FD->getLocation()))
440          if (IsInStdNamespace(FD))
441            return false;
442    }
443  }
444
445  // It is possible that the live variables analysis cannot be
446  // run.  If so, bail out.
447  if (!CalleeADC->getAnalysis<RelaxedLiveVariables>())
448    return false;
449
450  return true;
451}
452
453// The GDM component containing the dynamic dispatch bifurcation info. When
454// the exact type of the receiver is not known, we want to explore both paths -
455// one on which we do inline it and the other one on which we don't. This is
456// done to ensure we do not drop coverage.
457// This is the map from the receiver region to a bool, specifying either we
458// consider this region's information precise or not along the given path.
459namespace {
460  enum DynamicDispatchMode {
461    DynamicDispatchModeInlined = 1,
462    DynamicDispatchModeConservative
463  };
464}
465REGISTER_TRAIT_WITH_PROGRAMSTATE(DynamicDispatchBifurcationMap,
466                                 CLANG_ENTO_PROGRAMSTATE_MAP(const MemRegion *,
467                                                             unsigned))
468
469bool ExprEngine::inlineCall(const CallEvent &Call, const Decl *D,
470                            NodeBuilder &Bldr, ExplodedNode *Pred,
471                            ProgramStateRef State) {
472  assert(D);
473
474  const LocationContext *CurLC = Pred->getLocationContext();
475  const StackFrameContext *CallerSFC = CurLC->getCurrentStackFrame();
476  const LocationContext *ParentOfCallee = 0;
477
478  AnalyzerOptions &Opts = getAnalysisManager().options;
479
480  // FIXME: Refactor this check into a hypothetical CallEvent::canInline.
481  switch (Call.getKind()) {
482  case CE_Function:
483    break;
484  case CE_CXXMember:
485  case CE_CXXMemberOperator:
486    if (!Opts.mayInlineCXXMemberFunction(CIMK_MemberFunctions))
487      return false;
488    break;
489  case CE_CXXConstructor: {
490    if (!Opts.mayInlineCXXMemberFunction(CIMK_Constructors))
491      return false;
492
493    const CXXConstructorCall &Ctor = cast<CXXConstructorCall>(Call);
494
495    // FIXME: We don't handle constructors or destructors for arrays properly.
496    const MemRegion *Target = Ctor.getCXXThisVal().getAsRegion();
497    if (Target && isa<ElementRegion>(Target))
498      return false;
499
500    // FIXME: This is a hack. We don't use the correct region for a new
501    // expression, so if we inline the constructor its result will just be
502    // thrown away. This short-term hack is tracked in <rdar://problem/12180598>
503    // and the longer-term possible fix is discussed in PR12014.
504    const CXXConstructExpr *CtorExpr = Ctor.getOriginExpr();
505    if (const Stmt *Parent = CurLC->getParentMap().getParent(CtorExpr))
506      if (isa<CXXNewExpr>(Parent))
507        return false;
508
509    // Inlining constructors requires including initializers in the CFG.
510    const AnalysisDeclContext *ADC = CallerSFC->getAnalysisDeclContext();
511    assert(ADC->getCFGBuildOptions().AddInitializers && "No CFG initializers");
512    (void)ADC;
513
514    // If the destructor is trivial, it's always safe to inline the constructor.
515    if (Ctor.getDecl()->getParent()->hasTrivialDestructor())
516      break;
517
518    // For other types, only inline constructors if destructor inlining is
519    // also enabled.
520    if (!Opts.mayInlineCXXMemberFunction(CIMK_Destructors))
521      return false;
522
523    // FIXME: This is a hack. We don't handle temporary destructors
524    // right now, so we shouldn't inline their constructors.
525    if (CtorExpr->getConstructionKind() == CXXConstructExpr::CK_Complete)
526      if (!Target || !isa<DeclRegion>(Target))
527        return false;
528
529    break;
530  }
531  case CE_CXXDestructor: {
532    if (!Opts.mayInlineCXXMemberFunction(CIMK_Destructors))
533      return false;
534
535    // Inlining destructors requires building the CFG correctly.
536    const AnalysisDeclContext *ADC = CallerSFC->getAnalysisDeclContext();
537    assert(ADC->getCFGBuildOptions().AddImplicitDtors && "No CFG destructors");
538    (void)ADC;
539
540    const CXXDestructorCall &Dtor = cast<CXXDestructorCall>(Call);
541
542    // FIXME: We don't handle constructors or destructors for arrays properly.
543    const MemRegion *Target = Dtor.getCXXThisVal().getAsRegion();
544    if (Target && isa<ElementRegion>(Target))
545      return false;
546
547    break;
548  }
549  case CE_CXXAllocator:
550    // Do not inline allocators until we model deallocators.
551    // This is unfortunate, but basically necessary for smart pointers and such.
552    return false;
553  case CE_Block: {
554    const BlockDataRegion *BR = cast<BlockCall>(Call).getBlockRegion();
555    assert(BR && "If we have the block definition we should have its region");
556    AnalysisDeclContext *BlockCtx = AMgr.getAnalysisDeclContext(D);
557    ParentOfCallee = BlockCtx->getBlockInvocationContext(CallerSFC,
558                                                         cast<BlockDecl>(D),
559                                                         BR);
560    break;
561  }
562  case CE_ObjCMessage:
563    if (!Opts.mayInlineObjCMethod())
564      return false;
565    if (!(getAnalysisManager().options.IPAMode == DynamicDispatch ||
566          getAnalysisManager().options.IPAMode == DynamicDispatchBifurcate))
567      return false;
568    break;
569  }
570
571  if (!shouldInlineDecl(D, Pred))
572    return false;
573
574  if (!ParentOfCallee)
575    ParentOfCallee = CallerSFC;
576
577  // This may be NULL, but that's fine.
578  const Expr *CallE = Call.getOriginExpr();
579
580  // Construct a new stack frame for the callee.
581  AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(D);
582  const StackFrameContext *CalleeSFC =
583    CalleeADC->getStackFrame(ParentOfCallee, CallE,
584                             currBldrCtx->getBlock(),
585                             currStmtIdx);
586
587  CallEnter Loc(CallE, CalleeSFC, CurLC);
588
589  // Construct a new state which contains the mapping from actual to
590  // formal arguments.
591  State = State->enterStackFrame(Call, CalleeSFC);
592
593  bool isNew;
594  if (ExplodedNode *N = G.getNode(Loc, State, false, &isNew)) {
595    N->addPredecessor(Pred, G);
596    if (isNew)
597      Engine.getWorkList()->enqueue(N);
598  }
599
600  // If we decided to inline the call, the successor has been manually
601  // added onto the work list so remove it from the node builder.
602  Bldr.takeNodes(Pred);
603
604  NumInlinedCalls++;
605
606  // Mark the decl as visited.
607  if (VisitedCallees)
608    VisitedCallees->insert(D);
609
610  return true;
611}
612
613static ProgramStateRef getInlineFailedState(ProgramStateRef State,
614                                            const Stmt *CallE) {
615  void *ReplayState = State->get<ReplayWithoutInlining>();
616  if (!ReplayState)
617    return 0;
618
619  assert(ReplayState == (const void*)CallE && "Backtracked to the wrong call.");
620  (void)CallE;
621
622  return State->remove<ReplayWithoutInlining>();
623}
624
625void ExprEngine::VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
626                               ExplodedNodeSet &dst) {
627  // Perform the previsit of the CallExpr.
628  ExplodedNodeSet dstPreVisit;
629  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, CE, *this);
630
631  // Get the call in its initial state. We use this as a template to perform
632  // all the checks.
633  CallEventManager &CEMgr = getStateManager().getCallEventManager();
634  CallEventRef<> CallTemplate
635    = CEMgr.getSimpleCall(CE, Pred->getState(), Pred->getLocationContext());
636
637  // Evaluate the function call.  We try each of the checkers
638  // to see if the can evaluate the function call.
639  ExplodedNodeSet dstCallEvaluated;
640  for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
641       I != E; ++I) {
642    evalCall(dstCallEvaluated, *I, *CallTemplate);
643  }
644
645  // Finally, perform the post-condition check of the CallExpr and store
646  // the created nodes in 'Dst'.
647  // Note that if the call was inlined, dstCallEvaluated will be empty.
648  // The post-CallExpr check will occur in processCallExit.
649  getCheckerManager().runCheckersForPostStmt(dst, dstCallEvaluated, CE,
650                                             *this);
651}
652
653void ExprEngine::evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred,
654                          const CallEvent &Call) {
655  // WARNING: At this time, the state attached to 'Call' may be older than the
656  // state in 'Pred'. This is a minor optimization since CheckerManager will
657  // use an updated CallEvent instance when calling checkers, but if 'Call' is
658  // ever used directly in this function all callers should be updated to pass
659  // the most recent state. (It is probably not worth doing the work here since
660  // for some callers this will not be necessary.)
661
662  // Run any pre-call checks using the generic call interface.
663  ExplodedNodeSet dstPreVisit;
664  getCheckerManager().runCheckersForPreCall(dstPreVisit, Pred, Call, *this);
665
666  // Actually evaluate the function call.  We try each of the checkers
667  // to see if the can evaluate the function call, and get a callback at
668  // defaultEvalCall if all of them fail.
669  ExplodedNodeSet dstCallEvaluated;
670  getCheckerManager().runCheckersForEvalCall(dstCallEvaluated, dstPreVisit,
671                                             Call, *this);
672
673  // Finally, run any post-call checks.
674  getCheckerManager().runCheckersForPostCall(Dst, dstCallEvaluated,
675                                             Call, *this);
676}
677
678ProgramStateRef ExprEngine::bindReturnValue(const CallEvent &Call,
679                                            const LocationContext *LCtx,
680                                            ProgramStateRef State) {
681  const Expr *E = Call.getOriginExpr();
682  if (!E)
683    return State;
684
685  // Some method families have known return values.
686  if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(&Call)) {
687    switch (Msg->getMethodFamily()) {
688    default:
689      break;
690    case OMF_autorelease:
691    case OMF_retain:
692    case OMF_self: {
693      // These methods return their receivers.
694      return State->BindExpr(E, LCtx, Msg->getReceiverSVal());
695    }
696    }
697  } else if (const CXXConstructorCall *C = dyn_cast<CXXConstructorCall>(&Call)){
698    return State->BindExpr(E, LCtx, C->getCXXThisVal());
699  }
700
701  // Conjure a symbol if the return value is unknown.
702  QualType ResultTy = Call.getResultType();
703  SValBuilder &SVB = getSValBuilder();
704  unsigned Count = currBldrCtx->blockCount();
705  SVal R = SVB.conjureSymbolVal(0, E, LCtx, ResultTy, Count);
706  return State->BindExpr(E, LCtx, R);
707}
708
709// Conservatively evaluate call by invalidating regions and binding
710// a conjured return value.
711void ExprEngine::conservativeEvalCall(const CallEvent &Call, NodeBuilder &Bldr,
712                                      ExplodedNode *Pred, ProgramStateRef State) {
713  State = Call.invalidateRegions(currBldrCtx->blockCount(), State);
714  State = bindReturnValue(Call, Pred->getLocationContext(), State);
715
716  // And make the result node.
717  Bldr.generateNode(Call.getProgramPoint(), State, Pred);
718}
719
720void ExprEngine::defaultEvalCall(NodeBuilder &Bldr, ExplodedNode *Pred,
721                                 const CallEvent &CallTemplate) {
722  // Make sure we have the most recent state attached to the call.
723  ProgramStateRef State = Pred->getState();
724  CallEventRef<> Call = CallTemplate.cloneWithState(State);
725
726  if (!getAnalysisManager().shouldInlineCall()) {
727    conservativeEvalCall(*Call, Bldr, Pred, State);
728    return;
729  }
730  // Try to inline the call.
731  // The origin expression here is just used as a kind of checksum;
732  // this should still be safe even for CallEvents that don't come from exprs.
733  const Expr *E = Call->getOriginExpr();
734  ProgramStateRef InlinedFailedState = getInlineFailedState(State, E);
735
736  if (InlinedFailedState) {
737    // If we already tried once and failed, make sure we don't retry later.
738    State = InlinedFailedState;
739  } else {
740    RuntimeDefinition RD = Call->getRuntimeDefinition();
741    const Decl *D = RD.getDecl();
742    if (D) {
743      if (RD.mayHaveOtherDefinitions()) {
744        // Explore with and without inlining the call.
745        if (getAnalysisManager().options.IPAMode == DynamicDispatchBifurcate) {
746          BifurcateCall(RD.getDispatchRegion(), *Call, D, Bldr, Pred);
747          return;
748        }
749
750        // Don't inline if we're not in any dynamic dispatch mode.
751        if (getAnalysisManager().options.IPAMode != DynamicDispatch) {
752          conservativeEvalCall(*Call, Bldr, Pred, State);
753          return;
754        }
755      }
756
757      // We are not bifurcating and we do have a Decl, so just inline.
758      if (inlineCall(*Call, D, Bldr, Pred, State))
759        return;
760    }
761  }
762
763  // If we can't inline it, handle the return value and invalidate the regions.
764  conservativeEvalCall(*Call, Bldr, Pred, State);
765}
766
767void ExprEngine::BifurcateCall(const MemRegion *BifurReg,
768                               const CallEvent &Call, const Decl *D,
769                               NodeBuilder &Bldr, ExplodedNode *Pred) {
770  assert(BifurReg);
771  BifurReg = BifurReg->StripCasts();
772
773  // Check if we've performed the split already - note, we only want
774  // to split the path once per memory region.
775  ProgramStateRef State = Pred->getState();
776  const unsigned *BState =
777                        State->get<DynamicDispatchBifurcationMap>(BifurReg);
778  if (BState) {
779    // If we are on "inline path", keep inlining if possible.
780    if (*BState == DynamicDispatchModeInlined)
781      if (inlineCall(Call, D, Bldr, Pred, State))
782        return;
783    // If inline failed, or we are on the path where we assume we
784    // don't have enough info about the receiver to inline, conjure the
785    // return value and invalidate the regions.
786    conservativeEvalCall(Call, Bldr, Pred, State);
787    return;
788  }
789
790  // If we got here, this is the first time we process a message to this
791  // region, so split the path.
792  ProgramStateRef IState =
793      State->set<DynamicDispatchBifurcationMap>(BifurReg,
794                                               DynamicDispatchModeInlined);
795  inlineCall(Call, D, Bldr, Pred, IState);
796
797  ProgramStateRef NoIState =
798      State->set<DynamicDispatchBifurcationMap>(BifurReg,
799                                               DynamicDispatchModeConservative);
800  conservativeEvalCall(Call, Bldr, Pred, NoIState);
801
802  NumOfDynamicDispatchPathSplits++;
803  return;
804}
805
806
807void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred,
808                                 ExplodedNodeSet &Dst) {
809
810  ExplodedNodeSet dstPreVisit;
811  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, RS, *this);
812
813  StmtNodeBuilder B(dstPreVisit, Dst, *currBldrCtx);
814
815  if (RS->getRetValue()) {
816    for (ExplodedNodeSet::iterator it = dstPreVisit.begin(),
817                                  ei = dstPreVisit.end(); it != ei; ++it) {
818      B.generateNode(RS, *it, (*it)->getState());
819    }
820  }
821}
822