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