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