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