ExprEngineCallAndReturn.cpp revision 9b072b31ee2f41b8e30d1d22142c9ab72ac5ff1f
1cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)//=-- ExprEngineCallAndReturn.cpp - Support for call/return -----*- C++ -*-===//
28bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)//
38bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)//                     The LLVM Compiler Infrastructure
48bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)//
5cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source
68bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)// License. See LICENSE.TXT for details.
75d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)//
81320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci//===----------------------------------------------------------------------===//
98bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)//
108bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)//  This file defines ExprEngine's support for calls and returns.
111e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)//
128bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)//===----------------------------------------------------------------------===//
138bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
148bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)#define DEBUG_TYPE "ExprEngine"
155d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
168bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
178bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)#include "PrettyStackTraceLocationContext.h"
185f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "clang/AST/CXXInheritance.h"
195f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "clang/AST/DeclCXX.h"
206e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)#include "clang/AST/ParentMap.h"
215d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "clang/Analysis/Analyses/LiveVariables.h"
22f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)#include "clang/StaticAnalyzer/Core/CheckerManager.h"
23f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
24116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch#include "llvm/ADT/SmallSet.h"
258bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)#include "llvm/ADT/Statistic.h"
26116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch#include "llvm/Support/SaveAndRestore.h"
278bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
288bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)using namespace clang;
298bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)using namespace ento;
308bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
318bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)STATISTIC(NumOfDynamicDispatchPathSplits,
328bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  "The # of times we split the path due to imprecise dynamic dispatch info");
338bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
345d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)STATISTIC(NumInlinedCalls,
355f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  "The # of times we inlined a call");
365f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)
378bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)STATISTIC(NumReachedInlineCountMax,
385f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  "The # of times we reached inline count maximum");
395f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)
408bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)void ExprEngine::processCallEnter(CallEnter CE, ExplodedNode *Pred) {
415f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  // Get the entry block in the CFG of the callee.
425f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  const StackFrameContext *calleeCtx = CE.getCalleeContext();
438bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  PrettyStackTraceLocationContext CrashInfo(calleeCtx);
445f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)
45f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  const CFG *CalleeCFG = calleeCtx->getCFG();
468bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  const CFGBlock *Entry = &(CalleeCFG->getEntry());
478bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
485f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  // Validate the CFG.
495f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  assert(Entry->empty());
505f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  assert(Entry->succ_size() == 1);
518bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
525f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  // Get the solitary sucessor.
535f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  const CFGBlock *Succ = *(Entry->succ_begin());
548bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
555f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  // Construct an edge representing the starting location in the callee.
565f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  BlockEdge Loc(Entry, Succ, calleeCtx);
578bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
588bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  ProgramStateRef state = Pred->getState();
595f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)
605f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  // Construct a new node and add it to the worklist.
618bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  bool isNew;
628bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  ExplodedNode *Node = G.getNode(Loc, state, false, &isNew);
635d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  Node->addPredecessor(Pred, G);
645d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  if (isNew)
655d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    Engine.getWorkList()->enqueue(Node);
665d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)}
675d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
685d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)// Find the last statement on the path to the exploded node and the
695d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)// corresponding Block.
705d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)static std::pair<const Stmt*,
715d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                 const CFGBlock*> getLastStmt(const ExplodedNode *Node) {
725d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  const Stmt *S = 0;
735d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  const CFGBlock *Blk = 0;
745d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  const StackFrameContext *SF =
75c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch          Node->getLocation().getLocationContext()->getCurrentStackFrame();
76c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch
77c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch  // Back up through the ExplodedGraph until we reach a statement node in this
78c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch  // stack frame.
79c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch  while (Node) {
80c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    const ProgramPoint &PP = Node->getLocation();
81c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch
82c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    if (PP.getLocationContext()->getCurrentStackFrame() == SF) {
83c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch      if (Optional<StmtPoint> SP = PP.getAs<StmtPoint>()) {
845d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)        S = SP->getStmt();
855d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)        break;
865d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      } else if (Optional<CallExitEnd> CEE = PP.getAs<CallExitEnd>()) {
87f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)        S = CEE->getCalleeContext()->getCallSite();
885d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)        if (S)
895d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)          break;
905d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
915d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)        // If there is no statement, this is an implicitly-generated call.
925d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)        // We'll walk backwards over it and then continue the loop to find
935d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)        // an actual statement.
948bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)        Optional<CallEnter> CE;
958bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)        do {
968bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)          Node = Node->getFirstPred();
978bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)          CE = Node->getLocationAs<CallEnter>();
985d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)        } while (!CE || CE->getCalleeContext() != CEE->getCalleeContext());
995d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
1005d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)        // Continue searching the graph.
10123730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)      } else if (Optional<BlockEdge> BE = PP.getAs<BlockEdge>()) {
1025d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)        Blk = BE->getSrc();
1035d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      }
104effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch    } else if (Optional<CallEnter> CE = PP.getAs<CallEnter>()) {
10523730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)      // If we reached the CallEnter for this function, it has no statements.
10623730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)      if (CE->getCalleeContext() == SF)
10723730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)        break;
1085d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    }
1095d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
1105d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    if (Node->pred_empty())
1118bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)      return std::pair<const Stmt*, const CFGBlock*>((Stmt*)0, (CFGBlock*)0);
1128bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
1135f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)    Node = *Node->pred_begin();
1145f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  }
1158bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
1165f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  return std::pair<const Stmt*, const CFGBlock*>(S, Blk);
1178bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)}
1185f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)
119f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)/// Adjusts a return value when the called function's return type does not
120f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)/// match the caller's expression type. This can happen when a dynamic call
121f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)/// is devirtualized, and the overridding method has a covariant (more specific)
122f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)/// return type than the parent's method. For C++ objects, this means we need
1235d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)/// to add base casts.
1245d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)static SVal adjustReturnValue(SVal V, QualType ExpectedTy, QualType ActualTy,
1255d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                              StoreManager &StoreMgr) {
1265d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // For now, the only adjustments we handle apply only to locations.
127c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch  if (!V.getAs<Loc>())
128c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    return V;
129c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch
1308bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // If the types already match, don't do any unnecessary work.
1318bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  ExpectedTy = ExpectedTy.getCanonicalType();
1326e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)  ActualTy = ActualTy.getCanonicalType();
1336e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)  if (ExpectedTy == ActualTy)
1345f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)    return V;
1358bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
1368bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // No adjustment is needed between Objective-C pointer types.
1375d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  if (ExpectedTy->isObjCObjectPointerType() &&
1388bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)      ActualTy->isObjCObjectPointerType())
1398bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)    return V;
1408bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
1418bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // C++ object pointers may need "derived-to-base" casts.
1428bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  const CXXRecordDecl *ExpectedClass = ExpectedTy->getPointeeCXXRecordDecl();
1438bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  const CXXRecordDecl *ActualClass = ActualTy->getPointeeCXXRecordDecl();
1448bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  if (ExpectedClass && ActualClass) {
1455f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1468bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)                       /*DetectVirtual=*/false);
1478bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)    if (ActualClass->isDerivedFrom(ExpectedClass, Paths) &&
1488bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)        !Paths.isAmbiguous(ActualTy->getCanonicalTypeUnqualified())) {
149116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch      return StoreMgr.evalDerivedToBase(V, Paths.front());
1505f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)    }
1518bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  }
1528bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
1538bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // Unfortunately, Objective-C does not enforce that overridden methods have
1548bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // covariant return types, so we can't assert that that never happens.
1558bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // Be safe and return UnknownVal().
1568bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  return UnknownVal();
1578bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)}
1588bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
1598bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)void ExprEngine::removeDeadOnEndOfFunction(NodeBuilderContext& BC,
1605f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)                                           ExplodedNode *Pred,
1618bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)                                           ExplodedNodeSet &Dst) {
1628bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // Find the last statement in the function and the corresponding basic block.
1638bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  const Stmt *LastSt = 0;
1648bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  const CFGBlock *Blk = 0;
1658bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  llvm::tie(LastSt, Blk) = getLastStmt(Pred);
1665d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  if (!Blk || !LastSt) {
1675d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    Dst.Add(Pred);
1685f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)    return;
1695f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  }
1705f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)
1715f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  // Here, we destroy the current location context. We use the current
1725f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  // function's entire body as a diagnostic statement, with which the program
1735d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // point will be associated. However, we only want to use LastStmt as a
1745d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // reference for what to clean up if it's a ReturnStmt; otherwise, everything
1755d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // is dead.
1765d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
1775d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  const LocationContext *LCtx = Pred->getLocationContext();
1785d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  removeDead(Pred, Dst, dyn_cast<ReturnStmt>(LastSt), LCtx,
1795d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)             LCtx->getAnalysisDeclContext()->getBody(),
1805f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)             ProgramPoint::PostStmtPurgeDeadSymbolsKind);
1815f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)}
1825f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)
1835f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)static bool wasDifferentDeclUsedForInlining(CallEventRef<> Call,
1845f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)    const StackFrameContext *calleeCtx) {
1855f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  const Decl *RuntimeCallee = calleeCtx->getDecl();
1868bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  const Decl *StaticDecl = Call->getDecl();
1878bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  assert(RuntimeCallee);
1888bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  if (!StaticDecl)
1895f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)    return true;
1908bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  return RuntimeCallee->getCanonicalDecl() != StaticDecl->getCanonicalDecl();
1918bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)}
1928bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
1938bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)/// Returns true if the CXXConstructExpr \p E was intended to construct a
1945f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)/// prvalue for the region in \p V.
1955f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)///
1968bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)/// Note that we can't just test for rvalue vs. glvalue because
1978bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)/// CXXConstructExprs embedded in DeclStmts and initializers are considered
1988bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)/// rvalues by the AST, and the analyzer would like to treat them as lvalues.
1998bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)static bool isTemporaryPRValue(const CXXConstructExpr *E, SVal V) {
2005f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  if (E->isGLValue())
201f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)    return false;
202f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)
2038bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  const MemRegion *MR = V.getAsRegion();
204f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  if (!MR)
205f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)    return false;
206f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)
207f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  return isa<CXXTempObjectRegion>(MR);
2088bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)}
2098bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
2108bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)/// The call exit is simulated with a sequence of nodes, which occur between
2118bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)/// CallExitBegin and CallExitEnd. The following operations occur between the
2128bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)/// two program points:
2138bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)/// 1. CallExitBegin (triggers the start of call exit sequence)
2148bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)/// 2. Bind the return value
2158bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)/// 3. Run Remove dead bindings to clean up the dead symbols from the callee.
2168bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)/// 4. CallExitEnd (switch to the caller context)
2178bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)/// 5. PostStmt<CallExpr>
2188bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)void ExprEngine::processCallExit(ExplodedNode *CEBNode) {
2198bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // Step 1 CEBNode was generated before the call.
2208bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  PrettyStackTraceLocationContext CrashInfo(CEBNode->getLocationContext());
2218bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  const StackFrameContext *calleeCtx =
2228bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)      CEBNode->getLocationContext()->getCurrentStackFrame();
2238bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
2248bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // The parent context might not be a stack frame, so make sure we
2258bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // look up the first enclosing stack frame.
2268bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  const StackFrameContext *callerCtx =
2278bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)    calleeCtx->getParent()->getCurrentStackFrame();
2288bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
229f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  const Stmt *CE = calleeCtx->getCallSite();
2308bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  ProgramStateRef state = CEBNode->getState();
2318bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // Find the last statement in the function and the corresponding basic block.
2328bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  const Stmt *LastSt = 0;
2335d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  const CFGBlock *Blk = 0;
2348bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  llvm::tie(LastSt, Blk) = getLastStmt(CEBNode);
2358bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
2365d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // Generate a CallEvent /before/ cleaning the state, so that we can get the
237f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  // correct value for 'this' (if necessary).
238a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  CallEventManager &CEMgr = getStateManager().getCallEventManager();
2398bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  CallEventRef<> Call = CEMgr.getCaller(calleeCtx, state);
2408bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
2418bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // Step 2: generate node with bound return value: CEBNode -> BindedRetNode.
2425d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
2438bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // If the callee returns an expression, bind its value to CallExpr.
2448bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  if (CE) {
2458bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)    if (const ReturnStmt *RS = dyn_cast_or_null<ReturnStmt>(LastSt)) {
2468bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)      const LocationContext *LCtx = CEBNode->getLocationContext();
2478bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)      SVal V = state->getSVal(RS, LCtx);
248f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)
2498bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)      // Ensure that the return type matches the type of the returned Expr.
2508bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)      if (wasDifferentDeclUsedForInlining(Call, calleeCtx)) {
2518bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)        QualType ReturnedTy =
2528bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)          CallEvent::getDeclaredResultType(calleeCtx->getDecl());
2538bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)        if (!ReturnedTy.isNull()) {
2548bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)          if (const Expr *Ex = dyn_cast<Expr>(CE)) {
255f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)            V = adjustReturnValue(V, Ex->getType(), ReturnedTy,
256f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)                                  getStoreManager());
257f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)          }
2585d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)        }
2598bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)      }
2608bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
2618bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)      state = state->BindExpr(CE, callerCtx, V);
2628bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)    }
2635d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
2645d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    // Bind the constructed object value to CXXConstructExpr.
2655d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(CE)) {
2665d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      loc::MemRegionVal This =
2675d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)        svalBuilder.getCXXThis(CCE->getConstructor()->getParent(), calleeCtx);
2685d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      SVal ThisV = state->getSVal(This);
2695d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
2705d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      // If the constructed object is a temporary prvalue, get its bindings.
2715d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      if (isTemporaryPRValue(CCE, ThisV))
272c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch        ThisV = state->getSVal(ThisV.castAs<Loc>());
273c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch
274c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch      state = state->BindExpr(CCE, callerCtx, ThisV);
275c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    }
276c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch  }
277c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch
2785d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // Step 3: BindedRetNode -> CleanedNodes
2795d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // If we can find a statement and a block in the inlined function, run remove
2805d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // dead bindings before returning from the call. This is important to ensure
2815d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // that we report the issues such as leaks in the stack contexts in which
2825d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // they occurred.
2835d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  ExplodedNodeSet CleanedNodes;
2845d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  if (LastSt && Blk && AMgr.options.AnalysisPurgeOpt != PurgeNone) {
2855d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    static SimpleProgramPointTag retValBind("ExprEngine : Bind Return Value");
2865d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    PostStmt Loc(LastSt, calleeCtx, &retValBind);
2875d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    bool isNew;
2885d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    ExplodedNode *BindedRetNode = G.getNode(Loc, state, false, &isNew);
2895d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    BindedRetNode->addPredecessor(CEBNode, G);
2905d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    if (!isNew)
2915d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      return;
292c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch
293c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    NodeBuilderContext Ctx(getCoreEngine(), Blk, BindedRetNode);
294c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    currBldrCtx = &Ctx;
295c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    // Here, we call the Symbol Reaper with 0 statement and callee location
296c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    // context, telling it to clean up everything in the callee's context
297c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    // (and its children). We use the callee's function body as a diagnostic
298c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    // statement, with which the program point will be associated.
299c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    removeDead(BindedRetNode, CleanedNodes, 0, calleeCtx,
3005d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)               calleeCtx->getAnalysisDeclContext()->getBody(),
3015d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)               ProgramPoint::PostStmtPurgeDeadSymbolsKind);
3025d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    currBldrCtx = 0;
3035d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  } else {
3045d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    CleanedNodes.Add(CEBNode);
3055d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  }
3065d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
3075d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  for (ExplodedNodeSet::iterator I = CleanedNodes.begin(),
3085d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                                 E = CleanedNodes.end(); I != E; ++I) {
3095d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
3105d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    // Step 4: Generate the CallExit and leave the callee's context.
3115d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    // CleanedNodes -> CEENode
3125d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    CallExitEnd Loc(calleeCtx, callerCtx);
3135d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    bool isNew;
3145d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    ProgramStateRef CEEState = (*I == CEBNode) ? state : (*I)->getState();
3155d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    ExplodedNode *CEENode = G.getNode(Loc, CEEState, false, &isNew);
3165d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    CEENode->addPredecessor(*I, G);
3175d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    if (!isNew)
3185d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      return;
3195d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
3205d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    // Step 5: Perform the post-condition check of the CallExpr and enqueue the
3215d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    // result onto the work list.
3225d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    // CEENode -> Dst -> WorkList
3235d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    NodeBuilderContext Ctx(Engine, calleeCtx->getCallSiteBlock(), CEENode);
324c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    SaveAndRestore<const NodeBuilderContext*> NBCSave(currBldrCtx,
325c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch        &Ctx);
326c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    SaveAndRestore<unsigned> CBISave(currStmtIdx, calleeCtx->getIndex());
327c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch
328c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    CallEventRef<> UpdatedCall = Call.cloneWithState(CEEState);
329c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch
330c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    ExplodedNodeSet DstPostCall;
331c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    getCheckerManager().runCheckersForPostCall(DstPostCall, CEENode,
3325d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                                               *UpdatedCall, *this,
3335d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                                               /*WasInlined=*/true);
3345d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
3355d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    ExplodedNodeSet Dst;
3365d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
3375d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      getCheckerManager().runCheckersForPostObjCMessage(Dst, DstPostCall, *Msg,
3385d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                                                        *this,
3395d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                                                        /*WasInlined=*/true);
3405d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    } else if (CE) {
3415d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      getCheckerManager().runCheckersForPostStmt(Dst, DstPostCall, CE,
3425d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                                                 *this, /*WasInlined=*/true);
3435d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    } else {
3445d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      Dst.insert(DstPostCall);
3455d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    }
3465d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
3475d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    // Enqueue the next element in the block.
3485d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    for (ExplodedNodeSet::iterator PSI = Dst.begin(), PSE = Dst.end();
3495d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                                   PSI != PSE; ++PSI) {
350c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch      Engine.getWorkList()->enqueue(*PSI, calleeCtx->getCallSiteBlock(),
351c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch                                    calleeCtx->getIndex()+1);
352c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    }
353c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch  }
354c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch}
355c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch
356c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdochvoid ExprEngine::examineStackFrames(const Decl *D, const LocationContext *LCtx,
357c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch                               bool &IsRecursive, unsigned &StackDepth) {
3585f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  IsRecursive = false;
359a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  StackDepth = 0;
3608bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
3615f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  while (LCtx) {
3625f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)    if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LCtx)) {
3635f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)      const Decl *DI = SFC->getDecl();
3645f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)
3655f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)      // Mark recursive (and mutually recursive) functions and always count
3668bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)      // them when measuring the stack depth.
3678bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)      if (DI == D) {
3688bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)        IsRecursive = true;
3698bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)        ++StackDepth;
3708bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)        LCtx = LCtx->getParent();
3718bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)        continue;
3728bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)      }
3735f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)
3748bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)      // Do not count the small functions when determining the stack depth.
3758bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)      AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(DI);
3765f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)      const CFG *CalleeCFG = CalleeADC->getCFG();
3775f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)      if (CalleeCFG->getNumBlockIDs() > AMgr.options.getAlwaysInlineSize())
3785f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)        ++StackDepth;
3795f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)    }
3805f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)    LCtx = LCtx->getParent();
3818bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  }
3828bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
3838bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)}
3848bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
3858bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)static bool IsInStdNamespace(const FunctionDecl *FD) {
3868bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  const DeclContext *DC = FD->getEnclosingNamespaceContext();
3878bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3888bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  if (!ND)
389a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)    return false;
3908bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
3915f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  while (const DeclContext *Parent = ND->getParent()) {
392a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    if (!isa<NamespaceDecl>(Parent))
3938bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)      break;
3948bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)    ND = cast<NamespaceDecl>(Parent);
3958bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  }
3968bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
3978bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  return ND->getName() == "std";
3988bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)}
3995f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)
4008bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)// The GDM component containing the dynamic dispatch bifurcation info. When
4018bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)// the exact type of the receiver is not known, we want to explore both paths -
4028bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)// one on which we do inline it and the other one on which we don't. This is
4038bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)// done to ensure we do not drop coverage.
4048bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)// This is the map from the receiver region to a bool, specifying either we
4058bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)// consider this region's information precise or not along the given path.
4065f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)namespace {
4078bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  enum DynamicDispatchMode {
4085f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)    DynamicDispatchModeInlined = 1,
4098bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)    DynamicDispatchModeConservative
4108bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  };
4118bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)}
4128bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)REGISTER_TRAIT_WITH_PROGRAMSTATE(DynamicDispatchBifurcationMap,
4138bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)                                 CLANG_ENTO_PROGRAMSTATE_MAP(const MemRegion *,
4145f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)                                                             unsigned))
4158bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
4168bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)bool ExprEngine::inlineCall(const CallEvent &Call, const Decl *D,
4178bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)                            NodeBuilder &Bldr, ExplodedNode *Pred,
4188bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)                            ProgramStateRef State) {
4198bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  assert(D);
4208bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
4218bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  const LocationContext *CurLC = Pred->getLocationContext();
4225f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  const StackFrameContext *CallerSFC = CurLC->getCurrentStackFrame();
4238bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  const LocationContext *ParentOfCallee = CallerSFC;
4245f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  if (Call.getKind() == CE_Block) {
4258bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)    const BlockDataRegion *BR = cast<BlockCall>(Call).getBlockRegion();
4268bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)    assert(BR && "If we have the block definition we should have its region");
4278bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)    AnalysisDeclContext *BlockCtx = AMgr.getAnalysisDeclContext(D);
4288bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)    ParentOfCallee = BlockCtx->getBlockInvocationContext(CallerSFC,
4298bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)                                                         cast<BlockDecl>(D),
4308bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)                                                         BR);
4315f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  }
432f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
4338bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // This may be NULL, but that's fine.
4348bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  const Expr *CallE = Call.getOriginExpr();
4358bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
4368bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // Construct a new stack frame for the callee.
4375f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(D);
4385f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  const StackFrameContext *CalleeSFC =
4398bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)    CalleeADC->getStackFrame(ParentOfCallee, CallE,
4405f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)                             currBldrCtx->getBlock(),
4415f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)                             currStmtIdx);
442f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
4438bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
4448bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  CallEnter Loc(CallE, CalleeSFC, CurLC);
445f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
4468bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // Construct a new state which contains the mapping from actual to
4475f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  // formal arguments.
4485f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  State = State->enterStackFrame(Call, CalleeSFC);
4498bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
4508bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  bool isNew;
4518bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  if (ExplodedNode *N = G.getNode(Loc, State, false, &isNew)) {
4528bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)    N->addPredecessor(Pred, G);
4538bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)    if (isNew)
4548bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)      Engine.getWorkList()->enqueue(N);
4555f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  }
4568bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
4578bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // If we decided to inline the call, the successor has been manually
458f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  // added onto the work list so remove it from the node builder.
459f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  Bldr.takeNodes(Pred);
460f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)
461f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  NumInlinedCalls++;
4625d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
4635d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // Mark the decl as visited.
4645d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  if (VisitedCallees)
465c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    VisitedCallees->insert(D);
466c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch
4675d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  return true;
4688bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)}
4695d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
4705d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)static ProgramStateRef getInlineFailedState(ProgramStateRef State,
4715d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                                            const Stmt *CallE) {
4725d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  const void *ReplayState = State->get<ReplayWithoutInlining>();
4735d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  if (!ReplayState)
4748bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)    return 0;
4758bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
4768bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  assert(ReplayState == CallE && "Backtracked to the wrong call.");
4778bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  (void)CallE;
4785f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)
4798bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  return State->remove<ReplayWithoutInlining>();
4808bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)}
4818bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
4828bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)void ExprEngine::VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
483a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)                               ExplodedNodeSet &dst) {
4848bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // Perform the previsit of the CallExpr.
4858bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  ExplodedNodeSet dstPreVisit;
4865d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, CE, *this);
487f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)
4888bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // Get the call in its initial state. We use this as a template to perform
4898bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // all the checks.
490f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  CallEventManager &CEMgr = getStateManager().getCallEventManager();
4915d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  CallEventRef<> CallTemplate
4928bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)    = CEMgr.getSimpleCall(CE, Pred->getState(), Pred->getLocationContext());
4938bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
4948bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // Evaluate the function call.  We try each of the checkers
4958bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // to see if the can evaluate the function call.
4968bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  ExplodedNodeSet dstCallEvaluated;
4978bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
4988bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)       I != E; ++I) {
4998bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)    evalCall(dstCallEvaluated, *I, *CallTemplate);
5008bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  }
5018bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)
5028bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // Finally, perform the post-condition check of the CallExpr and store
5038bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  // the created nodes in 'Dst'.
5045d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // Note that if the call was inlined, dstCallEvaluated will be empty.
5055d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // The post-CallExpr check will occur in processCallExit.
5065d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  getCheckerManager().runCheckersForPostStmt(dst, dstCallEvaluated, CE,
5075d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                                             *this);
5085d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)}
5095d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
5105d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)void ExprEngine::evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred,
5115d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                          const CallEvent &Call) {
5125d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // WARNING: At this time, the state attached to 'Call' may be older than the
513116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // state in 'Pred'. This is a minor optimization since CheckerManager will
5145d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // use an updated CallEvent instance when calling checkers, but if 'Call' is
5155d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // ever used directly in this function all callers should be updated to pass
5165d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // the most recent state. (It is probably not worth doing the work here since
5175d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // for some callers this will not be necessary.)
5185d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
5195d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // Run any pre-call checks using the generic call interface.
5205d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  ExplodedNodeSet dstPreVisit;
5215d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  getCheckerManager().runCheckersForPreCall(dstPreVisit, Pred, Call, *this);
5225d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
5235d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // Actually evaluate the function call.  We try each of the checkers
5245d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // to see if the can evaluate the function call, and get a callback at
525f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  // defaultEvalCall if all of them fail.
5265d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  ExplodedNodeSet dstCallEvaluated;
5278bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)  getCheckerManager().runCheckersForEvalCall(dstCallEvaluated, dstPreVisit,
5288bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)                                             Call, *this);
529
530  // Finally, run any post-call checks.
531  getCheckerManager().runCheckersForPostCall(Dst, dstCallEvaluated,
532                                             Call, *this);
533}
534
535ProgramStateRef ExprEngine::bindReturnValue(const CallEvent &Call,
536                                            const LocationContext *LCtx,
537                                            ProgramStateRef State) {
538  const Expr *E = Call.getOriginExpr();
539  if (!E)
540    return State;
541
542  // Some method families have known return values.
543  if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(&Call)) {
544    switch (Msg->getMethodFamily()) {
545    default:
546      break;
547    case OMF_autorelease:
548    case OMF_retain:
549    case OMF_self: {
550      // These methods return their receivers.
551      return State->BindExpr(E, LCtx, Msg->getReceiverSVal());
552    }
553    }
554  } else if (const CXXConstructorCall *C = dyn_cast<CXXConstructorCall>(&Call)){
555    SVal ThisV = C->getCXXThisVal();
556
557    // If the constructed object is a temporary prvalue, get its bindings.
558    if (isTemporaryPRValue(cast<CXXConstructExpr>(E), ThisV))
559      ThisV = State->getSVal(ThisV.castAs<Loc>());
560
561    return State->BindExpr(E, LCtx, ThisV);
562  }
563
564  // Conjure a symbol if the return value is unknown.
565  QualType ResultTy = Call.getResultType();
566  SValBuilder &SVB = getSValBuilder();
567  unsigned Count = currBldrCtx->blockCount();
568  SVal R = SVB.conjureSymbolVal(0, E, LCtx, ResultTy, Count);
569  return State->BindExpr(E, LCtx, R);
570}
571
572// Conservatively evaluate call by invalidating regions and binding
573// a conjured return value.
574void ExprEngine::conservativeEvalCall(const CallEvent &Call, NodeBuilder &Bldr,
575                                      ExplodedNode *Pred,
576                                      ProgramStateRef State) {
577  State = Call.invalidateRegions(currBldrCtx->blockCount(), State);
578  State = bindReturnValue(Call, Pred->getLocationContext(), State);
579
580  // And make the result node.
581  Bldr.generateNode(Call.getProgramPoint(), State, Pred);
582}
583
584enum CallInlinePolicy {
585  CIP_Allowed,
586  CIP_DisallowedOnce,
587  CIP_DisallowedAlways
588};
589
590static CallInlinePolicy mayInlineCallKind(const CallEvent &Call,
591                                          const ExplodedNode *Pred,
592                                          AnalyzerOptions &Opts) {
593  const LocationContext *CurLC = Pred->getLocationContext();
594  const StackFrameContext *CallerSFC = CurLC->getCurrentStackFrame();
595  switch (Call.getKind()) {
596  case CE_Function:
597  case CE_Block:
598    break;
599  case CE_CXXMember:
600  case CE_CXXMemberOperator:
601    if (!Opts.mayInlineCXXMemberFunction(CIMK_MemberFunctions))
602      return CIP_DisallowedAlways;
603    break;
604  case CE_CXXConstructor: {
605    if (!Opts.mayInlineCXXMemberFunction(CIMK_Constructors))
606      return CIP_DisallowedAlways;
607
608    const CXXConstructorCall &Ctor = cast<CXXConstructorCall>(Call);
609
610    // FIXME: We don't handle constructors or destructors for arrays properly.
611    // Even once we do, we still need to be careful about implicitly-generated
612    // initializers for array fields in default move/copy constructors.
613    const MemRegion *Target = Ctor.getCXXThisVal().getAsRegion();
614    if (Target && isa<ElementRegion>(Target))
615      return CIP_DisallowedOnce;
616
617    // FIXME: This is a hack. We don't use the correct region for a new
618    // expression, so if we inline the constructor its result will just be
619    // thrown away. This short-term hack is tracked in <rdar://problem/12180598>
620    // and the longer-term possible fix is discussed in PR12014.
621    const CXXConstructExpr *CtorExpr = Ctor.getOriginExpr();
622    if (const Stmt *Parent = CurLC->getParentMap().getParent(CtorExpr))
623      if (isa<CXXNewExpr>(Parent))
624        return CIP_DisallowedOnce;
625
626    // Inlining constructors requires including initializers in the CFG.
627    const AnalysisDeclContext *ADC = CallerSFC->getAnalysisDeclContext();
628    assert(ADC->getCFGBuildOptions().AddInitializers && "No CFG initializers");
629    (void)ADC;
630
631    // If the destructor is trivial, it's always safe to inline the constructor.
632    if (Ctor.getDecl()->getParent()->hasTrivialDestructor())
633      break;
634
635    // For other types, only inline constructors if destructor inlining is
636    // also enabled.
637    if (!Opts.mayInlineCXXMemberFunction(CIMK_Destructors))
638      return CIP_DisallowedAlways;
639
640    // FIXME: This is a hack. We don't handle temporary destructors
641    // right now, so we shouldn't inline their constructors.
642    if (CtorExpr->getConstructionKind() == CXXConstructExpr::CK_Complete)
643      if (!Target || !isa<DeclRegion>(Target))
644        return CIP_DisallowedOnce;
645
646    break;
647  }
648  case CE_CXXDestructor: {
649    if (!Opts.mayInlineCXXMemberFunction(CIMK_Destructors))
650      return CIP_DisallowedAlways;
651
652    // Inlining destructors requires building the CFG correctly.
653    const AnalysisDeclContext *ADC = CallerSFC->getAnalysisDeclContext();
654    assert(ADC->getCFGBuildOptions().AddImplicitDtors && "No CFG destructors");
655    (void)ADC;
656
657    const CXXDestructorCall &Dtor = cast<CXXDestructorCall>(Call);
658
659    // FIXME: We don't handle constructors or destructors for arrays properly.
660    const MemRegion *Target = Dtor.getCXXThisVal().getAsRegion();
661    if (Target && isa<ElementRegion>(Target))
662      return CIP_DisallowedOnce;
663
664    break;
665  }
666  case CE_CXXAllocator:
667    // Do not inline allocators until we model deallocators.
668    // This is unfortunate, but basically necessary for smart pointers and such.
669    return CIP_DisallowedAlways;
670  case CE_ObjCMessage:
671    if (!Opts.mayInlineObjCMethod())
672      return CIP_DisallowedAlways;
673    if (!(Opts.getIPAMode() == IPAK_DynamicDispatch ||
674          Opts.getIPAMode() == IPAK_DynamicDispatchBifurcate))
675      return CIP_DisallowedAlways;
676    break;
677  }
678
679  return CIP_Allowed;
680}
681
682/// Returns true if the given C++ class contains a member with the given name.
683static bool hasMember(const ASTContext &Ctx, const CXXRecordDecl *RD,
684                      StringRef Name) {
685  const IdentifierInfo &II = Ctx.Idents.get(Name);
686  DeclarationName DeclName = Ctx.DeclarationNames.getIdentifier(&II);
687  if (!RD->lookup(DeclName).empty())
688    return true;
689
690  CXXBasePaths Paths(false, false, false);
691  if (RD->lookupInBases(&CXXRecordDecl::FindOrdinaryMember,
692                        DeclName.getAsOpaquePtr(),
693                        Paths))
694    return true;
695
696  return false;
697}
698
699/// Returns true if the given C++ class is a container or iterator.
700///
701/// Our heuristic for this is whether it contains a method named 'begin()' or a
702/// nested type named 'iterator' or 'iterator_category'.
703static bool isContainerClass(const ASTContext &Ctx, const CXXRecordDecl *RD) {
704  return hasMember(Ctx, RD, "begin") ||
705         hasMember(Ctx, RD, "iterator") ||
706         hasMember(Ctx, RD, "iterator_category");
707}
708
709/// Returns true if the given function refers to a constructor or destructor of
710/// a C++ container or iterator.
711///
712/// We generally do a poor job modeling most containers right now, and would
713/// prefer not to inline their setup and teardown.
714static bool isContainerCtorOrDtor(const ASTContext &Ctx,
715                                  const FunctionDecl *FD) {
716  if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)))
717    return false;
718
719  const CXXRecordDecl *RD = cast<CXXMethodDecl>(FD)->getParent();
720  return isContainerClass(Ctx, RD);
721}
722
723/// Returns true if the given function is the destructor of a class named
724/// "shared_ptr".
725static bool isCXXSharedPtrDtor(const FunctionDecl *FD) {
726  const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(FD);
727  if (!Dtor)
728    return false;
729
730  const CXXRecordDecl *RD = Dtor->getParent();
731  if (const IdentifierInfo *II = RD->getDeclName().getAsIdentifierInfo())
732    if (II->isStr("shared_ptr"))
733        return true;
734
735  return false;
736}
737
738/// Returns true if the function in \p CalleeADC may be inlined in general.
739///
740/// This checks static properties of the function, such as its signature and
741/// CFG, to determine whether the analyzer should ever consider inlining it,
742/// in any context.
743static bool mayInlineDecl(AnalysisDeclContext *CalleeADC,
744                          AnalyzerOptions &Opts) {
745  // FIXME: Do not inline variadic calls.
746  if (CallEvent::isVariadic(CalleeADC->getDecl()))
747    return false;
748
749  // Check certain C++-related inlining policies.
750  ASTContext &Ctx = CalleeADC->getASTContext();
751  if (Ctx.getLangOpts().CPlusPlus) {
752    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CalleeADC->getDecl())) {
753      // Conditionally control the inlining of template functions.
754      if (!Opts.mayInlineTemplateFunctions())
755        if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
756          return false;
757
758      // Conditionally control the inlining of C++ standard library functions.
759      if (!Opts.mayInlineCXXStandardLibrary())
760        if (Ctx.getSourceManager().isInSystemHeader(FD->getLocation()))
761          if (IsInStdNamespace(FD))
762            return false;
763
764      // Conditionally control the inlining of methods on objects that look
765      // like C++ containers.
766      if (!Opts.mayInlineCXXContainerCtorsAndDtors())
767        if (!Ctx.getSourceManager().isInMainFile(FD->getLocation()))
768          if (isContainerCtorOrDtor(Ctx, FD))
769            return false;
770
771      // Conditionally control the inlining of the destructor of C++ shared_ptr.
772      // We don't currently do a good job modeling shared_ptr because we can't
773      // see the reference count, so treating as opaque is probably the best
774      // idea.
775      if (!Opts.mayInlineCXXSharedPtrDtor())
776        if (isCXXSharedPtrDtor(FD))
777          return false;
778
779    }
780  }
781
782  // It is possible that the CFG cannot be constructed.
783  // Be safe, and check if the CalleeCFG is valid.
784  const CFG *CalleeCFG = CalleeADC->getCFG();
785  if (!CalleeCFG)
786    return false;
787
788  // Do not inline large functions.
789  if (CalleeCFG->getNumBlockIDs() > Opts.getMaxInlinableSize())
790    return false;
791
792  // It is possible that the live variables analysis cannot be
793  // run.  If so, bail out.
794  if (!CalleeADC->getAnalysis<RelaxedLiveVariables>())
795    return false;
796
797  return true;
798}
799
800bool ExprEngine::shouldInlineCall(const CallEvent &Call, const Decl *D,
801                                  const ExplodedNode *Pred) {
802  if (!D)
803    return false;
804
805  AnalysisManager &AMgr = getAnalysisManager();
806  AnalyzerOptions &Opts = AMgr.options;
807  AnalysisDeclContextManager &ADCMgr = AMgr.getAnalysisDeclContextManager();
808  AnalysisDeclContext *CalleeADC = ADCMgr.getContext(D);
809
810  // Temporary object destructor processing is currently broken, so we never
811  // inline them.
812  // FIXME: Remove this once temp destructors are working.
813  if (isa<CXXDestructorCall>(Call)) {
814    if ((*currBldrCtx->getBlock())[currStmtIdx].getAs<CFGTemporaryDtor>())
815      return false;
816  }
817
818  // The auto-synthesized bodies are essential to inline as they are
819  // usually small and commonly used. Note: we should do this check early on to
820  // ensure we always inline these calls.
821  if (CalleeADC->isBodyAutosynthesized())
822    return true;
823
824  if (!AMgr.shouldInlineCall())
825    return false;
826
827  // Check if this function has been marked as non-inlinable.
828  Optional<bool> MayInline = Engine.FunctionSummaries->mayInline(D);
829  if (MayInline.hasValue()) {
830    if (!MayInline.getValue())
831      return false;
832
833  } else {
834    // We haven't actually checked the static properties of this function yet.
835    // Do that now, and record our decision in the function summaries.
836    if (mayInlineDecl(CalleeADC, Opts)) {
837      Engine.FunctionSummaries->markMayInline(D);
838    } else {
839      Engine.FunctionSummaries->markShouldNotInline(D);
840      return false;
841    }
842  }
843
844  // Check if we should inline a call based on its kind.
845  // FIXME: this checks both static and dynamic properties of the call, which
846  // means we're redoing a bit of work that could be cached in the function
847  // summary.
848  CallInlinePolicy CIP = mayInlineCallKind(Call, Pred, Opts);
849  if (CIP != CIP_Allowed) {
850    if (CIP == CIP_DisallowedAlways) {
851      assert(!MayInline.hasValue() || MayInline.getValue());
852      Engine.FunctionSummaries->markShouldNotInline(D);
853    }
854    return false;
855  }
856
857  const CFG *CalleeCFG = CalleeADC->getCFG();
858
859  // Do not inline if recursive or we've reached max stack frame count.
860  bool IsRecursive = false;
861  unsigned StackDepth = 0;
862  examineStackFrames(D, Pred->getLocationContext(), IsRecursive, StackDepth);
863  if ((StackDepth >= Opts.InlineMaxStackDepth) &&
864      ((CalleeCFG->getNumBlockIDs() > Opts.getAlwaysInlineSize())
865       || IsRecursive))
866    return false;
867
868  // Do not inline large functions too many times.
869  if ((Engine.FunctionSummaries->getNumTimesInlined(D) >
870       Opts.getMaxTimesInlineLarge()) &&
871      CalleeCFG->getNumBlockIDs() > 13) {
872    NumReachedInlineCountMax++;
873    return false;
874  }
875
876  if (HowToInline == Inline_Minimal &&
877      (CalleeCFG->getNumBlockIDs() > Opts.getAlwaysInlineSize()
878      || IsRecursive))
879    return false;
880
881  Engine.FunctionSummaries->bumpNumTimesInlined(D);
882
883  return true;
884}
885
886static bool isTrivialObjectAssignment(const CallEvent &Call) {
887  const CXXInstanceCall *ICall = dyn_cast<CXXInstanceCall>(&Call);
888  if (!ICall)
889    return false;
890
891  const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(ICall->getDecl());
892  if (!MD)
893    return false;
894  if (!(MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()))
895    return false;
896
897  return MD->isTrivial();
898}
899
900void ExprEngine::defaultEvalCall(NodeBuilder &Bldr, ExplodedNode *Pred,
901                                 const CallEvent &CallTemplate) {
902  // Make sure we have the most recent state attached to the call.
903  ProgramStateRef State = Pred->getState();
904  CallEventRef<> Call = CallTemplate.cloneWithState(State);
905
906  // Special-case trivial assignment operators.
907  if (isTrivialObjectAssignment(*Call)) {
908    performTrivialCopy(Bldr, Pred, *Call);
909    return;
910  }
911
912  // Try to inline the call.
913  // The origin expression here is just used as a kind of checksum;
914  // this should still be safe even for CallEvents that don't come from exprs.
915  const Expr *E = Call->getOriginExpr();
916
917  ProgramStateRef InlinedFailedState = getInlineFailedState(State, E);
918  if (InlinedFailedState) {
919    // If we already tried once and failed, make sure we don't retry later.
920    State = InlinedFailedState;
921  } else {
922    RuntimeDefinition RD = Call->getRuntimeDefinition();
923    const Decl *D = RD.getDecl();
924    if (shouldInlineCall(*Call, D, Pred)) {
925      if (RD.mayHaveOtherDefinitions()) {
926        AnalyzerOptions &Options = getAnalysisManager().options;
927
928        // Explore with and without inlining the call.
929        if (Options.getIPAMode() == IPAK_DynamicDispatchBifurcate) {
930          BifurcateCall(RD.getDispatchRegion(), *Call, D, Bldr, Pred);
931          return;
932        }
933
934        // Don't inline if we're not in any dynamic dispatch mode.
935        if (Options.getIPAMode() != IPAK_DynamicDispatch) {
936          conservativeEvalCall(*Call, Bldr, Pred, State);
937          return;
938        }
939      }
940
941      // We are not bifurcating and we do have a Decl, so just inline.
942      if (inlineCall(*Call, D, Bldr, Pred, State))
943        return;
944    }
945  }
946
947  // If we can't inline it, handle the return value and invalidate the regions.
948  conservativeEvalCall(*Call, Bldr, Pred, State);
949}
950
951void ExprEngine::BifurcateCall(const MemRegion *BifurReg,
952                               const CallEvent &Call, const Decl *D,
953                               NodeBuilder &Bldr, ExplodedNode *Pred) {
954  assert(BifurReg);
955  BifurReg = BifurReg->StripCasts();
956
957  // Check if we've performed the split already - note, we only want
958  // to split the path once per memory region.
959  ProgramStateRef State = Pred->getState();
960  const unsigned *BState =
961                        State->get<DynamicDispatchBifurcationMap>(BifurReg);
962  if (BState) {
963    // If we are on "inline path", keep inlining if possible.
964    if (*BState == DynamicDispatchModeInlined)
965      if (inlineCall(Call, D, Bldr, Pred, State))
966        return;
967    // If inline failed, or we are on the path where we assume we
968    // don't have enough info about the receiver to inline, conjure the
969    // return value and invalidate the regions.
970    conservativeEvalCall(Call, Bldr, Pred, State);
971    return;
972  }
973
974  // If we got here, this is the first time we process a message to this
975  // region, so split the path.
976  ProgramStateRef IState =
977      State->set<DynamicDispatchBifurcationMap>(BifurReg,
978                                               DynamicDispatchModeInlined);
979  inlineCall(Call, D, Bldr, Pred, IState);
980
981  ProgramStateRef NoIState =
982      State->set<DynamicDispatchBifurcationMap>(BifurReg,
983                                               DynamicDispatchModeConservative);
984  conservativeEvalCall(Call, Bldr, Pred, NoIState);
985
986  NumOfDynamicDispatchPathSplits++;
987  return;
988}
989
990
991void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred,
992                                 ExplodedNodeSet &Dst) {
993
994  ExplodedNodeSet dstPreVisit;
995  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, RS, *this);
996
997  StmtNodeBuilder B(dstPreVisit, Dst, *currBldrCtx);
998
999  if (RS->getRetValue()) {
1000    for (ExplodedNodeSet::iterator it = dstPreVisit.begin(),
1001                                  ei = dstPreVisit.end(); it != ei; ++it) {
1002      B.generateNode(RS, *it, (*it)->getState());
1003    }
1004  }
1005}
1006