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 #include "clang/StaticAnalyzer/Core/CheckerManager.h" 17 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 18 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 19 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 20 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngineBuilders.h" 21 #include "clang/AST/CharUnits.h" 22 #include "clang/AST/ParentMap.h" 23 #include "clang/AST/StmtObjC.h" 24 #include "clang/AST/DeclCXX.h" 25 #include "clang/Basic/Builtins.h" 26 #include "clang/Basic/SourceManager.h" 27 #include "clang/Basic/SourceManager.h" 28 #include "clang/Basic/PrettyStackTrace.h" 29 #include "llvm/Support/raw_ostream.h" 30 #include "llvm/ADT/ImmutableList.h" 31 32 #ifndef NDEBUG 33 #include "llvm/Support/GraphWriter.h" 34 #endif 35 36 using namespace clang; 37 using namespace ento; 38 using llvm::APSInt; 39 40 namespace { 41 // Trait class for recording returned expression in the state. 42 struct ReturnExpr { 43 static int TagInt; 44 typedef const Stmt *data_type; 45 }; 46 int ReturnExpr::TagInt; 47 } 48 49 //===----------------------------------------------------------------------===// 50 // Utility functions. 51 //===----------------------------------------------------------------------===// 52 53 static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) { 54 IdentifierInfo* II = &Ctx.Idents.get(name); 55 return Ctx.Selectors.getSelector(0, &II); 56 } 57 58 //===----------------------------------------------------------------------===// 59 // Engine construction and deletion. 60 //===----------------------------------------------------------------------===// 61 62 ExprEngine::ExprEngine(AnalysisManager &mgr, TransferFuncs *tf) 63 : AMgr(mgr), 64 Engine(*this), 65 G(Engine.getGraph()), 66 Builder(NULL), 67 StateMgr(getContext(), mgr.getStoreManagerCreator(), 68 mgr.getConstraintManagerCreator(), G.getAllocator(), 69 *this), 70 SymMgr(StateMgr.getSymbolManager()), 71 svalBuilder(StateMgr.getSValBuilder()), 72 EntryNode(NULL), currentStmt(NULL), 73 NSExceptionII(NULL), NSExceptionInstanceRaiseSelectors(NULL), 74 RaiseSel(GetNullarySelector("raise", getContext())), 75 BR(mgr, *this), TF(tf) { 76 77 // FIXME: Eventually remove the TF object entirely. 78 TF->RegisterChecks(*this); 79 TF->RegisterPrinters(getStateManager().Printers); 80 81 if (mgr.shouldEagerlyTrimExplodedGraph()) { 82 // Enable eager node reclaimation when constructing the ExplodedGraph. 83 G.enableNodeReclamation(); 84 } 85 } 86 87 ExprEngine::~ExprEngine() { 88 BR.FlushReports(); 89 delete [] NSExceptionInstanceRaiseSelectors; 90 } 91 92 //===----------------------------------------------------------------------===// 93 // Utility methods. 94 //===----------------------------------------------------------------------===// 95 96 const GRState* ExprEngine::getInitialState(const LocationContext *InitLoc) { 97 const GRState *state = StateMgr.getInitialState(InitLoc); 98 99 // Preconditions. 100 101 // FIXME: It would be nice if we had a more general mechanism to add 102 // such preconditions. Some day. 103 do { 104 const Decl *D = InitLoc->getDecl(); 105 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 106 // Precondition: the first argument of 'main' is an integer guaranteed 107 // to be > 0. 108 const IdentifierInfo *II = FD->getIdentifier(); 109 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0)) 110 break; 111 112 const ParmVarDecl *PD = FD->getParamDecl(0); 113 QualType T = PD->getType(); 114 if (!T->isIntegerType()) 115 break; 116 117 const MemRegion *R = state->getRegion(PD, InitLoc); 118 if (!R) 119 break; 120 121 SVal V = state->getSVal(loc::MemRegionVal(R)); 122 SVal Constraint_untested = evalBinOp(state, BO_GT, V, 123 svalBuilder.makeZeroVal(T), 124 getContext().IntTy); 125 126 DefinedOrUnknownSVal *Constraint = 127 dyn_cast<DefinedOrUnknownSVal>(&Constraint_untested); 128 129 if (!Constraint) 130 break; 131 132 if (const GRState *newState = state->assume(*Constraint, true)) 133 state = newState; 134 135 break; 136 } 137 138 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 139 // Precondition: 'self' is always non-null upon entry to an Objective-C 140 // method. 141 const ImplicitParamDecl *SelfD = MD->getSelfDecl(); 142 const MemRegion *R = state->getRegion(SelfD, InitLoc); 143 SVal V = state->getSVal(loc::MemRegionVal(R)); 144 145 if (const Loc *LV = dyn_cast<Loc>(&V)) { 146 // Assume that the pointer value in 'self' is non-null. 147 state = state->assume(*LV, true); 148 assert(state && "'self' cannot be null"); 149 } 150 } 151 } while (0); 152 153 return state; 154 } 155 156 bool 157 ExprEngine::doesInvalidateGlobals(const CallOrObjCMessage &callOrMessage) const 158 { 159 if (callOrMessage.isFunctionCall() && !callOrMessage.isCXXCall()) { 160 SVal calleeV = callOrMessage.getFunctionCallee(); 161 if (const FunctionTextRegion *codeR = 162 dyn_cast_or_null<FunctionTextRegion>(calleeV.getAsRegion())) { 163 164 const FunctionDecl *fd = codeR->getDecl(); 165 if (const IdentifierInfo *ii = fd->getIdentifier()) { 166 StringRef fname = ii->getName(); 167 if (fname == "strlen") 168 return false; 169 } 170 } 171 } 172 173 // The conservative answer: invalidates globals. 174 return true; 175 } 176 177 //===----------------------------------------------------------------------===// 178 // Top-level transfer function logic (Dispatcher). 179 //===----------------------------------------------------------------------===// 180 181 /// evalAssume - Called by ConstraintManager. Used to call checker-specific 182 /// logic for handling assumptions on symbolic values. 183 const GRState *ExprEngine::processAssume(const GRState *state, SVal cond, 184 bool assumption) { 185 state = getCheckerManager().runCheckersForEvalAssume(state, cond, assumption); 186 187 // If the state is infeasible at this point, bail out. 188 if (!state) 189 return NULL; 190 191 return TF->evalAssume(state, cond, assumption); 192 } 193 194 bool ExprEngine::wantsRegionChangeUpdate(const GRState* state) { 195 return getCheckerManager().wantsRegionChangeUpdate(state); 196 } 197 198 const GRState * 199 ExprEngine::processRegionChanges(const GRState *state, 200 const StoreManager::InvalidatedSymbols *invalidated, 201 const MemRegion * const *Begin, 202 const MemRegion * const *End) { 203 return getCheckerManager().runCheckersForRegionChanges(state, invalidated, 204 Begin, End); 205 } 206 207 void ExprEngine::processEndWorklist(bool hasWorkRemaining) { 208 getCheckerManager().runCheckersForEndAnalysis(G, BR, *this); 209 } 210 211 void ExprEngine::processCFGElement(const CFGElement E, 212 StmtNodeBuilder& builder) { 213 switch (E.getKind()) { 214 case CFGElement::Invalid: 215 llvm_unreachable("Unexpected CFGElement kind."); 216 case CFGElement::Statement: 217 ProcessStmt(E.getAs<CFGStmt>()->getStmt(), builder); 218 return; 219 case CFGElement::Initializer: 220 ProcessInitializer(E.getAs<CFGInitializer>()->getInitializer(), builder); 221 return; 222 case CFGElement::AutomaticObjectDtor: 223 case CFGElement::BaseDtor: 224 case CFGElement::MemberDtor: 225 case CFGElement::TemporaryDtor: 226 ProcessImplicitDtor(*E.getAs<CFGImplicitDtor>(), builder); 227 return; 228 } 229 } 230 231 void ExprEngine::ProcessStmt(const CFGStmt S, StmtNodeBuilder& builder) { 232 // TODO: Use RAII to remove the unnecessary, tagged nodes. 233 //RegisterCreatedNodes registerCreatedNodes(getGraph()); 234 235 // Reclaim any unnecessary nodes in the ExplodedGraph. 236 G.reclaimRecentlyAllocatedNodes(); 237 // Recycle any unused states in the GRStateManager. 238 StateMgr.recycleUnusedStates(); 239 240 currentStmt = S.getStmt(); 241 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 242 currentStmt->getLocStart(), 243 "Error evaluating statement"); 244 245 // A tag to track convenience transitions, which can be removed at cleanup. 246 static unsigned tag; 247 Builder = &builder; 248 EntryNode = builder.getPredecessor(); 249 250 const GRState *EntryState = EntryNode->getState(); 251 CleanedState = EntryState; 252 ExplodedNode *CleanedNode = 0; 253 254 // Create the cleaned state. 255 const LocationContext *LC = EntryNode->getLocationContext(); 256 SymbolReaper SymReaper(LC, currentStmt, SymMgr, getStoreManager()); 257 258 if (AMgr.shouldPurgeDead()) { 259 getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper); 260 261 const StackFrameContext *SFC = LC->getCurrentStackFrame(); 262 263 // Create a state in which dead bindings are removed from the environment 264 // and the store. TODO: The function should just return new env and store, 265 // not a new state. 266 CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper); 267 } 268 269 // Process any special transfer function for dead symbols. 270 ExplodedNodeSet Tmp; 271 if (!SymReaper.hasDeadSymbols()) { 272 // Generate a CleanedNode that has the environment and store cleaned 273 // up. Since no symbols are dead, we can optimize and not clean out 274 // the constraint manager. 275 CleanedNode = 276 Builder->generateNode(currentStmt, CleanedState, EntryNode, &tag); 277 Tmp.Add(CleanedNode); 278 279 } else { 280 SaveAndRestore<bool> OldSink(Builder->BuildSinks); 281 SaveOr OldHasGen(Builder->hasGeneratedNode); 282 283 SaveAndRestore<bool> OldPurgeDeadSymbols(Builder->PurgingDeadSymbols); 284 Builder->PurgingDeadSymbols = true; 285 286 // Call checkers with the non-cleaned state so that they could query the 287 // values of the soon to be dead symbols. 288 // FIXME: This should soon be removed. 289 ExplodedNodeSet Tmp2; 290 getTF().evalDeadSymbols(Tmp2, *this, *Builder, EntryNode, 291 EntryState, SymReaper); 292 293 ExplodedNodeSet Tmp3; 294 getCheckerManager().runCheckersForDeadSymbols(Tmp3, Tmp2, 295 SymReaper, currentStmt, *this); 296 297 // For each node in Tmp3, generate CleanedNodes that have the environment, 298 // the store, and the constraints cleaned up but have the user supplied 299 // states as the predecessors. 300 for (ExplodedNodeSet::const_iterator I = Tmp3.begin(), E = Tmp3.end(); 301 I != E; ++I) { 302 const GRState *CheckerState = (*I)->getState(); 303 304 // The constraint manager has not been cleaned up yet, so clean up now. 305 CheckerState = getConstraintManager().removeDeadBindings(CheckerState, 306 SymReaper); 307 308 assert(StateMgr.haveEqualEnvironments(CheckerState, EntryState) && 309 "Checkers are not allowed to modify the Environment as a part of " 310 "checkDeadSymbols processing."); 311 assert(StateMgr.haveEqualStores(CheckerState, EntryState) && 312 "Checkers are not allowed to modify the Store as a part of " 313 "checkDeadSymbols processing."); 314 315 // Create a state based on CleanedState with CheckerState GDM and 316 // generate a transition to that state. 317 const GRState *CleanedCheckerSt = 318 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState); 319 ExplodedNode *CleanedNode = Builder->generateNode(currentStmt, 320 CleanedCheckerSt, *I, 321 &tag); 322 Tmp.Add(CleanedNode); 323 } 324 } 325 326 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { 327 // TODO: Remove Dest set, it's no longer needed. 328 ExplodedNodeSet Dst; 329 // Visit the statement. 330 Visit(currentStmt, *I, Dst); 331 } 332 333 // NULL out these variables to cleanup. 334 CleanedState = NULL; 335 EntryNode = NULL; 336 currentStmt = 0; 337 Builder = NULL; 338 } 339 340 void ExprEngine::ProcessInitializer(const CFGInitializer Init, 341 StmtNodeBuilder &builder) { 342 // We don't set EntryNode and currentStmt. And we don't clean up state. 343 const CXXCtorInitializer *BMI = Init.getInitializer(); 344 345 ExplodedNode *pred = builder.getPredecessor(); 346 347 const StackFrameContext *stackFrame = cast<StackFrameContext>(pred->getLocationContext()); 348 const CXXConstructorDecl *decl = cast<CXXConstructorDecl>(stackFrame->getDecl()); 349 const CXXThisRegion *thisReg = getCXXThisRegion(decl, stackFrame); 350 351 SVal thisVal = pred->getState()->getSVal(thisReg); 352 353 if (BMI->isAnyMemberInitializer()) { 354 ExplodedNodeSet Dst; 355 356 // Evaluate the initializer. 357 Visit(BMI->getInit(), pred, Dst); 358 359 for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end(); I != E; ++I){ 360 ExplodedNode *Pred = *I; 361 const GRState *state = Pred->getState(); 362 363 const FieldDecl *FD = BMI->getAnyMember(); 364 365 SVal FieldLoc = state->getLValue(FD, thisVal); 366 SVal InitVal = state->getSVal(BMI->getInit()); 367 state = state->bindLoc(FieldLoc, InitVal); 368 369 // Use a custom node building process. 370 PostInitializer PP(BMI, stackFrame); 371 // Builder automatically add the generated node to the deferred set, 372 // which are processed in the builder's dtor. 373 builder.generateNode(PP, state, Pred); 374 } 375 return; 376 } 377 378 assert(BMI->isBaseInitializer()); 379 380 // Get the base class declaration. 381 const CXXConstructExpr *ctorExpr = cast<CXXConstructExpr>(BMI->getInit()); 382 383 // Create the base object region. 384 SVal baseVal = 385 getStoreManager().evalDerivedToBase(thisVal, ctorExpr->getType()); 386 const MemRegion *baseReg = baseVal.getAsRegion(); 387 assert(baseReg); 388 Builder = &builder; 389 ExplodedNodeSet dst; 390 VisitCXXConstructExpr(ctorExpr, baseReg, pred, dst); 391 } 392 393 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D, 394 StmtNodeBuilder &builder) { 395 Builder = &builder; 396 397 switch (D.getKind()) { 398 case CFGElement::AutomaticObjectDtor: 399 ProcessAutomaticObjDtor(cast<CFGAutomaticObjDtor>(D), builder); 400 break; 401 case CFGElement::BaseDtor: 402 ProcessBaseDtor(cast<CFGBaseDtor>(D), builder); 403 break; 404 case CFGElement::MemberDtor: 405 ProcessMemberDtor(cast<CFGMemberDtor>(D), builder); 406 break; 407 case CFGElement::TemporaryDtor: 408 ProcessTemporaryDtor(cast<CFGTemporaryDtor>(D), builder); 409 break; 410 default: 411 llvm_unreachable("Unexpected dtor kind."); 412 } 413 } 414 415 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor dtor, 416 StmtNodeBuilder &builder) { 417 ExplodedNode *pred = builder.getPredecessor(); 418 const GRState *state = pred->getState(); 419 const VarDecl *varDecl = dtor.getVarDecl(); 420 421 QualType varType = varDecl->getType(); 422 423 if (const ReferenceType *refType = varType->getAs<ReferenceType>()) 424 varType = refType->getPointeeType(); 425 426 const CXXRecordDecl *recordDecl = varType->getAsCXXRecordDecl(); 427 assert(recordDecl && "get CXXRecordDecl fail"); 428 const CXXDestructorDecl *dtorDecl = recordDecl->getDestructor(); 429 430 Loc dest = state->getLValue(varDecl, pred->getLocationContext()); 431 432 ExplodedNodeSet dstSet; 433 VisitCXXDestructor(dtorDecl, cast<loc::MemRegionVal>(dest).getRegion(), 434 dtor.getTriggerStmt(), pred, dstSet); 435 } 436 437 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D, 438 StmtNodeBuilder &builder) { 439 } 440 441 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D, 442 StmtNodeBuilder &builder) { 443 } 444 445 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D, 446 StmtNodeBuilder &builder) { 447 } 448 449 void ExprEngine::Visit(const Stmt* S, ExplodedNode* Pred, 450 ExplodedNodeSet& Dst) { 451 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 452 S->getLocStart(), 453 "Error evaluating statement"); 454 455 // Expressions to ignore. 456 if (const Expr *Ex = dyn_cast<Expr>(S)) 457 S = Ex->IgnoreParens(); 458 459 // FIXME: add metadata to the CFG so that we can disable 460 // this check when we KNOW that there is no block-level subexpression. 461 // The motivation is that this check requires a hashtable lookup. 462 463 if (S != currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(S)) { 464 Dst.Add(Pred); 465 return; 466 } 467 468 switch (S->getStmtClass()) { 469 // C++ and ARC stuff we don't support yet. 470 case Expr::ObjCIndirectCopyRestoreExprClass: 471 case Stmt::CXXBindTemporaryExprClass: 472 case Stmt::CXXCatchStmtClass: 473 case Stmt::CXXDependentScopeMemberExprClass: 474 case Stmt::CXXForRangeStmtClass: 475 case Stmt::CXXPseudoDestructorExprClass: 476 case Stmt::CXXTemporaryObjectExprClass: 477 case Stmt::CXXThrowExprClass: 478 case Stmt::CXXTryStmtClass: 479 case Stmt::CXXTypeidExprClass: 480 case Stmt::CXXUuidofExprClass: 481 case Stmt::CXXUnresolvedConstructExprClass: 482 case Stmt::CXXScalarValueInitExprClass: 483 case Stmt::DependentScopeDeclRefExprClass: 484 case Stmt::UnaryTypeTraitExprClass: 485 case Stmt::BinaryTypeTraitExprClass: 486 case Stmt::ArrayTypeTraitExprClass: 487 case Stmt::ExpressionTraitExprClass: 488 case Stmt::UnresolvedLookupExprClass: 489 case Stmt::UnresolvedMemberExprClass: 490 case Stmt::CXXNoexceptExprClass: 491 case Stmt::PackExpansionExprClass: 492 case Stmt::SubstNonTypeTemplateParmPackExprClass: 493 case Stmt::SEHTryStmtClass: 494 case Stmt::SEHExceptStmtClass: 495 case Stmt::SEHFinallyStmtClass: 496 { 497 SaveAndRestore<bool> OldSink(Builder->BuildSinks); 498 Builder->BuildSinks = true; 499 const ExplodedNode *node = MakeNode(Dst, S, Pred, Pred->getState()); 500 Engine.addAbortedBlock(node, Builder->getBlock()); 501 break; 502 } 503 504 // We don't handle default arguments either yet, but we can fake it 505 // for now by just skipping them. 506 case Stmt::SubstNonTypeTemplateParmExprClass: 507 case Stmt::CXXDefaultArgExprClass: { 508 Dst.Add(Pred); 509 break; 510 } 511 512 case Stmt::ParenExprClass: 513 llvm_unreachable("ParenExprs already handled."); 514 case Stmt::GenericSelectionExprClass: 515 llvm_unreachable("GenericSelectionExprs already handled."); 516 // Cases that should never be evaluated simply because they shouldn't 517 // appear in the CFG. 518 case Stmt::BreakStmtClass: 519 case Stmt::CaseStmtClass: 520 case Stmt::CompoundStmtClass: 521 case Stmt::ContinueStmtClass: 522 case Stmt::DefaultStmtClass: 523 case Stmt::DoStmtClass: 524 case Stmt::ForStmtClass: 525 case Stmt::GotoStmtClass: 526 case Stmt::IfStmtClass: 527 case Stmt::IndirectGotoStmtClass: 528 case Stmt::LabelStmtClass: 529 case Stmt::NoStmtClass: 530 case Stmt::NullStmtClass: 531 case Stmt::SwitchStmtClass: 532 case Stmt::WhileStmtClass: 533 llvm_unreachable("Stmt should not be in analyzer evaluation loop"); 534 break; 535 536 case Stmt::GNUNullExprClass: { 537 // GNU __null is a pointer-width integer, not an actual pointer. 538 const GRState *state = Pred->getState(); 539 state = state->BindExpr(S, svalBuilder.makeIntValWithPtrWidth(0, false)); 540 MakeNode(Dst, S, Pred, state); 541 break; 542 } 543 544 case Stmt::ObjCAtSynchronizedStmtClass: 545 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst); 546 break; 547 548 case Stmt::ObjCPropertyRefExprClass: 549 VisitObjCPropertyRefExpr(cast<ObjCPropertyRefExpr>(S), Pred, Dst); 550 break; 551 552 case Stmt::ImplicitValueInitExprClass: { 553 const GRState *state = Pred->getState(); 554 QualType ty = cast<ImplicitValueInitExpr>(S)->getType(); 555 SVal val = svalBuilder.makeZeroVal(ty); 556 MakeNode(Dst, S, Pred, state->BindExpr(S, val)); 557 break; 558 } 559 560 case Stmt::ExprWithCleanupsClass: { 561 Visit(cast<ExprWithCleanups>(S)->getSubExpr(), Pred, Dst); 562 break; 563 } 564 565 // Cases not handled yet; but will handle some day. 566 case Stmt::DesignatedInitExprClass: 567 case Stmt::ExtVectorElementExprClass: 568 case Stmt::ImaginaryLiteralClass: 569 case Stmt::ObjCAtCatchStmtClass: 570 case Stmt::ObjCAtFinallyStmtClass: 571 case Stmt::ObjCAtTryStmtClass: 572 case Stmt::ObjCAutoreleasePoolStmtClass: 573 case Stmt::ObjCEncodeExprClass: 574 case Stmt::ObjCIsaExprClass: 575 case Stmt::ObjCProtocolExprClass: 576 case Stmt::ObjCSelectorExprClass: 577 case Stmt::ObjCStringLiteralClass: 578 case Stmt::ParenListExprClass: 579 case Stmt::PredefinedExprClass: 580 case Stmt::ShuffleVectorExprClass: 581 case Stmt::VAArgExprClass: 582 case Stmt::CUDAKernelCallExprClass: 583 case Stmt::OpaqueValueExprClass: 584 case Stmt::AsTypeExprClass: 585 // Fall through. 586 587 // Cases we intentionally don't evaluate, since they don't need 588 // to be explicitly evaluated. 589 case Stmt::AddrLabelExprClass: 590 case Stmt::IntegerLiteralClass: 591 case Stmt::CharacterLiteralClass: 592 case Stmt::CXXBoolLiteralExprClass: 593 case Stmt::FloatingLiteralClass: 594 case Stmt::SizeOfPackExprClass: 595 case Stmt::CXXNullPtrLiteralExprClass: 596 Dst.Add(Pred); // No-op. Simply propagate the current state unchanged. 597 break; 598 599 case Stmt::ArraySubscriptExprClass: 600 VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst); 601 break; 602 603 case Stmt::AsmStmtClass: 604 VisitAsmStmt(cast<AsmStmt>(S), Pred, Dst); 605 break; 606 607 case Stmt::BlockDeclRefExprClass: { 608 const BlockDeclRefExpr *BE = cast<BlockDeclRefExpr>(S); 609 VisitCommonDeclRefExpr(BE, BE->getDecl(), Pred, Dst); 610 break; 611 } 612 613 case Stmt::BlockExprClass: 614 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst); 615 break; 616 617 case Stmt::BinaryOperatorClass: { 618 const BinaryOperator* B = cast<BinaryOperator>(S); 619 if (B->isLogicalOp()) { 620 VisitLogicalExpr(B, Pred, Dst); 621 break; 622 } 623 else if (B->getOpcode() == BO_Comma) { 624 const GRState* state = Pred->getState(); 625 MakeNode(Dst, B, Pred, state->BindExpr(B, state->getSVal(B->getRHS()))); 626 break; 627 } 628 629 if (AMgr.shouldEagerlyAssume() && 630 (B->isRelationalOp() || B->isEqualityOp())) { 631 ExplodedNodeSet Tmp; 632 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp); 633 evalEagerlyAssume(Dst, Tmp, cast<Expr>(S)); 634 } 635 else 636 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 637 638 break; 639 } 640 641 case Stmt::CallExprClass: 642 case Stmt::CXXOperatorCallExprClass: 643 case Stmt::CXXMemberCallExprClass: { 644 VisitCallExpr(cast<CallExpr>(S), Pred, Dst); 645 break; 646 } 647 648 case Stmt::CXXConstructExprClass: { 649 const CXXConstructExpr *C = cast<CXXConstructExpr>(S); 650 // For block-level CXXConstructExpr, we don't have a destination region. 651 // Let VisitCXXConstructExpr() create one. 652 VisitCXXConstructExpr(C, 0, Pred, Dst); 653 break; 654 } 655 656 case Stmt::CXXNewExprClass: { 657 const CXXNewExpr *NE = cast<CXXNewExpr>(S); 658 VisitCXXNewExpr(NE, Pred, Dst); 659 break; 660 } 661 662 case Stmt::CXXDeleteExprClass: { 663 const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S); 664 VisitCXXDeleteExpr(CDE, Pred, Dst); 665 break; 666 } 667 // FIXME: ChooseExpr is really a constant. We need to fix 668 // the CFG do not model them as explicit control-flow. 669 670 case Stmt::ChooseExprClass: { // __builtin_choose_expr 671 const ChooseExpr* C = cast<ChooseExpr>(S); 672 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst); 673 break; 674 } 675 676 case Stmt::CompoundAssignOperatorClass: 677 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 678 break; 679 680 case Stmt::CompoundLiteralExprClass: 681 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst); 682 break; 683 684 case Stmt::BinaryConditionalOperatorClass: 685 case Stmt::ConditionalOperatorClass: { // '?' operator 686 const AbstractConditionalOperator *C 687 = cast<AbstractConditionalOperator>(S); 688 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst); 689 break; 690 } 691 692 case Stmt::CXXThisExprClass: 693 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst); 694 break; 695 696 case Stmt::DeclRefExprClass: { 697 const DeclRefExpr *DE = cast<DeclRefExpr>(S); 698 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst); 699 break; 700 } 701 702 case Stmt::DeclStmtClass: 703 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst); 704 break; 705 706 case Stmt::ImplicitCastExprClass: 707 case Stmt::CStyleCastExprClass: 708 case Stmt::CXXStaticCastExprClass: 709 case Stmt::CXXDynamicCastExprClass: 710 case Stmt::CXXReinterpretCastExprClass: 711 case Stmt::CXXConstCastExprClass: 712 case Stmt::CXXFunctionalCastExprClass: 713 case Stmt::ObjCBridgedCastExprClass: { 714 const CastExpr* C = cast<CastExpr>(S); 715 // Handle the previsit checks. 716 ExplodedNodeSet dstPrevisit; 717 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this); 718 719 // Handle the expression itself. 720 ExplodedNodeSet dstExpr; 721 for (ExplodedNodeSet::iterator i = dstPrevisit.begin(), 722 e = dstPrevisit.end(); i != e ; ++i) { 723 VisitCast(C, C->getSubExpr(), *i, dstExpr); 724 } 725 726 // Handle the postvisit checks. 727 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this); 728 break; 729 } 730 731 case Expr::MaterializeTemporaryExprClass: { 732 const MaterializeTemporaryExpr *Materialize 733 = cast<MaterializeTemporaryExpr>(S); 734 if (!Materialize->getType()->isRecordType()) 735 CreateCXXTemporaryObject(Materialize, Pred, Dst); 736 else 737 Visit(Materialize->GetTemporaryExpr(), Pred, Dst); 738 break; 739 } 740 741 case Stmt::InitListExprClass: 742 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst); 743 break; 744 745 case Stmt::MemberExprClass: 746 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst); 747 break; 748 case Stmt::ObjCIvarRefExprClass: 749 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst); 750 break; 751 752 case Stmt::ObjCForCollectionStmtClass: 753 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst); 754 break; 755 756 case Stmt::ObjCMessageExprClass: 757 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst); 758 break; 759 760 case Stmt::ObjCAtThrowStmtClass: { 761 // FIXME: This is not complete. We basically treat @throw as 762 // an abort. 763 SaveAndRestore<bool> OldSink(Builder->BuildSinks); 764 Builder->BuildSinks = true; 765 MakeNode(Dst, S, Pred, Pred->getState()); 766 break; 767 } 768 769 case Stmt::ReturnStmtClass: 770 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst); 771 break; 772 773 case Stmt::OffsetOfExprClass: 774 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst); 775 break; 776 777 case Stmt::UnaryExprOrTypeTraitExprClass: 778 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), 779 Pred, Dst); 780 break; 781 782 case Stmt::StmtExprClass: { 783 const StmtExpr* SE = cast<StmtExpr>(S); 784 785 if (SE->getSubStmt()->body_empty()) { 786 // Empty statement expression. 787 assert(SE->getType() == getContext().VoidTy 788 && "Empty statement expression must have void type."); 789 Dst.Add(Pred); 790 break; 791 } 792 793 if (Expr* LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) { 794 const GRState* state = Pred->getState(); 795 MakeNode(Dst, SE, Pred, state->BindExpr(SE, state->getSVal(LastExpr))); 796 } 797 else 798 Dst.Add(Pred); 799 800 break; 801 } 802 803 case Stmt::StringLiteralClass: { 804 const GRState* state = Pred->getState(); 805 SVal V = state->getLValue(cast<StringLiteral>(S)); 806 MakeNode(Dst, S, Pred, state->BindExpr(S, V)); 807 return; 808 } 809 810 case Stmt::UnaryOperatorClass: { 811 const UnaryOperator *U = cast<UnaryOperator>(S); 812 if (AMgr.shouldEagerlyAssume()&&(U->getOpcode() == UO_LNot)) { 813 ExplodedNodeSet Tmp; 814 VisitUnaryOperator(U, Pred, Tmp); 815 evalEagerlyAssume(Dst, Tmp, U); 816 } 817 else 818 VisitUnaryOperator(U, Pred, Dst); 819 break; 820 } 821 } 822 } 823 824 //===----------------------------------------------------------------------===// 825 // Block entrance. (Update counters). 826 //===----------------------------------------------------------------------===// 827 828 void ExprEngine::processCFGBlockEntrance(ExplodedNodeSet &dstNodes, 829 GenericNodeBuilder<BlockEntrance> &nodeBuilder){ 830 831 // FIXME: Refactor this into a checker. 832 const CFGBlock *block = nodeBuilder.getProgramPoint().getBlock(); 833 ExplodedNode *pred = nodeBuilder.getPredecessor(); 834 835 if (nodeBuilder.getBlockCounter().getNumVisited( 836 pred->getLocationContext()->getCurrentStackFrame(), 837 block->getBlockID()) >= AMgr.getMaxVisit()) { 838 839 static int tag = 0; 840 nodeBuilder.generateNode(pred->getState(), pred, &tag, true); 841 } 842 } 843 844 //===----------------------------------------------------------------------===// 845 // Generic node creation. 846 //===----------------------------------------------------------------------===// 847 848 ExplodedNode* ExprEngine::MakeNode(ExplodedNodeSet& Dst, const Stmt* S, 849 ExplodedNode* Pred, const GRState* St, 850 ProgramPoint::Kind K, const void *tag) { 851 assert (Builder && "StmtNodeBuilder not present."); 852 SaveAndRestore<const void*> OldTag(Builder->Tag); 853 Builder->Tag = tag; 854 return Builder->MakeNode(Dst, S, Pred, St, K); 855 } 856 857 //===----------------------------------------------------------------------===// 858 // Branch processing. 859 //===----------------------------------------------------------------------===// 860 861 const GRState* ExprEngine::MarkBranch(const GRState* state, 862 const Stmt* Terminator, 863 bool branchTaken) { 864 865 switch (Terminator->getStmtClass()) { 866 default: 867 return state; 868 869 case Stmt::BinaryOperatorClass: { // '&&' and '||' 870 871 const BinaryOperator* B = cast<BinaryOperator>(Terminator); 872 BinaryOperator::Opcode Op = B->getOpcode(); 873 874 assert (Op == BO_LAnd || Op == BO_LOr); 875 876 // For &&, if we take the true branch, then the value of the whole 877 // expression is that of the RHS expression. 878 // 879 // For ||, if we take the false branch, then the value of the whole 880 // expression is that of the RHS expression. 881 882 const Expr* Ex = (Op == BO_LAnd && branchTaken) || 883 (Op == BO_LOr && !branchTaken) 884 ? B->getRHS() : B->getLHS(); 885 886 return state->BindExpr(B, UndefinedVal(Ex)); 887 } 888 889 case Stmt::BinaryConditionalOperatorClass: 890 case Stmt::ConditionalOperatorClass: { // ?: 891 const AbstractConditionalOperator* C 892 = cast<AbstractConditionalOperator>(Terminator); 893 894 // For ?, if branchTaken == true then the value is either the LHS or 895 // the condition itself. (GNU extension). 896 897 const Expr* Ex; 898 899 if (branchTaken) 900 Ex = C->getTrueExpr(); 901 else 902 Ex = C->getFalseExpr(); 903 904 return state->BindExpr(C, UndefinedVal(Ex)); 905 } 906 907 case Stmt::ChooseExprClass: { // ?: 908 909 const ChooseExpr* C = cast<ChooseExpr>(Terminator); 910 911 const Expr* Ex = branchTaken ? C->getLHS() : C->getRHS(); 912 return state->BindExpr(C, UndefinedVal(Ex)); 913 } 914 } 915 } 916 917 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used 918 /// to try to recover some path-sensitivity for casts of symbolic 919 /// integers that promote their values (which are currently not tracked well). 920 /// This function returns the SVal bound to Condition->IgnoreCasts if all the 921 // cast(s) did was sign-extend the original value. 922 static SVal RecoverCastedSymbol(GRStateManager& StateMgr, const GRState* state, 923 const Stmt* Condition, ASTContext& Ctx) { 924 925 const Expr *Ex = dyn_cast<Expr>(Condition); 926 if (!Ex) 927 return UnknownVal(); 928 929 uint64_t bits = 0; 930 bool bitsInit = false; 931 932 while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) { 933 QualType T = CE->getType(); 934 935 if (!T->isIntegerType()) 936 return UnknownVal(); 937 938 uint64_t newBits = Ctx.getTypeSize(T); 939 if (!bitsInit || newBits < bits) { 940 bitsInit = true; 941 bits = newBits; 942 } 943 944 Ex = CE->getSubExpr(); 945 } 946 947 // We reached a non-cast. Is it a symbolic value? 948 QualType T = Ex->getType(); 949 950 if (!bitsInit || !T->isIntegerType() || Ctx.getTypeSize(T) > bits) 951 return UnknownVal(); 952 953 return state->getSVal(Ex); 954 } 955 956 void ExprEngine::processBranch(const Stmt* Condition, const Stmt* Term, 957 BranchNodeBuilder& builder) { 958 959 // Check for NULL conditions; e.g. "for(;;)" 960 if (!Condition) { 961 builder.markInfeasible(false); 962 return; 963 } 964 965 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 966 Condition->getLocStart(), 967 "Error evaluating branch"); 968 969 getCheckerManager().runCheckersForBranchCondition(Condition, builder, *this); 970 971 // If the branch condition is undefined, return; 972 if (!builder.isFeasible(true) && !builder.isFeasible(false)) 973 return; 974 975 const GRState* PrevState = builder.getState(); 976 SVal X = PrevState->getSVal(Condition); 977 978 if (X.isUnknownOrUndef()) { 979 // Give it a chance to recover from unknown. 980 if (const Expr *Ex = dyn_cast<Expr>(Condition)) { 981 if (Ex->getType()->isIntegerType()) { 982 // Try to recover some path-sensitivity. Right now casts of symbolic 983 // integers that promote their values are currently not tracked well. 984 // If 'Condition' is such an expression, try and recover the 985 // underlying value and use that instead. 986 SVal recovered = RecoverCastedSymbol(getStateManager(), 987 builder.getState(), Condition, 988 getContext()); 989 990 if (!recovered.isUnknown()) { 991 X = recovered; 992 } 993 } 994 } 995 // If the condition is still unknown, give up. 996 if (X.isUnknownOrUndef()) { 997 builder.generateNode(MarkBranch(PrevState, Term, true), true); 998 builder.generateNode(MarkBranch(PrevState, Term, false), false); 999 return; 1000 } 1001 } 1002 1003 DefinedSVal V = cast<DefinedSVal>(X); 1004 1005 // Process the true branch. 1006 if (builder.isFeasible(true)) { 1007 if (const GRState *state = PrevState->assume(V, true)) 1008 builder.generateNode(MarkBranch(state, Term, true), true); 1009 else 1010 builder.markInfeasible(true); 1011 } 1012 1013 // Process the false branch. 1014 if (builder.isFeasible(false)) { 1015 if (const GRState *state = PrevState->assume(V, false)) 1016 builder.generateNode(MarkBranch(state, Term, false), false); 1017 else 1018 builder.markInfeasible(false); 1019 } 1020 } 1021 1022 /// processIndirectGoto - Called by CoreEngine. Used to generate successor 1023 /// nodes by processing the 'effects' of a computed goto jump. 1024 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) { 1025 1026 const GRState *state = builder.getState(); 1027 SVal V = state->getSVal(builder.getTarget()); 1028 1029 // Three possibilities: 1030 // 1031 // (1) We know the computed label. 1032 // (2) The label is NULL (or some other constant), or Undefined. 1033 // (3) We have no clue about the label. Dispatch to all targets. 1034 // 1035 1036 typedef IndirectGotoNodeBuilder::iterator iterator; 1037 1038 if (isa<loc::GotoLabel>(V)) { 1039 const LabelDecl *L = cast<loc::GotoLabel>(V).getLabel(); 1040 1041 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) { 1042 if (I.getLabel() == L) { 1043 builder.generateNode(I, state); 1044 return; 1045 } 1046 } 1047 1048 assert(false && "No block with label."); 1049 return; 1050 } 1051 1052 if (isa<loc::ConcreteInt>(V) || isa<UndefinedVal>(V)) { 1053 // Dispatch to the first target and mark it as a sink. 1054 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true); 1055 // FIXME: add checker visit. 1056 // UndefBranches.insert(N); 1057 return; 1058 } 1059 1060 // This is really a catch-all. We don't support symbolics yet. 1061 // FIXME: Implement dispatch for symbolic pointers. 1062 1063 for (iterator I=builder.begin(), E=builder.end(); I != E; ++I) 1064 builder.generateNode(I, state); 1065 } 1066 1067 1068 void ExprEngine::VisitGuardedExpr(const Expr* Ex, const Expr* L, 1069 const Expr* R, 1070 ExplodedNode* Pred, ExplodedNodeSet& Dst) { 1071 1072 assert(Ex == currentStmt && 1073 Pred->getLocationContext()->getCFG()->isBlkExpr(Ex)); 1074 1075 const GRState* state = Pred->getState(); 1076 SVal X = state->getSVal(Ex); 1077 1078 assert (X.isUndef()); 1079 1080 const Expr *SE = (Expr*) cast<UndefinedVal>(X).getData(); 1081 assert(SE); 1082 X = state->getSVal(SE); 1083 1084 // Make sure that we invalidate the previous binding. 1085 MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, X, true)); 1086 } 1087 1088 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path 1089 /// nodes when the control reaches the end of a function. 1090 void ExprEngine::processEndOfFunction(EndOfFunctionNodeBuilder& builder) { 1091 getTF().evalEndPath(*this, builder); 1092 StateMgr.EndPath(builder.getState()); 1093 getCheckerManager().runCheckersForEndPath(builder, *this); 1094 } 1095 1096 /// ProcessSwitch - Called by CoreEngine. Used to generate successor 1097 /// nodes by processing the 'effects' of a switch statement. 1098 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) { 1099 typedef SwitchNodeBuilder::iterator iterator; 1100 const GRState* state = builder.getState(); 1101 const Expr* CondE = builder.getCondition(); 1102 SVal CondV_untested = state->getSVal(CondE); 1103 1104 if (CondV_untested.isUndef()) { 1105 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true); 1106 // FIXME: add checker 1107 //UndefBranches.insert(N); 1108 1109 return; 1110 } 1111 DefinedOrUnknownSVal CondV = cast<DefinedOrUnknownSVal>(CondV_untested); 1112 1113 const GRState *DefaultSt = state; 1114 1115 iterator I = builder.begin(), EI = builder.end(); 1116 bool defaultIsFeasible = I == EI; 1117 1118 for ( ; I != EI; ++I) { 1119 // Successor may be pruned out during CFG construction. 1120 if (!I.getBlock()) 1121 continue; 1122 1123 const CaseStmt* Case = I.getCase(); 1124 1125 // Evaluate the LHS of the case value. 1126 Expr::EvalResult V1; 1127 bool b = Case->getLHS()->Evaluate(V1, getContext()); 1128 1129 // Sanity checks. These go away in Release builds. 1130 assert(b && V1.Val.isInt() && !V1.HasSideEffects 1131 && "Case condition must evaluate to an integer constant."); 1132 (void)b; // silence unused variable warning 1133 assert(V1.Val.getInt().getBitWidth() == 1134 getContext().getTypeSize(CondE->getType())); 1135 1136 // Get the RHS of the case, if it exists. 1137 Expr::EvalResult V2; 1138 1139 if (const Expr* E = Case->getRHS()) { 1140 b = E->Evaluate(V2, getContext()); 1141 assert(b && V2.Val.isInt() && !V2.HasSideEffects 1142 && "Case condition must evaluate to an integer constant."); 1143 (void)b; // silence unused variable warning 1144 } 1145 else 1146 V2 = V1; 1147 1148 // FIXME: Eventually we should replace the logic below with a range 1149 // comparison, rather than concretize the values within the range. 1150 // This should be easy once we have "ranges" for NonLVals. 1151 1152 do { 1153 nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1.Val.getInt())); 1154 DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state, 1155 CondV, CaseVal); 1156 1157 // Now "assume" that the case matches. 1158 if (const GRState* stateNew = state->assume(Res, true)) { 1159 builder.generateCaseStmtNode(I, stateNew); 1160 1161 // If CondV evaluates to a constant, then we know that this 1162 // is the *only* case that we can take, so stop evaluating the 1163 // others. 1164 if (isa<nonloc::ConcreteInt>(CondV)) 1165 return; 1166 } 1167 1168 // Now "assume" that the case doesn't match. Add this state 1169 // to the default state (if it is feasible). 1170 if (DefaultSt) { 1171 if (const GRState *stateNew = DefaultSt->assume(Res, false)) { 1172 defaultIsFeasible = true; 1173 DefaultSt = stateNew; 1174 } 1175 else { 1176 defaultIsFeasible = false; 1177 DefaultSt = NULL; 1178 } 1179 } 1180 1181 // Concretize the next value in the range. 1182 if (V1.Val.getInt() == V2.Val.getInt()) 1183 break; 1184 1185 ++V1.Val.getInt(); 1186 assert (V1.Val.getInt() <= V2.Val.getInt()); 1187 1188 } while (true); 1189 } 1190 1191 if (!defaultIsFeasible) 1192 return; 1193 1194 // If we have switch(enum value), the default branch is not 1195 // feasible if all of the enum constants not covered by 'case:' statements 1196 // are not feasible values for the switch condition. 1197 // 1198 // Note that this isn't as accurate as it could be. Even if there isn't 1199 // a case for a particular enum value as long as that enum value isn't 1200 // feasible then it shouldn't be considered for making 'default:' reachable. 1201 const SwitchStmt *SS = builder.getSwitch(); 1202 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts(); 1203 if (CondExpr->getType()->getAs<EnumType>()) { 1204 if (SS->isAllEnumCasesCovered()) 1205 return; 1206 } 1207 1208 builder.generateDefaultCaseNode(DefaultSt); 1209 } 1210 1211 void ExprEngine::processCallEnter(CallEnterNodeBuilder &B) { 1212 const GRState *state = B.getState()->enterStackFrame(B.getCalleeContext()); 1213 B.generateNode(state); 1214 } 1215 1216 void ExprEngine::processCallExit(CallExitNodeBuilder &B) { 1217 const GRState *state = B.getState(); 1218 const ExplodedNode *Pred = B.getPredecessor(); 1219 const StackFrameContext *calleeCtx = 1220 cast<StackFrameContext>(Pred->getLocationContext()); 1221 const Stmt *CE = calleeCtx->getCallSite(); 1222 1223 // If the callee returns an expression, bind its value to CallExpr. 1224 const Stmt *ReturnedExpr = state->get<ReturnExpr>(); 1225 if (ReturnedExpr) { 1226 SVal RetVal = state->getSVal(ReturnedExpr); 1227 state = state->BindExpr(CE, RetVal); 1228 // Clear the return expr GDM. 1229 state = state->remove<ReturnExpr>(); 1230 } 1231 1232 // Bind the constructed object value to CXXConstructExpr. 1233 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(CE)) { 1234 const CXXThisRegion *ThisR = 1235 getCXXThisRegion(CCE->getConstructor()->getParent(), calleeCtx); 1236 1237 SVal ThisV = state->getSVal(ThisR); 1238 // Always bind the region to the CXXConstructExpr. 1239 state = state->BindExpr(CCE, ThisV); 1240 } 1241 1242 B.generateNode(state); 1243 } 1244 1245 //===----------------------------------------------------------------------===// 1246 // Transfer functions: logical operations ('&&', '||'). 1247 //===----------------------------------------------------------------------===// 1248 1249 void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode* Pred, 1250 ExplodedNodeSet& Dst) { 1251 1252 assert(B->getOpcode() == BO_LAnd || 1253 B->getOpcode() == BO_LOr); 1254 1255 assert(B==currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(B)); 1256 1257 const GRState* state = Pred->getState(); 1258 SVal X = state->getSVal(B); 1259 assert(X.isUndef()); 1260 1261 const Expr *Ex = (const Expr*) cast<UndefinedVal>(X).getData(); 1262 assert(Ex); 1263 1264 if (Ex == B->getRHS()) { 1265 X = state->getSVal(Ex); 1266 1267 // Handle undefined values. 1268 if (X.isUndef()) { 1269 MakeNode(Dst, B, Pred, state->BindExpr(B, X)); 1270 return; 1271 } 1272 1273 DefinedOrUnknownSVal XD = cast<DefinedOrUnknownSVal>(X); 1274 1275 // We took the RHS. Because the value of the '&&' or '||' expression must 1276 // evaluate to 0 or 1, we must assume the value of the RHS evaluates to 0 1277 // or 1. Alternatively, we could take a lazy approach, and calculate this 1278 // value later when necessary. We don't have the machinery in place for 1279 // this right now, and since most logical expressions are used for branches, 1280 // the payoff is not likely to be large. Instead, we do eager evaluation. 1281 if (const GRState *newState = state->assume(XD, true)) 1282 MakeNode(Dst, B, Pred, 1283 newState->BindExpr(B, svalBuilder.makeIntVal(1U, B->getType()))); 1284 1285 if (const GRState *newState = state->assume(XD, false)) 1286 MakeNode(Dst, B, Pred, 1287 newState->BindExpr(B, svalBuilder.makeIntVal(0U, B->getType()))); 1288 } 1289 else { 1290 // We took the LHS expression. Depending on whether we are '&&' or 1291 // '||' we know what the value of the expression is via properties of 1292 // the short-circuiting. 1293 X = svalBuilder.makeIntVal(B->getOpcode() == BO_LAnd ? 0U : 1U, 1294 B->getType()); 1295 MakeNode(Dst, B, Pred, state->BindExpr(B, X)); 1296 } 1297 } 1298 1299 //===----------------------------------------------------------------------===// 1300 // Transfer functions: Loads and stores. 1301 //===----------------------------------------------------------------------===// 1302 1303 void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, 1304 ExplodedNodeSet &Dst) { 1305 1306 ExplodedNodeSet Tmp; 1307 1308 CanQualType T = getContext().getCanonicalType(BE->getType()); 1309 SVal V = svalBuilder.getBlockPointer(BE->getBlockDecl(), T, 1310 Pred->getLocationContext()); 1311 1312 MakeNode(Tmp, BE, Pred, Pred->getState()->BindExpr(BE, V), 1313 ProgramPoint::PostLValueKind); 1314 1315 // Post-visit the BlockExpr. 1316 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this); 1317 } 1318 1319 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D, 1320 ExplodedNode *Pred, 1321 ExplodedNodeSet &Dst) { 1322 const GRState *state = Pred->getState(); 1323 1324 if (const VarDecl* VD = dyn_cast<VarDecl>(D)) { 1325 assert(Ex->isLValue()); 1326 SVal V = state->getLValue(VD, Pred->getLocationContext()); 1327 1328 // For references, the 'lvalue' is the pointer address stored in the 1329 // reference region. 1330 if (VD->getType()->isReferenceType()) { 1331 if (const MemRegion *R = V.getAsRegion()) 1332 V = state->getSVal(R); 1333 else 1334 V = UnknownVal(); 1335 } 1336 1337 MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V), 1338 ProgramPoint::PostLValueKind); 1339 return; 1340 } 1341 if (const EnumConstantDecl* ED = dyn_cast<EnumConstantDecl>(D)) { 1342 assert(!Ex->isLValue()); 1343 SVal V = svalBuilder.makeIntVal(ED->getInitVal()); 1344 MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V)); 1345 return; 1346 } 1347 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) { 1348 SVal V = svalBuilder.getFunctionPointer(FD); 1349 MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V), 1350 ProgramPoint::PostLValueKind); 1351 return; 1352 } 1353 assert (false && 1354 "ValueDecl support for this ValueDecl not implemented."); 1355 } 1356 1357 /// VisitArraySubscriptExpr - Transfer function for array accesses 1358 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr* A, 1359 ExplodedNode* Pred, 1360 ExplodedNodeSet& Dst){ 1361 1362 const Expr* Base = A->getBase()->IgnoreParens(); 1363 const Expr* Idx = A->getIdx()->IgnoreParens(); 1364 1365 1366 ExplodedNodeSet checkerPreStmt; 1367 getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this); 1368 1369 for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(), 1370 ei = checkerPreStmt.end(); it != ei; ++it) { 1371 const GRState* state = (*it)->getState(); 1372 SVal V = state->getLValue(A->getType(), state->getSVal(Idx), 1373 state->getSVal(Base)); 1374 assert(A->isLValue()); 1375 MakeNode(Dst, A, *it, state->BindExpr(A, V), ProgramPoint::PostLValueKind); 1376 } 1377 } 1378 1379 /// VisitMemberExpr - Transfer function for member expressions. 1380 void ExprEngine::VisitMemberExpr(const MemberExpr* M, ExplodedNode *Pred, 1381 ExplodedNodeSet& Dst) { 1382 1383 FieldDecl *field = dyn_cast<FieldDecl>(M->getMemberDecl()); 1384 if (!field) // FIXME: skipping member expressions for non-fields 1385 return; 1386 1387 Expr *baseExpr = M->getBase()->IgnoreParens(); 1388 const GRState* state = Pred->getState(); 1389 SVal baseExprVal = state->getSVal(baseExpr); 1390 if (isa<nonloc::LazyCompoundVal>(baseExprVal) || 1391 isa<nonloc::CompoundVal>(baseExprVal) || 1392 // FIXME: This can originate by conjuring a symbol for an unknown 1393 // temporary struct object, see test/Analysis/fields.c: 1394 // (p = getit()).x 1395 isa<nonloc::SymbolVal>(baseExprVal)) { 1396 MakeNode(Dst, M, Pred, state->BindExpr(M, UnknownVal())); 1397 return; 1398 } 1399 1400 // FIXME: Should we insert some assumption logic in here to determine 1401 // if "Base" is a valid piece of memory? Before we put this assumption 1402 // later when using FieldOffset lvals (which we no longer have). 1403 1404 // For all other cases, compute an lvalue. 1405 SVal L = state->getLValue(field, baseExprVal); 1406 if (M->isLValue()) 1407 MakeNode(Dst, M, Pred, state->BindExpr(M, L), ProgramPoint::PostLValueKind); 1408 else 1409 evalLoad(Dst, M, Pred, state, L); 1410 } 1411 1412 /// evalBind - Handle the semantics of binding a value to a specific location. 1413 /// This method is used by evalStore and (soon) VisitDeclStmt, and others. 1414 void ExprEngine::evalBind(ExplodedNodeSet& Dst, const Stmt* StoreE, 1415 ExplodedNode* Pred, const GRState* state, 1416 SVal location, SVal Val, bool atDeclInit) { 1417 1418 1419 // Do a previsit of the bind. 1420 ExplodedNodeSet CheckedSet, Src; 1421 Src.Add(Pred); 1422 getCheckerManager().runCheckersForBind(CheckedSet, Src, location, Val, StoreE, 1423 *this); 1424 1425 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 1426 I!=E; ++I) { 1427 1428 if (Pred != *I) 1429 state = (*I)->getState(); 1430 1431 const GRState* newState = 0; 1432 1433 if (atDeclInit) { 1434 const VarRegion *VR = 1435 cast<VarRegion>(cast<loc::MemRegionVal>(location).getRegion()); 1436 1437 newState = state->bindDecl(VR, Val); 1438 } 1439 else { 1440 if (location.isUnknown()) { 1441 // We know that the new state will be the same as the old state since 1442 // the location of the binding is "unknown". Consequently, there 1443 // is no reason to just create a new node. 1444 newState = state; 1445 } 1446 else { 1447 // We are binding to a value other than 'unknown'. Perform the binding 1448 // using the StoreManager. 1449 newState = state->bindLoc(cast<Loc>(location), Val); 1450 } 1451 } 1452 1453 // The next thing to do is check if the TransferFuncs object wants to 1454 // update the state based on the new binding. If the GRTransferFunc object 1455 // doesn't do anything, just auto-propagate the current state. 1456 1457 // NOTE: We use 'AssignE' for the location of the PostStore if 'AssignE' 1458 // is non-NULL. Checkers typically care about 1459 1460 StmtNodeBuilderRef BuilderRef(Dst, *Builder, *this, *I, newState, StoreE, 1461 true); 1462 1463 getTF().evalBind(BuilderRef, location, Val); 1464 } 1465 } 1466 1467 /// evalStore - Handle the semantics of a store via an assignment. 1468 /// @param Dst The node set to store generated state nodes 1469 /// @param AssignE The assignment expression if the store happens in an 1470 /// assignment. 1471 /// @param LocatioinE The location expression that is stored to. 1472 /// @param state The current simulation state 1473 /// @param location The location to store the value 1474 /// @param Val The value to be stored 1475 void ExprEngine::evalStore(ExplodedNodeSet& Dst, const Expr *AssignE, 1476 const Expr* LocationE, 1477 ExplodedNode* Pred, 1478 const GRState* state, SVal location, SVal Val, 1479 const void *tag) { 1480 1481 assert(Builder && "StmtNodeBuilder must be defined."); 1482 1483 // Proceed with the store. We use AssignE as the anchor for the PostStore 1484 // ProgramPoint if it is non-NULL, and LocationE otherwise. 1485 const Expr *StoreE = AssignE ? AssignE : LocationE; 1486 1487 if (isa<loc::ObjCPropRef>(location)) { 1488 loc::ObjCPropRef prop = cast<loc::ObjCPropRef>(location); 1489 return VisitObjCMessage(ObjCPropertySetter(prop.getPropRefExpr(), 1490 StoreE, Val), Pred, Dst); 1491 } 1492 1493 // Evaluate the location (checks for bad dereferences). 1494 ExplodedNodeSet Tmp; 1495 evalLocation(Tmp, LocationE, Pred, state, location, tag, false); 1496 1497 if (Tmp.empty()) 1498 return; 1499 1500 if (location.isUndef()) 1501 return; 1502 1503 SaveAndRestore<ProgramPoint::Kind> OldSPointKind(Builder->PointKind, 1504 ProgramPoint::PostStoreKind); 1505 1506 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) 1507 evalBind(Dst, StoreE, *NI, (*NI)->getState(), location, Val); 1508 } 1509 1510 void ExprEngine::evalLoad(ExplodedNodeSet& Dst, const Expr *Ex, 1511 ExplodedNode* Pred, 1512 const GRState* state, SVal location, 1513 const void *tag, QualType LoadTy) { 1514 assert(!isa<NonLoc>(location) && "location cannot be a NonLoc."); 1515 1516 if (isa<loc::ObjCPropRef>(location)) { 1517 loc::ObjCPropRef prop = cast<loc::ObjCPropRef>(location); 1518 return VisitObjCMessage(ObjCPropertyGetter(prop.getPropRefExpr(), Ex), 1519 Pred, Dst); 1520 } 1521 1522 // Are we loading from a region? This actually results in two loads; one 1523 // to fetch the address of the referenced value and one to fetch the 1524 // referenced value. 1525 if (const TypedRegion *TR = 1526 dyn_cast_or_null<TypedRegion>(location.getAsRegion())) { 1527 1528 QualType ValTy = TR->getValueType(); 1529 if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) { 1530 static int loadReferenceTag = 0; 1531 ExplodedNodeSet Tmp; 1532 evalLoadCommon(Tmp, Ex, Pred, state, location, &loadReferenceTag, 1533 getContext().getPointerType(RT->getPointeeType())); 1534 1535 // Perform the load from the referenced value. 1536 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) { 1537 state = (*I)->getState(); 1538 location = state->getSVal(Ex); 1539 evalLoadCommon(Dst, Ex, *I, state, location, tag, LoadTy); 1540 } 1541 return; 1542 } 1543 } 1544 1545 evalLoadCommon(Dst, Ex, Pred, state, location, tag, LoadTy); 1546 } 1547 1548 void ExprEngine::evalLoadCommon(ExplodedNodeSet& Dst, const Expr *Ex, 1549 ExplodedNode* Pred, 1550 const GRState* state, SVal location, 1551 const void *tag, QualType LoadTy) { 1552 1553 // Evaluate the location (checks for bad dereferences). 1554 ExplodedNodeSet Tmp; 1555 evalLocation(Tmp, Ex, Pred, state, location, tag, true); 1556 1557 if (Tmp.empty()) 1558 return; 1559 1560 if (location.isUndef()) 1561 return; 1562 1563 SaveAndRestore<ProgramPoint::Kind> OldSPointKind(Builder->PointKind); 1564 1565 // Proceed with the load. 1566 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) { 1567 state = (*NI)->getState(); 1568 1569 if (location.isUnknown()) { 1570 // This is important. We must nuke the old binding. 1571 MakeNode(Dst, Ex, *NI, state->BindExpr(Ex, UnknownVal()), 1572 ProgramPoint::PostLoadKind, tag); 1573 } 1574 else { 1575 if (LoadTy.isNull()) 1576 LoadTy = Ex->getType(); 1577 SVal V = state->getSVal(cast<Loc>(location), LoadTy); 1578 MakeNode(Dst, Ex, *NI, state->bindExprAndLocation(Ex, location, V), 1579 ProgramPoint::PostLoadKind, tag); 1580 } 1581 } 1582 } 1583 1584 void ExprEngine::evalLocation(ExplodedNodeSet &Dst, const Stmt *S, 1585 ExplodedNode* Pred, 1586 const GRState* state, SVal location, 1587 const void *tag, bool isLoad) { 1588 // Early checks for performance reason. 1589 if (location.isUnknown()) { 1590 Dst.Add(Pred); 1591 return; 1592 } 1593 1594 ExplodedNodeSet Src; 1595 if (Pred->getState() == state) { 1596 Src.Add(Pred); 1597 } else { 1598 // Associate this new state with an ExplodedNode. 1599 // FIXME: If I pass null tag, the graph is incorrect, e.g for 1600 // int *p; 1601 // p = 0; 1602 // *p = 0xDEADBEEF; 1603 // "p = 0" is not noted as "Null pointer value stored to 'p'" but 1604 // instead "int *p" is noted as 1605 // "Variable 'p' initialized to a null pointer value" 1606 ExplodedNode *N = Builder->generateNode(S, state, Pred, this); 1607 Src.Add(N ? N : Pred); 1608 } 1609 getCheckerManager().runCheckersForLocation(Dst, Src, location, isLoad, S, 1610 *this); 1611 } 1612 1613 bool ExprEngine::InlineCall(ExplodedNodeSet &Dst, const CallExpr *CE, 1614 ExplodedNode *Pred) { 1615 return false; 1616 1617 // Inlining isn't correct right now because we: 1618 // (a) don't generate CallExit nodes. 1619 // (b) we need a way to postpone doing post-visits of CallExprs until 1620 // the CallExit. This means we need CallExits for the non-inline 1621 // cases as well. 1622 1623 #if 0 1624 const GRState *state = Pred->getState(); 1625 const Expr *Callee = CE->getCallee(); 1626 SVal L = state->getSVal(Callee); 1627 1628 const FunctionDecl *FD = L.getAsFunctionDecl(); 1629 if (!FD) 1630 return false; 1631 1632 // Specially handle CXXMethods. 1633 const CXXMethodDecl *methodDecl = 0; 1634 1635 switch (CE->getStmtClass()) { 1636 default: break; 1637 case Stmt::CXXOperatorCallExprClass: { 1638 const CXXOperatorCallExpr *opCall = cast<CXXOperatorCallExpr>(CE); 1639 methodDecl = 1640 dyn_cast_or_null<CXXMethodDecl>(opCall->getCalleeDecl()); 1641 break; 1642 } 1643 case Stmt::CXXMemberCallExprClass: { 1644 const CXXMemberCallExpr *memberCall = cast<CXXMemberCallExpr>(CE); 1645 const MemberExpr *memberExpr = 1646 cast<MemberExpr>(memberCall->getCallee()->IgnoreParens()); 1647 methodDecl = cast<CXXMethodDecl>(memberExpr->getMemberDecl()); 1648 break; 1649 } 1650 } 1651 1652 1653 1654 1655 // Check if the function definition is in the same translation unit. 1656 if (FD->hasBody(FD)) { 1657 const StackFrameContext *stackFrame = 1658 AMgr.getStackFrame(AMgr.getAnalysisContext(FD), 1659 Pred->getLocationContext(), 1660 CE, Builder->getBlock(), Builder->getIndex()); 1661 // Now we have the definition of the callee, create a CallEnter node. 1662 CallEnter Loc(CE, stackFrame, Pred->getLocationContext()); 1663 1664 ExplodedNode *N = Builder->generateNode(Loc, state, Pred); 1665 Dst.Add(N); 1666 return true; 1667 } 1668 1669 // Check if we can find the function definition in other translation units. 1670 if (AMgr.hasIndexer()) { 1671 AnalysisContext *C = AMgr.getAnalysisContextInAnotherTU(FD); 1672 if (C == 0) 1673 return false; 1674 const StackFrameContext *stackFrame = 1675 AMgr.getStackFrame(C, Pred->getLocationContext(), 1676 CE, Builder->getBlock(), Builder->getIndex()); 1677 CallEnter Loc(CE, stackFrame, Pred->getLocationContext()); 1678 ExplodedNode *N = Builder->generateNode(Loc, state, Pred); 1679 Dst.Add(N); 1680 return true; 1681 } 1682 1683 // Generate the CallExit node. 1684 1685 return false; 1686 #endif 1687 } 1688 1689 void ExprEngine::VisitCallExpr(const CallExpr* CE, ExplodedNode* Pred, 1690 ExplodedNodeSet& dst) { 1691 // Perform the previsit of the CallExpr. 1692 ExplodedNodeSet dstPreVisit; 1693 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, CE, *this); 1694 1695 // Now evaluate the call itself. 1696 class DefaultEval : public GraphExpander { 1697 ExprEngine &Eng; 1698 const CallExpr *CE; 1699 public: 1700 1701 DefaultEval(ExprEngine &eng, const CallExpr *ce) 1702 : Eng(eng), CE(ce) {} 1703 virtual void expandGraph(ExplodedNodeSet &Dst, ExplodedNode *Pred) { 1704 // Should we inline the call? 1705 if (Eng.getAnalysisManager().shouldInlineCall() && 1706 Eng.InlineCall(Dst, CE, Pred)) { 1707 return; 1708 } 1709 1710 StmtNodeBuilder &Builder = Eng.getBuilder(); 1711 assert(&Builder && "StmtNodeBuilder must be defined."); 1712 1713 // Dispatch to the plug-in transfer function. 1714 unsigned oldSize = Dst.size(); 1715 SaveOr OldHasGen(Builder.hasGeneratedNode); 1716 1717 // Dispatch to transfer function logic to handle the call itself. 1718 const Expr* Callee = CE->getCallee()->IgnoreParens(); 1719 const GRState* state = Pred->getState(); 1720 SVal L = state->getSVal(Callee); 1721 Eng.getTF().evalCall(Dst, Eng, Builder, CE, L, Pred); 1722 1723 // Handle the case where no nodes where generated. Auto-generate that 1724 // contains the updated state if we aren't generating sinks. 1725 if (!Builder.BuildSinks && Dst.size() == oldSize && 1726 !Builder.hasGeneratedNode) 1727 Eng.MakeNode(Dst, CE, Pred, state); 1728 } 1729 }; 1730 1731 // Finally, evaluate the function call. We try each of the checkers 1732 // to see if the can evaluate the function call. 1733 ExplodedNodeSet dstCallEvaluated; 1734 DefaultEval defEval(*this, CE); 1735 getCheckerManager().runCheckersForEvalCall(dstCallEvaluated, 1736 dstPreVisit, 1737 CE, *this, &defEval); 1738 1739 // Finally, perform the post-condition check of the CallExpr and store 1740 // the created nodes in 'Dst'. 1741 getCheckerManager().runCheckersForPostStmt(dst, dstCallEvaluated, CE, 1742 *this); 1743 } 1744 1745 //===----------------------------------------------------------------------===// 1746 // Transfer function: Objective-C dot-syntax to access a property. 1747 //===----------------------------------------------------------------------===// 1748 1749 void ExprEngine::VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *Ex, 1750 ExplodedNode *Pred, 1751 ExplodedNodeSet &Dst) { 1752 MakeNode(Dst, Ex, Pred, Pred->getState()->BindExpr(Ex, loc::ObjCPropRef(Ex))); 1753 } 1754 1755 //===----------------------------------------------------------------------===// 1756 // Transfer function: Objective-C ivar references. 1757 //===----------------------------------------------------------------------===// 1758 1759 static std::pair<const void*,const void*> EagerlyAssumeTag 1760 = std::pair<const void*,const void*>(&EagerlyAssumeTag,static_cast<void*>(0)); 1761 1762 void ExprEngine::evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, 1763 const Expr *Ex) { 1764 for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) { 1765 ExplodedNode *Pred = *I; 1766 1767 // Test if the previous node was as the same expression. This can happen 1768 // when the expression fails to evaluate to anything meaningful and 1769 // (as an optimization) we don't generate a node. 1770 ProgramPoint P = Pred->getLocation(); 1771 if (!isa<PostStmt>(P) || cast<PostStmt>(P).getStmt() != Ex) { 1772 Dst.Add(Pred); 1773 continue; 1774 } 1775 1776 const GRState* state = Pred->getState(); 1777 SVal V = state->getSVal(Ex); 1778 if (nonloc::SymExprVal *SEV = dyn_cast<nonloc::SymExprVal>(&V)) { 1779 // First assume that the condition is true. 1780 if (const GRState *stateTrue = state->assume(*SEV, true)) { 1781 stateTrue = stateTrue->BindExpr(Ex, 1782 svalBuilder.makeIntVal(1U, Ex->getType())); 1783 Dst.Add(Builder->generateNode(PostStmtCustom(Ex, 1784 &EagerlyAssumeTag, Pred->getLocationContext()), 1785 stateTrue, Pred)); 1786 } 1787 1788 // Next, assume that the condition is false. 1789 if (const GRState *stateFalse = state->assume(*SEV, false)) { 1790 stateFalse = stateFalse->BindExpr(Ex, 1791 svalBuilder.makeIntVal(0U, Ex->getType())); 1792 Dst.Add(Builder->generateNode(PostStmtCustom(Ex, &EagerlyAssumeTag, 1793 Pred->getLocationContext()), 1794 stateFalse, Pred)); 1795 } 1796 } 1797 else 1798 Dst.Add(Pred); 1799 } 1800 } 1801 1802 //===----------------------------------------------------------------------===// 1803 // Transfer function: Objective-C @synchronized. 1804 //===----------------------------------------------------------------------===// 1805 1806 void ExprEngine::VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S, 1807 ExplodedNode *Pred, 1808 ExplodedNodeSet &Dst) { 1809 getCheckerManager().runCheckersForPreStmt(Dst, Pred, S, *this); 1810 } 1811 1812 //===----------------------------------------------------------------------===// 1813 // Transfer function: Objective-C ivar references. 1814 //===----------------------------------------------------------------------===// 1815 1816 void ExprEngine::VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr* Ex, 1817 ExplodedNode* Pred, 1818 ExplodedNodeSet& Dst) { 1819 1820 const GRState *state = Pred->getState(); 1821 SVal baseVal = state->getSVal(Ex->getBase()); 1822 SVal location = state->getLValue(Ex->getDecl(), baseVal); 1823 1824 ExplodedNodeSet dstIvar; 1825 MakeNode(dstIvar, Ex, Pred, state->BindExpr(Ex, location)); 1826 1827 // Perform the post-condition check of the ObjCIvarRefExpr and store 1828 // the created nodes in 'Dst'. 1829 getCheckerManager().runCheckersForPostStmt(Dst, dstIvar, Ex, *this); 1830 } 1831 1832 //===----------------------------------------------------------------------===// 1833 // Transfer function: Objective-C fast enumeration 'for' statements. 1834 //===----------------------------------------------------------------------===// 1835 1836 void ExprEngine::VisitObjCForCollectionStmt(const ObjCForCollectionStmt* S, 1837 ExplodedNode* Pred, ExplodedNodeSet& Dst) { 1838 1839 // ObjCForCollectionStmts are processed in two places. This method 1840 // handles the case where an ObjCForCollectionStmt* occurs as one of the 1841 // statements within a basic block. This transfer function does two things: 1842 // 1843 // (1) binds the next container value to 'element'. This creates a new 1844 // node in the ExplodedGraph. 1845 // 1846 // (2) binds the value 0/1 to the ObjCForCollectionStmt* itself, indicating 1847 // whether or not the container has any more elements. This value 1848 // will be tested in ProcessBranch. We need to explicitly bind 1849 // this value because a container can contain nil elements. 1850 // 1851 // FIXME: Eventually this logic should actually do dispatches to 1852 // 'countByEnumeratingWithState:objects:count:' (NSFastEnumeration). 1853 // This will require simulating a temporary NSFastEnumerationState, either 1854 // through an SVal or through the use of MemRegions. This value can 1855 // be affixed to the ObjCForCollectionStmt* instead of 0/1; when the loop 1856 // terminates we reclaim the temporary (it goes out of scope) and we 1857 // we can test if the SVal is 0 or if the MemRegion is null (depending 1858 // on what approach we take). 1859 // 1860 // For now: simulate (1) by assigning either a symbol or nil if the 1861 // container is empty. Thus this transfer function will by default 1862 // result in state splitting. 1863 1864 const Stmt* elem = S->getElement(); 1865 const GRState *state = Pred->getState(); 1866 SVal elementV; 1867 1868 if (const DeclStmt* DS = dyn_cast<DeclStmt>(elem)) { 1869 const VarDecl* elemD = cast<VarDecl>(DS->getSingleDecl()); 1870 assert(elemD->getInit() == 0); 1871 elementV = state->getLValue(elemD, Pred->getLocationContext()); 1872 } 1873 else { 1874 elementV = state->getSVal(elem); 1875 } 1876 1877 ExplodedNodeSet dstLocation; 1878 evalLocation(dstLocation, elem, Pred, state, elementV, NULL, false); 1879 1880 if (dstLocation.empty()) 1881 return; 1882 1883 for (ExplodedNodeSet::iterator NI = dstLocation.begin(), 1884 NE = dstLocation.end(); NI!=NE; ++NI) { 1885 Pred = *NI; 1886 const GRState *state = Pred->getState(); 1887 1888 // Handle the case where the container still has elements. 1889 SVal TrueV = svalBuilder.makeTruthVal(1); 1890 const GRState *hasElems = state->BindExpr(S, TrueV); 1891 1892 // Handle the case where the container has no elements. 1893 SVal FalseV = svalBuilder.makeTruthVal(0); 1894 const GRState *noElems = state->BindExpr(S, FalseV); 1895 1896 if (loc::MemRegionVal *MV = dyn_cast<loc::MemRegionVal>(&elementV)) 1897 if (const TypedRegion *R = dyn_cast<TypedRegion>(MV->getRegion())) { 1898 // FIXME: The proper thing to do is to really iterate over the 1899 // container. We will do this with dispatch logic to the store. 1900 // For now, just 'conjure' up a symbolic value. 1901 QualType T = R->getValueType(); 1902 assert(Loc::isLocType(T)); 1903 unsigned Count = Builder->getCurrentBlockCount(); 1904 SymbolRef Sym = SymMgr.getConjuredSymbol(elem, T, Count); 1905 SVal V = svalBuilder.makeLoc(Sym); 1906 hasElems = hasElems->bindLoc(elementV, V); 1907 1908 // Bind the location to 'nil' on the false branch. 1909 SVal nilV = svalBuilder.makeIntVal(0, T); 1910 noElems = noElems->bindLoc(elementV, nilV); 1911 } 1912 1913 // Create the new nodes. 1914 MakeNode(Dst, S, Pred, hasElems); 1915 MakeNode(Dst, S, Pred, noElems); 1916 } 1917 } 1918 1919 //===----------------------------------------------------------------------===// 1920 // Transfer function: Objective-C message expressions. 1921 //===----------------------------------------------------------------------===// 1922 1923 void ExprEngine::VisitObjCMessage(const ObjCMessage &msg, 1924 ExplodedNode *Pred, ExplodedNodeSet& Dst) { 1925 1926 // Handle the previsits checks. 1927 ExplodedNodeSet dstPrevisit; 1928 getCheckerManager().runCheckersForPreObjCMessage(dstPrevisit, Pred, 1929 msg, *this); 1930 1931 // Proceed with evaluate the message expression. 1932 ExplodedNodeSet dstEval; 1933 1934 for (ExplodedNodeSet::iterator DI = dstPrevisit.begin(), 1935 DE = dstPrevisit.end(); DI != DE; ++DI) { 1936 1937 ExplodedNode *Pred = *DI; 1938 bool RaisesException = false; 1939 unsigned oldSize = dstEval.size(); 1940 SaveAndRestore<bool> OldSink(Builder->BuildSinks); 1941 SaveOr OldHasGen(Builder->hasGeneratedNode); 1942 1943 if (const Expr *Receiver = msg.getInstanceReceiver()) { 1944 const GRState *state = Pred->getState(); 1945 SVal recVal = state->getSVal(Receiver); 1946 if (!recVal.isUndef()) { 1947 // Bifurcate the state into nil and non-nil ones. 1948 DefinedOrUnknownSVal receiverVal = cast<DefinedOrUnknownSVal>(recVal); 1949 1950 const GRState *notNilState, *nilState; 1951 llvm::tie(notNilState, nilState) = state->assume(receiverVal); 1952 1953 // There are three cases: can be nil or non-nil, must be nil, must be 1954 // non-nil. We ignore must be nil, and merge the rest two into non-nil. 1955 if (nilState && !notNilState) { 1956 dstEval.insert(Pred); 1957 continue; 1958 } 1959 1960 // Check if the "raise" message was sent. 1961 assert(notNilState); 1962 if (msg.getSelector() == RaiseSel) 1963 RaisesException = true; 1964 1965 // Check if we raise an exception. For now treat these as sinks. 1966 // Eventually we will want to handle exceptions properly. 1967 if (RaisesException) 1968 Builder->BuildSinks = true; 1969 1970 // Dispatch to plug-in transfer function. 1971 evalObjCMessage(dstEval, msg, Pred, notNilState); 1972 } 1973 } 1974 else if (const ObjCInterfaceDecl *Iface = msg.getReceiverInterface()) { 1975 IdentifierInfo* ClsName = Iface->getIdentifier(); 1976 Selector S = msg.getSelector(); 1977 1978 // Check for special instance methods. 1979 if (!NSExceptionII) { 1980 ASTContext& Ctx = getContext(); 1981 NSExceptionII = &Ctx.Idents.get("NSException"); 1982 } 1983 1984 if (ClsName == NSExceptionII) { 1985 enum { NUM_RAISE_SELECTORS = 2 }; 1986 1987 // Lazily create a cache of the selectors. 1988 if (!NSExceptionInstanceRaiseSelectors) { 1989 ASTContext& Ctx = getContext(); 1990 NSExceptionInstanceRaiseSelectors = 1991 new Selector[NUM_RAISE_SELECTORS]; 1992 SmallVector<IdentifierInfo*, NUM_RAISE_SELECTORS> II; 1993 unsigned idx = 0; 1994 1995 // raise:format: 1996 II.push_back(&Ctx.Idents.get("raise")); 1997 II.push_back(&Ctx.Idents.get("format")); 1998 NSExceptionInstanceRaiseSelectors[idx++] = 1999 Ctx.Selectors.getSelector(II.size(), &II[0]); 2000 2001 // raise:format::arguments: 2002 II.push_back(&Ctx.Idents.get("arguments")); 2003 NSExceptionInstanceRaiseSelectors[idx++] = 2004 Ctx.Selectors.getSelector(II.size(), &II[0]); 2005 } 2006 2007 for (unsigned i = 0; i < NUM_RAISE_SELECTORS; ++i) 2008 if (S == NSExceptionInstanceRaiseSelectors[i]) { 2009 RaisesException = true; 2010 break; 2011 } 2012 } 2013 2014 // Check if we raise an exception. For now treat these as sinks. 2015 // Eventually we will want to handle exceptions properly. 2016 if (RaisesException) 2017 Builder->BuildSinks = true; 2018 2019 // Dispatch to plug-in transfer function. 2020 evalObjCMessage(dstEval, msg, Pred, Pred->getState()); 2021 } 2022 2023 // Handle the case where no nodes where generated. Auto-generate that 2024 // contains the updated state if we aren't generating sinks. 2025 if (!Builder->BuildSinks && dstEval.size() == oldSize && 2026 !Builder->hasGeneratedNode) 2027 MakeNode(dstEval, msg.getOriginExpr(), Pred, Pred->getState()); 2028 } 2029 2030 // Finally, perform the post-condition check of the ObjCMessageExpr and store 2031 // the created nodes in 'Dst'. 2032 getCheckerManager().runCheckersForPostObjCMessage(Dst, dstEval, msg, *this); 2033 } 2034 2035 //===----------------------------------------------------------------------===// 2036 // Transfer functions: Miscellaneous statements. 2037 //===----------------------------------------------------------------------===// 2038 2039 void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex, 2040 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 2041 2042 ExplodedNodeSet dstPreStmt; 2043 getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this); 2044 2045 if (CastE->getCastKind() == CK_LValueToRValue || 2046 CastE->getCastKind() == CK_GetObjCProperty) { 2047 for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end(); 2048 I!=E; ++I) { 2049 ExplodedNode *subExprNode = *I; 2050 const GRState *state = subExprNode->getState(); 2051 evalLoad(Dst, CastE, subExprNode, state, state->getSVal(Ex)); 2052 } 2053 return; 2054 } 2055 2056 // All other casts. 2057 QualType T = CastE->getType(); 2058 QualType ExTy = Ex->getType(); 2059 2060 if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE)) 2061 T = ExCast->getTypeAsWritten(); 2062 2063 for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end(); 2064 I != E; ++I) { 2065 2066 Pred = *I; 2067 2068 switch (CastE->getCastKind()) { 2069 case CK_LValueToRValue: 2070 assert(false && "LValueToRValue casts handled earlier."); 2071 case CK_GetObjCProperty: 2072 assert(false && "GetObjCProperty casts handled earlier."); 2073 case CK_ToVoid: 2074 Dst.Add(Pred); 2075 continue; 2076 // The analyzer doesn't do anything special with these casts, 2077 // since it understands retain/release semantics already. 2078 case CK_ObjCProduceObject: 2079 case CK_ObjCConsumeObject: 2080 case CK_ObjCReclaimReturnedObject: // Fall-through. 2081 // True no-ops. 2082 case CK_NoOp: 2083 case CK_FunctionToPointerDecay: { 2084 // Copy the SVal of Ex to CastE. 2085 const GRState *state = Pred->getState(); 2086 SVal V = state->getSVal(Ex); 2087 state = state->BindExpr(CastE, V); 2088 MakeNode(Dst, CastE, Pred, state); 2089 continue; 2090 } 2091 case CK_Dependent: 2092 case CK_ArrayToPointerDecay: 2093 case CK_BitCast: 2094 case CK_LValueBitCast: 2095 case CK_IntegralCast: 2096 case CK_NullToPointer: 2097 case CK_IntegralToPointer: 2098 case CK_PointerToIntegral: 2099 case CK_PointerToBoolean: 2100 case CK_IntegralToBoolean: 2101 case CK_IntegralToFloating: 2102 case CK_FloatingToIntegral: 2103 case CK_FloatingToBoolean: 2104 case CK_FloatingCast: 2105 case CK_FloatingRealToComplex: 2106 case CK_FloatingComplexToReal: 2107 case CK_FloatingComplexToBoolean: 2108 case CK_FloatingComplexCast: 2109 case CK_FloatingComplexToIntegralComplex: 2110 case CK_IntegralRealToComplex: 2111 case CK_IntegralComplexToReal: 2112 case CK_IntegralComplexToBoolean: 2113 case CK_IntegralComplexCast: 2114 case CK_IntegralComplexToFloatingComplex: 2115 case CK_AnyPointerToObjCPointerCast: 2116 case CK_AnyPointerToBlockPointerCast: 2117 case CK_ObjCObjectLValueCast: { 2118 // Delegate to SValBuilder to process. 2119 const GRState* state = Pred->getState(); 2120 SVal V = state->getSVal(Ex); 2121 V = svalBuilder.evalCast(V, T, ExTy); 2122 state = state->BindExpr(CastE, V); 2123 MakeNode(Dst, CastE, Pred, state); 2124 continue; 2125 } 2126 case CK_DerivedToBase: 2127 case CK_UncheckedDerivedToBase: { 2128 // For DerivedToBase cast, delegate to the store manager. 2129 const GRState *state = Pred->getState(); 2130 SVal val = state->getSVal(Ex); 2131 val = getStoreManager().evalDerivedToBase(val, T); 2132 state = state->BindExpr(CastE, val); 2133 MakeNode(Dst, CastE, Pred, state); 2134 continue; 2135 } 2136 // Various C++ casts that are not handled yet. 2137 case CK_Dynamic: 2138 case CK_ToUnion: 2139 case CK_BaseToDerived: 2140 case CK_NullToMemberPointer: 2141 case CK_BaseToDerivedMemberPointer: 2142 case CK_DerivedToBaseMemberPointer: 2143 case CK_UserDefinedConversion: 2144 case CK_ConstructorConversion: 2145 case CK_VectorSplat: 2146 case CK_MemberPointerToBoolean: { 2147 // Recover some path-sensitivty by conjuring a new value. 2148 QualType resultType = CastE->getType(); 2149 if (CastE->isLValue()) 2150 resultType = getContext().getPointerType(resultType); 2151 2152 SVal result = 2153 svalBuilder.getConjuredSymbolVal(NULL, CastE, resultType, 2154 Builder->getCurrentBlockCount()); 2155 2156 const GRState *state = Pred->getState()->BindExpr(CastE, result); 2157 MakeNode(Dst, CastE, Pred, state); 2158 continue; 2159 } 2160 } 2161 } 2162 } 2163 2164 void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr* CL, 2165 ExplodedNode* Pred, 2166 ExplodedNodeSet& Dst) { 2167 const InitListExpr* ILE 2168 = cast<InitListExpr>(CL->getInitializer()->IgnoreParens()); 2169 2170 const GRState* state = Pred->getState(); 2171 SVal ILV = state->getSVal(ILE); 2172 2173 const LocationContext *LC = Pred->getLocationContext(); 2174 state = state->bindCompoundLiteral(CL, LC, ILV); 2175 2176 if (CL->isLValue()) { 2177 MakeNode(Dst, CL, Pred, state->BindExpr(CL, state->getLValue(CL, LC))); 2178 } 2179 else 2180 MakeNode(Dst, CL, Pred, state->BindExpr(CL, ILV)); 2181 } 2182 2183 void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, 2184 ExplodedNodeSet& Dst) { 2185 2186 // FIXME: static variables may have an initializer, but the second 2187 // time a function is called those values may not be current. 2188 // This may need to be reflected in the CFG. 2189 2190 // Assumption: The CFG has one DeclStmt per Decl. 2191 const Decl* D = *DS->decl_begin(); 2192 2193 if (!D || !isa<VarDecl>(D)) 2194 return; 2195 2196 2197 ExplodedNodeSet dstPreVisit; 2198 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this); 2199 2200 const VarDecl *VD = dyn_cast<VarDecl>(D); 2201 2202 for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end(); 2203 I!=E; ++I) 2204 { 2205 ExplodedNode *N = *I; 2206 const GRState *state = N->getState(); 2207 2208 // Decls without InitExpr are not initialized explicitly. 2209 const LocationContext *LC = N->getLocationContext(); 2210 2211 if (const Expr *InitEx = VD->getInit()) { 2212 SVal InitVal = state->getSVal(InitEx); 2213 2214 // We bound the temp obj region to the CXXConstructExpr. Now recover 2215 // the lazy compound value when the variable is not a reference. 2216 if (AMgr.getLangOptions().CPlusPlus && VD->getType()->isRecordType() && 2217 !VD->getType()->isReferenceType() && isa<loc::MemRegionVal>(InitVal)){ 2218 InitVal = state->getSVal(cast<loc::MemRegionVal>(InitVal).getRegion()); 2219 assert(isa<nonloc::LazyCompoundVal>(InitVal)); 2220 } 2221 2222 // Recover some path-sensitivity if a scalar value evaluated to 2223 // UnknownVal. 2224 if ((InitVal.isUnknown() || 2225 !getConstraintManager().canReasonAbout(InitVal)) && 2226 !VD->getType()->isReferenceType()) { 2227 InitVal = svalBuilder.getConjuredSymbolVal(NULL, InitEx, 2228 Builder->getCurrentBlockCount()); 2229 } 2230 2231 evalBind(Dst, DS, N, state, 2232 loc::MemRegionVal(state->getRegion(VD, LC)), InitVal, true); 2233 } 2234 else { 2235 MakeNode(Dst, DS, N, state->bindDeclWithNoInit(state->getRegion(VD, LC))); 2236 } 2237 } 2238 } 2239 2240 void ExprEngine::VisitInitListExpr(const InitListExpr *IE, ExplodedNode *Pred, 2241 ExplodedNodeSet& Dst) { 2242 2243 const GRState* state = Pred->getState(); 2244 QualType T = getContext().getCanonicalType(IE->getType()); 2245 unsigned NumInitElements = IE->getNumInits(); 2246 2247 if (T->isArrayType() || T->isRecordType() || T->isVectorType()) { 2248 llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList(); 2249 2250 // Handle base case where the initializer has no elements. 2251 // e.g: static int* myArray[] = {}; 2252 if (NumInitElements == 0) { 2253 SVal V = svalBuilder.makeCompoundVal(T, vals); 2254 MakeNode(Dst, IE, Pred, state->BindExpr(IE, V)); 2255 return; 2256 } 2257 2258 for (InitListExpr::const_reverse_iterator it = IE->rbegin(), 2259 ei = IE->rend(); it != ei; ++it) { 2260 vals = getBasicVals().consVals(state->getSVal(cast<Expr>(*it)), vals); 2261 } 2262 2263 MakeNode(Dst, IE, Pred, 2264 state->BindExpr(IE, svalBuilder.makeCompoundVal(T, vals))); 2265 return; 2266 } 2267 2268 if (Loc::isLocType(T) || T->isIntegerType()) { 2269 assert(IE->getNumInits() == 1); 2270 const Expr *initEx = IE->getInit(0); 2271 MakeNode(Dst, IE, Pred, state->BindExpr(IE, state->getSVal(initEx))); 2272 return; 2273 } 2274 2275 llvm_unreachable("unprocessed InitListExpr type"); 2276 } 2277 2278 /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof(type). 2279 void ExprEngine::VisitUnaryExprOrTypeTraitExpr( 2280 const UnaryExprOrTypeTraitExpr* Ex, 2281 ExplodedNode* Pred, 2282 ExplodedNodeSet& Dst) { 2283 QualType T = Ex->getTypeOfArgument(); 2284 2285 if (Ex->getKind() == UETT_SizeOf) { 2286 if (!T->isIncompleteType() && !T->isConstantSizeType()) { 2287 assert(T->isVariableArrayType() && "Unknown non-constant-sized type."); 2288 2289 // FIXME: Add support for VLA type arguments, not just VLA expressions. 2290 // When that happens, we should probably refactor VLASizeChecker's code. 2291 if (Ex->isArgumentType()) { 2292 Dst.Add(Pred); 2293 return; 2294 } 2295 2296 // Get the size by getting the extent of the sub-expression. 2297 // First, visit the sub-expression to find its region. 2298 const Expr *Arg = Ex->getArgumentExpr(); 2299 const GRState *state = Pred->getState(); 2300 const MemRegion *MR = state->getSVal(Arg).getAsRegion(); 2301 2302 // If the subexpression can't be resolved to a region, we don't know 2303 // anything about its size. Just leave the state as is and continue. 2304 if (!MR) { 2305 Dst.Add(Pred); 2306 return; 2307 } 2308 2309 // The result is the extent of the VLA. 2310 SVal Extent = cast<SubRegion>(MR)->getExtent(svalBuilder); 2311 MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, Extent)); 2312 2313 return; 2314 } 2315 else if (T->getAs<ObjCObjectType>()) { 2316 // Some code tries to take the sizeof an ObjCObjectType, relying that 2317 // the compiler has laid out its representation. Just report Unknown 2318 // for these. 2319 Dst.Add(Pred); 2320 return; 2321 } 2322 } 2323 2324 Expr::EvalResult Result; 2325 Ex->Evaluate(Result, getContext()); 2326 CharUnits amt = CharUnits::fromQuantity(Result.Val.getInt().getZExtValue()); 2327 2328 MakeNode(Dst, Ex, Pred, 2329 Pred->getState()->BindExpr(Ex, 2330 svalBuilder.makeIntVal(amt.getQuantity(), Ex->getType()))); 2331 } 2332 2333 void ExprEngine::VisitOffsetOfExpr(const OffsetOfExpr* OOE, 2334 ExplodedNode* Pred, ExplodedNodeSet& Dst) { 2335 Expr::EvalResult Res; 2336 if (OOE->Evaluate(Res, getContext()) && Res.Val.isInt()) { 2337 const APSInt &IV = Res.Val.getInt(); 2338 assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType())); 2339 assert(OOE->getType()->isIntegerType()); 2340 assert(IV.isSigned() == OOE->getType()->isSignedIntegerOrEnumerationType()); 2341 SVal X = svalBuilder.makeIntVal(IV); 2342 MakeNode(Dst, OOE, Pred, Pred->getState()->BindExpr(OOE, X)); 2343 return; 2344 } 2345 // FIXME: Handle the case where __builtin_offsetof is not a constant. 2346 Dst.Add(Pred); 2347 } 2348 2349 void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, 2350 ExplodedNode* Pred, 2351 ExplodedNodeSet& Dst) { 2352 2353 switch (U->getOpcode()) { 2354 2355 default: 2356 break; 2357 2358 case UO_Real: { 2359 const Expr* Ex = U->getSubExpr()->IgnoreParens(); 2360 ExplodedNodeSet Tmp; 2361 Visit(Ex, Pred, Tmp); 2362 2363 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { 2364 2365 // FIXME: We don't have complex SValues yet. 2366 if (Ex->getType()->isAnyComplexType()) { 2367 // Just report "Unknown." 2368 Dst.Add(*I); 2369 continue; 2370 } 2371 2372 // For all other types, UO_Real is an identity operation. 2373 assert (U->getType() == Ex->getType()); 2374 const GRState* state = (*I)->getState(); 2375 MakeNode(Dst, U, *I, state->BindExpr(U, state->getSVal(Ex))); 2376 } 2377 2378 return; 2379 } 2380 2381 case UO_Imag: { 2382 2383 const Expr* Ex = U->getSubExpr()->IgnoreParens(); 2384 ExplodedNodeSet Tmp; 2385 Visit(Ex, Pred, Tmp); 2386 2387 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { 2388 // FIXME: We don't have complex SValues yet. 2389 if (Ex->getType()->isAnyComplexType()) { 2390 // Just report "Unknown." 2391 Dst.Add(*I); 2392 continue; 2393 } 2394 2395 // For all other types, UO_Imag returns 0. 2396 const GRState* state = (*I)->getState(); 2397 SVal X = svalBuilder.makeZeroVal(Ex->getType()); 2398 MakeNode(Dst, U, *I, state->BindExpr(U, X)); 2399 } 2400 2401 return; 2402 } 2403 2404 case UO_Plus: 2405 assert(!U->isLValue()); 2406 // FALL-THROUGH. 2407 case UO_Deref: 2408 case UO_AddrOf: 2409 case UO_Extension: { 2410 2411 // Unary "+" is a no-op, similar to a parentheses. We still have places 2412 // where it may be a block-level expression, so we need to 2413 // generate an extra node that just propagates the value of the 2414 // subexpression. 2415 2416 const Expr* Ex = U->getSubExpr()->IgnoreParens(); 2417 ExplodedNodeSet Tmp; 2418 Visit(Ex, Pred, Tmp); 2419 2420 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { 2421 const GRState* state = (*I)->getState(); 2422 MakeNode(Dst, U, *I, state->BindExpr(U, state->getSVal(Ex))); 2423 } 2424 2425 return; 2426 } 2427 2428 case UO_LNot: 2429 case UO_Minus: 2430 case UO_Not: { 2431 assert (!U->isLValue()); 2432 const Expr* Ex = U->getSubExpr()->IgnoreParens(); 2433 ExplodedNodeSet Tmp; 2434 Visit(Ex, Pred, Tmp); 2435 2436 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { 2437 const GRState* state = (*I)->getState(); 2438 2439 // Get the value of the subexpression. 2440 SVal V = state->getSVal(Ex); 2441 2442 if (V.isUnknownOrUndef()) { 2443 MakeNode(Dst, U, *I, state->BindExpr(U, V)); 2444 continue; 2445 } 2446 2447 // QualType DstT = getContext().getCanonicalType(U->getType()); 2448 // QualType SrcT = getContext().getCanonicalType(Ex->getType()); 2449 // 2450 // if (DstT != SrcT) // Perform promotions. 2451 // V = evalCast(V, DstT); 2452 // 2453 // if (V.isUnknownOrUndef()) { 2454 // MakeNode(Dst, U, *I, BindExpr(St, U, V)); 2455 // continue; 2456 // } 2457 2458 switch (U->getOpcode()) { 2459 default: 2460 assert(false && "Invalid Opcode."); 2461 break; 2462 2463 case UO_Not: 2464 // FIXME: Do we need to handle promotions? 2465 state = state->BindExpr(U, evalComplement(cast<NonLoc>(V))); 2466 break; 2467 2468 case UO_Minus: 2469 // FIXME: Do we need to handle promotions? 2470 state = state->BindExpr(U, evalMinus(cast<NonLoc>(V))); 2471 break; 2472 2473 case UO_LNot: 2474 2475 // C99 6.5.3.3: "The expression !E is equivalent to (0==E)." 2476 // 2477 // Note: technically we do "E == 0", but this is the same in the 2478 // transfer functions as "0 == E". 2479 SVal Result; 2480 2481 if (isa<Loc>(V)) { 2482 Loc X = svalBuilder.makeNull(); 2483 Result = evalBinOp(state, BO_EQ, cast<Loc>(V), X, 2484 U->getType()); 2485 } 2486 else { 2487 nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType())); 2488 Result = evalBinOp(state, BO_EQ, cast<NonLoc>(V), X, 2489 U->getType()); 2490 } 2491 2492 state = state->BindExpr(U, Result); 2493 2494 break; 2495 } 2496 2497 MakeNode(Dst, U, *I, state); 2498 } 2499 2500 return; 2501 } 2502 } 2503 2504 // Handle ++ and -- (both pre- and post-increment). 2505 assert (U->isIncrementDecrementOp()); 2506 ExplodedNodeSet Tmp; 2507 const Expr* Ex = U->getSubExpr()->IgnoreParens(); 2508 Visit(Ex, Pred, Tmp); 2509 2510 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I) { 2511 2512 const GRState* state = (*I)->getState(); 2513 SVal loc = state->getSVal(Ex); 2514 2515 // Perform a load. 2516 ExplodedNodeSet Tmp2; 2517 evalLoad(Tmp2, Ex, *I, state, loc); 2518 2519 for (ExplodedNodeSet::iterator I2=Tmp2.begin(), E2=Tmp2.end();I2!=E2;++I2) { 2520 2521 state = (*I2)->getState(); 2522 SVal V2_untested = state->getSVal(Ex); 2523 2524 // Propagate unknown and undefined values. 2525 if (V2_untested.isUnknownOrUndef()) { 2526 MakeNode(Dst, U, *I2, state->BindExpr(U, V2_untested)); 2527 continue; 2528 } 2529 DefinedSVal V2 = cast<DefinedSVal>(V2_untested); 2530 2531 // Handle all other values. 2532 BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add 2533 : BO_Sub; 2534 2535 // If the UnaryOperator has non-location type, use its type to create the 2536 // constant value. If the UnaryOperator has location type, create the 2537 // constant with int type and pointer width. 2538 SVal RHS; 2539 2540 if (U->getType()->isAnyPointerType()) 2541 RHS = svalBuilder.makeArrayIndex(1); 2542 else 2543 RHS = svalBuilder.makeIntVal(1, U->getType()); 2544 2545 SVal Result = evalBinOp(state, Op, V2, RHS, U->getType()); 2546 2547 // Conjure a new symbol if necessary to recover precision. 2548 if (Result.isUnknown() || !getConstraintManager().canReasonAbout(Result)){ 2549 DefinedOrUnknownSVal SymVal = 2550 svalBuilder.getConjuredSymbolVal(NULL, Ex, 2551 Builder->getCurrentBlockCount()); 2552 Result = SymVal; 2553 2554 // If the value is a location, ++/-- should always preserve 2555 // non-nullness. Check if the original value was non-null, and if so 2556 // propagate that constraint. 2557 if (Loc::isLocType(U->getType())) { 2558 DefinedOrUnknownSVal Constraint = 2559 svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType())); 2560 2561 if (!state->assume(Constraint, true)) { 2562 // It isn't feasible for the original value to be null. 2563 // Propagate this constraint. 2564 Constraint = svalBuilder.evalEQ(state, SymVal, 2565 svalBuilder.makeZeroVal(U->getType())); 2566 2567 2568 state = state->assume(Constraint, false); 2569 assert(state); 2570 } 2571 } 2572 } 2573 2574 // Since the lvalue-to-rvalue conversion is explicit in the AST, 2575 // we bind an l-value if the operator is prefix and an lvalue (in C++). 2576 if (U->isLValue()) 2577 state = state->BindExpr(U, loc); 2578 else 2579 state = state->BindExpr(U, U->isPostfix() ? V2 : Result); 2580 2581 // Perform the store. 2582 evalStore(Dst, NULL, U, *I2, state, loc, Result); 2583 } 2584 } 2585 } 2586 2587 void ExprEngine::VisitAsmStmt(const AsmStmt* A, ExplodedNode* Pred, 2588 ExplodedNodeSet& Dst) { 2589 VisitAsmStmtHelperOutputs(A, A->begin_outputs(), A->end_outputs(), Pred, Dst); 2590 } 2591 2592 void ExprEngine::VisitAsmStmtHelperOutputs(const AsmStmt* A, 2593 AsmStmt::const_outputs_iterator I, 2594 AsmStmt::const_outputs_iterator E, 2595 ExplodedNode* Pred, ExplodedNodeSet& Dst) { 2596 if (I == E) { 2597 VisitAsmStmtHelperInputs(A, A->begin_inputs(), A->end_inputs(), Pred, Dst); 2598 return; 2599 } 2600 2601 ExplodedNodeSet Tmp; 2602 Visit(*I, Pred, Tmp); 2603 ++I; 2604 2605 for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end();NI != NE;++NI) 2606 VisitAsmStmtHelperOutputs(A, I, E, *NI, Dst); 2607 } 2608 2609 void ExprEngine::VisitAsmStmtHelperInputs(const AsmStmt* A, 2610 AsmStmt::const_inputs_iterator I, 2611 AsmStmt::const_inputs_iterator E, 2612 ExplodedNode* Pred, 2613 ExplodedNodeSet& Dst) { 2614 if (I == E) { 2615 2616 // We have processed both the inputs and the outputs. All of the outputs 2617 // should evaluate to Locs. Nuke all of their values. 2618 2619 // FIXME: Some day in the future it would be nice to allow a "plug-in" 2620 // which interprets the inline asm and stores proper results in the 2621 // outputs. 2622 2623 const GRState* state = Pred->getState(); 2624 2625 for (AsmStmt::const_outputs_iterator OI = A->begin_outputs(), 2626 OE = A->end_outputs(); OI != OE; ++OI) { 2627 2628 SVal X = state->getSVal(*OI); 2629 assert (!isa<NonLoc>(X)); // Should be an Lval, or unknown, undef. 2630 2631 if (isa<Loc>(X)) 2632 state = state->bindLoc(cast<Loc>(X), UnknownVal()); 2633 } 2634 2635 MakeNode(Dst, A, Pred, state); 2636 return; 2637 } 2638 2639 ExplodedNodeSet Tmp; 2640 Visit(*I, Pred, Tmp); 2641 2642 ++I; 2643 2644 for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end(); NI!=NE; ++NI) 2645 VisitAsmStmtHelperInputs(A, I, E, *NI, Dst); 2646 } 2647 2648 void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred, 2649 ExplodedNodeSet &Dst) { 2650 ExplodedNodeSet Src; 2651 if (const Expr *RetE = RS->getRetValue()) { 2652 // Record the returned expression in the state. It will be used in 2653 // processCallExit to bind the return value to the call expr. 2654 { 2655 static int tag = 0; 2656 const GRState *state = Pred->getState(); 2657 state = state->set<ReturnExpr>(RetE); 2658 Pred = Builder->generateNode(RetE, state, Pred, &tag); 2659 } 2660 // We may get a NULL Pred because we generated a cached node. 2661 if (Pred) 2662 Visit(RetE, Pred, Src); 2663 } 2664 else { 2665 Src.Add(Pred); 2666 } 2667 2668 ExplodedNodeSet CheckedSet; 2669 getCheckerManager().runCheckersForPreStmt(CheckedSet, Src, RS, *this); 2670 2671 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 2672 I != E; ++I) { 2673 2674 assert(Builder && "StmtNodeBuilder must be defined."); 2675 2676 Pred = *I; 2677 unsigned size = Dst.size(); 2678 2679 SaveAndRestore<bool> OldSink(Builder->BuildSinks); 2680 SaveOr OldHasGen(Builder->hasGeneratedNode); 2681 2682 getTF().evalReturn(Dst, *this, *Builder, RS, Pred); 2683 2684 // Handle the case where no nodes where generated. 2685 if (!Builder->BuildSinks && Dst.size() == size && 2686 !Builder->hasGeneratedNode) 2687 MakeNode(Dst, RS, Pred, Pred->getState()); 2688 } 2689 } 2690 2691 //===----------------------------------------------------------------------===// 2692 // Transfer functions: Binary operators. 2693 //===----------------------------------------------------------------------===// 2694 2695 void ExprEngine::VisitBinaryOperator(const BinaryOperator* B, 2696 ExplodedNode* Pred, 2697 ExplodedNodeSet& Dst) { 2698 ExplodedNodeSet Tmp1; 2699 Expr* LHS = B->getLHS()->IgnoreParens(); 2700 Expr* RHS = B->getRHS()->IgnoreParens(); 2701 2702 Visit(LHS, Pred, Tmp1); 2703 ExplodedNodeSet Tmp3; 2704 2705 for (ExplodedNodeSet::iterator I1=Tmp1.begin(), E1=Tmp1.end(); I1!=E1; ++I1) { 2706 SVal LeftV = (*I1)->getState()->getSVal(LHS); 2707 ExplodedNodeSet Tmp2; 2708 Visit(RHS, *I1, Tmp2); 2709 2710 ExplodedNodeSet CheckedSet; 2711 getCheckerManager().runCheckersForPreStmt(CheckedSet, Tmp2, B, *this); 2712 2713 // With both the LHS and RHS evaluated, process the operation itself. 2714 2715 for (ExplodedNodeSet::iterator I2=CheckedSet.begin(), E2=CheckedSet.end(); 2716 I2 != E2; ++I2) { 2717 2718 const GRState *state = (*I2)->getState(); 2719 SVal RightV = state->getSVal(RHS); 2720 2721 BinaryOperator::Opcode Op = B->getOpcode(); 2722 2723 if (Op == BO_Assign) { 2724 // EXPERIMENTAL: "Conjured" symbols. 2725 // FIXME: Handle structs. 2726 if (RightV.isUnknown() ||!getConstraintManager().canReasonAbout(RightV)) 2727 { 2728 unsigned Count = Builder->getCurrentBlockCount(); 2729 RightV = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), Count); 2730 } 2731 2732 SVal ExprVal = B->isLValue() ? LeftV : RightV; 2733 2734 // Simulate the effects of a "store": bind the value of the RHS 2735 // to the L-Value represented by the LHS. 2736 evalStore(Tmp3, B, LHS, *I2, state->BindExpr(B, ExprVal), LeftV,RightV); 2737 continue; 2738 } 2739 2740 if (!B->isAssignmentOp()) { 2741 // Process non-assignments except commas or short-circuited 2742 // logical expressions (LAnd and LOr). 2743 SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType()); 2744 2745 if (Result.isUnknown()) { 2746 MakeNode(Tmp3, B, *I2, state); 2747 continue; 2748 } 2749 2750 state = state->BindExpr(B, Result); 2751 2752 MakeNode(Tmp3, B, *I2, state); 2753 continue; 2754 } 2755 2756 assert (B->isCompoundAssignmentOp()); 2757 2758 switch (Op) { 2759 default: 2760 assert(0 && "Invalid opcode for compound assignment."); 2761 case BO_MulAssign: Op = BO_Mul; break; 2762 case BO_DivAssign: Op = BO_Div; break; 2763 case BO_RemAssign: Op = BO_Rem; break; 2764 case BO_AddAssign: Op = BO_Add; break; 2765 case BO_SubAssign: Op = BO_Sub; break; 2766 case BO_ShlAssign: Op = BO_Shl; break; 2767 case BO_ShrAssign: Op = BO_Shr; break; 2768 case BO_AndAssign: Op = BO_And; break; 2769 case BO_XorAssign: Op = BO_Xor; break; 2770 case BO_OrAssign: Op = BO_Or; break; 2771 } 2772 2773 // Perform a load (the LHS). This performs the checks for 2774 // null dereferences, and so on. 2775 ExplodedNodeSet Tmp4; 2776 SVal location = state->getSVal(LHS); 2777 evalLoad(Tmp4, LHS, *I2, state, location); 2778 2779 for (ExplodedNodeSet::iterator I4=Tmp4.begin(), E4=Tmp4.end(); I4!=E4; 2780 ++I4) { 2781 state = (*I4)->getState(); 2782 SVal V = state->getSVal(LHS); 2783 2784 // Get the computation type. 2785 QualType CTy = 2786 cast<CompoundAssignOperator>(B)->getComputationResultType(); 2787 CTy = getContext().getCanonicalType(CTy); 2788 2789 QualType CLHSTy = 2790 cast<CompoundAssignOperator>(B)->getComputationLHSType(); 2791 CLHSTy = getContext().getCanonicalType(CLHSTy); 2792 2793 QualType LTy = getContext().getCanonicalType(LHS->getType()); 2794 2795 // Promote LHS. 2796 V = svalBuilder.evalCast(V, CLHSTy, LTy); 2797 2798 // Compute the result of the operation. 2799 SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy), 2800 B->getType(), CTy); 2801 2802 // EXPERIMENTAL: "Conjured" symbols. 2803 // FIXME: Handle structs. 2804 2805 SVal LHSVal; 2806 2807 if (Result.isUnknown() || 2808 !getConstraintManager().canReasonAbout(Result)) { 2809 2810 unsigned Count = Builder->getCurrentBlockCount(); 2811 2812 // The symbolic value is actually for the type of the left-hand side 2813 // expression, not the computation type, as this is the value the 2814 // LValue on the LHS will bind to. 2815 LHSVal = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), LTy, Count); 2816 2817 // However, we need to convert the symbol to the computation type. 2818 Result = svalBuilder.evalCast(LHSVal, CTy, LTy); 2819 } 2820 else { 2821 // The left-hand side may bind to a different value then the 2822 // computation type. 2823 LHSVal = svalBuilder.evalCast(Result, LTy, CTy); 2824 } 2825 2826 // In C++, assignment and compound assignment operators return an 2827 // lvalue. 2828 if (B->isLValue()) 2829 state = state->BindExpr(B, location); 2830 else 2831 state = state->BindExpr(B, Result); 2832 2833 evalStore(Tmp3, B, LHS, *I4, state, location, LHSVal); 2834 } 2835 } 2836 } 2837 2838 getCheckerManager().runCheckersForPostStmt(Dst, Tmp3, B, *this); 2839 } 2840 2841 //===----------------------------------------------------------------------===// 2842 // Visualization. 2843 //===----------------------------------------------------------------------===// 2844 2845 #ifndef NDEBUG 2846 static ExprEngine* GraphPrintCheckerState; 2847 static SourceManager* GraphPrintSourceManager; 2848 2849 namespace llvm { 2850 template<> 2851 struct DOTGraphTraits<ExplodedNode*> : 2852 public DefaultDOTGraphTraits { 2853 2854 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 2855 2856 // FIXME: Since we do not cache error nodes in ExprEngine now, this does not 2857 // work. 2858 static std::string getNodeAttributes(const ExplodedNode* N, void*) { 2859 2860 #if 0 2861 // FIXME: Replace with a general scheme to tell if the node is 2862 // an error node. 2863 if (GraphPrintCheckerState->isImplicitNullDeref(N) || 2864 GraphPrintCheckerState->isExplicitNullDeref(N) || 2865 GraphPrintCheckerState->isUndefDeref(N) || 2866 GraphPrintCheckerState->isUndefStore(N) || 2867 GraphPrintCheckerState->isUndefControlFlow(N) || 2868 GraphPrintCheckerState->isUndefResult(N) || 2869 GraphPrintCheckerState->isBadCall(N) || 2870 GraphPrintCheckerState->isUndefArg(N)) 2871 return "color=\"red\",style=\"filled\""; 2872 2873 if (GraphPrintCheckerState->isNoReturnCall(N)) 2874 return "color=\"blue\",style=\"filled\""; 2875 #endif 2876 return ""; 2877 } 2878 2879 static std::string getNodeLabel(const ExplodedNode* N, void*){ 2880 2881 std::string sbuf; 2882 llvm::raw_string_ostream Out(sbuf); 2883 2884 // Program Location. 2885 ProgramPoint Loc = N->getLocation(); 2886 2887 switch (Loc.getKind()) { 2888 case ProgramPoint::BlockEntranceKind: 2889 Out << "Block Entrance: B" 2890 << cast<BlockEntrance>(Loc).getBlock()->getBlockID(); 2891 break; 2892 2893 case ProgramPoint::BlockExitKind: 2894 assert (false); 2895 break; 2896 2897 case ProgramPoint::CallEnterKind: 2898 Out << "CallEnter"; 2899 break; 2900 2901 case ProgramPoint::CallExitKind: 2902 Out << "CallExit"; 2903 break; 2904 2905 default: { 2906 if (StmtPoint *L = dyn_cast<StmtPoint>(&Loc)) { 2907 const Stmt* S = L->getStmt(); 2908 SourceLocation SLoc = S->getLocStart(); 2909 2910 Out << S->getStmtClassName() << ' ' << (void*) S << ' '; 2911 LangOptions LO; // FIXME. 2912 S->printPretty(Out, 0, PrintingPolicy(LO)); 2913 2914 if (SLoc.isFileID()) { 2915 Out << "\\lline=" 2916 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 2917 << " col=" 2918 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc) 2919 << "\\l"; 2920 } 2921 2922 if (isa<PreStmt>(Loc)) 2923 Out << "\\lPreStmt\\l;"; 2924 else if (isa<PostLoad>(Loc)) 2925 Out << "\\lPostLoad\\l;"; 2926 else if (isa<PostStore>(Loc)) 2927 Out << "\\lPostStore\\l"; 2928 else if (isa<PostLValue>(Loc)) 2929 Out << "\\lPostLValue\\l"; 2930 2931 #if 0 2932 // FIXME: Replace with a general scheme to determine 2933 // the name of the check. 2934 if (GraphPrintCheckerState->isImplicitNullDeref(N)) 2935 Out << "\\|Implicit-Null Dereference.\\l"; 2936 else if (GraphPrintCheckerState->isExplicitNullDeref(N)) 2937 Out << "\\|Explicit-Null Dereference.\\l"; 2938 else if (GraphPrintCheckerState->isUndefDeref(N)) 2939 Out << "\\|Dereference of undefialied value.\\l"; 2940 else if (GraphPrintCheckerState->isUndefStore(N)) 2941 Out << "\\|Store to Undefined Loc."; 2942 else if (GraphPrintCheckerState->isUndefResult(N)) 2943 Out << "\\|Result of operation is undefined."; 2944 else if (GraphPrintCheckerState->isNoReturnCall(N)) 2945 Out << "\\|Call to function marked \"noreturn\"."; 2946 else if (GraphPrintCheckerState->isBadCall(N)) 2947 Out << "\\|Call to NULL/Undefined."; 2948 else if (GraphPrintCheckerState->isUndefArg(N)) 2949 Out << "\\|Argument in call is undefined"; 2950 #endif 2951 2952 break; 2953 } 2954 2955 const BlockEdge& E = cast<BlockEdge>(Loc); 2956 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B" 2957 << E.getDst()->getBlockID() << ')'; 2958 2959 if (const Stmt* T = E.getSrc()->getTerminator()) { 2960 2961 SourceLocation SLoc = T->getLocStart(); 2962 2963 Out << "\\|Terminator: "; 2964 LangOptions LO; // FIXME. 2965 E.getSrc()->printTerminator(Out, LO); 2966 2967 if (SLoc.isFileID()) { 2968 Out << "\\lline=" 2969 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 2970 << " col=" 2971 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc); 2972 } 2973 2974 if (isa<SwitchStmt>(T)) { 2975 const Stmt* Label = E.getDst()->getLabel(); 2976 2977 if (Label) { 2978 if (const CaseStmt* C = dyn_cast<CaseStmt>(Label)) { 2979 Out << "\\lcase "; 2980 LangOptions LO; // FIXME. 2981 C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO)); 2982 2983 if (const Stmt* RHS = C->getRHS()) { 2984 Out << " .. "; 2985 RHS->printPretty(Out, 0, PrintingPolicy(LO)); 2986 } 2987 2988 Out << ":"; 2989 } 2990 else { 2991 assert (isa<DefaultStmt>(Label)); 2992 Out << "\\ldefault:"; 2993 } 2994 } 2995 else 2996 Out << "\\l(implicit) default:"; 2997 } 2998 else if (isa<IndirectGotoStmt>(T)) { 2999 // FIXME 3000 } 3001 else { 3002 Out << "\\lCondition: "; 3003 if (*E.getSrc()->succ_begin() == E.getDst()) 3004 Out << "true"; 3005 else 3006 Out << "false"; 3007 } 3008 3009 Out << "\\l"; 3010 } 3011 3012 #if 0 3013 // FIXME: Replace with a general scheme to determine 3014 // the name of the check. 3015 if (GraphPrintCheckerState->isUndefControlFlow(N)) { 3016 Out << "\\|Control-flow based on\\lUndefined value.\\l"; 3017 } 3018 #endif 3019 } 3020 } 3021 3022 const GRState *state = N->getState(); 3023 Out << "\\|StateID: " << (void*) state 3024 << " NodeID: " << (void*) N << "\\|"; 3025 state->printDOT(Out, *N->getLocationContext()->getCFG()); 3026 Out << "\\l"; 3027 return Out.str(); 3028 } 3029 }; 3030 } // end llvm namespace 3031 #endif 3032 3033 #ifndef NDEBUG 3034 template <typename ITERATOR> 3035 ExplodedNode* GetGraphNode(ITERATOR I) { return *I; } 3036 3037 template <> ExplodedNode* 3038 GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator> 3039 (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) { 3040 return I->first; 3041 } 3042 #endif 3043 3044 void ExprEngine::ViewGraph(bool trim) { 3045 #ifndef NDEBUG 3046 if (trim) { 3047 std::vector<ExplodedNode*> Src; 3048 3049 // Flush any outstanding reports to make sure we cover all the nodes. 3050 // This does not cause them to get displayed. 3051 for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I) 3052 const_cast<BugType*>(*I)->FlushReports(BR); 3053 3054 // Iterate through the reports and get their nodes. 3055 for (BugReporter::EQClasses_iterator 3056 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) { 3057 BugReportEquivClass& EQ = *EI; 3058 const BugReport &R = **EQ.begin(); 3059 ExplodedNode *N = const_cast<ExplodedNode*>(R.getErrorNode()); 3060 if (N) Src.push_back(N); 3061 } 3062 3063 ViewGraph(&Src[0], &Src[0]+Src.size()); 3064 } 3065 else { 3066 GraphPrintCheckerState = this; 3067 GraphPrintSourceManager = &getContext().getSourceManager(); 3068 3069 llvm::ViewGraph(*G.roots_begin(), "ExprEngine"); 3070 3071 GraphPrintCheckerState = NULL; 3072 GraphPrintSourceManager = NULL; 3073 } 3074 #endif 3075 } 3076 3077 void ExprEngine::ViewGraph(ExplodedNode** Beg, ExplodedNode** End) { 3078 #ifndef NDEBUG 3079 GraphPrintCheckerState = this; 3080 GraphPrintSourceManager = &getContext().getSourceManager(); 3081 3082 std::auto_ptr<ExplodedGraph> TrimmedG(G.Trim(Beg, End).first); 3083 3084 if (!TrimmedG.get()) 3085 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n"; 3086 else 3087 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine"); 3088 3089 GraphPrintCheckerState = NULL; 3090 GraphPrintSourceManager = NULL; 3091 #endif 3092 } 3093