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