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