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