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