ExprEngine.cpp revision be2e1b11e3350e3a6e632c71beaab83aae3824d2
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 594 QualType varType = D.getBindTemporaryExpr()->getSubExpr()->getType(); 595 596 // FIXME: Inlining of temporary destructors is not supported yet anyway, so we 597 // just put a NULL region for now. This will need to be changed later. 598 VisitCXXDestructor(varType, NULL, D.getBindTemporaryExpr(), 599 /*IsBase=*/ false, Pred, Dst); 600} 601 602void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred, 603 ExplodedNodeSet &DstTop) { 604 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 605 S->getLocStart(), 606 "Error evaluating statement"); 607 ExplodedNodeSet Dst; 608 StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx); 609 610 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens()); 611 612 switch (S->getStmtClass()) { 613 // C++ and ARC stuff we don't support yet. 614 case Expr::ObjCIndirectCopyRestoreExprClass: 615 case Stmt::CXXDefaultInitExprClass: 616 case Stmt::CXXDependentScopeMemberExprClass: 617 case Stmt::CXXPseudoDestructorExprClass: 618 case Stmt::CXXTryStmtClass: 619 case Stmt::CXXTypeidExprClass: 620 case Stmt::CXXUuidofExprClass: 621 case Stmt::MSPropertyRefExprClass: 622 case Stmt::CXXUnresolvedConstructExprClass: 623 case Stmt::DependentScopeDeclRefExprClass: 624 case Stmt::UnaryTypeTraitExprClass: 625 case Stmt::BinaryTypeTraitExprClass: 626 case Stmt::TypeTraitExprClass: 627 case Stmt::ArrayTypeTraitExprClass: 628 case Stmt::ExpressionTraitExprClass: 629 case Stmt::UnresolvedLookupExprClass: 630 case Stmt::UnresolvedMemberExprClass: 631 case Stmt::CXXNoexceptExprClass: 632 case Stmt::PackExpansionExprClass: 633 case Stmt::SubstNonTypeTemplateParmPackExprClass: 634 case Stmt::FunctionParmPackExprClass: 635 case Stmt::SEHTryStmtClass: 636 case Stmt::SEHExceptStmtClass: 637 case Stmt::LambdaExprClass: 638 case Stmt::SEHFinallyStmtClass: { 639 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState()); 640 Engine.addAbortedBlock(node, currBldrCtx->getBlock()); 641 break; 642 } 643 644 case Stmt::ParenExprClass: 645 llvm_unreachable("ParenExprs already handled."); 646 case Stmt::GenericSelectionExprClass: 647 llvm_unreachable("GenericSelectionExprs already handled."); 648 // Cases that should never be evaluated simply because they shouldn't 649 // appear in the CFG. 650 case Stmt::BreakStmtClass: 651 case Stmt::CaseStmtClass: 652 case Stmt::CompoundStmtClass: 653 case Stmt::ContinueStmtClass: 654 case Stmt::CXXForRangeStmtClass: 655 case Stmt::DefaultStmtClass: 656 case Stmt::DoStmtClass: 657 case Stmt::ForStmtClass: 658 case Stmt::GotoStmtClass: 659 case Stmt::IfStmtClass: 660 case Stmt::IndirectGotoStmtClass: 661 case Stmt::LabelStmtClass: 662 case Stmt::NoStmtClass: 663 case Stmt::NullStmtClass: 664 case Stmt::SwitchStmtClass: 665 case Stmt::WhileStmtClass: 666 case Expr::MSDependentExistsStmtClass: 667 case Stmt::CapturedStmtClass: 668 llvm_unreachable("Stmt should not be in analyzer evaluation loop"); 669 670 case Stmt::ObjCSubscriptRefExprClass: 671 case Stmt::ObjCPropertyRefExprClass: 672 llvm_unreachable("These are handled by PseudoObjectExpr"); 673 674 case Stmt::GNUNullExprClass: { 675 // GNU __null is a pointer-width integer, not an actual pointer. 676 ProgramStateRef state = Pred->getState(); 677 state = state->BindExpr(S, Pred->getLocationContext(), 678 svalBuilder.makeIntValWithPtrWidth(0, false)); 679 Bldr.generateNode(S, Pred, state); 680 break; 681 } 682 683 case Stmt::ObjCAtSynchronizedStmtClass: 684 Bldr.takeNodes(Pred); 685 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst); 686 Bldr.addNodes(Dst); 687 break; 688 689 case Stmt::ExprWithCleanupsClass: 690 // Handled due to fully linearised CFG. 691 break; 692 693 // Cases not handled yet; but will handle some day. 694 case Stmt::DesignatedInitExprClass: 695 case Stmt::ExtVectorElementExprClass: 696 case Stmt::ImaginaryLiteralClass: 697 case Stmt::ObjCAtCatchStmtClass: 698 case Stmt::ObjCAtFinallyStmtClass: 699 case Stmt::ObjCAtTryStmtClass: 700 case Stmt::ObjCAutoreleasePoolStmtClass: 701 case Stmt::ObjCEncodeExprClass: 702 case Stmt::ObjCIsaExprClass: 703 case Stmt::ObjCProtocolExprClass: 704 case Stmt::ObjCSelectorExprClass: 705 case Stmt::ParenListExprClass: 706 case Stmt::PredefinedExprClass: 707 case Stmt::ShuffleVectorExprClass: 708 case Stmt::VAArgExprClass: 709 case Stmt::CUDAKernelCallExprClass: 710 case Stmt::OpaqueValueExprClass: 711 case Stmt::AsTypeExprClass: 712 case Stmt::AtomicExprClass: 713 // Fall through. 714 715 // Cases we intentionally don't evaluate, since they don't need 716 // to be explicitly evaluated. 717 case Stmt::AddrLabelExprClass: 718 case Stmt::AttributedStmtClass: 719 case Stmt::IntegerLiteralClass: 720 case Stmt::CharacterLiteralClass: 721 case Stmt::ImplicitValueInitExprClass: 722 case Stmt::CXXScalarValueInitExprClass: 723 case Stmt::CXXBoolLiteralExprClass: 724 case Stmt::ObjCBoolLiteralExprClass: 725 case Stmt::FloatingLiteralClass: 726 case Stmt::SizeOfPackExprClass: 727 case Stmt::StringLiteralClass: 728 case Stmt::ObjCStringLiteralClass: 729 case Stmt::CXXBindTemporaryExprClass: 730 case Stmt::SubstNonTypeTemplateParmExprClass: 731 case Stmt::CXXNullPtrLiteralExprClass: { 732 Bldr.takeNodes(Pred); 733 ExplodedNodeSet preVisit; 734 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this); 735 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this); 736 Bldr.addNodes(Dst); 737 break; 738 } 739 740 case Stmt::CXXDefaultArgExprClass: { 741 Bldr.takeNodes(Pred); 742 ExplodedNodeSet PreVisit; 743 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 744 745 ExplodedNodeSet Tmp; 746 StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx); 747 748 const LocationContext *LCtx = Pred->getLocationContext(); 749 const CXXDefaultArgExpr *DefaultE = cast<CXXDefaultArgExpr>(S); 750 const Expr *ArgE = DefaultE->getExpr(); 751 752 bool IsTemporary = false; 753 if (const MaterializeTemporaryExpr *MTE = 754 dyn_cast<MaterializeTemporaryExpr>(ArgE)) { 755 ArgE = MTE->GetTemporaryExpr(); 756 IsTemporary = true; 757 } 758 759 Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE); 760 if (!ConstantVal) 761 ConstantVal = UnknownVal(); 762 763 for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end(); 764 I != E; ++I) { 765 ProgramStateRef State = (*I)->getState(); 766 State = State->BindExpr(DefaultE, LCtx, *ConstantVal); 767 if (IsTemporary) 768 State = createTemporaryRegionIfNeeded(State, LCtx, DefaultE, 769 DefaultE); 770 Bldr2.generateNode(S, *I, State); 771 } 772 773 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this); 774 Bldr.addNodes(Dst); 775 break; 776 } 777 778 // Cases we evaluate as opaque expressions, conjuring a symbol. 779 case Stmt::CXXStdInitializerListExprClass: 780 case Expr::ObjCArrayLiteralClass: 781 case Expr::ObjCDictionaryLiteralClass: 782 case Expr::ObjCBoxedExprClass: { 783 Bldr.takeNodes(Pred); 784 785 ExplodedNodeSet preVisit; 786 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this); 787 788 ExplodedNodeSet Tmp; 789 StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx); 790 791 const Expr *Ex = cast<Expr>(S); 792 QualType resultType = Ex->getType(); 793 794 for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end(); 795 it != et; ++it) { 796 ExplodedNode *N = *it; 797 const LocationContext *LCtx = N->getLocationContext(); 798 SVal result = svalBuilder.conjureSymbolVal(0, Ex, LCtx, resultType, 799 currBldrCtx->blockCount()); 800 ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result); 801 Bldr2.generateNode(S, N, state); 802 } 803 804 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this); 805 Bldr.addNodes(Dst); 806 break; 807 } 808 809 case Stmt::ArraySubscriptExprClass: 810 Bldr.takeNodes(Pred); 811 VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst); 812 Bldr.addNodes(Dst); 813 break; 814 815 case Stmt::GCCAsmStmtClass: 816 Bldr.takeNodes(Pred); 817 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst); 818 Bldr.addNodes(Dst); 819 break; 820 821 case Stmt::MSAsmStmtClass: 822 Bldr.takeNodes(Pred); 823 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst); 824 Bldr.addNodes(Dst); 825 break; 826 827 case Stmt::BlockExprClass: 828 Bldr.takeNodes(Pred); 829 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst); 830 Bldr.addNodes(Dst); 831 break; 832 833 case Stmt::BinaryOperatorClass: { 834 const BinaryOperator* B = cast<BinaryOperator>(S); 835 if (B->isLogicalOp()) { 836 Bldr.takeNodes(Pred); 837 VisitLogicalExpr(B, Pred, Dst); 838 Bldr.addNodes(Dst); 839 break; 840 } 841 else if (B->getOpcode() == BO_Comma) { 842 ProgramStateRef state = Pred->getState(); 843 Bldr.generateNode(B, Pred, 844 state->BindExpr(B, Pred->getLocationContext(), 845 state->getSVal(B->getRHS(), 846 Pred->getLocationContext()))); 847 break; 848 } 849 850 Bldr.takeNodes(Pred); 851 852 if (AMgr.options.eagerlyAssumeBinOpBifurcation && 853 (B->isRelationalOp() || B->isEqualityOp())) { 854 ExplodedNodeSet Tmp; 855 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp); 856 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S)); 857 } 858 else 859 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 860 861 Bldr.addNodes(Dst); 862 break; 863 } 864 865 case Stmt::CXXOperatorCallExprClass: { 866 const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S); 867 868 // For instance method operators, make sure the 'this' argument has a 869 // valid region. 870 const Decl *Callee = OCE->getCalleeDecl(); 871 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) { 872 if (MD->isInstance()) { 873 ProgramStateRef State = Pred->getState(); 874 const LocationContext *LCtx = Pred->getLocationContext(); 875 ProgramStateRef NewState = 876 createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0)); 877 if (NewState != State) { 878 Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/0, 879 ProgramPoint::PreStmtKind); 880 // Did we cache out? 881 if (!Pred) 882 break; 883 } 884 } 885 } 886 // FALLTHROUGH 887 } 888 case Stmt::CallExprClass: 889 case Stmt::CXXMemberCallExprClass: 890 case Stmt::UserDefinedLiteralClass: { 891 Bldr.takeNodes(Pred); 892 VisitCallExpr(cast<CallExpr>(S), Pred, Dst); 893 Bldr.addNodes(Dst); 894 break; 895 } 896 897 case Stmt::CXXCatchStmtClass: { 898 Bldr.takeNodes(Pred); 899 VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst); 900 Bldr.addNodes(Dst); 901 break; 902 } 903 904 case Stmt::CXXTemporaryObjectExprClass: 905 case Stmt::CXXConstructExprClass: { 906 Bldr.takeNodes(Pred); 907 VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst); 908 Bldr.addNodes(Dst); 909 break; 910 } 911 912 case Stmt::CXXNewExprClass: { 913 Bldr.takeNodes(Pred); 914 ExplodedNodeSet PostVisit; 915 VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit); 916 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this); 917 Bldr.addNodes(Dst); 918 break; 919 } 920 921 case Stmt::CXXDeleteExprClass: { 922 Bldr.takeNodes(Pred); 923 ExplodedNodeSet PreVisit; 924 const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S); 925 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this); 926 927 for (ExplodedNodeSet::iterator i = PreVisit.begin(), 928 e = PreVisit.end(); i != e ; ++i) 929 VisitCXXDeleteExpr(CDE, *i, Dst); 930 931 Bldr.addNodes(Dst); 932 break; 933 } 934 // FIXME: ChooseExpr is really a constant. We need to fix 935 // the CFG do not model them as explicit control-flow. 936 937 case Stmt::ChooseExprClass: { // __builtin_choose_expr 938 Bldr.takeNodes(Pred); 939 const ChooseExpr *C = cast<ChooseExpr>(S); 940 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst); 941 Bldr.addNodes(Dst); 942 break; 943 } 944 945 case Stmt::CompoundAssignOperatorClass: 946 Bldr.takeNodes(Pred); 947 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 948 Bldr.addNodes(Dst); 949 break; 950 951 case Stmt::CompoundLiteralExprClass: 952 Bldr.takeNodes(Pred); 953 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst); 954 Bldr.addNodes(Dst); 955 break; 956 957 case Stmt::BinaryConditionalOperatorClass: 958 case Stmt::ConditionalOperatorClass: { // '?' operator 959 Bldr.takeNodes(Pred); 960 const AbstractConditionalOperator *C 961 = cast<AbstractConditionalOperator>(S); 962 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst); 963 Bldr.addNodes(Dst); 964 break; 965 } 966 967 case Stmt::CXXThisExprClass: 968 Bldr.takeNodes(Pred); 969 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst); 970 Bldr.addNodes(Dst); 971 break; 972 973 case Stmt::DeclRefExprClass: { 974 Bldr.takeNodes(Pred); 975 const DeclRefExpr *DE = cast<DeclRefExpr>(S); 976 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst); 977 Bldr.addNodes(Dst); 978 break; 979 } 980 981 case Stmt::DeclStmtClass: 982 Bldr.takeNodes(Pred); 983 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst); 984 Bldr.addNodes(Dst); 985 break; 986 987 case Stmt::ImplicitCastExprClass: 988 case Stmt::CStyleCastExprClass: 989 case Stmt::CXXStaticCastExprClass: 990 case Stmt::CXXDynamicCastExprClass: 991 case Stmt::CXXReinterpretCastExprClass: 992 case Stmt::CXXConstCastExprClass: 993 case Stmt::CXXFunctionalCastExprClass: 994 case Stmt::ObjCBridgedCastExprClass: { 995 Bldr.takeNodes(Pred); 996 const CastExpr *C = cast<CastExpr>(S); 997 // Handle the previsit checks. 998 ExplodedNodeSet dstPrevisit; 999 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this); 1000 1001 // Handle the expression itself. 1002 ExplodedNodeSet dstExpr; 1003 for (ExplodedNodeSet::iterator i = dstPrevisit.begin(), 1004 e = dstPrevisit.end(); i != e ; ++i) { 1005 VisitCast(C, C->getSubExpr(), *i, dstExpr); 1006 } 1007 1008 // Handle the postvisit checks. 1009 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this); 1010 Bldr.addNodes(Dst); 1011 break; 1012 } 1013 1014 case Expr::MaterializeTemporaryExprClass: { 1015 Bldr.takeNodes(Pred); 1016 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S); 1017 CreateCXXTemporaryObject(MTE, Pred, Dst); 1018 Bldr.addNodes(Dst); 1019 break; 1020 } 1021 1022 case Stmt::InitListExprClass: 1023 Bldr.takeNodes(Pred); 1024 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst); 1025 Bldr.addNodes(Dst); 1026 break; 1027 1028 case Stmt::MemberExprClass: 1029 Bldr.takeNodes(Pred); 1030 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst); 1031 Bldr.addNodes(Dst); 1032 break; 1033 1034 case Stmt::ObjCIvarRefExprClass: 1035 Bldr.takeNodes(Pred); 1036 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst); 1037 Bldr.addNodes(Dst); 1038 break; 1039 1040 case Stmt::ObjCForCollectionStmtClass: 1041 Bldr.takeNodes(Pred); 1042 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst); 1043 Bldr.addNodes(Dst); 1044 break; 1045 1046 case Stmt::ObjCMessageExprClass: 1047 Bldr.takeNodes(Pred); 1048 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst); 1049 Bldr.addNodes(Dst); 1050 break; 1051 1052 case Stmt::ObjCAtThrowStmtClass: 1053 case Stmt::CXXThrowExprClass: 1054 // FIXME: This is not complete. We basically treat @throw as 1055 // an abort. 1056 Bldr.generateSink(S, Pred, Pred->getState()); 1057 break; 1058 1059 case Stmt::ReturnStmtClass: 1060 Bldr.takeNodes(Pred); 1061 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst); 1062 Bldr.addNodes(Dst); 1063 break; 1064 1065 case Stmt::OffsetOfExprClass: 1066 Bldr.takeNodes(Pred); 1067 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst); 1068 Bldr.addNodes(Dst); 1069 break; 1070 1071 case Stmt::UnaryExprOrTypeTraitExprClass: 1072 Bldr.takeNodes(Pred); 1073 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), 1074 Pred, Dst); 1075 Bldr.addNodes(Dst); 1076 break; 1077 1078 case Stmt::StmtExprClass: { 1079 const StmtExpr *SE = cast<StmtExpr>(S); 1080 1081 if (SE->getSubStmt()->body_empty()) { 1082 // Empty statement expression. 1083 assert(SE->getType() == getContext().VoidTy 1084 && "Empty statement expression must have void type."); 1085 break; 1086 } 1087 1088 if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) { 1089 ProgramStateRef state = Pred->getState(); 1090 Bldr.generateNode(SE, Pred, 1091 state->BindExpr(SE, Pred->getLocationContext(), 1092 state->getSVal(LastExpr, 1093 Pred->getLocationContext()))); 1094 } 1095 break; 1096 } 1097 1098 case Stmt::UnaryOperatorClass: { 1099 Bldr.takeNodes(Pred); 1100 const UnaryOperator *U = cast<UnaryOperator>(S); 1101 if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) { 1102 ExplodedNodeSet Tmp; 1103 VisitUnaryOperator(U, Pred, Tmp); 1104 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U); 1105 } 1106 else 1107 VisitUnaryOperator(U, Pred, Dst); 1108 Bldr.addNodes(Dst); 1109 break; 1110 } 1111 1112 case Stmt::PseudoObjectExprClass: { 1113 Bldr.takeNodes(Pred); 1114 ProgramStateRef state = Pred->getState(); 1115 const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S); 1116 if (const Expr *Result = PE->getResultExpr()) { 1117 SVal V = state->getSVal(Result, Pred->getLocationContext()); 1118 Bldr.generateNode(S, Pred, 1119 state->BindExpr(S, Pred->getLocationContext(), V)); 1120 } 1121 else 1122 Bldr.generateNode(S, Pred, 1123 state->BindExpr(S, Pred->getLocationContext(), 1124 UnknownVal())); 1125 1126 Bldr.addNodes(Dst); 1127 break; 1128 } 1129 } 1130} 1131 1132bool ExprEngine::replayWithoutInlining(ExplodedNode *N, 1133 const LocationContext *CalleeLC) { 1134 const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame(); 1135 const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame(); 1136 assert(CalleeSF && CallerSF); 1137 ExplodedNode *BeforeProcessingCall = 0; 1138 const Stmt *CE = CalleeSF->getCallSite(); 1139 1140 // Find the first node before we started processing the call expression. 1141 while (N) { 1142 ProgramPoint L = N->getLocation(); 1143 BeforeProcessingCall = N; 1144 N = N->pred_empty() ? NULL : *(N->pred_begin()); 1145 1146 // Skip the nodes corresponding to the inlined code. 1147 if (L.getLocationContext()->getCurrentStackFrame() != CallerSF) 1148 continue; 1149 // We reached the caller. Find the node right before we started 1150 // processing the call. 1151 if (L.isPurgeKind()) 1152 continue; 1153 if (L.getAs<PreImplicitCall>()) 1154 continue; 1155 if (L.getAs<CallEnter>()) 1156 continue; 1157 if (Optional<StmtPoint> SP = L.getAs<StmtPoint>()) 1158 if (SP->getStmt() == CE) 1159 continue; 1160 break; 1161 } 1162 1163 if (!BeforeProcessingCall) 1164 return false; 1165 1166 // TODO: Clean up the unneeded nodes. 1167 1168 // Build an Epsilon node from which we will restart the analyzes. 1169 // Note that CE is permitted to be NULL! 1170 ProgramPoint NewNodeLoc = 1171 EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE); 1172 // Add the special flag to GDM to signal retrying with no inlining. 1173 // Note, changing the state ensures that we are not going to cache out. 1174 ProgramStateRef NewNodeState = BeforeProcessingCall->getState(); 1175 NewNodeState = 1176 NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE)); 1177 1178 // Make the new node a successor of BeforeProcessingCall. 1179 bool IsNew = false; 1180 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew); 1181 // We cached out at this point. Caching out is common due to us backtracking 1182 // from the inlined function, which might spawn several paths. 1183 if (!IsNew) 1184 return true; 1185 1186 NewNode->addPredecessor(BeforeProcessingCall, G); 1187 1188 // Add the new node to the work list. 1189 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(), 1190 CalleeSF->getIndex()); 1191 NumTimesRetriedWithoutInlining++; 1192 return true; 1193} 1194 1195/// Block entrance. (Update counters). 1196void ExprEngine::processCFGBlockEntrance(const BlockEdge &L, 1197 NodeBuilderWithSinks &nodeBuilder, 1198 ExplodedNode *Pred) { 1199 1200 // FIXME: Refactor this into a checker. 1201 if (nodeBuilder.getContext().blockCount() >= AMgr.options.maxBlockVisitOnPath) { 1202 static SimpleProgramPointTag tag("ExprEngine : Block count exceeded"); 1203 const ExplodedNode *Sink = 1204 nodeBuilder.generateSink(Pred->getState(), Pred, &tag); 1205 1206 // Check if we stopped at the top level function or not. 1207 // Root node should have the location context of the top most function. 1208 const LocationContext *CalleeLC = Pred->getLocation().getLocationContext(); 1209 const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame(); 1210 const LocationContext *RootLC = 1211 (*G.roots_begin())->getLocation().getLocationContext(); 1212 if (RootLC->getCurrentStackFrame() != CalleeSF) { 1213 Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl()); 1214 1215 // Re-run the call evaluation without inlining it, by storing the 1216 // no-inlining policy in the state and enqueuing the new work item on 1217 // the list. Replay should almost never fail. Use the stats to catch it 1218 // if it does. 1219 if ((!AMgr.options.NoRetryExhausted && 1220 replayWithoutInlining(Pred, CalleeLC))) 1221 return; 1222 NumMaxBlockCountReachedInInlined++; 1223 } else 1224 NumMaxBlockCountReached++; 1225 1226 // Make sink nodes as exhausted(for stats) only if retry failed. 1227 Engine.blocksExhausted.push_back(std::make_pair(L, Sink)); 1228 } 1229} 1230 1231//===----------------------------------------------------------------------===// 1232// Branch processing. 1233//===----------------------------------------------------------------------===// 1234 1235/// RecoverCastedSymbol - A helper function for ProcessBranch that is used 1236/// to try to recover some path-sensitivity for casts of symbolic 1237/// integers that promote their values (which are currently not tracked well). 1238/// This function returns the SVal bound to Condition->IgnoreCasts if all the 1239// cast(s) did was sign-extend the original value. 1240static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr, 1241 ProgramStateRef state, 1242 const Stmt *Condition, 1243 const LocationContext *LCtx, 1244 ASTContext &Ctx) { 1245 1246 const Expr *Ex = dyn_cast<Expr>(Condition); 1247 if (!Ex) 1248 return UnknownVal(); 1249 1250 uint64_t bits = 0; 1251 bool bitsInit = false; 1252 1253 while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) { 1254 QualType T = CE->getType(); 1255 1256 if (!T->isIntegralOrEnumerationType()) 1257 return UnknownVal(); 1258 1259 uint64_t newBits = Ctx.getTypeSize(T); 1260 if (!bitsInit || newBits < bits) { 1261 bitsInit = true; 1262 bits = newBits; 1263 } 1264 1265 Ex = CE->getSubExpr(); 1266 } 1267 1268 // We reached a non-cast. Is it a symbolic value? 1269 QualType T = Ex->getType(); 1270 1271 if (!bitsInit || !T->isIntegralOrEnumerationType() || 1272 Ctx.getTypeSize(T) > bits) 1273 return UnknownVal(); 1274 1275 return state->getSVal(Ex, LCtx); 1276} 1277 1278static const Stmt *ResolveCondition(const Stmt *Condition, 1279 const CFGBlock *B) { 1280 if (const Expr *Ex = dyn_cast<Expr>(Condition)) 1281 Condition = Ex->IgnoreParens(); 1282 1283 const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition); 1284 if (!BO || !BO->isLogicalOp()) 1285 return Condition; 1286 1287 // For logical operations, we still have the case where some branches 1288 // use the traditional "merge" approach and others sink the branch 1289 // directly into the basic blocks representing the logical operation. 1290 // We need to distinguish between those two cases here. 1291 1292 // The invariants are still shifting, but it is possible that the 1293 // last element in a CFGBlock is not a CFGStmt. Look for the last 1294 // CFGStmt as the value of the condition. 1295 CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend(); 1296 for (; I != E; ++I) { 1297 CFGElement Elem = *I; 1298 Optional<CFGStmt> CS = Elem.getAs<CFGStmt>(); 1299 if (!CS) 1300 continue; 1301 if (CS->getStmt() != Condition) 1302 break; 1303 return Condition; 1304 } 1305 1306 assert(I != E); 1307 1308 while (Condition) { 1309 BO = dyn_cast<BinaryOperator>(Condition); 1310 if (!BO || !BO->isLogicalOp()) 1311 return Condition; 1312 Condition = BO->getRHS()->IgnoreParens(); 1313 } 1314 llvm_unreachable("could not resolve condition"); 1315} 1316 1317void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term, 1318 NodeBuilderContext& BldCtx, 1319 ExplodedNode *Pred, 1320 ExplodedNodeSet &Dst, 1321 const CFGBlock *DstT, 1322 const CFGBlock *DstF) { 1323 currBldrCtx = &BldCtx; 1324 1325 // Check for NULL conditions; e.g. "for(;;)" 1326 if (!Condition) { 1327 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF); 1328 NullCondBldr.markInfeasible(false); 1329 NullCondBldr.generateNode(Pred->getState(), true, Pred); 1330 return; 1331 } 1332 1333 1334 // Resolve the condition in the precense of nested '||' and '&&'. 1335 if (const Expr *Ex = dyn_cast<Expr>(Condition)) 1336 Condition = Ex->IgnoreParens(); 1337 1338 Condition = ResolveCondition(Condition, BldCtx.getBlock()); 1339 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 1340 Condition->getLocStart(), 1341 "Error evaluating branch"); 1342 1343 ExplodedNodeSet CheckersOutSet; 1344 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet, 1345 Pred, *this); 1346 // We generated only sinks. 1347 if (CheckersOutSet.empty()) 1348 return; 1349 1350 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF); 1351 for (NodeBuilder::iterator I = CheckersOutSet.begin(), 1352 E = CheckersOutSet.end(); E != I; ++I) { 1353 ExplodedNode *PredI = *I; 1354 1355 if (PredI->isSink()) 1356 continue; 1357 1358 ProgramStateRef PrevState = PredI->getState(); 1359 SVal X = PrevState->getSVal(Condition, PredI->getLocationContext()); 1360 1361 if (X.isUnknownOrUndef()) { 1362 // Give it a chance to recover from unknown. 1363 if (const Expr *Ex = dyn_cast<Expr>(Condition)) { 1364 if (Ex->getType()->isIntegralOrEnumerationType()) { 1365 // Try to recover some path-sensitivity. Right now casts of symbolic 1366 // integers that promote their values are currently not tracked well. 1367 // If 'Condition' is such an expression, try and recover the 1368 // underlying value and use that instead. 1369 SVal recovered = RecoverCastedSymbol(getStateManager(), 1370 PrevState, Condition, 1371 PredI->getLocationContext(), 1372 getContext()); 1373 1374 if (!recovered.isUnknown()) { 1375 X = recovered; 1376 } 1377 } 1378 } 1379 } 1380 1381 // If the condition is still unknown, give up. 1382 if (X.isUnknownOrUndef()) { 1383 builder.generateNode(PrevState, true, PredI); 1384 builder.generateNode(PrevState, false, PredI); 1385 continue; 1386 } 1387 1388 DefinedSVal V = X.castAs<DefinedSVal>(); 1389 1390 ProgramStateRef StTrue, StFalse; 1391 tie(StTrue, StFalse) = PrevState->assume(V); 1392 1393 // Process the true branch. 1394 if (builder.isFeasible(true)) { 1395 if (StTrue) 1396 builder.generateNode(StTrue, true, PredI); 1397 else 1398 builder.markInfeasible(true); 1399 } 1400 1401 // Process the false branch. 1402 if (builder.isFeasible(false)) { 1403 if (StFalse) 1404 builder.generateNode(StFalse, false, PredI); 1405 else 1406 builder.markInfeasible(false); 1407 } 1408 } 1409 currBldrCtx = 0; 1410} 1411 1412/// The GDM component containing the set of global variables which have been 1413/// previously initialized with explicit initializers. 1414REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet, 1415 llvm::ImmutableSet<const VarDecl *>) 1416 1417void ExprEngine::processStaticInitializer(const DeclStmt *DS, 1418 NodeBuilderContext &BuilderCtx, 1419 ExplodedNode *Pred, 1420 clang::ento::ExplodedNodeSet &Dst, 1421 const CFGBlock *DstT, 1422 const CFGBlock *DstF) { 1423 currBldrCtx = &BuilderCtx; 1424 1425 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl()); 1426 ProgramStateRef state = Pred->getState(); 1427 bool initHasRun = state->contains<InitializedGlobalsSet>(VD); 1428 BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF); 1429 1430 if (!initHasRun) { 1431 state = state->add<InitializedGlobalsSet>(VD); 1432 } 1433 1434 builder.generateNode(state, initHasRun, Pred); 1435 builder.markInfeasible(!initHasRun); 1436 1437 currBldrCtx = 0; 1438} 1439 1440/// processIndirectGoto - Called by CoreEngine. Used to generate successor 1441/// nodes by processing the 'effects' of a computed goto jump. 1442void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) { 1443 1444 ProgramStateRef state = builder.getState(); 1445 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext()); 1446 1447 // Three possibilities: 1448 // 1449 // (1) We know the computed label. 1450 // (2) The label is NULL (or some other constant), or Undefined. 1451 // (3) We have no clue about the label. Dispatch to all targets. 1452 // 1453 1454 typedef IndirectGotoNodeBuilder::iterator iterator; 1455 1456 if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) { 1457 const LabelDecl *L = LV->getLabel(); 1458 1459 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) { 1460 if (I.getLabel() == L) { 1461 builder.generateNode(I, state); 1462 return; 1463 } 1464 } 1465 1466 llvm_unreachable("No block with label."); 1467 } 1468 1469 if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) { 1470 // Dispatch to the first target and mark it as a sink. 1471 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true); 1472 // FIXME: add checker visit. 1473 // UndefBranches.insert(N); 1474 return; 1475 } 1476 1477 // This is really a catch-all. We don't support symbolics yet. 1478 // FIXME: Implement dispatch for symbolic pointers. 1479 1480 for (iterator I=builder.begin(), E=builder.end(); I != E; ++I) 1481 builder.generateNode(I, state); 1482} 1483 1484/// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path 1485/// nodes when the control reaches the end of a function. 1486void ExprEngine::processEndOfFunction(NodeBuilderContext& BC, 1487 ExplodedNode *Pred) { 1488 StateMgr.EndPath(Pred->getState()); 1489 1490 ExplodedNodeSet Dst; 1491 if (Pred->getLocationContext()->inTopFrame()) { 1492 // Remove dead symbols. 1493 ExplodedNodeSet AfterRemovedDead; 1494 removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead); 1495 1496 // Notify checkers. 1497 for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(), 1498 E = AfterRemovedDead.end(); I != E; ++I) { 1499 getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this); 1500 } 1501 } else { 1502 getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this); 1503 } 1504 1505 Engine.enqueueEndOfFunction(Dst); 1506} 1507 1508/// ProcessSwitch - Called by CoreEngine. Used to generate successor 1509/// nodes by processing the 'effects' of a switch statement. 1510void ExprEngine::processSwitch(SwitchNodeBuilder& builder) { 1511 typedef SwitchNodeBuilder::iterator iterator; 1512 ProgramStateRef state = builder.getState(); 1513 const Expr *CondE = builder.getCondition(); 1514 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext()); 1515 1516 if (CondV_untested.isUndef()) { 1517 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true); 1518 // FIXME: add checker 1519 //UndefBranches.insert(N); 1520 1521 return; 1522 } 1523 DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>(); 1524 1525 ProgramStateRef DefaultSt = state; 1526 1527 iterator I = builder.begin(), EI = builder.end(); 1528 bool defaultIsFeasible = I == EI; 1529 1530 for ( ; I != EI; ++I) { 1531 // Successor may be pruned out during CFG construction. 1532 if (!I.getBlock()) 1533 continue; 1534 1535 const CaseStmt *Case = I.getCase(); 1536 1537 // Evaluate the LHS of the case value. 1538 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext()); 1539 assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType())); 1540 1541 // Get the RHS of the case, if it exists. 1542 llvm::APSInt V2; 1543 if (const Expr *E = Case->getRHS()) 1544 V2 = E->EvaluateKnownConstInt(getContext()); 1545 else 1546 V2 = V1; 1547 1548 // FIXME: Eventually we should replace the logic below with a range 1549 // comparison, rather than concretize the values within the range. 1550 // This should be easy once we have "ranges" for NonLVals. 1551 1552 do { 1553 nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1)); 1554 DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state, 1555 CondV, CaseVal); 1556 1557 // Now "assume" that the case matches. 1558 if (ProgramStateRef stateNew = state->assume(Res, true)) { 1559 builder.generateCaseStmtNode(I, stateNew); 1560 1561 // If CondV evaluates to a constant, then we know that this 1562 // is the *only* case that we can take, so stop evaluating the 1563 // others. 1564 if (CondV.getAs<nonloc::ConcreteInt>()) 1565 return; 1566 } 1567 1568 // Now "assume" that the case doesn't match. Add this state 1569 // to the default state (if it is feasible). 1570 if (DefaultSt) { 1571 if (ProgramStateRef stateNew = DefaultSt->assume(Res, false)) { 1572 defaultIsFeasible = true; 1573 DefaultSt = stateNew; 1574 } 1575 else { 1576 defaultIsFeasible = false; 1577 DefaultSt = NULL; 1578 } 1579 } 1580 1581 // Concretize the next value in the range. 1582 if (V1 == V2) 1583 break; 1584 1585 ++V1; 1586 assert (V1 <= V2); 1587 1588 } while (true); 1589 } 1590 1591 if (!defaultIsFeasible) 1592 return; 1593 1594 // If we have switch(enum value), the default branch is not 1595 // feasible if all of the enum constants not covered by 'case:' statements 1596 // are not feasible values for the switch condition. 1597 // 1598 // Note that this isn't as accurate as it could be. Even if there isn't 1599 // a case for a particular enum value as long as that enum value isn't 1600 // feasible then it shouldn't be considered for making 'default:' reachable. 1601 const SwitchStmt *SS = builder.getSwitch(); 1602 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts(); 1603 if (CondExpr->getType()->getAs<EnumType>()) { 1604 if (SS->isAllEnumCasesCovered()) 1605 return; 1606 } 1607 1608 builder.generateDefaultCaseNode(DefaultSt); 1609} 1610 1611//===----------------------------------------------------------------------===// 1612// Transfer functions: Loads and stores. 1613//===----------------------------------------------------------------------===// 1614 1615void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D, 1616 ExplodedNode *Pred, 1617 ExplodedNodeSet &Dst) { 1618 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1619 1620 ProgramStateRef state = Pred->getState(); 1621 const LocationContext *LCtx = Pred->getLocationContext(); 1622 1623 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1624 // C permits "extern void v", and if you cast the address to a valid type, 1625 // you can even do things with it. We simply pretend 1626 assert(Ex->isGLValue() || VD->getType()->isVoidType()); 1627 SVal V = state->getLValue(VD, Pred->getLocationContext()); 1628 1629 // For references, the 'lvalue' is the pointer address stored in the 1630 // reference region. 1631 if (VD->getType()->isReferenceType()) { 1632 if (const MemRegion *R = V.getAsRegion()) 1633 V = state->getSVal(R); 1634 else 1635 V = UnknownVal(); 1636 } 1637 1638 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0, 1639 ProgramPoint::PostLValueKind); 1640 return; 1641 } 1642 if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 1643 assert(!Ex->isGLValue()); 1644 SVal V = svalBuilder.makeIntVal(ED->getInitVal()); 1645 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V)); 1646 return; 1647 } 1648 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1649 SVal V = svalBuilder.getFunctionPointer(FD); 1650 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0, 1651 ProgramPoint::PostLValueKind); 1652 return; 1653 } 1654 if (isa<FieldDecl>(D)) { 1655 // FIXME: Compute lvalue of field pointers-to-member. 1656 // Right now we just use a non-null void pointer, so that it gives proper 1657 // results in boolean contexts. 1658 SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy, 1659 currBldrCtx->blockCount()); 1660 state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true); 1661 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0, 1662 ProgramPoint::PostLValueKind); 1663 return; 1664 } 1665 1666 llvm_unreachable("Support for this Decl not implemented."); 1667} 1668 1669/// VisitArraySubscriptExpr - Transfer function for array accesses 1670void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A, 1671 ExplodedNode *Pred, 1672 ExplodedNodeSet &Dst){ 1673 1674 const Expr *Base = A->getBase()->IgnoreParens(); 1675 const Expr *Idx = A->getIdx()->IgnoreParens(); 1676 1677 1678 ExplodedNodeSet checkerPreStmt; 1679 getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this); 1680 1681 StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currBldrCtx); 1682 1683 for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(), 1684 ei = checkerPreStmt.end(); it != ei; ++it) { 1685 const LocationContext *LCtx = (*it)->getLocationContext(); 1686 ProgramStateRef state = (*it)->getState(); 1687 SVal V = state->getLValue(A->getType(), 1688 state->getSVal(Idx, LCtx), 1689 state->getSVal(Base, LCtx)); 1690 assert(A->isGLValue()); 1691 Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), 0, 1692 ProgramPoint::PostLValueKind); 1693 } 1694} 1695 1696/// VisitMemberExpr - Transfer function for member expressions. 1697void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, 1698 ExplodedNodeSet &TopDst) { 1699 1700 StmtNodeBuilder Bldr(Pred, TopDst, *currBldrCtx); 1701 ExplodedNodeSet Dst; 1702 ValueDecl *Member = M->getMemberDecl(); 1703 1704 // Handle static member variables and enum constants accessed via 1705 // member syntax. 1706 if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) { 1707 Bldr.takeNodes(Pred); 1708 VisitCommonDeclRefExpr(M, Member, Pred, Dst); 1709 Bldr.addNodes(Dst); 1710 return; 1711 } 1712 1713 ProgramStateRef state = Pred->getState(); 1714 const LocationContext *LCtx = Pred->getLocationContext(); 1715 Expr *BaseExpr = M->getBase(); 1716 1717 // Handle C++ method calls. 1718 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) { 1719 if (MD->isInstance()) 1720 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr); 1721 1722 SVal MDVal = svalBuilder.getFunctionPointer(MD); 1723 state = state->BindExpr(M, LCtx, MDVal); 1724 1725 Bldr.generateNode(M, Pred, state); 1726 return; 1727 } 1728 1729 // Handle regular struct fields / member variables. 1730 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr); 1731 SVal baseExprVal = state->getSVal(BaseExpr, LCtx); 1732 1733 FieldDecl *field = cast<FieldDecl>(Member); 1734 SVal L = state->getLValue(field, baseExprVal); 1735 1736 if (M->isGLValue() || M->getType()->isArrayType()) { 1737 1738 // We special case rvalue of array type because the analyzer cannot reason 1739 // about it, since we expect all regions to be wrapped in Locs. So we will 1740 // treat these as lvalues assuming that they will decay to pointers as soon 1741 // as they are used. 1742 if (!M->isGLValue()) { 1743 assert(M->getType()->isArrayType()); 1744 const ImplicitCastExpr *PE = 1745 dyn_cast<ImplicitCastExpr>(Pred->getParentMap().getParent(M)); 1746 if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) { 1747 assert(false && 1748 "We assume that array is always wrapped in ArrayToPointerDecay"); 1749 L = UnknownVal(); 1750 } 1751 } 1752 1753 if (field->getType()->isReferenceType()) { 1754 if (const MemRegion *R = L.getAsRegion()) 1755 L = state->getSVal(R); 1756 else 1757 L = UnknownVal(); 1758 } 1759 1760 Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, L), 0, 1761 ProgramPoint::PostLValueKind); 1762 } else { 1763 Bldr.takeNodes(Pred); 1764 evalLoad(Dst, M, M, Pred, state, L); 1765 Bldr.addNodes(Dst); 1766 } 1767} 1768 1769namespace { 1770class CollectReachableSymbolsCallback : public SymbolVisitor { 1771 InvalidatedSymbols Symbols; 1772public: 1773 CollectReachableSymbolsCallback(ProgramStateRef State) {} 1774 const InvalidatedSymbols &getSymbols() const { return Symbols; } 1775 1776 bool VisitSymbol(SymbolRef Sym) { 1777 Symbols.insert(Sym); 1778 return true; 1779 } 1780}; 1781} // end anonymous namespace 1782 1783// A value escapes in three possible cases: 1784// (1) We are binding to something that is not a memory region. 1785// (2) We are binding to a MemrRegion that does not have stack storage. 1786// (3) We are binding to a MemRegion with stack storage that the store 1787// does not understand. 1788ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State, 1789 SVal Loc, SVal Val) { 1790 // Are we storing to something that causes the value to "escape"? 1791 bool escapes = true; 1792 1793 // TODO: Move to StoreManager. 1794 if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) { 1795 escapes = !regionLoc->getRegion()->hasStackStorage(); 1796 1797 if (!escapes) { 1798 // To test (3), generate a new state with the binding added. If it is 1799 // the same state, then it escapes (since the store cannot represent 1800 // the binding). 1801 // Do this only if we know that the store is not supposed to generate the 1802 // same state. 1803 SVal StoredVal = State->getSVal(regionLoc->getRegion()); 1804 if (StoredVal != Val) 1805 escapes = (State == (State->bindLoc(*regionLoc, Val))); 1806 } 1807 } 1808 1809 // If our store can represent the binding and we aren't storing to something 1810 // that doesn't have local storage then just return and have the simulation 1811 // state continue as is. 1812 if (!escapes) 1813 return State; 1814 1815 // Otherwise, find all symbols referenced by 'val' that we are tracking 1816 // and stop tracking them. 1817 CollectReachableSymbolsCallback Scanner = 1818 State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val); 1819 const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols(); 1820 State = getCheckerManager().runCheckersForPointerEscape(State, 1821 EscapedSymbols, 1822 /*CallEvent*/ 0, 1823 PSK_EscapeOnBind); 1824 1825 return State; 1826} 1827 1828ProgramStateRef 1829ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State, 1830 const InvalidatedSymbols *Invalidated, 1831 ArrayRef<const MemRegion *> ExplicitRegions, 1832 ArrayRef<const MemRegion *> Regions, 1833 const CallEvent *Call, 1834 bool IsConst) { 1835 1836 if (!Invalidated || Invalidated->empty()) 1837 return State; 1838 1839 if (!Call) 1840 return getCheckerManager().runCheckersForPointerEscape(State, 1841 *Invalidated, 1842 0, 1843 PSK_EscapeOther, 1844 IsConst); 1845 1846 // Note: Due to current limitations of RegionStore, we only process the top 1847 // level const pointers correctly. The lower level const pointers are 1848 // currently treated as non-const. 1849 if (IsConst) 1850 return getCheckerManager().runCheckersForPointerEscape(State, 1851 *Invalidated, 1852 Call, 1853 PSK_DirectEscapeOnCall, 1854 true); 1855 1856 // If the symbols were invalidated by a call, we want to find out which ones 1857 // were invalidated directly due to being arguments to the call. 1858 InvalidatedSymbols SymbolsDirectlyInvalidated; 1859 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(), 1860 E = ExplicitRegions.end(); I != E; ++I) { 1861 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>()) 1862 SymbolsDirectlyInvalidated.insert(R->getSymbol()); 1863 } 1864 1865 InvalidatedSymbols SymbolsIndirectlyInvalidated; 1866 for (InvalidatedSymbols::const_iterator I=Invalidated->begin(), 1867 E = Invalidated->end(); I!=E; ++I) { 1868 SymbolRef sym = *I; 1869 if (SymbolsDirectlyInvalidated.count(sym)) 1870 continue; 1871 SymbolsIndirectlyInvalidated.insert(sym); 1872 } 1873 1874 if (!SymbolsDirectlyInvalidated.empty()) 1875 State = getCheckerManager().runCheckersForPointerEscape(State, 1876 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall); 1877 1878 // Notify about the symbols that get indirectly invalidated by the call. 1879 if (!SymbolsIndirectlyInvalidated.empty()) 1880 State = getCheckerManager().runCheckersForPointerEscape(State, 1881 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall); 1882 1883 return State; 1884} 1885 1886/// evalBind - Handle the semantics of binding a value to a specific location. 1887/// This method is used by evalStore and (soon) VisitDeclStmt, and others. 1888void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, 1889 ExplodedNode *Pred, 1890 SVal location, SVal Val, 1891 bool atDeclInit, const ProgramPoint *PP) { 1892 1893 const LocationContext *LC = Pred->getLocationContext(); 1894 PostStmt PS(StoreE, LC); 1895 if (!PP) 1896 PP = &PS; 1897 1898 // Do a previsit of the bind. 1899 ExplodedNodeSet CheckedSet; 1900 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val, 1901 StoreE, *this, *PP); 1902 1903 1904 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx); 1905 1906 // If the location is not a 'Loc', it will already be handled by 1907 // the checkers. There is nothing left to do. 1908 if (!location.getAs<Loc>()) { 1909 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/0, /*tag*/0); 1910 ProgramStateRef state = Pred->getState(); 1911 state = processPointerEscapedOnBind(state, location, Val); 1912 Bldr.generateNode(L, state, Pred); 1913 return; 1914 } 1915 1916 1917 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 1918 I!=E; ++I) { 1919 ExplodedNode *PredI = *I; 1920 ProgramStateRef state = PredI->getState(); 1921 1922 state = processPointerEscapedOnBind(state, location, Val); 1923 1924 // When binding the value, pass on the hint that this is a initialization. 1925 // For initializations, we do not need to inform clients of region 1926 // changes. 1927 state = state->bindLoc(location.castAs<Loc>(), 1928 Val, /* notifyChanges = */ !atDeclInit); 1929 1930 const MemRegion *LocReg = 0; 1931 if (Optional<loc::MemRegionVal> LocRegVal = 1932 location.getAs<loc::MemRegionVal>()) { 1933 LocReg = LocRegVal->getRegion(); 1934 } 1935 1936 const ProgramPoint L = PostStore(StoreE, LC, LocReg, 0); 1937 Bldr.generateNode(L, state, PredI); 1938 } 1939} 1940 1941/// evalStore - Handle the semantics of a store via an assignment. 1942/// @param Dst The node set to store generated state nodes 1943/// @param AssignE The assignment expression if the store happens in an 1944/// assignment. 1945/// @param LocationE The location expression that is stored to. 1946/// @param state The current simulation state 1947/// @param location The location to store the value 1948/// @param Val The value to be stored 1949void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, 1950 const Expr *LocationE, 1951 ExplodedNode *Pred, 1952 ProgramStateRef state, SVal location, SVal Val, 1953 const ProgramPointTag *tag) { 1954 // Proceed with the store. We use AssignE as the anchor for the PostStore 1955 // ProgramPoint if it is non-NULL, and LocationE otherwise. 1956 const Expr *StoreE = AssignE ? AssignE : LocationE; 1957 1958 // Evaluate the location (checks for bad dereferences). 1959 ExplodedNodeSet Tmp; 1960 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false); 1961 1962 if (Tmp.empty()) 1963 return; 1964 1965 if (location.isUndef()) 1966 return; 1967 1968 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) 1969 evalBind(Dst, StoreE, *NI, location, Val, false); 1970} 1971 1972void ExprEngine::evalLoad(ExplodedNodeSet &Dst, 1973 const Expr *NodeEx, 1974 const Expr *BoundEx, 1975 ExplodedNode *Pred, 1976 ProgramStateRef state, 1977 SVal location, 1978 const ProgramPointTag *tag, 1979 QualType LoadTy) 1980{ 1981 assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc."); 1982 1983 // Are we loading from a region? This actually results in two loads; one 1984 // to fetch the address of the referenced value and one to fetch the 1985 // referenced value. 1986 if (const TypedValueRegion *TR = 1987 dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) { 1988 1989 QualType ValTy = TR->getValueType(); 1990 if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) { 1991 static SimpleProgramPointTag 1992 loadReferenceTag("ExprEngine : Load Reference"); 1993 ExplodedNodeSet Tmp; 1994 evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state, 1995 location, &loadReferenceTag, 1996 getContext().getPointerType(RT->getPointeeType())); 1997 1998 // Perform the load from the referenced value. 1999 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) { 2000 state = (*I)->getState(); 2001 location = state->getSVal(BoundEx, (*I)->getLocationContext()); 2002 evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy); 2003 } 2004 return; 2005 } 2006 } 2007 2008 evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy); 2009} 2010 2011void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst, 2012 const Expr *NodeEx, 2013 const Expr *BoundEx, 2014 ExplodedNode *Pred, 2015 ProgramStateRef state, 2016 SVal location, 2017 const ProgramPointTag *tag, 2018 QualType LoadTy) { 2019 assert(NodeEx); 2020 assert(BoundEx); 2021 // Evaluate the location (checks for bad dereferences). 2022 ExplodedNodeSet Tmp; 2023 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true); 2024 if (Tmp.empty()) 2025 return; 2026 2027 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx); 2028 if (location.isUndef()) 2029 return; 2030 2031 // Proceed with the load. 2032 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) { 2033 state = (*NI)->getState(); 2034 const LocationContext *LCtx = (*NI)->getLocationContext(); 2035 2036 SVal V = UnknownVal(); 2037 if (location.isValid()) { 2038 if (LoadTy.isNull()) 2039 LoadTy = BoundEx->getType(); 2040 V = state->getSVal(location.castAs<Loc>(), LoadTy); 2041 } 2042 2043 Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag, 2044 ProgramPoint::PostLoadKind); 2045 } 2046} 2047 2048void ExprEngine::evalLocation(ExplodedNodeSet &Dst, 2049 const Stmt *NodeEx, 2050 const Stmt *BoundEx, 2051 ExplodedNode *Pred, 2052 ProgramStateRef state, 2053 SVal location, 2054 const ProgramPointTag *tag, 2055 bool isLoad) { 2056 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx); 2057 // Early checks for performance reason. 2058 if (location.isUnknown()) { 2059 return; 2060 } 2061 2062 ExplodedNodeSet Src; 2063 BldrTop.takeNodes(Pred); 2064 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx); 2065 if (Pred->getState() != state) { 2066 // Associate this new state with an ExplodedNode. 2067 // FIXME: If I pass null tag, the graph is incorrect, e.g for 2068 // int *p; 2069 // p = 0; 2070 // *p = 0xDEADBEEF; 2071 // "p = 0" is not noted as "Null pointer value stored to 'p'" but 2072 // instead "int *p" is noted as 2073 // "Variable 'p' initialized to a null pointer value" 2074 2075 static SimpleProgramPointTag tag("ExprEngine: Location"); 2076 Bldr.generateNode(NodeEx, Pred, state, &tag); 2077 } 2078 ExplodedNodeSet Tmp; 2079 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad, 2080 NodeEx, BoundEx, *this); 2081 BldrTop.addNodes(Tmp); 2082} 2083 2084std::pair<const ProgramPointTag *, const ProgramPointTag*> 2085ExprEngine::geteagerlyAssumeBinOpBifurcationTags() { 2086 static SimpleProgramPointTag 2087 eagerlyAssumeBinOpBifurcationTrue("ExprEngine : Eagerly Assume True"), 2088 eagerlyAssumeBinOpBifurcationFalse("ExprEngine : Eagerly Assume False"); 2089 return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue, 2090 &eagerlyAssumeBinOpBifurcationFalse); 2091} 2092 2093void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, 2094 ExplodedNodeSet &Src, 2095 const Expr *Ex) { 2096 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx); 2097 2098 for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) { 2099 ExplodedNode *Pred = *I; 2100 // Test if the previous node was as the same expression. This can happen 2101 // when the expression fails to evaluate to anything meaningful and 2102 // (as an optimization) we don't generate a node. 2103 ProgramPoint P = Pred->getLocation(); 2104 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) { 2105 continue; 2106 } 2107 2108 ProgramStateRef state = Pred->getState(); 2109 SVal V = state->getSVal(Ex, Pred->getLocationContext()); 2110 Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>(); 2111 if (SEV && SEV->isExpression()) { 2112 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags = 2113 geteagerlyAssumeBinOpBifurcationTags(); 2114 2115 ProgramStateRef StateTrue, StateFalse; 2116 tie(StateTrue, StateFalse) = state->assume(*SEV); 2117 2118 // First assume that the condition is true. 2119 if (StateTrue) { 2120 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType()); 2121 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val); 2122 Bldr.generateNode(Ex, Pred, StateTrue, tags.first); 2123 } 2124 2125 // Next, assume that the condition is false. 2126 if (StateFalse) { 2127 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType()); 2128 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val); 2129 Bldr.generateNode(Ex, Pred, StateFalse, tags.second); 2130 } 2131 } 2132 } 2133} 2134 2135void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, 2136 ExplodedNodeSet &Dst) { 2137 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 2138 // We have processed both the inputs and the outputs. All of the outputs 2139 // should evaluate to Locs. Nuke all of their values. 2140 2141 // FIXME: Some day in the future it would be nice to allow a "plug-in" 2142 // which interprets the inline asm and stores proper results in the 2143 // outputs. 2144 2145 ProgramStateRef state = Pred->getState(); 2146 2147 for (GCCAsmStmt::const_outputs_iterator OI = A->begin_outputs(), 2148 OE = A->end_outputs(); OI != OE; ++OI) { 2149 SVal X = state->getSVal(*OI, Pred->getLocationContext()); 2150 assert (!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef. 2151 2152 if (Optional<Loc> LV = X.getAs<Loc>()) 2153 state = state->bindLoc(*LV, UnknownVal()); 2154 } 2155 2156 Bldr.generateNode(A, Pred, state); 2157} 2158 2159void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred, 2160 ExplodedNodeSet &Dst) { 2161 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 2162 Bldr.generateNode(A, Pred, Pred->getState()); 2163} 2164 2165//===----------------------------------------------------------------------===// 2166// Visualization. 2167//===----------------------------------------------------------------------===// 2168 2169#ifndef NDEBUG 2170static ExprEngine* GraphPrintCheckerState; 2171static SourceManager* GraphPrintSourceManager; 2172 2173namespace llvm { 2174template<> 2175struct DOTGraphTraits<ExplodedNode*> : 2176 public DefaultDOTGraphTraits { 2177 2178 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 2179 2180 // FIXME: Since we do not cache error nodes in ExprEngine now, this does not 2181 // work. 2182 static std::string getNodeAttributes(const ExplodedNode *N, void*) { 2183 2184#if 0 2185 // FIXME: Replace with a general scheme to tell if the node is 2186 // an error node. 2187 if (GraphPrintCheckerState->isImplicitNullDeref(N) || 2188 GraphPrintCheckerState->isExplicitNullDeref(N) || 2189 GraphPrintCheckerState->isUndefDeref(N) || 2190 GraphPrintCheckerState->isUndefStore(N) || 2191 GraphPrintCheckerState->isUndefControlFlow(N) || 2192 GraphPrintCheckerState->isUndefResult(N) || 2193 GraphPrintCheckerState->isBadCall(N) || 2194 GraphPrintCheckerState->isUndefArg(N)) 2195 return "color=\"red\",style=\"filled\""; 2196 2197 if (GraphPrintCheckerState->isNoReturnCall(N)) 2198 return "color=\"blue\",style=\"filled\""; 2199#endif 2200 return ""; 2201 } 2202 2203 static void printLocation(raw_ostream &Out, SourceLocation SLoc) { 2204 if (SLoc.isFileID()) { 2205 Out << "\\lline=" 2206 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 2207 << " col=" 2208 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc) 2209 << "\\l"; 2210 } 2211 } 2212 2213 static std::string getNodeLabel(const ExplodedNode *N, void*){ 2214 2215 std::string sbuf; 2216 llvm::raw_string_ostream Out(sbuf); 2217 2218 // Program Location. 2219 ProgramPoint Loc = N->getLocation(); 2220 2221 switch (Loc.getKind()) { 2222 case ProgramPoint::BlockEntranceKind: { 2223 Out << "Block Entrance: B" 2224 << Loc.castAs<BlockEntrance>().getBlock()->getBlockID(); 2225 if (const NamedDecl *ND = 2226 dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) { 2227 Out << " ("; 2228 ND->printName(Out); 2229 Out << ")"; 2230 } 2231 break; 2232 } 2233 2234 case ProgramPoint::BlockExitKind: 2235 assert (false); 2236 break; 2237 2238 case ProgramPoint::CallEnterKind: 2239 Out << "CallEnter"; 2240 break; 2241 2242 case ProgramPoint::CallExitBeginKind: 2243 Out << "CallExitBegin"; 2244 break; 2245 2246 case ProgramPoint::CallExitEndKind: 2247 Out << "CallExitEnd"; 2248 break; 2249 2250 case ProgramPoint::PostStmtPurgeDeadSymbolsKind: 2251 Out << "PostStmtPurgeDeadSymbols"; 2252 break; 2253 2254 case ProgramPoint::PreStmtPurgeDeadSymbolsKind: 2255 Out << "PreStmtPurgeDeadSymbols"; 2256 break; 2257 2258 case ProgramPoint::EpsilonKind: 2259 Out << "Epsilon Point"; 2260 break; 2261 2262 case ProgramPoint::PreImplicitCallKind: { 2263 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>(); 2264 Out << "PreCall: "; 2265 2266 // FIXME: Get proper printing options. 2267 PC.getDecl()->print(Out, LangOptions()); 2268 printLocation(Out, PC.getLocation()); 2269 break; 2270 } 2271 2272 case ProgramPoint::PostImplicitCallKind: { 2273 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>(); 2274 Out << "PostCall: "; 2275 2276 // FIXME: Get proper printing options. 2277 PC.getDecl()->print(Out, LangOptions()); 2278 printLocation(Out, PC.getLocation()); 2279 break; 2280 } 2281 2282 case ProgramPoint::PostInitializerKind: { 2283 Out << "PostInitializer: "; 2284 const CXXCtorInitializer *Init = 2285 Loc.castAs<PostInitializer>().getInitializer(); 2286 if (const FieldDecl *FD = Init->getAnyMember()) 2287 Out << *FD; 2288 else { 2289 QualType Ty = Init->getTypeSourceInfo()->getType(); 2290 Ty = Ty.getLocalUnqualifiedType(); 2291 LangOptions LO; // FIXME. 2292 Ty.print(Out, LO); 2293 } 2294 break; 2295 } 2296 2297 case ProgramPoint::BlockEdgeKind: { 2298 const BlockEdge &E = Loc.castAs<BlockEdge>(); 2299 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B" 2300 << E.getDst()->getBlockID() << ')'; 2301 2302 if (const Stmt *T = E.getSrc()->getTerminator()) { 2303 SourceLocation SLoc = T->getLocStart(); 2304 2305 Out << "\\|Terminator: "; 2306 LangOptions LO; // FIXME. 2307 E.getSrc()->printTerminator(Out, LO); 2308 2309 if (SLoc.isFileID()) { 2310 Out << "\\lline=" 2311 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 2312 << " col=" 2313 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc); 2314 } 2315 2316 if (isa<SwitchStmt>(T)) { 2317 const Stmt *Label = E.getDst()->getLabel(); 2318 2319 if (Label) { 2320 if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) { 2321 Out << "\\lcase "; 2322 LangOptions LO; // FIXME. 2323 C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO)); 2324 2325 if (const Stmt *RHS = C->getRHS()) { 2326 Out << " .. "; 2327 RHS->printPretty(Out, 0, PrintingPolicy(LO)); 2328 } 2329 2330 Out << ":"; 2331 } 2332 else { 2333 assert (isa<DefaultStmt>(Label)); 2334 Out << "\\ldefault:"; 2335 } 2336 } 2337 else 2338 Out << "\\l(implicit) default:"; 2339 } 2340 else if (isa<IndirectGotoStmt>(T)) { 2341 // FIXME 2342 } 2343 else { 2344 Out << "\\lCondition: "; 2345 if (*E.getSrc()->succ_begin() == E.getDst()) 2346 Out << "true"; 2347 else 2348 Out << "false"; 2349 } 2350 2351 Out << "\\l"; 2352 } 2353 2354#if 0 2355 // FIXME: Replace with a general scheme to determine 2356 // the name of the check. 2357 if (GraphPrintCheckerState->isUndefControlFlow(N)) { 2358 Out << "\\|Control-flow based on\\lUndefined value.\\l"; 2359 } 2360#endif 2361 break; 2362 } 2363 2364 default: { 2365 const Stmt *S = Loc.castAs<StmtPoint>().getStmt(); 2366 2367 Out << S->getStmtClassName() << ' ' << (const void*) S << ' '; 2368 LangOptions LO; // FIXME. 2369 S->printPretty(Out, 0, PrintingPolicy(LO)); 2370 printLocation(Out, S->getLocStart()); 2371 2372 if (Loc.getAs<PreStmt>()) 2373 Out << "\\lPreStmt\\l;"; 2374 else if (Loc.getAs<PostLoad>()) 2375 Out << "\\lPostLoad\\l;"; 2376 else if (Loc.getAs<PostStore>()) 2377 Out << "\\lPostStore\\l"; 2378 else if (Loc.getAs<PostLValue>()) 2379 Out << "\\lPostLValue\\l"; 2380 2381#if 0 2382 // FIXME: Replace with a general scheme to determine 2383 // the name of the check. 2384 if (GraphPrintCheckerState->isImplicitNullDeref(N)) 2385 Out << "\\|Implicit-Null Dereference.\\l"; 2386 else if (GraphPrintCheckerState->isExplicitNullDeref(N)) 2387 Out << "\\|Explicit-Null Dereference.\\l"; 2388 else if (GraphPrintCheckerState->isUndefDeref(N)) 2389 Out << "\\|Dereference of undefialied value.\\l"; 2390 else if (GraphPrintCheckerState->isUndefStore(N)) 2391 Out << "\\|Store to Undefined Loc."; 2392 else if (GraphPrintCheckerState->isUndefResult(N)) 2393 Out << "\\|Result of operation is undefined."; 2394 else if (GraphPrintCheckerState->isNoReturnCall(N)) 2395 Out << "\\|Call to function marked \"noreturn\"."; 2396 else if (GraphPrintCheckerState->isBadCall(N)) 2397 Out << "\\|Call to NULL/Undefined."; 2398 else if (GraphPrintCheckerState->isUndefArg(N)) 2399 Out << "\\|Argument in call is undefined"; 2400#endif 2401 2402 break; 2403 } 2404 } 2405 2406 ProgramStateRef state = N->getState(); 2407 Out << "\\|StateID: " << (const void*) state.getPtr() 2408 << " NodeID: " << (const void*) N << "\\|"; 2409 state->printDOT(Out); 2410 2411 Out << "\\l"; 2412 2413 if (const ProgramPointTag *tag = Loc.getTag()) { 2414 Out << "\\|Tag: " << tag->getTagDescription(); 2415 Out << "\\l"; 2416 } 2417 return Out.str(); 2418 } 2419}; 2420} // end llvm namespace 2421#endif 2422 2423#ifndef NDEBUG 2424template <typename ITERATOR> 2425ExplodedNode *GetGraphNode(ITERATOR I) { return *I; } 2426 2427template <> ExplodedNode* 2428GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator> 2429 (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) { 2430 return I->first; 2431} 2432#endif 2433 2434void ExprEngine::ViewGraph(bool trim) { 2435#ifndef NDEBUG 2436 if (trim) { 2437 std::vector<const ExplodedNode*> Src; 2438 2439 // Flush any outstanding reports to make sure we cover all the nodes. 2440 // This does not cause them to get displayed. 2441 for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I) 2442 const_cast<BugType*>(*I)->FlushReports(BR); 2443 2444 // Iterate through the reports and get their nodes. 2445 for (BugReporter::EQClasses_iterator 2446 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) { 2447 ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode()); 2448 if (N) Src.push_back(N); 2449 } 2450 2451 ViewGraph(Src); 2452 } 2453 else { 2454 GraphPrintCheckerState = this; 2455 GraphPrintSourceManager = &getContext().getSourceManager(); 2456 2457 llvm::ViewGraph(*G.roots_begin(), "ExprEngine"); 2458 2459 GraphPrintCheckerState = NULL; 2460 GraphPrintSourceManager = NULL; 2461 } 2462#endif 2463} 2464 2465void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) { 2466#ifndef NDEBUG 2467 GraphPrintCheckerState = this; 2468 GraphPrintSourceManager = &getContext().getSourceManager(); 2469 2470 OwningPtr<ExplodedGraph> TrimmedG(G.trim(Nodes)); 2471 2472 if (!TrimmedG.get()) 2473 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n"; 2474 else 2475 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine"); 2476 2477 GraphPrintCheckerState = NULL; 2478 GraphPrintSourceManager = NULL; 2479#endif 2480} 2481