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