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