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