ExprEngineCallAndReturn.cpp revision 48b6247804eacc262cc5508e0fbb74ed819fbb6e
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#include "clang/Analysis/Analyses/LiveVariables.h" 15#include "clang/StaticAnalyzer/Core/CheckerManager.h" 16#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 17#include "clang/StaticAnalyzer/Core/PathSensitive/Calls.h" 18#include "clang/AST/DeclCXX.h" 19#include "llvm/ADT/SmallSet.h" 20#include "llvm/Support/SaveAndRestore.h" 21 22using namespace clang; 23using namespace ento; 24 25static CallEventKind classifyCallExpr(const CallExpr *CE) { 26 if (isa<CXXMemberCallExpr>(CE)) 27 return CE_CXXMember; 28 29 const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE); 30 if (OpCE) { 31 const FunctionDecl *DirectCallee = CE->getDirectCallee(); 32 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee)) 33 if (MD->isInstance()) 34 return CE_CXXMemberOperator; 35 } else if (CE->getCallee()->getType()->isBlockPointerType()) { 36 return CE_Block; 37 } 38 39 return CE_Function; 40} 41 42void ExprEngine::processCallEnter(CallEnter CE, ExplodedNode *Pred) { 43 // Get the entry block in the CFG of the callee. 44 const StackFrameContext *calleeCtx = CE.getCalleeContext(); 45 const CFG *CalleeCFG = calleeCtx->getCFG(); 46 const CFGBlock *Entry = &(CalleeCFG->getEntry()); 47 48 // Validate the CFG. 49 assert(Entry->empty()); 50 assert(Entry->succ_size() == 1); 51 52 // Get the solitary sucessor. 53 const CFGBlock *Succ = *(Entry->succ_begin()); 54 55 // Construct an edge representing the starting location in the callee. 56 BlockEdge Loc(Entry, Succ, calleeCtx); 57 58 ProgramStateRef state = Pred->getState(); 59 60 // Construct a new node and add it to the worklist. 61 bool isNew; 62 ExplodedNode *Node = G.getNode(Loc, state, false, &isNew); 63 Node->addPredecessor(Pred, G); 64 if (isNew) 65 Engine.getWorkList()->enqueue(Node); 66} 67 68// Find the last statement on the path to the exploded node and the 69// corresponding Block. 70static std::pair<const Stmt*, 71 const CFGBlock*> getLastStmt(const ExplodedNode *Node) { 72 const Stmt *S = 0; 73 const CFGBlock *Blk = 0; 74 const StackFrameContext *SF = 75 Node->getLocation().getLocationContext()->getCurrentStackFrame(); 76 while (Node) { 77 const ProgramPoint &PP = Node->getLocation(); 78 // Skip any BlockEdges, empty blocks, and the CallExitBegin node. 79 if (isa<BlockEdge>(PP) || isa<CallExitBegin>(PP) || isa<BlockEntrance>(PP)){ 80 assert(Node->pred_size() == 1); 81 Node = *Node->pred_begin(); 82 continue; 83 } 84 // If we reached the CallEnter, the function has no statements. 85 if (isa<CallEnter>(PP)) 86 break; 87 if (const StmtPoint *SP = dyn_cast<StmtPoint>(&PP)) { 88 S = SP->getStmt(); 89 // Now, get the enclosing basic block. 90 while (Node && Node->pred_size() >=1 ) { 91 const ProgramPoint &PP = Node->getLocation(); 92 if (isa<BlockEdge>(PP) && 93 (PP.getLocationContext()->getCurrentStackFrame() == SF)) { 94 BlockEdge &EPP = cast<BlockEdge>(PP); 95 Blk = EPP.getDst(); 96 break; 97 } 98 Node = *Node->pred_begin(); 99 } 100 break; 101 } 102 break; 103 } 104 return std::pair<const Stmt*, const CFGBlock*>(S, Blk); 105} 106 107/// The call exit is simulated with a sequence of nodes, which occur between 108/// CallExitBegin and CallExitEnd. The following operations occur between the 109/// two program points: 110/// 1. CallExitBegin (triggers the start of call exit sequence) 111/// 2. Bind the return value 112/// 3. Run Remove dead bindings to clean up the dead symbols from the callee. 113/// 4. CallExitEnd (switch to the caller context) 114/// 5. PostStmt<CallExpr> 115void ExprEngine::processCallExit(ExplodedNode *CEBNode) { 116 // Step 1 CEBNode was generated before the call. 117 118 const StackFrameContext *calleeCtx = 119 CEBNode->getLocationContext()->getCurrentStackFrame(); 120 121 // The parent context might not be a stack frame, so make sure we 122 // look up the first enclosing stack frame. 123 const StackFrameContext *callerCtx = 124 calleeCtx->getParent()->getCurrentStackFrame(); 125 126 const Stmt *CE = calleeCtx->getCallSite(); 127 ProgramStateRef state = CEBNode->getState(); 128 // Find the last statement in the function and the corresponding basic block. 129 const Stmt *LastSt = 0; 130 const CFGBlock *Blk = 0; 131 llvm::tie(LastSt, Blk) = getLastStmt(CEBNode); 132 133 // Step 2: generate node with bound return value: CEBNode -> BindedRetNode. 134 135 // If the callee returns an expression, bind its value to CallExpr. 136 if (CE) { 137 if (const ReturnStmt *RS = dyn_cast_or_null<ReturnStmt>(LastSt)) { 138 const LocationContext *LCtx = CEBNode->getLocationContext(); 139 SVal V = state->getSVal(RS, LCtx); 140 state = state->BindExpr(CE, calleeCtx->getParent(), V); 141 } 142 143 // Bind the constructed object value to CXXConstructExpr. 144 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(CE)) { 145 loc::MemRegionVal This = 146 svalBuilder.getCXXThis(CCE->getConstructor()->getParent(), calleeCtx); 147 SVal ThisV = state->getSVal(This); 148 149 // Always bind the region to the CXXConstructExpr. 150 state = state->BindExpr(CCE, calleeCtx->getParent(), ThisV); 151 } 152 } 153 154 // Step 3: BindedRetNode -> CleanedNodes 155 // If we can find a statement and a block in the inlined function, run remove 156 // dead bindings before returning from the call. This is important to ensure 157 // that we report the issues such as leaks in the stack contexts in which 158 // they occurred. 159 ExplodedNodeSet CleanedNodes; 160 if (LastSt && Blk) { 161 static SimpleProgramPointTag retValBind("ExprEngine : Bind Return Value"); 162 PostStmt Loc(LastSt, calleeCtx, &retValBind); 163 bool isNew; 164 ExplodedNode *BindedRetNode = G.getNode(Loc, state, false, &isNew); 165 BindedRetNode->addPredecessor(CEBNode, G); 166 if (!isNew) 167 return; 168 169 NodeBuilderContext Ctx(getCoreEngine(), Blk, BindedRetNode); 170 currentBuilderContext = &Ctx; 171 // Here, we call the Symbol Reaper with 0 statement and caller location 172 // context, telling it to clean up everything in the callee's context 173 // (and it's children). We use LastStmt as a diagnostic statement, which 174 // which the PreStmtPurge Dead point will be associated. 175 removeDead(BindedRetNode, CleanedNodes, 0, callerCtx, LastSt, 176 ProgramPoint::PostStmtPurgeDeadSymbolsKind); 177 currentBuilderContext = 0; 178 } else { 179 CleanedNodes.Add(CEBNode); 180 } 181 182 for (ExplodedNodeSet::iterator I = CleanedNodes.begin(), 183 E = CleanedNodes.end(); I != E; ++I) { 184 185 // Step 4: Generate the CallExit and leave the callee's context. 186 // CleanedNodes -> CEENode 187 CallExitEnd Loc(calleeCtx, callerCtx); 188 bool isNew; 189 ProgramStateRef CEEState = (*I == CEBNode) ? state : (*I)->getState(); 190 ExplodedNode *CEENode = G.getNode(Loc, CEEState, false, &isNew); 191 CEENode->addPredecessor(*I, G); 192 if (!isNew) 193 return; 194 195 // Step 5: Perform the post-condition check of the CallExpr and enqueue the 196 // result onto the work list. 197 // CEENode -> Dst -> WorkList 198 ExplodedNodeSet Dst; 199 NodeBuilderContext Ctx(Engine, calleeCtx->getCallSiteBlock(), CEENode); 200 SaveAndRestore<const NodeBuilderContext*> NBCSave(currentBuilderContext, 201 &Ctx); 202 SaveAndRestore<unsigned> CBISave(currentStmtIdx, calleeCtx->getIndex()); 203 204 // FIXME: This needs to call PostCall. 205 // FIXME: If/when we inline Objective-C messages, this also needs to call 206 // PostObjCMessage. 207 if (CE) 208 getCheckerManager().runCheckersForPostStmt(Dst, CEENode, CE, *this, true); 209 else 210 Dst.Add(CEENode); 211 212 // Enqueue the next element in the block. 213 for (ExplodedNodeSet::iterator PSI = Dst.begin(), PSE = Dst.end(); 214 PSI != PSE; ++PSI) { 215 Engine.getWorkList()->enqueue(*PSI, calleeCtx->getCallSiteBlock(), 216 calleeCtx->getIndex()+1); 217 } 218 } 219} 220 221static unsigned getNumberStackFrames(const LocationContext *LCtx) { 222 unsigned count = 0; 223 while (LCtx) { 224 if (isa<StackFrameContext>(LCtx)) 225 ++count; 226 LCtx = LCtx->getParent(); 227 } 228 return count; 229} 230 231// Determine if we should inline the call. 232bool ExprEngine::shouldInlineDecl(const Decl *D, ExplodedNode *Pred) { 233 // FIXME: default constructors don't have bodies. 234 if (!D->hasBody()) 235 return false; 236 237 AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(D); 238 const CFG *CalleeCFG = CalleeADC->getCFG(); 239 240 // It is possible that the CFG cannot be constructed. 241 // Be safe, and check if the CalleeCFG is valid. 242 if (!CalleeCFG) 243 return false; 244 245 if (getNumberStackFrames(Pred->getLocationContext()) 246 == AMgr.InlineMaxStackDepth) 247 return false; 248 249 if (Engine.FunctionSummaries->hasReachedMaxBlockCount(D)) 250 return false; 251 252 if (CalleeCFG->getNumBlockIDs() > AMgr.InlineMaxFunctionSize) 253 return false; 254 255 // Do not inline variadic calls (for now). 256 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 257 if (BD->isVariadic()) 258 return false; 259 } 260 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 261 if (FD->isVariadic()) 262 return false; 263 } 264 265 // It is possible that the live variables analysis cannot be 266 // run. If so, bail out. 267 if (!CalleeADC->getAnalysis<RelaxedLiveVariables>()) 268 return false; 269 270 return true; 271} 272 273bool ExprEngine::inlineCall(ExplodedNodeSet &Dst, 274 const CallEvent &Call, 275 ExplodedNode *Pred) { 276 if (!getAnalysisManager().shouldInlineCall()) 277 return false; 278 279 const StackFrameContext *CallerSFC = 280 Pred->getLocationContext()->getCurrentStackFrame(); 281 282 const Decl *D = Call.getDefinition(); 283 if (!D) 284 return false; 285 286 const LocationContext *ParentOfCallee = 0; 287 288 switch (Call.getKind()) { 289 case CE_Function: 290 case CE_CXXMember: 291 case CE_CXXMemberOperator: 292 // These are always at least possible to inline. 293 break; 294 case CE_CXXConstructor: 295 case CE_CXXDestructor: 296 // Do not inline constructors until we can really model destructors. 297 // This is unfortunate, but basically necessary for smart pointers and such. 298 return false; 299 case CE_CXXAllocator: 300 // Do not inline allocators until we model deallocators. 301 // This is unfortunate, but basically necessary for smart pointers and such. 302 return false; 303 case CE_Block: { 304 const BlockDataRegion *BR = cast<BlockCall>(Call).getBlockRegion(); 305 assert(BR && "If we have the block definition we should have its region"); 306 AnalysisDeclContext *BlockCtx = AMgr.getAnalysisDeclContext(D); 307 ParentOfCallee = BlockCtx->getBlockInvocationContext(CallerSFC, 308 cast<BlockDecl>(D), 309 BR); 310 break; 311 } 312 case CE_ObjCMessage: 313 case CE_ObjCPropertyAccess: 314 // These always use dynamic dispatch; enabling inlining means assuming 315 // that a particular method will be called at runtime. 316 return false; 317 } 318 319 if (!shouldInlineDecl(D, Pred)) 320 return false; 321 322 if (!ParentOfCallee) 323 ParentOfCallee = CallerSFC; 324 325 // This may be NULL, but that's fine. 326 const Expr *CallE = Call.getOriginExpr(); 327 328 // Construct a new stack frame for the callee. 329 AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(D); 330 const StackFrameContext *CalleeSFC = 331 CalleeADC->getStackFrame(ParentOfCallee, CallE, 332 currentBuilderContext->getBlock(), 333 currentStmtIdx); 334 335 CallEnter Loc(CallE, CalleeSFC, Pred->getLocationContext()); 336 337 // Construct a new state which contains the mapping from actual to 338 // formal arguments. 339 ProgramStateRef State = Pred->getState()->enterStackFrame(Call, CalleeSFC); 340 341 bool isNew; 342 if (ExplodedNode *N = G.getNode(Loc, State, false, &isNew)) { 343 N->addPredecessor(Pred, G); 344 if (isNew) 345 Engine.getWorkList()->enqueue(N); 346 } 347 return true; 348} 349 350static ProgramStateRef getInlineFailedState(ExplodedNode *&N, 351 const Stmt *CallE) { 352 void *ReplayState = N->getState()->get<ReplayWithoutInlining>(); 353 if (!ReplayState) 354 return 0; 355 356 assert(ReplayState == (const void*)CallE && "Backtracked to the wrong call."); 357 (void)CallE; 358 359 return N->getState()->remove<ReplayWithoutInlining>(); 360} 361 362void ExprEngine::VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred, 363 ExplodedNodeSet &dst) { 364 // Perform the previsit of the CallExpr. 365 ExplodedNodeSet dstPreVisit; 366 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, CE, *this); 367 368 // Get the callee kind. 369 CallEventKind K = classifyCallExpr(CE); 370 371 // Evaluate the function call. We try each of the checkers 372 // to see if the can evaluate the function call. 373 ExplodedNodeSet dstCallEvaluated; 374 for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end(); 375 I != E; ++I) { 376 ProgramStateRef State = (*I)->getState(); 377 const LocationContext *LCtx = (*I)->getLocationContext(); 378 379 // Evaluate the call. 380 switch (K) { 381 case CE_Function: 382 evalCall(dstCallEvaluated, *I, FunctionCall(CE, State, LCtx)); 383 break; 384 case CE_CXXMember: 385 evalCall(dstCallEvaluated, *I, CXXMemberCall(cast<CXXMemberCallExpr>(CE), 386 State, LCtx)); 387 break; 388 case CE_CXXMemberOperator: 389 evalCall(dstCallEvaluated, *I, 390 CXXMemberOperatorCall(cast<CXXOperatorCallExpr>(CE), 391 State, LCtx)); 392 break; 393 case CE_Block: 394 evalCall(dstCallEvaluated, *I, BlockCall(CE, State, LCtx)); 395 break; 396 default: 397 llvm_unreachable("Non-CallExpr CallEventKind"); 398 } 399 } 400 401 // Finally, perform the post-condition check of the CallExpr and store 402 // the created nodes in 'Dst'. 403 // Note that if the call was inlined, dstCallEvaluated will be empty. 404 // The post-CallExpr check will occur in processCallExit. 405 getCheckerManager().runCheckersForPostStmt(dst, dstCallEvaluated, CE, 406 *this); 407} 408 409void ExprEngine::evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred, 410 const SimpleCall &Call) { 411 // Run any pre-call checks using the generic call interface. 412 ExplodedNodeSet dstPreVisit; 413 getCheckerManager().runCheckersForPreCall(dstPreVisit, Pred, Call, *this); 414 415 // Actually evaluate the function call. We try each of the checkers 416 // to see if the can evaluate the function call, and get a callback at 417 // defaultEvalCall if all of them fail. 418 ExplodedNodeSet dstCallEvaluated; 419 getCheckerManager().runCheckersForEvalCall(dstCallEvaluated, dstPreVisit, 420 Call, *this); 421 422 // Finally, run any post-call checks. 423 getCheckerManager().runCheckersForPostCall(Dst, dstCallEvaluated, 424 Call, *this); 425} 426 427void ExprEngine::defaultEvalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred, 428 const CallEvent &Call) { 429 // Try to inline the call. 430 // The origin expression here is just used as a kind of checksum; 431 // for CallEvents that do not have origin expressions, this should still be 432 // safe. 433 const Expr *E = Call.getOriginExpr(); 434 ProgramStateRef state = getInlineFailedState(Pred, E); 435 if (state == 0 && inlineCall(Dst, Call, Pred)) 436 return; 437 438 // If we can't inline it, handle the return value and invalidate the regions. 439 NodeBuilder Bldr(Pred, Dst, *currentBuilderContext); 440 441 // Invalidate any regions touched by the call. 442 unsigned Count = currentBuilderContext->getCurrentBlockCount(); 443 if (state == 0) 444 state = Pred->getState(); 445 state = Call.invalidateRegions(Count, state); 446 447 // Conjure a symbol value to use as the result. 448 if (E) { 449 QualType ResultTy = Call.getResultType(); 450 SValBuilder &SVB = getSValBuilder(); 451 const LocationContext *LCtx = Pred->getLocationContext(); 452 SVal RetVal = SVB.getConjuredSymbolVal(0, E, LCtx, ResultTy, Count); 453 454 state = state->BindExpr(E, LCtx, RetVal); 455 } 456 457 // And make the result node. 458 Bldr.generateNode(Call.getProgramPoint(), state, Pred); 459} 460 461void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred, 462 ExplodedNodeSet &Dst) { 463 464 ExplodedNodeSet dstPreVisit; 465 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, RS, *this); 466 467 StmtNodeBuilder B(dstPreVisit, Dst, *currentBuilderContext); 468 469 if (RS->getRetValue()) { 470 for (ExplodedNodeSet::iterator it = dstPreVisit.begin(), 471 ei = dstPreVisit.end(); it != ei; ++it) { 472 B.generateNode(RS, *it, (*it)->getState()); 473 } 474 } 475} 476