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