ExprEngine.cpp revision bf53dfac8195835028bd6347433f7dbebcc29fc1
1//=-- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- 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 a meta-engine for path-sensitive dataflow analysis that 11// is built on GREngine, but provides the boilerplate to execute transfer 12// functions and build the ExplodedGraph at the expression level. 13// 14//===----------------------------------------------------------------------===// 15 16#define DEBUG_TYPE "ExprEngine" 17 18#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 19#include "clang/AST/CharUnits.h" 20#include "clang/AST/ParentMap.h" 21#include "clang/AST/StmtCXX.h" 22#include "clang/AST/StmtObjC.h" 23#include "clang/Basic/Builtins.h" 24#include "clang/Basic/PrettyStackTrace.h" 25#include "clang/Basic/SourceManager.h" 26#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 27#include "clang/StaticAnalyzer/Core/CheckerManager.h" 28#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 29#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 30#include "llvm/ADT/ImmutableList.h" 31#include "llvm/ADT/Statistic.h" 32#include "llvm/Support/raw_ostream.h" 33 34#ifndef NDEBUG 35#include "llvm/Support/GraphWriter.h" 36#endif 37 38using namespace clang; 39using namespace ento; 40using llvm::APSInt; 41 42STATISTIC(NumRemoveDeadBindings, 43 "The # of times RemoveDeadBindings is called"); 44STATISTIC(NumMaxBlockCountReached, 45 "The # of aborted paths due to reaching the maximum block count in " 46 "a top level function"); 47STATISTIC(NumMaxBlockCountReachedInInlined, 48 "The # of aborted paths due to reaching the maximum block count in " 49 "an inlined function"); 50STATISTIC(NumTimesRetriedWithoutInlining, 51 "The # of times we re-evaluated a call without inlining"); 52 53//===----------------------------------------------------------------------===// 54// Engine construction and deletion. 55//===----------------------------------------------------------------------===// 56 57ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled, 58 SetOfConstDecls *VisitedCalleesIn, 59 FunctionSummariesTy *FS, 60 InliningModes HowToInlineIn) 61 : AMgr(mgr), 62 AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()), 63 Engine(*this, FS), 64 G(Engine.getGraph()), 65 StateMgr(getContext(), mgr.getStoreManagerCreator(), 66 mgr.getConstraintManagerCreator(), G.getAllocator(), 67 this), 68 SymMgr(StateMgr.getSymbolManager()), 69 svalBuilder(StateMgr.getSValBuilder()), 70 currStmtIdx(0), currBldrCtx(0), 71 ObjCNoRet(mgr.getASTContext()), 72 ObjCGCEnabled(gcEnabled), BR(mgr, *this), 73 VisitedCallees(VisitedCalleesIn), 74 HowToInline(HowToInlineIn) 75{ 76 unsigned TrimInterval = mgr.options.getGraphTrimInterval(); 77 if (TrimInterval != 0) { 78 // Enable eager node reclaimation when constructing the ExplodedGraph. 79 G.enableNodeReclamation(TrimInterval); 80 } 81} 82 83ExprEngine::~ExprEngine() { 84 BR.FlushReports(); 85} 86 87//===----------------------------------------------------------------------===// 88// Utility methods. 89//===----------------------------------------------------------------------===// 90 91ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) { 92 ProgramStateRef state = StateMgr.getInitialState(InitLoc); 93 const Decl *D = InitLoc->getDecl(); 94 95 // Preconditions. 96 // FIXME: It would be nice if we had a more general mechanism to add 97 // such preconditions. Some day. 98 do { 99 100 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 101 // Precondition: the first argument of 'main' is an integer guaranteed 102 // to be > 0. 103 const IdentifierInfo *II = FD->getIdentifier(); 104 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0)) 105 break; 106 107 const ParmVarDecl *PD = FD->getParamDecl(0); 108 QualType T = PD->getType(); 109 if (!T->isIntegerType()) 110 break; 111 112 const MemRegion *R = state->getRegion(PD, InitLoc); 113 if (!R) 114 break; 115 116 SVal V = state->getSVal(loc::MemRegionVal(R)); 117 SVal Constraint_untested = evalBinOp(state, BO_GT, V, 118 svalBuilder.makeZeroVal(T), 119 getContext().IntTy); 120 121 DefinedOrUnknownSVal *Constraint = 122 dyn_cast<DefinedOrUnknownSVal>(&Constraint_untested); 123 124 if (!Constraint) 125 break; 126 127 if (ProgramStateRef newState = state->assume(*Constraint, true)) 128 state = newState; 129 } 130 break; 131 } 132 while (0); 133 134 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 135 // Precondition: 'self' is always non-null upon entry to an Objective-C 136 // method. 137 const ImplicitParamDecl *SelfD = MD->getSelfDecl(); 138 const MemRegion *R = state->getRegion(SelfD, InitLoc); 139 SVal V = state->getSVal(loc::MemRegionVal(R)); 140 141 if (const Loc *LV = dyn_cast<Loc>(&V)) { 142 // Assume that the pointer value in 'self' is non-null. 143 state = state->assume(*LV, true); 144 assert(state && "'self' cannot be null"); 145 } 146 } 147 148 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 149 if (!MD->isStatic()) { 150 // Precondition: 'this' is always non-null upon entry to the 151 // top-level function. This is our starting assumption for 152 // analyzing an "open" program. 153 const StackFrameContext *SFC = InitLoc->getCurrentStackFrame(); 154 if (SFC->getParent() == 0) { 155 loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC); 156 SVal V = state->getSVal(L); 157 if (const Loc *LV = dyn_cast<Loc>(&V)) { 158 state = state->assume(*LV, true); 159 assert(state && "'this' cannot be null"); 160 } 161 } 162 } 163 } 164 165 return state; 166} 167 168/// If the value of the given expression is a NonLoc, copy it into a new 169/// temporary region, and replace the value of the expression with that. 170static ProgramStateRef createTemporaryRegionIfNeeded(ProgramStateRef State, 171 const LocationContext *LC, 172 const Expr *E) { 173 SVal V = State->getSVal(E, LC); 174 175 if (isa<NonLoc>(V)) { 176 MemRegionManager &MRMgr = State->getStateManager().getRegionManager(); 177 const MemRegion *R = MRMgr.getCXXTempObjectRegion(E, LC); 178 State = State->bindLoc(loc::MemRegionVal(R), V); 179 State = State->BindExpr(E, LC, loc::MemRegionVal(R)); 180 } 181 182 return State; 183} 184 185//===----------------------------------------------------------------------===// 186// Top-level transfer function logic (Dispatcher). 187//===----------------------------------------------------------------------===// 188 189/// evalAssume - Called by ConstraintManager. Used to call checker-specific 190/// logic for handling assumptions on symbolic values. 191ProgramStateRef ExprEngine::processAssume(ProgramStateRef state, 192 SVal cond, bool assumption) { 193 return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption); 194} 195 196bool ExprEngine::wantsRegionChangeUpdate(ProgramStateRef state) { 197 return getCheckerManager().wantsRegionChangeUpdate(state); 198} 199 200ProgramStateRef 201ExprEngine::processRegionChanges(ProgramStateRef state, 202 const InvalidatedSymbols *invalidated, 203 ArrayRef<const MemRegion *> Explicits, 204 ArrayRef<const MemRegion *> Regions, 205 const CallEvent *Call) { 206 return getCheckerManager().runCheckersForRegionChanges(state, invalidated, 207 Explicits, Regions, Call); 208} 209 210void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State, 211 const char *NL, const char *Sep) { 212 getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep); 213} 214 215void ExprEngine::processEndWorklist(bool hasWorkRemaining) { 216 getCheckerManager().runCheckersForEndAnalysis(G, BR, *this); 217} 218 219void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred, 220 unsigned StmtIdx, NodeBuilderContext *Ctx) { 221 currStmtIdx = StmtIdx; 222 currBldrCtx = Ctx; 223 224 switch (E.getKind()) { 225 case CFGElement::Invalid: 226 llvm_unreachable("Unexpected CFGElement kind."); 227 case CFGElement::Statement: 228 ProcessStmt(const_cast<Stmt*>(E.getAs<CFGStmt>()->getStmt()), Pred); 229 return; 230 case CFGElement::Initializer: 231 ProcessInitializer(E.getAs<CFGInitializer>()->getInitializer(), Pred); 232 return; 233 case CFGElement::AutomaticObjectDtor: 234 case CFGElement::BaseDtor: 235 case CFGElement::MemberDtor: 236 case CFGElement::TemporaryDtor: 237 ProcessImplicitDtor(*E.getAs<CFGImplicitDtor>(), Pred); 238 return; 239 } 240 currBldrCtx = 0; 241} 242 243static bool shouldRemoveDeadBindings(AnalysisManager &AMgr, 244 const CFGStmt S, 245 const ExplodedNode *Pred, 246 const LocationContext *LC) { 247 248 // Are we never purging state values? 249 if (AMgr.options.AnalysisPurgeOpt == PurgeNone) 250 return false; 251 252 // Is this the beginning of a basic block? 253 if (isa<BlockEntrance>(Pred->getLocation())) 254 return true; 255 256 // Is this on a non-expression? 257 if (!isa<Expr>(S.getStmt())) 258 return true; 259 260 // Run before processing a call. 261 if (CallEvent::isCallStmt(S.getStmt())) 262 return true; 263 264 // Is this an expression that is consumed by another expression? If so, 265 // postpone cleaning out the state. 266 ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap(); 267 return !PM.isConsumedExpr(cast<Expr>(S.getStmt())); 268} 269 270void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out, 271 const Stmt *ReferenceStmt, 272 const LocationContext *LC, 273 const Stmt *DiagnosticStmt, 274 ProgramPoint::Kind K) { 275 assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind || 276 ReferenceStmt == 0 || isa<ReturnStmt>(ReferenceStmt)) 277 && "PostStmt is not generally supported by the SymbolReaper yet"); 278 assert(LC && "Must pass the current (or expiring) LocationContext"); 279 280 if (!DiagnosticStmt) { 281 DiagnosticStmt = ReferenceStmt; 282 assert(DiagnosticStmt && "Required for clearing a LocationContext"); 283 } 284 285 NumRemoveDeadBindings++; 286 ProgramStateRef CleanedState = Pred->getState(); 287 288 // LC is the location context being destroyed, but SymbolReaper wants a 289 // location context that is still live. (If this is the top-level stack 290 // frame, this will be null.) 291 if (!ReferenceStmt) { 292 assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind && 293 "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext"); 294 LC = LC->getParent(); 295 } 296 297 const StackFrameContext *SFC = LC ? LC->getCurrentStackFrame() : 0; 298 SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager()); 299 300 getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper); 301 302 // Create a state in which dead bindings are removed from the environment 303 // and the store. TODO: The function should just return new env and store, 304 // not a new state. 305 CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper); 306 307 // Process any special transfer function for dead symbols. 308 // A tag to track convenience transitions, which can be removed at cleanup. 309 static SimpleProgramPointTag cleanupTag("ExprEngine : Clean Node"); 310 if (!SymReaper.hasDeadSymbols()) { 311 // Generate a CleanedNode that has the environment and store cleaned 312 // up. Since no symbols are dead, we can optimize and not clean out 313 // the constraint manager. 314 StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx); 315 Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K); 316 317 } else { 318 // Call checkers with the non-cleaned state so that they could query the 319 // values of the soon to be dead symbols. 320 ExplodedNodeSet CheckedSet; 321 getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper, 322 DiagnosticStmt, *this, K); 323 324 // For each node in CheckedSet, generate CleanedNodes that have the 325 // environment, the store, and the constraints cleaned up but have the 326 // user-supplied states as the predecessors. 327 StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx); 328 for (ExplodedNodeSet::const_iterator 329 I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) { 330 ProgramStateRef CheckerState = (*I)->getState(); 331 332 // The constraint manager has not been cleaned up yet, so clean up now. 333 CheckerState = getConstraintManager().removeDeadBindings(CheckerState, 334 SymReaper); 335 336 assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) && 337 "Checkers are not allowed to modify the Environment as a part of " 338 "checkDeadSymbols processing."); 339 assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) && 340 "Checkers are not allowed to modify the Store as a part of " 341 "checkDeadSymbols processing."); 342 343 // Create a state based on CleanedState with CheckerState GDM and 344 // generate a transition to that state. 345 ProgramStateRef CleanedCheckerSt = 346 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState); 347 Bldr.generateNode(DiagnosticStmt, *I, CleanedCheckerSt, &cleanupTag, K); 348 } 349 } 350} 351 352void ExprEngine::ProcessStmt(const CFGStmt S, 353 ExplodedNode *Pred) { 354 // Reclaim any unnecessary nodes in the ExplodedGraph. 355 G.reclaimRecentlyAllocatedNodes(); 356 357 const Stmt *currStmt = S.getStmt(); 358 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 359 currStmt->getLocStart(), 360 "Error evaluating statement"); 361 362 // Remove dead bindings and symbols. 363 ExplodedNodeSet CleanedStates; 364 if (shouldRemoveDeadBindings(AMgr, S, Pred, Pred->getLocationContext())){ 365 removeDead(Pred, CleanedStates, currStmt, Pred->getLocationContext()); 366 } else 367 CleanedStates.Add(Pred); 368 369 // Visit the statement. 370 ExplodedNodeSet Dst; 371 for (ExplodedNodeSet::iterator I = CleanedStates.begin(), 372 E = CleanedStates.end(); I != E; ++I) { 373 ExplodedNodeSet DstI; 374 // Visit the statement. 375 Visit(currStmt, *I, DstI); 376 Dst.insert(DstI); 377 } 378 379 // Enqueue the new nodes onto the work list. 380 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 381} 382 383void ExprEngine::ProcessInitializer(const CFGInitializer Init, 384 ExplodedNode *Pred) { 385 const CXXCtorInitializer *BMI = Init.getInitializer(); 386 387 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 388 BMI->getSourceLocation(), 389 "Error evaluating initializer"); 390 391 // We don't clean up dead bindings here. 392 const StackFrameContext *stackFrame = 393 cast<StackFrameContext>(Pred->getLocationContext()); 394 const CXXConstructorDecl *decl = 395 cast<CXXConstructorDecl>(stackFrame->getDecl()); 396 397 ProgramStateRef State = Pred->getState(); 398 SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame)); 399 400 PostInitializer PP(BMI, stackFrame); 401 ExplodedNodeSet Tmp(Pred); 402 403 // Evaluate the initializer, if necessary 404 if (BMI->isAnyMemberInitializer()) { 405 // Constructors build the object directly in the field, 406 // but non-objects must be copied in from the initializer. 407 const Expr *Init = BMI->getInit(); 408 if (!isa<CXXConstructExpr>(Init)) { 409 SVal FieldLoc; 410 if (BMI->isIndirectMemberInitializer()) 411 FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal); 412 else 413 FieldLoc = State->getLValue(BMI->getMember(), thisVal); 414 415 SVal InitVal = State->getSVal(BMI->getInit(), stackFrame); 416 417 Tmp.clear(); 418 evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP); 419 } 420 } else { 421 assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer()); 422 // We already did all the work when visiting the CXXConstructExpr. 423 } 424 425 // Construct PostInitializer nodes whether the state changed or not, 426 // so that the diagnostics don't get confused. 427 ExplodedNodeSet Dst; 428 NodeBuilder Bldr(Tmp, Dst, *currBldrCtx); 429 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) { 430 ExplodedNode *N = *I; 431 Bldr.generateNode(PP, N->getState(), N); 432 } 433 434 // Enqueue the new nodes onto the work list. 435 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 436} 437 438void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D, 439 ExplodedNode *Pred) { 440 ExplodedNodeSet Dst; 441 switch (D.getKind()) { 442 case CFGElement::AutomaticObjectDtor: 443 ProcessAutomaticObjDtor(cast<CFGAutomaticObjDtor>(D), Pred, Dst); 444 break; 445 case CFGElement::BaseDtor: 446 ProcessBaseDtor(cast<CFGBaseDtor>(D), Pred, Dst); 447 break; 448 case CFGElement::MemberDtor: 449 ProcessMemberDtor(cast<CFGMemberDtor>(D), Pred, Dst); 450 break; 451 case CFGElement::TemporaryDtor: 452 ProcessTemporaryDtor(cast<CFGTemporaryDtor>(D), Pred, Dst); 453 break; 454 default: 455 llvm_unreachable("Unexpected dtor kind."); 456 } 457 458 // Enqueue the new nodes onto the work list. 459 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx); 460} 461 462void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor, 463 ExplodedNode *Pred, 464 ExplodedNodeSet &Dst) { 465 ProgramStateRef state = Pred->getState(); 466 const VarDecl *varDecl = Dtor.getVarDecl(); 467 468 QualType varType = varDecl->getType(); 469 470 if (const ReferenceType *refType = varType->getAs<ReferenceType>()) 471 varType = refType->getPointeeType(); 472 473 Loc dest = state->getLValue(varDecl, Pred->getLocationContext()); 474 475 VisitCXXDestructor(varType, cast<loc::MemRegionVal>(dest).getRegion(), 476 Dtor.getTriggerStmt(), /*IsBase=*/false, Pred, Dst); 477} 478 479void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D, 480 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 481 const LocationContext *LCtx = Pred->getLocationContext(); 482 ProgramStateRef State = Pred->getState(); 483 484 const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl()); 485 Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor, 486 LCtx->getCurrentStackFrame()); 487 SVal ThisVal = Pred->getState()->getSVal(ThisPtr); 488 489 // Create the base object region. 490 QualType BaseTy = D.getBaseSpecifier()->getType(); 491 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy); 492 493 VisitCXXDestructor(BaseTy, cast<loc::MemRegionVal>(BaseVal).getRegion(), 494 CurDtor->getBody(), /*IsBase=*/true, Pred, Dst); 495} 496 497void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D, 498 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 499 const FieldDecl *Member = D.getFieldDecl(); 500 ProgramStateRef State = Pred->getState(); 501 const LocationContext *LCtx = Pred->getLocationContext(); 502 503 const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl()); 504 Loc ThisVal = getSValBuilder().getCXXThis(CurDtor, 505 LCtx->getCurrentStackFrame()); 506 SVal FieldVal = State->getLValue(Member, cast<Loc>(State->getSVal(ThisVal))); 507 508 VisitCXXDestructor(Member->getType(), 509 cast<loc::MemRegionVal>(FieldVal).getRegion(), 510 CurDtor->getBody(), /*IsBase=*/false, Pred, Dst); 511} 512 513void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D, 514 ExplodedNode *Pred, 515 ExplodedNodeSet &Dst) {} 516 517void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred, 518 ExplodedNodeSet &DstTop) { 519 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 520 S->getLocStart(), 521 "Error evaluating statement"); 522 ExplodedNodeSet Dst; 523 StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx); 524 525 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens()); 526 527 switch (S->getStmtClass()) { 528 // C++ and ARC stuff we don't support yet. 529 case Expr::ObjCIndirectCopyRestoreExprClass: 530 case Stmt::CXXDependentScopeMemberExprClass: 531 case Stmt::CXXPseudoDestructorExprClass: 532 case Stmt::CXXTryStmtClass: 533 case Stmt::CXXTypeidExprClass: 534 case Stmt::CXXUuidofExprClass: 535 case Stmt::CXXUnresolvedConstructExprClass: 536 case Stmt::DependentScopeDeclRefExprClass: 537 case Stmt::UnaryTypeTraitExprClass: 538 case Stmt::BinaryTypeTraitExprClass: 539 case Stmt::TypeTraitExprClass: 540 case Stmt::ArrayTypeTraitExprClass: 541 case Stmt::ExpressionTraitExprClass: 542 case Stmt::UnresolvedLookupExprClass: 543 case Stmt::UnresolvedMemberExprClass: 544 case Stmt::CXXNoexceptExprClass: 545 case Stmt::PackExpansionExprClass: 546 case Stmt::SubstNonTypeTemplateParmPackExprClass: 547 case Stmt::FunctionParmPackExprClass: 548 case Stmt::SEHTryStmtClass: 549 case Stmt::SEHExceptStmtClass: 550 case Stmt::LambdaExprClass: 551 case Stmt::SEHFinallyStmtClass: { 552 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState()); 553 Engine.addAbortedBlock(node, currBldrCtx->getBlock()); 554 break; 555 } 556 557 case Stmt::ParenExprClass: 558 llvm_unreachable("ParenExprs already handled."); 559 case Stmt::GenericSelectionExprClass: 560 llvm_unreachable("GenericSelectionExprs already handled."); 561 // Cases that should never be evaluated simply because they shouldn't 562 // appear in the CFG. 563 case Stmt::BreakStmtClass: 564 case Stmt::CaseStmtClass: 565 case Stmt::CompoundStmtClass: 566 case Stmt::ContinueStmtClass: 567 case Stmt::CXXForRangeStmtClass: 568 case Stmt::DefaultStmtClass: 569 case Stmt::DoStmtClass: 570 case Stmt::ForStmtClass: 571 case Stmt::GotoStmtClass: 572 case Stmt::IfStmtClass: 573 case Stmt::IndirectGotoStmtClass: 574 case Stmt::LabelStmtClass: 575 case Stmt::AttributedStmtClass: 576 case Stmt::NoStmtClass: 577 case Stmt::NullStmtClass: 578 case Stmt::SwitchStmtClass: 579 case Stmt::WhileStmtClass: 580 case Expr::MSDependentExistsStmtClass: 581 llvm_unreachable("Stmt should not be in analyzer evaluation loop"); 582 583 case Stmt::ObjCSubscriptRefExprClass: 584 case Stmt::ObjCPropertyRefExprClass: 585 llvm_unreachable("These are handled by PseudoObjectExpr"); 586 587 case Stmt::GNUNullExprClass: { 588 // GNU __null is a pointer-width integer, not an actual pointer. 589 ProgramStateRef state = Pred->getState(); 590 state = state->BindExpr(S, Pred->getLocationContext(), 591 svalBuilder.makeIntValWithPtrWidth(0, false)); 592 Bldr.generateNode(S, Pred, state); 593 break; 594 } 595 596 case Stmt::ObjCAtSynchronizedStmtClass: 597 Bldr.takeNodes(Pred); 598 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst); 599 Bldr.addNodes(Dst); 600 break; 601 602 case Stmt::ExprWithCleanupsClass: 603 // Handled due to fully linearised CFG. 604 break; 605 606 // Cases not handled yet; but will handle some day. 607 case Stmt::DesignatedInitExprClass: 608 case Stmt::ExtVectorElementExprClass: 609 case Stmt::ImaginaryLiteralClass: 610 case Stmt::ObjCAtCatchStmtClass: 611 case Stmt::ObjCAtFinallyStmtClass: 612 case Stmt::ObjCAtTryStmtClass: 613 case Stmt::ObjCAutoreleasePoolStmtClass: 614 case Stmt::ObjCEncodeExprClass: 615 case Stmt::ObjCIsaExprClass: 616 case Stmt::ObjCProtocolExprClass: 617 case Stmt::ObjCSelectorExprClass: 618 case Stmt::ParenListExprClass: 619 case Stmt::PredefinedExprClass: 620 case Stmt::ShuffleVectorExprClass: 621 case Stmt::VAArgExprClass: 622 case Stmt::CUDAKernelCallExprClass: 623 case Stmt::OpaqueValueExprClass: 624 case Stmt::AsTypeExprClass: 625 case Stmt::AtomicExprClass: 626 // Fall through. 627 628 // Cases we intentionally don't evaluate, since they don't need 629 // to be explicitly evaluated. 630 case Stmt::AddrLabelExprClass: 631 case Stmt::IntegerLiteralClass: 632 case Stmt::CharacterLiteralClass: 633 case Stmt::ImplicitValueInitExprClass: 634 case Stmt::CXXScalarValueInitExprClass: 635 case Stmt::CXXBoolLiteralExprClass: 636 case Stmt::ObjCBoolLiteralExprClass: 637 case Stmt::FloatingLiteralClass: 638 case Stmt::SizeOfPackExprClass: 639 case Stmt::StringLiteralClass: 640 case Stmt::ObjCStringLiteralClass: 641 case Stmt::CXXBindTemporaryExprClass: 642 case Stmt::CXXDefaultArgExprClass: 643 case Stmt::SubstNonTypeTemplateParmExprClass: 644 case Stmt::CXXNullPtrLiteralExprClass: { 645 Bldr.takeNodes(Pred); 646 ExplodedNodeSet preVisit; 647 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this); 648 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this); 649 Bldr.addNodes(Dst); 650 break; 651 } 652 653 case Expr::ObjCArrayLiteralClass: 654 case Expr::ObjCDictionaryLiteralClass: 655 // FIXME: explicitly model with a region and the actual contents 656 // of the container. For now, conjure a symbol. 657 case Expr::ObjCBoxedExprClass: { 658 Bldr.takeNodes(Pred); 659 660 ExplodedNodeSet preVisit; 661 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this); 662 663 ExplodedNodeSet Tmp; 664 StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx); 665 666 const Expr *Ex = cast<Expr>(S); 667 QualType resultType = Ex->getType(); 668 669 for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end(); 670 it != et; ++it) { 671 ExplodedNode *N = *it; 672 const LocationContext *LCtx = N->getLocationContext(); 673 SVal result = svalBuilder.conjureSymbolVal(0, Ex, LCtx, resultType, 674 currBldrCtx->blockCount()); 675 ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result); 676 Bldr2.generateNode(S, N, state); 677 } 678 679 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this); 680 Bldr.addNodes(Dst); 681 break; 682 } 683 684 case Stmt::ArraySubscriptExprClass: 685 Bldr.takeNodes(Pred); 686 VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst); 687 Bldr.addNodes(Dst); 688 break; 689 690 case Stmt::GCCAsmStmtClass: 691 Bldr.takeNodes(Pred); 692 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst); 693 Bldr.addNodes(Dst); 694 break; 695 696 case Stmt::MSAsmStmtClass: 697 Bldr.takeNodes(Pred); 698 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst); 699 Bldr.addNodes(Dst); 700 break; 701 702 case Stmt::BlockExprClass: 703 Bldr.takeNodes(Pred); 704 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst); 705 Bldr.addNodes(Dst); 706 break; 707 708 case Stmt::BinaryOperatorClass: { 709 const BinaryOperator* B = cast<BinaryOperator>(S); 710 if (B->isLogicalOp()) { 711 Bldr.takeNodes(Pred); 712 VisitLogicalExpr(B, Pred, Dst); 713 Bldr.addNodes(Dst); 714 break; 715 } 716 else if (B->getOpcode() == BO_Comma) { 717 ProgramStateRef state = Pred->getState(); 718 Bldr.generateNode(B, Pred, 719 state->BindExpr(B, Pred->getLocationContext(), 720 state->getSVal(B->getRHS(), 721 Pred->getLocationContext()))); 722 break; 723 } 724 725 Bldr.takeNodes(Pred); 726 727 if (AMgr.options.eagerlyAssumeBinOpBifurcation && 728 (B->isRelationalOp() || B->isEqualityOp())) { 729 ExplodedNodeSet Tmp; 730 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp); 731 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S)); 732 } 733 else 734 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 735 736 Bldr.addNodes(Dst); 737 break; 738 } 739 740 case Stmt::CXXOperatorCallExprClass: { 741 const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S); 742 743 // For instance method operators, make sure the 'this' argument has a 744 // valid region. 745 const Decl *Callee = OCE->getCalleeDecl(); 746 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) { 747 if (MD->isInstance()) { 748 ProgramStateRef State = Pred->getState(); 749 const LocationContext *LCtx = Pred->getLocationContext(); 750 ProgramStateRef NewState = 751 createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0)); 752 if (NewState != State) 753 Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/0, 754 ProgramPoint::PreStmtKind); 755 } 756 } 757 // FALLTHROUGH 758 } 759 case Stmt::CallExprClass: 760 case Stmt::CXXMemberCallExprClass: 761 case Stmt::UserDefinedLiteralClass: { 762 Bldr.takeNodes(Pred); 763 VisitCallExpr(cast<CallExpr>(S), Pred, Dst); 764 Bldr.addNodes(Dst); 765 break; 766 } 767 768 case Stmt::CXXCatchStmtClass: { 769 Bldr.takeNodes(Pred); 770 VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst); 771 Bldr.addNodes(Dst); 772 break; 773 } 774 775 case Stmt::CXXTemporaryObjectExprClass: 776 case Stmt::CXXConstructExprClass: { 777 Bldr.takeNodes(Pred); 778 VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst); 779 Bldr.addNodes(Dst); 780 break; 781 } 782 783 case Stmt::CXXNewExprClass: { 784 Bldr.takeNodes(Pred); 785 ExplodedNodeSet PostVisit; 786 VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit); 787 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this); 788 Bldr.addNodes(Dst); 789 break; 790 } 791 792 case Stmt::CXXDeleteExprClass: { 793 Bldr.takeNodes(Pred); 794 ExplodedNodeSet PreVisit; 795 const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S); 796 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 797 798 for (ExplodedNodeSet::iterator i = PreVisit.begin(), 799 e = PreVisit.end(); i != e ; ++i) 800 VisitCXXDeleteExpr(CDE, *i, Dst); 801 802 Bldr.addNodes(Dst); 803 break; 804 } 805 // FIXME: ChooseExpr is really a constant. We need to fix 806 // the CFG do not model them as explicit control-flow. 807 808 case Stmt::ChooseExprClass: { // __builtin_choose_expr 809 Bldr.takeNodes(Pred); 810 const ChooseExpr *C = cast<ChooseExpr>(S); 811 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst); 812 Bldr.addNodes(Dst); 813 break; 814 } 815 816 case Stmt::CompoundAssignOperatorClass: 817 Bldr.takeNodes(Pred); 818 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 819 Bldr.addNodes(Dst); 820 break; 821 822 case Stmt::CompoundLiteralExprClass: 823 Bldr.takeNodes(Pred); 824 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst); 825 Bldr.addNodes(Dst); 826 break; 827 828 case Stmt::BinaryConditionalOperatorClass: 829 case Stmt::ConditionalOperatorClass: { // '?' operator 830 Bldr.takeNodes(Pred); 831 const AbstractConditionalOperator *C 832 = cast<AbstractConditionalOperator>(S); 833 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst); 834 Bldr.addNodes(Dst); 835 break; 836 } 837 838 case Stmt::CXXThisExprClass: 839 Bldr.takeNodes(Pred); 840 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst); 841 Bldr.addNodes(Dst); 842 break; 843 844 case Stmt::DeclRefExprClass: { 845 Bldr.takeNodes(Pred); 846 const DeclRefExpr *DE = cast<DeclRefExpr>(S); 847 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst); 848 Bldr.addNodes(Dst); 849 break; 850 } 851 852 case Stmt::DeclStmtClass: 853 Bldr.takeNodes(Pred); 854 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst); 855 Bldr.addNodes(Dst); 856 break; 857 858 case Stmt::ImplicitCastExprClass: 859 case Stmt::CStyleCastExprClass: 860 case Stmt::CXXStaticCastExprClass: 861 case Stmt::CXXDynamicCastExprClass: 862 case Stmt::CXXReinterpretCastExprClass: 863 case Stmt::CXXConstCastExprClass: 864 case Stmt::CXXFunctionalCastExprClass: 865 case Stmt::ObjCBridgedCastExprClass: { 866 Bldr.takeNodes(Pred); 867 const CastExpr *C = cast<CastExpr>(S); 868 // Handle the previsit checks. 869 ExplodedNodeSet dstPrevisit; 870 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this); 871 872 // Handle the expression itself. 873 ExplodedNodeSet dstExpr; 874 for (ExplodedNodeSet::iterator i = dstPrevisit.begin(), 875 e = dstPrevisit.end(); i != e ; ++i) { 876 VisitCast(C, C->getSubExpr(), *i, dstExpr); 877 } 878 879 // Handle the postvisit checks. 880 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this); 881 Bldr.addNodes(Dst); 882 break; 883 } 884 885 case Expr::MaterializeTemporaryExprClass: { 886 Bldr.takeNodes(Pred); 887 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S); 888 CreateCXXTemporaryObject(MTE, Pred, Dst); 889 Bldr.addNodes(Dst); 890 break; 891 } 892 893 case Stmt::InitListExprClass: 894 Bldr.takeNodes(Pred); 895 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst); 896 Bldr.addNodes(Dst); 897 break; 898 899 case Stmt::MemberExprClass: 900 Bldr.takeNodes(Pred); 901 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst); 902 Bldr.addNodes(Dst); 903 break; 904 905 case Stmt::ObjCIvarRefExprClass: 906 Bldr.takeNodes(Pred); 907 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst); 908 Bldr.addNodes(Dst); 909 break; 910 911 case Stmt::ObjCForCollectionStmtClass: 912 Bldr.takeNodes(Pred); 913 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst); 914 Bldr.addNodes(Dst); 915 break; 916 917 case Stmt::ObjCMessageExprClass: 918 Bldr.takeNodes(Pred); 919 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst); 920 Bldr.addNodes(Dst); 921 break; 922 923 case Stmt::ObjCAtThrowStmtClass: 924 case Stmt::CXXThrowExprClass: 925 // FIXME: This is not complete. We basically treat @throw as 926 // an abort. 927 Bldr.generateSink(S, Pred, Pred->getState()); 928 break; 929 930 case Stmt::ReturnStmtClass: 931 Bldr.takeNodes(Pred); 932 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst); 933 Bldr.addNodes(Dst); 934 break; 935 936 case Stmt::OffsetOfExprClass: 937 Bldr.takeNodes(Pred); 938 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst); 939 Bldr.addNodes(Dst); 940 break; 941 942 case Stmt::UnaryExprOrTypeTraitExprClass: 943 Bldr.takeNodes(Pred); 944 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), 945 Pred, Dst); 946 Bldr.addNodes(Dst); 947 break; 948 949 case Stmt::StmtExprClass: { 950 const StmtExpr *SE = cast<StmtExpr>(S); 951 952 if (SE->getSubStmt()->body_empty()) { 953 // Empty statement expression. 954 assert(SE->getType() == getContext().VoidTy 955 && "Empty statement expression must have void type."); 956 break; 957 } 958 959 if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) { 960 ProgramStateRef state = Pred->getState(); 961 Bldr.generateNode(SE, Pred, 962 state->BindExpr(SE, Pred->getLocationContext(), 963 state->getSVal(LastExpr, 964 Pred->getLocationContext()))); 965 } 966 break; 967 } 968 969 case Stmt::UnaryOperatorClass: { 970 Bldr.takeNodes(Pred); 971 const UnaryOperator *U = cast<UnaryOperator>(S); 972 if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) { 973 ExplodedNodeSet Tmp; 974 VisitUnaryOperator(U, Pred, Tmp); 975 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U); 976 } 977 else 978 VisitUnaryOperator(U, Pred, Dst); 979 Bldr.addNodes(Dst); 980 break; 981 } 982 983 case Stmt::PseudoObjectExprClass: { 984 Bldr.takeNodes(Pred); 985 ProgramStateRef state = Pred->getState(); 986 const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S); 987 if (const Expr *Result = PE->getResultExpr()) { 988 SVal V = state->getSVal(Result, Pred->getLocationContext()); 989 Bldr.generateNode(S, Pred, 990 state->BindExpr(S, Pred->getLocationContext(), V)); 991 } 992 else 993 Bldr.generateNode(S, Pred, 994 state->BindExpr(S, Pred->getLocationContext(), 995 UnknownVal())); 996 997 Bldr.addNodes(Dst); 998 break; 999 } 1000 } 1001} 1002 1003bool ExprEngine::replayWithoutInlining(ExplodedNode *N, 1004 const LocationContext *CalleeLC) { 1005 const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame(); 1006 const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame(); 1007 assert(CalleeSF && CallerSF); 1008 ExplodedNode *BeforeProcessingCall = 0; 1009 const Stmt *CE = CalleeSF->getCallSite(); 1010 1011 // Find the first node before we started processing the call expression. 1012 while (N) { 1013 ProgramPoint L = N->getLocation(); 1014 BeforeProcessingCall = N; 1015 N = N->pred_empty() ? NULL : *(N->pred_begin()); 1016 1017 // Skip the nodes corresponding to the inlined code. 1018 if (L.getLocationContext()->getCurrentStackFrame() != CallerSF) 1019 continue; 1020 // We reached the caller. Find the node right before we started 1021 // processing the call. 1022 if (L.isPurgeKind()) 1023 continue; 1024 if (isa<PreImplicitCall>(&L)) 1025 continue; 1026 if (isa<CallEnter>(&L)) 1027 continue; 1028 if (const StmtPoint *SP = dyn_cast<StmtPoint>(&L)) 1029 if (SP->getStmt() == CE) 1030 continue; 1031 break; 1032 } 1033 1034 if (!BeforeProcessingCall) 1035 return false; 1036 1037 // TODO: Clean up the unneeded nodes. 1038 1039 // Build an Epsilon node from which we will restart the analyzes. 1040 // Note that CE is permitted to be NULL! 1041 ProgramPoint NewNodeLoc = 1042 EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE); 1043 // Add the special flag to GDM to signal retrying with no inlining. 1044 // Note, changing the state ensures that we are not going to cache out. 1045 ProgramStateRef NewNodeState = BeforeProcessingCall->getState(); 1046 NewNodeState = NewNodeState->set<ReplayWithoutInlining>((void*)CE); 1047 1048 // Make the new node a successor of BeforeProcessingCall. 1049 bool IsNew = false; 1050 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew); 1051 // We cached out at this point. Caching out is common due to us backtracking 1052 // from the inlined function, which might spawn several paths. 1053 if (!IsNew) 1054 return true; 1055 1056 NewNode->addPredecessor(BeforeProcessingCall, G); 1057 1058 // Add the new node to the work list. 1059 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(), 1060 CalleeSF->getIndex()); 1061 NumTimesRetriedWithoutInlining++; 1062 return true; 1063} 1064 1065/// Block entrance. (Update counters). 1066void ExprEngine::processCFGBlockEntrance(const BlockEdge &L, 1067 NodeBuilderWithSinks &nodeBuilder, 1068 ExplodedNode *Pred) { 1069 1070 // FIXME: Refactor this into a checker. 1071 if (nodeBuilder.getContext().blockCount() >= AMgr.options.maxBlockVisitOnPath) { 1072 static SimpleProgramPointTag tag("ExprEngine : Block count exceeded"); 1073 const ExplodedNode *Sink = 1074 nodeBuilder.generateSink(Pred->getState(), Pred, &tag); 1075 1076 // Check if we stopped at the top level function or not. 1077 // Root node should have the location context of the top most function. 1078 const LocationContext *CalleeLC = Pred->getLocation().getLocationContext(); 1079 const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame(); 1080 const LocationContext *RootLC = 1081 (*G.roots_begin())->getLocation().getLocationContext(); 1082 if (RootLC->getCurrentStackFrame() != CalleeSF) { 1083 Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl()); 1084 1085 // Re-run the call evaluation without inlining it, by storing the 1086 // no-inlining policy in the state and enqueuing the new work item on 1087 // the list. Replay should almost never fail. Use the stats to catch it 1088 // if it does. 1089 if ((!AMgr.options.NoRetryExhausted && 1090 replayWithoutInlining(Pred, CalleeLC))) 1091 return; 1092 NumMaxBlockCountReachedInInlined++; 1093 } else 1094 NumMaxBlockCountReached++; 1095 1096 // Make sink nodes as exhausted(for stats) only if retry failed. 1097 Engine.blocksExhausted.push_back(std::make_pair(L, Sink)); 1098 } 1099} 1100 1101//===----------------------------------------------------------------------===// 1102// Branch processing. 1103//===----------------------------------------------------------------------===// 1104 1105/// RecoverCastedSymbol - A helper function for ProcessBranch that is used 1106/// to try to recover some path-sensitivity for casts of symbolic 1107/// integers that promote their values (which are currently not tracked well). 1108/// This function returns the SVal bound to Condition->IgnoreCasts if all the 1109// cast(s) did was sign-extend the original value. 1110static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr, 1111 ProgramStateRef state, 1112 const Stmt *Condition, 1113 const LocationContext *LCtx, 1114 ASTContext &Ctx) { 1115 1116 const Expr *Ex = dyn_cast<Expr>(Condition); 1117 if (!Ex) 1118 return UnknownVal(); 1119 1120 uint64_t bits = 0; 1121 bool bitsInit = false; 1122 1123 while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) { 1124 QualType T = CE->getType(); 1125 1126 if (!T->isIntegerType()) 1127 return UnknownVal(); 1128 1129 uint64_t newBits = Ctx.getTypeSize(T); 1130 if (!bitsInit || newBits < bits) { 1131 bitsInit = true; 1132 bits = newBits; 1133 } 1134 1135 Ex = CE->getSubExpr(); 1136 } 1137 1138 // We reached a non-cast. Is it a symbolic value? 1139 QualType T = Ex->getType(); 1140 1141 if (!bitsInit || !T->isIntegerType() || Ctx.getTypeSize(T) > bits) 1142 return UnknownVal(); 1143 1144 return state->getSVal(Ex, LCtx); 1145} 1146 1147static const Stmt *ResolveCondition(const Stmt *Condition, 1148 const CFGBlock *B) { 1149 if (const Expr *Ex = dyn_cast<Expr>(Condition)) 1150 Condition = Ex->IgnoreParens(); 1151 1152 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition); 1153 if (!BO || !BO->isLogicalOp()) 1154 return Condition; 1155 1156 // For logical operations, we still have the case where some branches 1157 // use the traditional "merge" approach and others sink the branch 1158 // directly into the basic blocks representing the logical operation. 1159 // We need to distinguish between those two cases here. 1160 1161 // The invariants are still shifting, but it is possible that the 1162 // last element in a CFGBlock is not a CFGStmt. Look for the last 1163 // CFGStmt as the value of the condition. 1164 CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend(); 1165 for (; I != E; ++I) { 1166 CFGElement Elem = *I; 1167 CFGStmt *CS = dyn_cast<CFGStmt>(&Elem); 1168 if (!CS) 1169 continue; 1170 if (CS->getStmt() != Condition) 1171 break; 1172 return Condition; 1173 } 1174 1175 assert(I != E); 1176 1177 while (Condition) { 1178 BO = dyn_cast<BinaryOperator>(Condition); 1179 if (!BO || !BO->isLogicalOp()) 1180 return Condition; 1181 Condition = BO->getRHS()->IgnoreParens(); 1182 } 1183 llvm_unreachable("could not resolve condition"); 1184} 1185 1186void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term, 1187 NodeBuilderContext& BldCtx, 1188 ExplodedNode *Pred, 1189 ExplodedNodeSet &Dst, 1190 const CFGBlock *DstT, 1191 const CFGBlock *DstF) { 1192 currBldrCtx = &BldCtx; 1193 1194 // Check for NULL conditions; e.g. "for(;;)" 1195 if (!Condition) { 1196 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF); 1197 NullCondBldr.markInfeasible(false); 1198 NullCondBldr.generateNode(Pred->getState(), true, Pred); 1199 return; 1200 } 1201 1202 1203 // Resolve the condition in the precense of nested '||' and '&&'. 1204 if (const Expr *Ex = dyn_cast<Expr>(Condition)) 1205 Condition = Ex->IgnoreParens(); 1206 1207 Condition = ResolveCondition(Condition, BldCtx.getBlock()); 1208 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 1209 Condition->getLocStart(), 1210 "Error evaluating branch"); 1211 1212 ExplodedNodeSet CheckersOutSet; 1213 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet, 1214 Pred, *this); 1215 // We generated only sinks. 1216 if (CheckersOutSet.empty()) 1217 return; 1218 1219 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF); 1220 for (NodeBuilder::iterator I = CheckersOutSet.begin(), 1221 E = CheckersOutSet.end(); E != I; ++I) { 1222 ExplodedNode *PredI = *I; 1223 1224 if (PredI->isSink()) 1225 continue; 1226 1227 ProgramStateRef PrevState = PredI->getState(); 1228 SVal X = PrevState->getSVal(Condition, PredI->getLocationContext()); 1229 1230 if (X.isUnknownOrUndef()) { 1231 // Give it a chance to recover from unknown. 1232 if (const Expr *Ex = dyn_cast<Expr>(Condition)) { 1233 if (Ex->getType()->isIntegerType()) { 1234 // Try to recover some path-sensitivity. Right now casts of symbolic 1235 // integers that promote their values are currently not tracked well. 1236 // If 'Condition' is such an expression, try and recover the 1237 // underlying value and use that instead. 1238 SVal recovered = RecoverCastedSymbol(getStateManager(), 1239 PrevState, Condition, 1240 PredI->getLocationContext(), 1241 getContext()); 1242 1243 if (!recovered.isUnknown()) { 1244 X = recovered; 1245 } 1246 } 1247 } 1248 } 1249 1250 // If the condition is still unknown, give up. 1251 if (X.isUnknownOrUndef()) { 1252 builder.generateNode(PrevState, true, PredI); 1253 builder.generateNode(PrevState, false, PredI); 1254 continue; 1255 } 1256 1257 DefinedSVal V = cast<DefinedSVal>(X); 1258 1259 ProgramStateRef StTrue, StFalse; 1260 tie(StTrue, StFalse) = PrevState->assume(V); 1261 1262 // Process the true branch. 1263 if (builder.isFeasible(true)) { 1264 if (StTrue) 1265 builder.generateNode(StTrue, true, PredI); 1266 else 1267 builder.markInfeasible(true); 1268 } 1269 1270 // Process the false branch. 1271 if (builder.isFeasible(false)) { 1272 if (StFalse) 1273 builder.generateNode(StFalse, false, PredI); 1274 else 1275 builder.markInfeasible(false); 1276 } 1277 } 1278 currBldrCtx = 0; 1279} 1280 1281/// processIndirectGoto - Called by CoreEngine. Used to generate successor 1282/// nodes by processing the 'effects' of a computed goto jump. 1283void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) { 1284 1285 ProgramStateRef state = builder.getState(); 1286 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext()); 1287 1288 // Three possibilities: 1289 // 1290 // (1) We know the computed label. 1291 // (2) The label is NULL (or some other constant), or Undefined. 1292 // (3) We have no clue about the label. Dispatch to all targets. 1293 // 1294 1295 typedef IndirectGotoNodeBuilder::iterator iterator; 1296 1297 if (isa<loc::GotoLabel>(V)) { 1298 const LabelDecl *L = cast<loc::GotoLabel>(V).getLabel(); 1299 1300 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) { 1301 if (I.getLabel() == L) { 1302 builder.generateNode(I, state); 1303 return; 1304 } 1305 } 1306 1307 llvm_unreachable("No block with label."); 1308 } 1309 1310 if (isa<loc::ConcreteInt>(V) || isa<UndefinedVal>(V)) { 1311 // Dispatch to the first target and mark it as a sink. 1312 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true); 1313 // FIXME: add checker visit. 1314 // UndefBranches.insert(N); 1315 return; 1316 } 1317 1318 // This is really a catch-all. We don't support symbolics yet. 1319 // FIXME: Implement dispatch for symbolic pointers. 1320 1321 for (iterator I=builder.begin(), E=builder.end(); I != E; ++I) 1322 builder.generateNode(I, state); 1323} 1324 1325/// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path 1326/// nodes when the control reaches the end of a function. 1327void ExprEngine::processEndOfFunction(NodeBuilderContext& BC, 1328 ExplodedNode *Pred) { 1329 StateMgr.EndPath(Pred->getState()); 1330 1331 ExplodedNodeSet Dst; 1332 if (Pred->getLocationContext()->inTopFrame()) { 1333 // Remove dead symbols. 1334 ExplodedNodeSet AfterRemovedDead; 1335 removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead); 1336 1337 // Notify checkers. 1338 for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(), 1339 E = AfterRemovedDead.end(); I != E; ++I) { 1340 getCheckerManager().runCheckersForEndPath(BC, Dst, *I, *this); 1341 } 1342 } else { 1343 getCheckerManager().runCheckersForEndPath(BC, Dst, Pred, *this); 1344 } 1345 1346 Engine.enqueueEndOfFunction(Dst); 1347} 1348 1349/// ProcessSwitch - Called by CoreEngine. Used to generate successor 1350/// nodes by processing the 'effects' of a switch statement. 1351void ExprEngine::processSwitch(SwitchNodeBuilder& builder) { 1352 typedef SwitchNodeBuilder::iterator iterator; 1353 ProgramStateRef state = builder.getState(); 1354 const Expr *CondE = builder.getCondition(); 1355 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext()); 1356 1357 if (CondV_untested.isUndef()) { 1358 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true); 1359 // FIXME: add checker 1360 //UndefBranches.insert(N); 1361 1362 return; 1363 } 1364 DefinedOrUnknownSVal CondV = cast<DefinedOrUnknownSVal>(CondV_untested); 1365 1366 ProgramStateRef DefaultSt = state; 1367 1368 iterator I = builder.begin(), EI = builder.end(); 1369 bool defaultIsFeasible = I == EI; 1370 1371 for ( ; I != EI; ++I) { 1372 // Successor may be pruned out during CFG construction. 1373 if (!I.getBlock()) 1374 continue; 1375 1376 const CaseStmt *Case = I.getCase(); 1377 1378 // Evaluate the LHS of the case value. 1379 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext()); 1380 assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType())); 1381 1382 // Get the RHS of the case, if it exists. 1383 llvm::APSInt V2; 1384 if (const Expr *E = Case->getRHS()) 1385 V2 = E->EvaluateKnownConstInt(getContext()); 1386 else 1387 V2 = V1; 1388 1389 // FIXME: Eventually we should replace the logic below with a range 1390 // comparison, rather than concretize the values within the range. 1391 // This should be easy once we have "ranges" for NonLVals. 1392 1393 do { 1394 nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1)); 1395 DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state, 1396 CondV, CaseVal); 1397 1398 // Now "assume" that the case matches. 1399 if (ProgramStateRef stateNew = state->assume(Res, true)) { 1400 builder.generateCaseStmtNode(I, stateNew); 1401 1402 // If CondV evaluates to a constant, then we know that this 1403 // is the *only* case that we can take, so stop evaluating the 1404 // others. 1405 if (isa<nonloc::ConcreteInt>(CondV)) 1406 return; 1407 } 1408 1409 // Now "assume" that the case doesn't match. Add this state 1410 // to the default state (if it is feasible). 1411 if (DefaultSt) { 1412 if (ProgramStateRef stateNew = DefaultSt->assume(Res, false)) { 1413 defaultIsFeasible = true; 1414 DefaultSt = stateNew; 1415 } 1416 else { 1417 defaultIsFeasible = false; 1418 DefaultSt = NULL; 1419 } 1420 } 1421 1422 // Concretize the next value in the range. 1423 if (V1 == V2) 1424 break; 1425 1426 ++V1; 1427 assert (V1 <= V2); 1428 1429 } while (true); 1430 } 1431 1432 if (!defaultIsFeasible) 1433 return; 1434 1435 // If we have switch(enum value), the default branch is not 1436 // feasible if all of the enum constants not covered by 'case:' statements 1437 // are not feasible values for the switch condition. 1438 // 1439 // Note that this isn't as accurate as it could be. Even if there isn't 1440 // a case for a particular enum value as long as that enum value isn't 1441 // feasible then it shouldn't be considered for making 'default:' reachable. 1442 const SwitchStmt *SS = builder.getSwitch(); 1443 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts(); 1444 if (CondExpr->getType()->getAs<EnumType>()) { 1445 if (SS->isAllEnumCasesCovered()) 1446 return; 1447 } 1448 1449 builder.generateDefaultCaseNode(DefaultSt); 1450} 1451 1452//===----------------------------------------------------------------------===// 1453// Transfer functions: Loads and stores. 1454//===----------------------------------------------------------------------===// 1455 1456void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D, 1457 ExplodedNode *Pred, 1458 ExplodedNodeSet &Dst) { 1459 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1460 1461 ProgramStateRef state = Pred->getState(); 1462 const LocationContext *LCtx = Pred->getLocationContext(); 1463 1464 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1465 assert(Ex->isGLValue()); 1466 SVal V = state->getLValue(VD, Pred->getLocationContext()); 1467 1468 // For references, the 'lvalue' is the pointer address stored in the 1469 // reference region. 1470 if (VD->getType()->isReferenceType()) { 1471 if (const MemRegion *R = V.getAsRegion()) 1472 V = state->getSVal(R); 1473 else 1474 V = UnknownVal(); 1475 } 1476 1477 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0, 1478 ProgramPoint::PostLValueKind); 1479 return; 1480 } 1481 if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 1482 assert(!Ex->isGLValue()); 1483 SVal V = svalBuilder.makeIntVal(ED->getInitVal()); 1484 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V)); 1485 return; 1486 } 1487 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1488 SVal V = svalBuilder.getFunctionPointer(FD); 1489 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0, 1490 ProgramPoint::PostLValueKind); 1491 return; 1492 } 1493 if (isa<FieldDecl>(D)) { 1494 // FIXME: Compute lvalue of field pointers-to-member. 1495 // Right now we just use a non-null void pointer, so that it gives proper 1496 // results in boolean contexts. 1497 SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy, 1498 currBldrCtx->blockCount()); 1499 state = state->assume(cast<DefinedOrUnknownSVal>(V), true); 1500 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0, 1501 ProgramPoint::PostLValueKind); 1502 return; 1503 } 1504 1505 llvm_unreachable("Support for this Decl not implemented."); 1506} 1507 1508/// VisitArraySubscriptExpr - Transfer function for array accesses 1509void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A, 1510 ExplodedNode *Pred, 1511 ExplodedNodeSet &Dst){ 1512 1513 const Expr *Base = A->getBase()->IgnoreParens(); 1514 const Expr *Idx = A->getIdx()->IgnoreParens(); 1515 1516 1517 ExplodedNodeSet checkerPreStmt; 1518 getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this); 1519 1520 StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currBldrCtx); 1521 1522 for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(), 1523 ei = checkerPreStmt.end(); it != ei; ++it) { 1524 const LocationContext *LCtx = (*it)->getLocationContext(); 1525 ProgramStateRef state = (*it)->getState(); 1526 SVal V = state->getLValue(A->getType(), 1527 state->getSVal(Idx, LCtx), 1528 state->getSVal(Base, LCtx)); 1529 assert(A->isGLValue()); 1530 Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), 0, 1531 ProgramPoint::PostLValueKind); 1532 } 1533} 1534 1535/// VisitMemberExpr - Transfer function for member expressions. 1536void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, 1537 ExplodedNodeSet &TopDst) { 1538 1539 StmtNodeBuilder Bldr(Pred, TopDst, *currBldrCtx); 1540 ExplodedNodeSet Dst; 1541 ValueDecl *Member = M->getMemberDecl(); 1542 1543 // Handle static member variables and enum constants accessed via 1544 // member syntax. 1545 if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) { 1546 Bldr.takeNodes(Pred); 1547 VisitCommonDeclRefExpr(M, Member, Pred, Dst); 1548 Bldr.addNodes(Dst); 1549 return; 1550 } 1551 1552 ProgramStateRef state = Pred->getState(); 1553 const LocationContext *LCtx = Pred->getLocationContext(); 1554 Expr *BaseExpr = M->getBase(); 1555 1556 // Handle C++ method calls. 1557 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) { 1558 if (MD->isInstance()) 1559 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr); 1560 1561 SVal MDVal = svalBuilder.getFunctionPointer(MD); 1562 state = state->BindExpr(M, LCtx, MDVal); 1563 1564 Bldr.generateNode(M, Pred, state); 1565 return; 1566 } 1567 1568 // Handle regular struct fields / member variables. 1569 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr); 1570 SVal baseExprVal = state->getSVal(BaseExpr, LCtx); 1571 1572 FieldDecl *field = cast<FieldDecl>(Member); 1573 SVal L = state->getLValue(field, baseExprVal); 1574 if (M->isGLValue()) { 1575 if (field->getType()->isReferenceType()) { 1576 if (const MemRegion *R = L.getAsRegion()) 1577 L = state->getSVal(R); 1578 else 1579 L = UnknownVal(); 1580 } 1581 1582 Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, L), 0, 1583 ProgramPoint::PostLValueKind); 1584 } else { 1585 Bldr.takeNodes(Pred); 1586 evalLoad(Dst, M, M, Pred, state, L); 1587 Bldr.addNodes(Dst); 1588 } 1589} 1590 1591namespace { 1592class CollectReachableSymbolsCallback : public SymbolVisitor { 1593 InvalidatedSymbols Symbols; 1594public: 1595 CollectReachableSymbolsCallback(ProgramStateRef State) {} 1596 const InvalidatedSymbols &getSymbols() const { return Symbols; } 1597 1598 bool VisitSymbol(SymbolRef Sym) { 1599 Symbols.insert(Sym); 1600 return true; 1601 } 1602}; 1603} // end anonymous namespace 1604 1605/// Call PointerEscape callback when a value escapes as a result of bind. 1606/// A value escapes in three possible cases: 1607/// (1) we are binding to something that is not a memory region. 1608/// (2) we are binding to a memregion that does not have stack storage 1609/// (3) we are binding to a memregion with stack storage that the store 1610/// does not understand. 1611ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State, 1612 SVal Loc, SVal Val) { 1613 // Are we storing to something that causes the value to "escape"? 1614 bool escapes = true; 1615 1616 // TODO: Move to StoreManager. 1617 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&Loc)) { 1618 escapes = !regionLoc->getRegion()->hasStackStorage(); 1619 1620 if (!escapes) { 1621 // To test (3), generate a new state with the binding added. If it is 1622 // the same state, then it escapes (since the store cannot represent 1623 // the binding). 1624 // Do this only if we know that the store is not supposed to generate the 1625 // same state. 1626 SVal StoredVal = State->getSVal(regionLoc->getRegion()); 1627 if (StoredVal != Val) 1628 escapes = (State == (State->bindLoc(*regionLoc, Val))); 1629 } 1630 } 1631 1632 // If our store can represent the binding and we aren't storing to something 1633 // that doesn't have local storage then just return and have the simulation 1634 // state continue as is. 1635 if (!escapes) 1636 return State; 1637 1638 // Otherwise, find all symbols referenced by 'val' that we are tracking 1639 // and stop tracking them. 1640 CollectReachableSymbolsCallback Scanner = 1641 State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val); 1642 const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols(); 1643 State = getCheckerManager().runCheckersForPointerEscape(State, 1644 EscapedSymbols, 1645 /*CallEvent*/ 0); 1646 1647 return State; 1648} 1649 1650/// Call PointerEscape callback when a value escapes as a result of 1651/// region invalidation. 1652ProgramStateRef 1653ExprEngine::processPointerEscapedOnInvalidateRegions(ProgramStateRef State, 1654 const InvalidatedSymbols *Invalidated, 1655 ArrayRef<const MemRegion *> ExplicitRegions, 1656 ArrayRef<const MemRegion *> Regions, 1657 const CallEvent *Call) { 1658 1659 if (!Invalidated || Invalidated->empty()) 1660 return State; 1661 1662 if (!Call) 1663 return getCheckerManager().runCheckersForPointerEscape(State, 1664 *Invalidated, 0); 1665 1666 // If the symbols were invalidated by a call, we want to find out which ones 1667 // were invalidated directly due to being arguments to the call. 1668 InvalidatedSymbols SymbolsDirectlyInvalidated; 1669 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(), 1670 E = ExplicitRegions.end(); I != E; ++I) { 1671 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>()) 1672 SymbolsDirectlyInvalidated.insert(R->getSymbol()); 1673 } 1674 1675 InvalidatedSymbols SymbolsIndirectlyInvalidated; 1676 for (InvalidatedSymbols::const_iterator I=Invalidated->begin(), 1677 E = Invalidated->end(); I!=E; ++I) { 1678 SymbolRef sym = *I; 1679 if (SymbolsDirectlyInvalidated.count(sym)) 1680 continue; 1681 SymbolsIndirectlyInvalidated.insert(sym); 1682 } 1683 1684 if (!SymbolsDirectlyInvalidated.empty()) 1685 State = getCheckerManager().runCheckersForPointerEscape(State, 1686 SymbolsDirectlyInvalidated, Call); 1687 1688 // Notify about the symbols that get indirectly invalidated by the call. 1689 if (!SymbolsIndirectlyInvalidated.empty()) 1690 State = getCheckerManager().runCheckersForPointerEscape(State, 1691 SymbolsIndirectlyInvalidated, /*CallEvent*/ 0); 1692 1693 return State; 1694} 1695 1696/// evalBind - Handle the semantics of binding a value to a specific location. 1697/// This method is used by evalStore and (soon) VisitDeclStmt, and others. 1698void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, 1699 ExplodedNode *Pred, 1700 SVal location, SVal Val, 1701 bool atDeclInit, const ProgramPoint *PP) { 1702 1703 const LocationContext *LC = Pred->getLocationContext(); 1704 PostStmt PS(StoreE, LC); 1705 if (!PP) 1706 PP = &PS; 1707 1708 // Do a previsit of the bind. 1709 ExplodedNodeSet CheckedSet; 1710 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val, 1711 StoreE, *this, *PP); 1712 1713 1714 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx); 1715 1716 // If the location is not a 'Loc', it will already be handled by 1717 // the checkers. There is nothing left to do. 1718 if (!isa<Loc>(location)) { 1719 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/0, /*tag*/0); 1720 ProgramStateRef state = Pred->getState(); 1721 state = processPointerEscapedOnBind(state, location, Val); 1722 Bldr.generateNode(L, state, Pred); 1723 return; 1724 } 1725 1726 1727 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 1728 I!=E; ++I) { 1729 ExplodedNode *PredI = *I; 1730 ProgramStateRef state = PredI->getState(); 1731 1732 state = processPointerEscapedOnBind(state, location, Val); 1733 1734 // When binding the value, pass on the hint that this is a initialization. 1735 // For initializations, we do not need to inform clients of region 1736 // changes. 1737 state = state->bindLoc(cast<Loc>(location), 1738 Val, /* notifyChanges = */ !atDeclInit); 1739 1740 const MemRegion *LocReg = 0; 1741 if (loc::MemRegionVal *LocRegVal = dyn_cast<loc::MemRegionVal>(&location)) { 1742 LocReg = LocRegVal->getRegion(); 1743 } 1744 1745 const ProgramPoint L = PostStore(StoreE, LC, LocReg, 0); 1746 Bldr.generateNode(L, state, PredI); 1747 } 1748} 1749 1750/// evalStore - Handle the semantics of a store via an assignment. 1751/// @param Dst The node set to store generated state nodes 1752/// @param AssignE The assignment expression if the store happens in an 1753/// assignment. 1754/// @param LocationE The location expression that is stored to. 1755/// @param state The current simulation state 1756/// @param location The location to store the value 1757/// @param Val The value to be stored 1758void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, 1759 const Expr *LocationE, 1760 ExplodedNode *Pred, 1761 ProgramStateRef state, SVal location, SVal Val, 1762 const ProgramPointTag *tag) { 1763 // Proceed with the store. We use AssignE as the anchor for the PostStore 1764 // ProgramPoint if it is non-NULL, and LocationE otherwise. 1765 const Expr *StoreE = AssignE ? AssignE : LocationE; 1766 1767 // Evaluate the location (checks for bad dereferences). 1768 ExplodedNodeSet Tmp; 1769 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false); 1770 1771 if (Tmp.empty()) 1772 return; 1773 1774 if (location.isUndef()) 1775 return; 1776 1777 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) 1778 evalBind(Dst, StoreE, *NI, location, Val, false); 1779} 1780 1781void ExprEngine::evalLoad(ExplodedNodeSet &Dst, 1782 const Expr *NodeEx, 1783 const Expr *BoundEx, 1784 ExplodedNode *Pred, 1785 ProgramStateRef state, 1786 SVal location, 1787 const ProgramPointTag *tag, 1788 QualType LoadTy) 1789{ 1790 assert(!isa<NonLoc>(location) && "location cannot be a NonLoc."); 1791 1792 // Are we loading from a region? This actually results in two loads; one 1793 // to fetch the address of the referenced value and one to fetch the 1794 // referenced value. 1795 if (const TypedValueRegion *TR = 1796 dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) { 1797 1798 QualType ValTy = TR->getValueType(); 1799 if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) { 1800 static SimpleProgramPointTag 1801 loadReferenceTag("ExprEngine : Load Reference"); 1802 ExplodedNodeSet Tmp; 1803 evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state, 1804 location, &loadReferenceTag, 1805 getContext().getPointerType(RT->getPointeeType())); 1806 1807 // Perform the load from the referenced value. 1808 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) { 1809 state = (*I)->getState(); 1810 location = state->getSVal(BoundEx, (*I)->getLocationContext()); 1811 evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy); 1812 } 1813 return; 1814 } 1815 } 1816 1817 evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy); 1818} 1819 1820void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst, 1821 const Expr *NodeEx, 1822 const Expr *BoundEx, 1823 ExplodedNode *Pred, 1824 ProgramStateRef state, 1825 SVal location, 1826 const ProgramPointTag *tag, 1827 QualType LoadTy) { 1828 assert(NodeEx); 1829 assert(BoundEx); 1830 // Evaluate the location (checks for bad dereferences). 1831 ExplodedNodeSet Tmp; 1832 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true); 1833 if (Tmp.empty()) 1834 return; 1835 1836 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx); 1837 if (location.isUndef()) 1838 return; 1839 1840 // Proceed with the load. 1841 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) { 1842 state = (*NI)->getState(); 1843 const LocationContext *LCtx = (*NI)->getLocationContext(); 1844 1845 SVal V = UnknownVal(); 1846 if (location.isValid()) { 1847 if (LoadTy.isNull()) 1848 LoadTy = BoundEx->getType(); 1849 V = state->getSVal(cast<Loc>(location), LoadTy); 1850 } 1851 1852 Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag, 1853 ProgramPoint::PostLoadKind); 1854 } 1855} 1856 1857void ExprEngine::evalLocation(ExplodedNodeSet &Dst, 1858 const Stmt *NodeEx, 1859 const Stmt *BoundEx, 1860 ExplodedNode *Pred, 1861 ProgramStateRef state, 1862 SVal location, 1863 const ProgramPointTag *tag, 1864 bool isLoad) { 1865 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx); 1866 // Early checks for performance reason. 1867 if (location.isUnknown()) { 1868 return; 1869 } 1870 1871 ExplodedNodeSet Src; 1872 BldrTop.takeNodes(Pred); 1873 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx); 1874 if (Pred->getState() != state) { 1875 // Associate this new state with an ExplodedNode. 1876 // FIXME: If I pass null tag, the graph is incorrect, e.g for 1877 // int *p; 1878 // p = 0; 1879 // *p = 0xDEADBEEF; 1880 // "p = 0" is not noted as "Null pointer value stored to 'p'" but 1881 // instead "int *p" is noted as 1882 // "Variable 'p' initialized to a null pointer value" 1883 1884 static SimpleProgramPointTag tag("ExprEngine: Location"); 1885 Bldr.generateNode(NodeEx, Pred, state, &tag); 1886 } 1887 ExplodedNodeSet Tmp; 1888 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad, 1889 NodeEx, BoundEx, *this); 1890 BldrTop.addNodes(Tmp); 1891} 1892 1893std::pair<const ProgramPointTag *, const ProgramPointTag*> 1894ExprEngine::geteagerlyAssumeBinOpBifurcationTags() { 1895 static SimpleProgramPointTag 1896 eagerlyAssumeBinOpBifurcationTrue("ExprEngine : Eagerly Assume True"), 1897 eagerlyAssumeBinOpBifurcationFalse("ExprEngine : Eagerly Assume False"); 1898 return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue, 1899 &eagerlyAssumeBinOpBifurcationFalse); 1900} 1901 1902void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, 1903 ExplodedNodeSet &Src, 1904 const Expr *Ex) { 1905 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx); 1906 1907 for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) { 1908 ExplodedNode *Pred = *I; 1909 // Test if the previous node was as the same expression. This can happen 1910 // when the expression fails to evaluate to anything meaningful and 1911 // (as an optimization) we don't generate a node. 1912 ProgramPoint P = Pred->getLocation(); 1913 if (!isa<PostStmt>(P) || cast<PostStmt>(P).getStmt() != Ex) { 1914 continue; 1915 } 1916 1917 ProgramStateRef state = Pred->getState(); 1918 SVal V = state->getSVal(Ex, Pred->getLocationContext()); 1919 nonloc::SymbolVal *SEV = dyn_cast<nonloc::SymbolVal>(&V); 1920 if (SEV && SEV->isExpression()) { 1921 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags = 1922 geteagerlyAssumeBinOpBifurcationTags(); 1923 1924 ProgramStateRef StateTrue, StateFalse; 1925 tie(StateTrue, StateFalse) = state->assume(*SEV); 1926 1927 // First assume that the condition is true. 1928 if (StateTrue) { 1929 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType()); 1930 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val); 1931 Bldr.generateNode(Ex, Pred, StateTrue, tags.first); 1932 } 1933 1934 // Next, assume that the condition is false. 1935 if (StateFalse) { 1936 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType()); 1937 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val); 1938 Bldr.generateNode(Ex, Pred, StateFalse, tags.second); 1939 } 1940 } 1941 } 1942} 1943 1944void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, 1945 ExplodedNodeSet &Dst) { 1946 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1947 // We have processed both the inputs and the outputs. All of the outputs 1948 // should evaluate to Locs. Nuke all of their values. 1949 1950 // FIXME: Some day in the future it would be nice to allow a "plug-in" 1951 // which interprets the inline asm and stores proper results in the 1952 // outputs. 1953 1954 ProgramStateRef state = Pred->getState(); 1955 1956 for (GCCAsmStmt::const_outputs_iterator OI = A->begin_outputs(), 1957 OE = A->end_outputs(); OI != OE; ++OI) { 1958 SVal X = state->getSVal(*OI, Pred->getLocationContext()); 1959 assert (!isa<NonLoc>(X)); // Should be an Lval, or unknown, undef. 1960 1961 if (isa<Loc>(X)) 1962 state = state->bindLoc(cast<Loc>(X), UnknownVal()); 1963 } 1964 1965 Bldr.generateNode(A, Pred, state); 1966} 1967 1968void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred, 1969 ExplodedNodeSet &Dst) { 1970 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1971 Bldr.generateNode(A, Pred, Pred->getState()); 1972} 1973 1974//===----------------------------------------------------------------------===// 1975// Visualization. 1976//===----------------------------------------------------------------------===// 1977 1978#ifndef NDEBUG 1979static ExprEngine* GraphPrintCheckerState; 1980static SourceManager* GraphPrintSourceManager; 1981 1982namespace llvm { 1983template<> 1984struct DOTGraphTraits<ExplodedNode*> : 1985 public DefaultDOTGraphTraits { 1986 1987 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 1988 1989 // FIXME: Since we do not cache error nodes in ExprEngine now, this does not 1990 // work. 1991 static std::string getNodeAttributes(const ExplodedNode *N, void*) { 1992 1993#if 0 1994 // FIXME: Replace with a general scheme to tell if the node is 1995 // an error node. 1996 if (GraphPrintCheckerState->isImplicitNullDeref(N) || 1997 GraphPrintCheckerState->isExplicitNullDeref(N) || 1998 GraphPrintCheckerState->isUndefDeref(N) || 1999 GraphPrintCheckerState->isUndefStore(N) || 2000 GraphPrintCheckerState->isUndefControlFlow(N) || 2001 GraphPrintCheckerState->isUndefResult(N) || 2002 GraphPrintCheckerState->isBadCall(N) || 2003 GraphPrintCheckerState->isUndefArg(N)) 2004 return "color=\"red\",style=\"filled\""; 2005 2006 if (GraphPrintCheckerState->isNoReturnCall(N)) 2007 return "color=\"blue\",style=\"filled\""; 2008#endif 2009 return ""; 2010 } 2011 2012 static void printLocation(llvm::raw_ostream &Out, SourceLocation SLoc) { 2013 if (SLoc.isFileID()) { 2014 Out << "\\lline=" 2015 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 2016 << " col=" 2017 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc) 2018 << "\\l"; 2019 } 2020 } 2021 2022 static std::string getNodeLabel(const ExplodedNode *N, void*){ 2023 2024 std::string sbuf; 2025 llvm::raw_string_ostream Out(sbuf); 2026 2027 // Program Location. 2028 ProgramPoint Loc = N->getLocation(); 2029 2030 switch (Loc.getKind()) { 2031 case ProgramPoint::BlockEntranceKind: { 2032 Out << "Block Entrance: B" 2033 << cast<BlockEntrance>(Loc).getBlock()->getBlockID(); 2034 if (const NamedDecl *ND = 2035 dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) { 2036 Out << " ("; 2037 ND->printName(Out); 2038 Out << ")"; 2039 } 2040 break; 2041 } 2042 2043 case ProgramPoint::BlockExitKind: 2044 assert (false); 2045 break; 2046 2047 case ProgramPoint::CallEnterKind: 2048 Out << "CallEnter"; 2049 break; 2050 2051 case ProgramPoint::CallExitBeginKind: 2052 Out << "CallExitBegin"; 2053 break; 2054 2055 case ProgramPoint::CallExitEndKind: 2056 Out << "CallExitEnd"; 2057 break; 2058 2059 case ProgramPoint::PostStmtPurgeDeadSymbolsKind: 2060 Out << "PostStmtPurgeDeadSymbols"; 2061 break; 2062 2063 case ProgramPoint::PreStmtPurgeDeadSymbolsKind: 2064 Out << "PreStmtPurgeDeadSymbols"; 2065 break; 2066 2067 case ProgramPoint::EpsilonKind: 2068 Out << "Epsilon Point"; 2069 break; 2070 2071 case ProgramPoint::PreImplicitCallKind: { 2072 ImplicitCallPoint *PC = cast<ImplicitCallPoint>(&Loc); 2073 Out << "PreCall: "; 2074 2075 // FIXME: Get proper printing options. 2076 PC->getDecl()->print(Out, LangOptions()); 2077 printLocation(Out, PC->getLocation()); 2078 break; 2079 } 2080 2081 case ProgramPoint::PostImplicitCallKind: { 2082 ImplicitCallPoint *PC = cast<ImplicitCallPoint>(&Loc); 2083 Out << "PostCall: "; 2084 2085 // FIXME: Get proper printing options. 2086 PC->getDecl()->print(Out, LangOptions()); 2087 printLocation(Out, PC->getLocation()); 2088 break; 2089 } 2090 2091 default: { 2092 if (StmtPoint *L = dyn_cast<StmtPoint>(&Loc)) { 2093 const Stmt *S = L->getStmt(); 2094 2095 Out << S->getStmtClassName() << ' ' << (const void*) S << ' '; 2096 LangOptions LO; // FIXME. 2097 S->printPretty(Out, 0, PrintingPolicy(LO)); 2098 printLocation(Out, S->getLocStart()); 2099 2100 if (isa<PreStmt>(Loc)) 2101 Out << "\\lPreStmt\\l;"; 2102 else if (isa<PostLoad>(Loc)) 2103 Out << "\\lPostLoad\\l;"; 2104 else if (isa<PostStore>(Loc)) 2105 Out << "\\lPostStore\\l"; 2106 else if (isa<PostLValue>(Loc)) 2107 Out << "\\lPostLValue\\l"; 2108 2109#if 0 2110 // FIXME: Replace with a general scheme to determine 2111 // the name of the check. 2112 if (GraphPrintCheckerState->isImplicitNullDeref(N)) 2113 Out << "\\|Implicit-Null Dereference.\\l"; 2114 else if (GraphPrintCheckerState->isExplicitNullDeref(N)) 2115 Out << "\\|Explicit-Null Dereference.\\l"; 2116 else if (GraphPrintCheckerState->isUndefDeref(N)) 2117 Out << "\\|Dereference of undefialied value.\\l"; 2118 else if (GraphPrintCheckerState->isUndefStore(N)) 2119 Out << "\\|Store to Undefined Loc."; 2120 else if (GraphPrintCheckerState->isUndefResult(N)) 2121 Out << "\\|Result of operation is undefined."; 2122 else if (GraphPrintCheckerState->isNoReturnCall(N)) 2123 Out << "\\|Call to function marked \"noreturn\"."; 2124 else if (GraphPrintCheckerState->isBadCall(N)) 2125 Out << "\\|Call to NULL/Undefined."; 2126 else if (GraphPrintCheckerState->isUndefArg(N)) 2127 Out << "\\|Argument in call is undefined"; 2128#endif 2129 2130 break; 2131 } 2132 2133 const BlockEdge &E = cast<BlockEdge>(Loc); 2134 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B" 2135 << E.getDst()->getBlockID() << ')'; 2136 2137 if (const Stmt *T = E.getSrc()->getTerminator()) { 2138 2139 SourceLocation SLoc = T->getLocStart(); 2140 2141 Out << "\\|Terminator: "; 2142 LangOptions LO; // FIXME. 2143 E.getSrc()->printTerminator(Out, LO); 2144 2145 if (SLoc.isFileID()) { 2146 Out << "\\lline=" 2147 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 2148 << " col=" 2149 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc); 2150 } 2151 2152 if (isa<SwitchStmt>(T)) { 2153 const Stmt *Label = E.getDst()->getLabel(); 2154 2155 if (Label) { 2156 if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) { 2157 Out << "\\lcase "; 2158 LangOptions LO; // FIXME. 2159 C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO)); 2160 2161 if (const Stmt *RHS = C->getRHS()) { 2162 Out << " .. "; 2163 RHS->printPretty(Out, 0, PrintingPolicy(LO)); 2164 } 2165 2166 Out << ":"; 2167 } 2168 else { 2169 assert (isa<DefaultStmt>(Label)); 2170 Out << "\\ldefault:"; 2171 } 2172 } 2173 else 2174 Out << "\\l(implicit) default:"; 2175 } 2176 else if (isa<IndirectGotoStmt>(T)) { 2177 // FIXME 2178 } 2179 else { 2180 Out << "\\lCondition: "; 2181 if (*E.getSrc()->succ_begin() == E.getDst()) 2182 Out << "true"; 2183 else 2184 Out << "false"; 2185 } 2186 2187 Out << "\\l"; 2188 } 2189 2190#if 0 2191 // FIXME: Replace with a general scheme to determine 2192 // the name of the check. 2193 if (GraphPrintCheckerState->isUndefControlFlow(N)) { 2194 Out << "\\|Control-flow based on\\lUndefined value.\\l"; 2195 } 2196#endif 2197 } 2198 } 2199 2200 ProgramStateRef state = N->getState(); 2201 Out << "\\|StateID: " << (const void*) state.getPtr() 2202 << " NodeID: " << (const void*) N << "\\|"; 2203 state->printDOT(Out); 2204 2205 Out << "\\l"; 2206 2207 if (const ProgramPointTag *tag = Loc.getTag()) { 2208 Out << "\\|Tag: " << tag->getTagDescription(); 2209 Out << "\\l"; 2210 } 2211 return Out.str(); 2212 } 2213}; 2214} // end llvm namespace 2215#endif 2216 2217#ifndef NDEBUG 2218template <typename ITERATOR> 2219ExplodedNode *GetGraphNode(ITERATOR I) { return *I; } 2220 2221template <> ExplodedNode* 2222GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator> 2223 (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) { 2224 return I->first; 2225} 2226#endif 2227 2228void ExprEngine::ViewGraph(bool trim) { 2229#ifndef NDEBUG 2230 if (trim) { 2231 std::vector<ExplodedNode*> Src; 2232 2233 // Flush any outstanding reports to make sure we cover all the nodes. 2234 // This does not cause them to get displayed. 2235 for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I) 2236 const_cast<BugType*>(*I)->FlushReports(BR); 2237 2238 // Iterate through the reports and get their nodes. 2239 for (BugReporter::EQClasses_iterator 2240 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) { 2241 ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode()); 2242 if (N) Src.push_back(N); 2243 } 2244 2245 ViewGraph(&Src[0], &Src[0]+Src.size()); 2246 } 2247 else { 2248 GraphPrintCheckerState = this; 2249 GraphPrintSourceManager = &getContext().getSourceManager(); 2250 2251 llvm::ViewGraph(*G.roots_begin(), "ExprEngine"); 2252 2253 GraphPrintCheckerState = NULL; 2254 GraphPrintSourceManager = NULL; 2255 } 2256#endif 2257} 2258 2259void ExprEngine::ViewGraph(ExplodedNode** Beg, ExplodedNode** End) { 2260#ifndef NDEBUG 2261 GraphPrintCheckerState = this; 2262 GraphPrintSourceManager = &getContext().getSourceManager(); 2263 2264 std::auto_ptr<ExplodedGraph> TrimmedG(G.Trim(Beg, End).first); 2265 2266 if (!TrimmedG.get()) 2267 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n"; 2268 else 2269 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine"); 2270 2271 GraphPrintCheckerState = NULL; 2272 GraphPrintSourceManager = NULL; 2273#endif 2274} 2275