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