clang API Documentation
00001 //=-- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- C++ -*-= 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file defines a meta-engine for path-sensitive dataflow analysis that 00011 // is built on GREngine, but provides the boilerplate to execute transfer 00012 // functions and build the ExplodedGraph at the expression level. 00013 // 00014 //===----------------------------------------------------------------------===// 00015 00016 #define DEBUG_TYPE "ExprEngine" 00017 00018 #include "clang/StaticAnalyzer/Core/CheckerManager.h" 00019 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 00020 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 00021 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 00022 #include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h" 00023 #include "clang/AST/CharUnits.h" 00024 #include "clang/AST/ParentMap.h" 00025 #include "clang/AST/StmtObjC.h" 00026 #include "clang/AST/StmtCXX.h" 00027 #include "clang/AST/DeclCXX.h" 00028 #include "clang/Basic/Builtins.h" 00029 #include "clang/Basic/SourceManager.h" 00030 #include "clang/Basic/PrettyStackTrace.h" 00031 #include "llvm/Support/raw_ostream.h" 00032 #include "llvm/ADT/ImmutableList.h" 00033 #include "llvm/ADT/Statistic.h" 00034 00035 #ifndef NDEBUG 00036 #include "llvm/Support/GraphWriter.h" 00037 #endif 00038 00039 using namespace clang; 00040 using namespace ento; 00041 using llvm::APSInt; 00042 00043 STATISTIC(NumRemoveDeadBindings, 00044 "The # of times RemoveDeadBindings is called"); 00045 STATISTIC(NumMaxBlockCountReached, 00046 "The # of aborted paths due to reaching the maximum block count in " 00047 "a top level function"); 00048 STATISTIC(NumMaxBlockCountReachedInInlined, 00049 "The # of aborted paths due to reaching the maximum block count in " 00050 "an inlined function"); 00051 STATISTIC(NumTimesRetriedWithoutInlining, 00052 "The # of times we re-evaluated a call without inlining"); 00053 00054 //===----------------------------------------------------------------------===// 00055 // Utility functions. 00056 //===----------------------------------------------------------------------===// 00057 00058 static inline Selector GetNullarySelector(const char* name, ASTContext &Ctx) { 00059 IdentifierInfo* II = &Ctx.Idents.get(name); 00060 return Ctx.Selectors.getSelector(0, &II); 00061 } 00062 00063 //===----------------------------------------------------------------------===// 00064 // Engine construction and deletion. 00065 //===----------------------------------------------------------------------===// 00066 00067 ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled, 00068 SetOfConstDecls *VisitedCallees, 00069 FunctionSummariesTy *FS) 00070 : AMgr(mgr), 00071 AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()), 00072 Engine(*this, VisitedCallees, FS), 00073 G(Engine.getGraph()), 00074 StateMgr(getContext(), mgr.getStoreManagerCreator(), 00075 mgr.getConstraintManagerCreator(), G.getAllocator(), 00076 *this), 00077 SymMgr(StateMgr.getSymbolManager()), 00078 svalBuilder(StateMgr.getSValBuilder()), 00079 EntryNode(NULL), 00080 currentStmt(NULL), currentStmtIdx(0), currentBuilderContext(0), 00081 NSExceptionII(NULL), NSExceptionInstanceRaiseSelectors(NULL), 00082 RaiseSel(GetNullarySelector("raise", getContext())), 00083 ObjCGCEnabled(gcEnabled), BR(mgr, *this) { 00084 00085 if (mgr.shouldEagerlyTrimExplodedGraph()) { 00086 // Enable eager node reclaimation when constructing the ExplodedGraph. 00087 G.enableNodeReclamation(); 00088 } 00089 } 00090 00091 ExprEngine::~ExprEngine() { 00092 BR.FlushReports(); 00093 delete [] NSExceptionInstanceRaiseSelectors; 00094 } 00095 00096 //===----------------------------------------------------------------------===// 00097 // Utility methods. 00098 //===----------------------------------------------------------------------===// 00099 00100 ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) { 00101 ProgramStateRef state = StateMgr.getInitialState(InitLoc); 00102 const Decl *D = InitLoc->getDecl(); 00103 00104 // Preconditions. 00105 // FIXME: It would be nice if we had a more general mechanism to add 00106 // such preconditions. Some day. 00107 do { 00108 00109 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 00110 // Precondition: the first argument of 'main' is an integer guaranteed 00111 // to be > 0. 00112 const IdentifierInfo *II = FD->getIdentifier(); 00113 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0)) 00114 break; 00115 00116 const ParmVarDecl *PD = FD->getParamDecl(0); 00117 QualType T = PD->getType(); 00118 if (!T->isIntegerType()) 00119 break; 00120 00121 const MemRegion *R = state->getRegion(PD, InitLoc); 00122 if (!R) 00123 break; 00124 00125 SVal V = state->getSVal(loc::MemRegionVal(R)); 00126 SVal Constraint_untested = evalBinOp(state, BO_GT, V, 00127 svalBuilder.makeZeroVal(T), 00128 getContext().IntTy); 00129 00130 DefinedOrUnknownSVal *Constraint = 00131 dyn_cast<DefinedOrUnknownSVal>(&Constraint_untested); 00132 00133 if (!Constraint) 00134 break; 00135 00136 if (ProgramStateRef newState = state->assume(*Constraint, true)) 00137 state = newState; 00138 } 00139 break; 00140 } 00141 while (0); 00142 00143 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 00144 // Precondition: 'self' is always non-null upon entry to an Objective-C 00145 // method. 00146 const ImplicitParamDecl *SelfD = MD->getSelfDecl(); 00147 const MemRegion *R = state->getRegion(SelfD, InitLoc); 00148 SVal V = state->getSVal(loc::MemRegionVal(R)); 00149 00150 if (const Loc *LV = dyn_cast<Loc>(&V)) { 00151 // Assume that the pointer value in 'self' is non-null. 00152 state = state->assume(*LV, true); 00153 assert(state && "'self' cannot be null"); 00154 } 00155 } 00156 00157 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 00158 if (!MD->isStatic()) { 00159 // Precondition: 'this' is always non-null upon entry to the 00160 // top-level function. This is our starting assumption for 00161 // analyzing an "open" program. 00162 const StackFrameContext *SFC = InitLoc->getCurrentStackFrame(); 00163 if (SFC->getParent() == 0) { 00164 loc::MemRegionVal L(getCXXThisRegion(MD, SFC)); 00165 SVal V = state->getSVal(L); 00166 if (const Loc *LV = dyn_cast<Loc>(&V)) { 00167 state = state->assume(*LV, true); 00168 assert(state && "'this' cannot be null"); 00169 } 00170 } 00171 } 00172 } 00173 00174 return state; 00175 } 00176 00177 //===----------------------------------------------------------------------===// 00178 // Top-level transfer function logic (Dispatcher). 00179 //===----------------------------------------------------------------------===// 00180 00181 /// evalAssume - Called by ConstraintManager. Used to call checker-specific 00182 /// logic for handling assumptions on symbolic values. 00183 ProgramStateRef ExprEngine::processAssume(ProgramStateRef state, 00184 SVal cond, bool assumption) { 00185 return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption); 00186 } 00187 00188 bool ExprEngine::wantsRegionChangeUpdate(ProgramStateRef state) { 00189 return getCheckerManager().wantsRegionChangeUpdate(state); 00190 } 00191 00192 ProgramStateRef 00193 ExprEngine::processRegionChanges(ProgramStateRef state, 00194 const StoreManager::InvalidatedSymbols *invalidated, 00195 ArrayRef<const MemRegion *> Explicits, 00196 ArrayRef<const MemRegion *> Regions, 00197 const CallOrObjCMessage *Call) { 00198 return getCheckerManager().runCheckersForRegionChanges(state, invalidated, 00199 Explicits, Regions, Call); 00200 } 00201 00202 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State, 00203 const char *NL, const char *Sep) { 00204 getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep); 00205 } 00206 00207 void ExprEngine::processEndWorklist(bool hasWorkRemaining) { 00208 getCheckerManager().runCheckersForEndAnalysis(G, BR, *this); 00209 } 00210 00211 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred, 00212 unsigned StmtIdx, NodeBuilderContext *Ctx) { 00213 currentStmtIdx = StmtIdx; 00214 currentBuilderContext = Ctx; 00215 00216 switch (E.getKind()) { 00217 case CFGElement::Invalid: 00218 llvm_unreachable("Unexpected CFGElement kind."); 00219 case CFGElement::Statement: 00220 ProcessStmt(const_cast<Stmt*>(E.getAs<CFGStmt>()->getStmt()), Pred); 00221 return; 00222 case CFGElement::Initializer: 00223 ProcessInitializer(E.getAs<CFGInitializer>()->getInitializer(), Pred); 00224 return; 00225 case CFGElement::AutomaticObjectDtor: 00226 case CFGElement::BaseDtor: 00227 case CFGElement::MemberDtor: 00228 case CFGElement::TemporaryDtor: 00229 ProcessImplicitDtor(*E.getAs<CFGImplicitDtor>(), Pred); 00230 return; 00231 } 00232 currentBuilderContext = 0; 00233 } 00234 00235 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr, 00236 const CFGStmt S, 00237 const ExplodedNode *Pred, 00238 const LocationContext *LC) { 00239 00240 // Are we never purging state values? 00241 if (AMgr.getPurgeMode() == PurgeNone) 00242 return false; 00243 00244 // Is this the beginning of a basic block? 00245 if (isa<BlockEntrance>(Pred->getLocation())) 00246 return true; 00247 00248 // Is this on a non-expression? 00249 if (!isa<Expr>(S.getStmt())) 00250 return true; 00251 00252 // Run before processing a call. 00253 if (isa<CallExpr>(S.getStmt())) 00254 return true; 00255 00256 // Is this an expression that is consumed by another expression? If so, 00257 // postpone cleaning out the state. 00258 ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap(); 00259 return !PM.isConsumedExpr(cast<Expr>(S.getStmt())); 00260 } 00261 00262 void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out, 00263 const Stmt *ReferenceStmt, 00264 const LocationContext *LC, 00265 const Stmt *DiagnosticStmt, 00266 ProgramPoint::Kind K) { 00267 assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind || 00268 ReferenceStmt == 0) && "PreStmt is not generally supported by " 00269 "the SymbolReaper yet"); 00270 NumRemoveDeadBindings++; 00271 CleanedState = Pred->getState(); 00272 SymbolReaper SymReaper(LC, ReferenceStmt, SymMgr, getStoreManager()); 00273 00274 getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper); 00275 00276 // Create a state in which dead bindings are removed from the environment 00277 // and the store. TODO: The function should just return new env and store, 00278 // not a new state. 00279 const StackFrameContext *SFC = LC->getCurrentStackFrame(); 00280 CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper); 00281 00282 // Process any special transfer function for dead symbols. 00283 // A tag to track convenience transitions, which can be removed at cleanup. 00284 static SimpleProgramPointTag cleanupTag("ExprEngine : Clean Node"); 00285 if (!SymReaper.hasDeadSymbols()) { 00286 // Generate a CleanedNode that has the environment and store cleaned 00287 // up. Since no symbols are dead, we can optimize and not clean out 00288 // the constraint manager. 00289 StmtNodeBuilder Bldr(Pred, Out, *currentBuilderContext); 00290 Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, false, &cleanupTag,K); 00291 00292 } else { 00293 // Call checkers with the non-cleaned state so that they could query the 00294 // values of the soon to be dead symbols. 00295 ExplodedNodeSet CheckedSet; 00296 getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper, 00297 DiagnosticStmt, *this, K); 00298 00299 // For each node in CheckedSet, generate CleanedNodes that have the 00300 // environment, the store, and the constraints cleaned up but have the 00301 // user-supplied states as the predecessors. 00302 StmtNodeBuilder Bldr(CheckedSet, Out, *currentBuilderContext); 00303 for (ExplodedNodeSet::const_iterator 00304 I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) { 00305 ProgramStateRef CheckerState = (*I)->getState(); 00306 00307 // The constraint manager has not been cleaned up yet, so clean up now. 00308 CheckerState = getConstraintManager().removeDeadBindings(CheckerState, 00309 SymReaper); 00310 00311 assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) && 00312 "Checkers are not allowed to modify the Environment as a part of " 00313 "checkDeadSymbols processing."); 00314 assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) && 00315 "Checkers are not allowed to modify the Store as a part of " 00316 "checkDeadSymbols processing."); 00317 00318 // Create a state based on CleanedState with CheckerState GDM and 00319 // generate a transition to that state. 00320 ProgramStateRef CleanedCheckerSt = 00321 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState); 00322 Bldr.generateNode(DiagnosticStmt, *I, CleanedCheckerSt, false, 00323 &cleanupTag, K); 00324 } 00325 } 00326 } 00327 00328 void ExprEngine::ProcessStmt(const CFGStmt S, 00329 ExplodedNode *Pred) { 00330 // Reclaim any unnecessary nodes in the ExplodedGraph. 00331 G.reclaimRecentlyAllocatedNodes(); 00332 00333 currentStmt = S.getStmt(); 00334 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 00335 currentStmt->getLocStart(), 00336 "Error evaluating statement"); 00337 00338 // Remove dead bindings and symbols. 00339 EntryNode = Pred; 00340 ExplodedNodeSet CleanedStates; 00341 if (shouldRemoveDeadBindings(AMgr, S, Pred, EntryNode->getLocationContext())){ 00342 removeDead(EntryNode, CleanedStates, currentStmt, 00343 Pred->getLocationContext(), currentStmt); 00344 } else 00345 CleanedStates.Add(EntryNode); 00346 00347 // Visit the statement. 00348 ExplodedNodeSet Dst; 00349 for (ExplodedNodeSet::iterator I = CleanedStates.begin(), 00350 E = CleanedStates.end(); I != E; ++I) { 00351 ExplodedNodeSet DstI; 00352 // Visit the statement. 00353 Visit(currentStmt, *I, DstI); 00354 Dst.insert(DstI); 00355 } 00356 00357 // Enqueue the new nodes onto the work list. 00358 Engine.enqueue(Dst, currentBuilderContext->getBlock(), currentStmtIdx); 00359 00360 // NULL out these variables to cleanup. 00361 CleanedState = NULL; 00362 EntryNode = NULL; 00363 currentStmt = 0; 00364 } 00365 00366 void ExprEngine::ProcessInitializer(const CFGInitializer Init, 00367 ExplodedNode *Pred) { 00368 ExplodedNodeSet Dst; 00369 00370 // We don't set EntryNode and currentStmt. And we don't clean up state. 00371 const CXXCtorInitializer *BMI = Init.getInitializer(); 00372 const StackFrameContext *stackFrame = 00373 cast<StackFrameContext>(Pred->getLocationContext()); 00374 const CXXConstructorDecl *decl = 00375 cast<CXXConstructorDecl>(stackFrame->getDecl()); 00376 const CXXThisRegion *thisReg = getCXXThisRegion(decl, stackFrame); 00377 00378 SVal thisVal = Pred->getState()->getSVal(thisReg); 00379 00380 if (BMI->isAnyMemberInitializer()) { 00381 // Evaluate the initializer. 00382 00383 StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext); 00384 ProgramStateRef state = Pred->getState(); 00385 00386 const FieldDecl *FD = BMI->getAnyMember(); 00387 00388 SVal FieldLoc = state->getLValue(FD, thisVal); 00389 SVal InitVal = state->getSVal(BMI->getInit(), Pred->getLocationContext()); 00390 state = state->bindLoc(FieldLoc, InitVal); 00391 00392 // Use a custom node building process. 00393 PostInitializer PP(BMI, stackFrame); 00394 // Builder automatically add the generated node to the deferred set, 00395 // which are processed in the builder's dtor. 00396 Bldr.generateNode(PP, Pred, state); 00397 } else { 00398 assert(BMI->isBaseInitializer()); 00399 00400 // Get the base class declaration. 00401 const CXXConstructExpr *ctorExpr = cast<CXXConstructExpr>(BMI->getInit()); 00402 00403 // Create the base object region. 00404 SVal baseVal = 00405 getStoreManager().evalDerivedToBase(thisVal, ctorExpr->getType()); 00406 const MemRegion *baseReg = baseVal.getAsRegion(); 00407 assert(baseReg); 00408 00409 VisitCXXConstructExpr(ctorExpr, baseReg, Pred, Dst); 00410 } 00411 00412 // Enqueue the new nodes onto the work list. 00413 Engine.enqueue(Dst, currentBuilderContext->getBlock(), currentStmtIdx); 00414 } 00415 00416 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D, 00417 ExplodedNode *Pred) { 00418 ExplodedNodeSet Dst; 00419 switch (D.getKind()) { 00420 case CFGElement::AutomaticObjectDtor: 00421 ProcessAutomaticObjDtor(cast<CFGAutomaticObjDtor>(D), Pred, Dst); 00422 break; 00423 case CFGElement::BaseDtor: 00424 ProcessBaseDtor(cast<CFGBaseDtor>(D), Pred, Dst); 00425 break; 00426 case CFGElement::MemberDtor: 00427 ProcessMemberDtor(cast<CFGMemberDtor>(D), Pred, Dst); 00428 break; 00429 case CFGElement::TemporaryDtor: 00430 ProcessTemporaryDtor(cast<CFGTemporaryDtor>(D), Pred, Dst); 00431 break; 00432 default: 00433 llvm_unreachable("Unexpected dtor kind."); 00434 } 00435 00436 // Enqueue the new nodes onto the work list. 00437 Engine.enqueue(Dst, currentBuilderContext->getBlock(), currentStmtIdx); 00438 } 00439 00440 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor, 00441 ExplodedNode *Pred, 00442 ExplodedNodeSet &Dst) { 00443 ProgramStateRef state = Pred->getState(); 00444 const VarDecl *varDecl = Dtor.getVarDecl(); 00445 00446 QualType varType = varDecl->getType(); 00447 00448 if (const ReferenceType *refType = varType->getAs<ReferenceType>()) 00449 varType = refType->getPointeeType(); 00450 00451 const CXXRecordDecl *recordDecl = varType->getAsCXXRecordDecl(); 00452 assert(recordDecl && "get CXXRecordDecl fail"); 00453 const CXXDestructorDecl *dtorDecl = recordDecl->getDestructor(); 00454 00455 Loc dest = state->getLValue(varDecl, Pred->getLocationContext()); 00456 00457 VisitCXXDestructor(dtorDecl, cast<loc::MemRegionVal>(dest).getRegion(), 00458 Dtor.getTriggerStmt(), Pred, Dst); 00459 } 00460 00461 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D, 00462 ExplodedNode *Pred, ExplodedNodeSet &Dst) {} 00463 00464 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D, 00465 ExplodedNode *Pred, ExplodedNodeSet &Dst) {} 00466 00467 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D, 00468 ExplodedNode *Pred, 00469 ExplodedNodeSet &Dst) {} 00470 00471 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred, 00472 ExplodedNodeSet &DstTop) { 00473 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 00474 S->getLocStart(), 00475 "Error evaluating statement"); 00476 ExplodedNodeSet Dst; 00477 StmtNodeBuilder Bldr(Pred, DstTop, *currentBuilderContext); 00478 00479 // Expressions to ignore. 00480 if (const Expr *Ex = dyn_cast<Expr>(S)) 00481 S = Ex->IgnoreParens(); 00482 00483 // FIXME: add metadata to the CFG so that we can disable 00484 // this check when we KNOW that there is no block-level subexpression. 00485 // The motivation is that this check requires a hashtable lookup. 00486 00487 if (S != currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(S)) 00488 return; 00489 00490 switch (S->getStmtClass()) { 00491 // C++ and ARC stuff we don't support yet. 00492 case Expr::ObjCIndirectCopyRestoreExprClass: 00493 case Stmt::CXXDependentScopeMemberExprClass: 00494 case Stmt::CXXPseudoDestructorExprClass: 00495 case Stmt::CXXTryStmtClass: 00496 case Stmt::CXXTypeidExprClass: 00497 case Stmt::CXXUuidofExprClass: 00498 case Stmt::CXXUnresolvedConstructExprClass: 00499 case Stmt::DependentScopeDeclRefExprClass: 00500 case Stmt::UnaryTypeTraitExprClass: 00501 case Stmt::BinaryTypeTraitExprClass: 00502 case Stmt::TypeTraitExprClass: 00503 case Stmt::ArrayTypeTraitExprClass: 00504 case Stmt::ExpressionTraitExprClass: 00505 case Stmt::UnresolvedLookupExprClass: 00506 case Stmt::UnresolvedMemberExprClass: 00507 case Stmt::CXXNoexceptExprClass: 00508 case Stmt::PackExpansionExprClass: 00509 case Stmt::SubstNonTypeTemplateParmPackExprClass: 00510 case Stmt::SEHTryStmtClass: 00511 case Stmt::SEHExceptStmtClass: 00512 case Stmt::LambdaExprClass: 00513 case Stmt::SEHFinallyStmtClass: { 00514 const ExplodedNode *node = Bldr.generateNode(S, Pred, Pred->getState(), 00515 /* sink */ true); 00516 Engine.addAbortedBlock(node, currentBuilderContext->getBlock()); 00517 break; 00518 } 00519 00520 // We don't handle default arguments either yet, but we can fake it 00521 // for now by just skipping them. 00522 case Stmt::SubstNonTypeTemplateParmExprClass: 00523 case Stmt::CXXDefaultArgExprClass: 00524 break; 00525 00526 case Stmt::ParenExprClass: 00527 llvm_unreachable("ParenExprs already handled."); 00528 case Stmt::GenericSelectionExprClass: 00529 llvm_unreachable("GenericSelectionExprs already handled."); 00530 // Cases that should never be evaluated simply because they shouldn't 00531 // appear in the CFG. 00532 case Stmt::BreakStmtClass: 00533 case Stmt::CaseStmtClass: 00534 case Stmt::CompoundStmtClass: 00535 case Stmt::ContinueStmtClass: 00536 case Stmt::CXXForRangeStmtClass: 00537 case Stmt::DefaultStmtClass: 00538 case Stmt::DoStmtClass: 00539 case Stmt::ForStmtClass: 00540 case Stmt::GotoStmtClass: 00541 case Stmt::IfStmtClass: 00542 case Stmt::IndirectGotoStmtClass: 00543 case Stmt::LabelStmtClass: 00544 case Stmt::AttributedStmtClass: 00545 case Stmt::NoStmtClass: 00546 case Stmt::NullStmtClass: 00547 case Stmt::SwitchStmtClass: 00548 case Stmt::WhileStmtClass: 00549 case Expr::MSDependentExistsStmtClass: 00550 llvm_unreachable("Stmt should not be in analyzer evaluation loop"); 00551 00552 case Stmt::GNUNullExprClass: { 00553 // GNU __null is a pointer-width integer, not an actual pointer. 00554 ProgramStateRef state = Pred->getState(); 00555 state = state->BindExpr(S, Pred->getLocationContext(), 00556 svalBuilder.makeIntValWithPtrWidth(0, false)); 00557 Bldr.generateNode(S, Pred, state); 00558 break; 00559 } 00560 00561 case Stmt::ObjCAtSynchronizedStmtClass: 00562 Bldr.takeNodes(Pred); 00563 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst); 00564 Bldr.addNodes(Dst); 00565 break; 00566 00567 // FIXME. 00568 case Stmt::ObjCSubscriptRefExprClass: 00569 break; 00570 00571 case Stmt::ObjCPropertyRefExprClass: 00572 // Implicitly handled by Environment::getSVal(). 00573 break; 00574 00575 case Stmt::ExprWithCleanupsClass: 00576 // Handled due to fully linearised CFG. 00577 break; 00578 00579 // Cases not handled yet; but will handle some day. 00580 case Stmt::DesignatedInitExprClass: 00581 case Stmt::ExtVectorElementExprClass: 00582 case Stmt::ImaginaryLiteralClass: 00583 case Stmt::ObjCAtCatchStmtClass: 00584 case Stmt::ObjCAtFinallyStmtClass: 00585 case Stmt::ObjCAtTryStmtClass: 00586 case Stmt::ObjCAutoreleasePoolStmtClass: 00587 case Stmt::ObjCEncodeExprClass: 00588 case Stmt::ObjCIsaExprClass: 00589 case Stmt::ObjCProtocolExprClass: 00590 case Stmt::ObjCSelectorExprClass: 00591 case Stmt::ParenListExprClass: 00592 case Stmt::PredefinedExprClass: 00593 case Stmt::ShuffleVectorExprClass: 00594 case Stmt::VAArgExprClass: 00595 case Stmt::CUDAKernelCallExprClass: 00596 case Stmt::OpaqueValueExprClass: 00597 case Stmt::AsTypeExprClass: 00598 case Stmt::AtomicExprClass: 00599 // Fall through. 00600 00601 // Currently all handling of 'throw' just falls to the CFG. We 00602 // can consider doing more if necessary. 00603 case Stmt::CXXThrowExprClass: 00604 // Fall through. 00605 00606 // Cases we intentionally don't evaluate, since they don't need 00607 // to be explicitly evaluated. 00608 case Stmt::AddrLabelExprClass: 00609 case Stmt::IntegerLiteralClass: 00610 case Stmt::CharacterLiteralClass: 00611 case Stmt::ImplicitValueInitExprClass: 00612 case Stmt::CXXScalarValueInitExprClass: 00613 case Stmt::CXXBoolLiteralExprClass: 00614 case Stmt::ObjCBoolLiteralExprClass: 00615 case Stmt::FloatingLiteralClass: 00616 case Stmt::SizeOfPackExprClass: 00617 case Stmt::StringLiteralClass: 00618 case Stmt::ObjCStringLiteralClass: 00619 case Stmt::CXXBindTemporaryExprClass: 00620 case Stmt::CXXNullPtrLiteralExprClass: { 00621 Bldr.takeNodes(Pred); 00622 ExplodedNodeSet preVisit; 00623 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this); 00624 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this); 00625 Bldr.addNodes(Dst); 00626 break; 00627 } 00628 00629 case Expr::ObjCArrayLiteralClass: 00630 case Expr::ObjCDictionaryLiteralClass: 00631 // FIXME: explicitly model with a region and the actual contents 00632 // of the container. For now, conjure a symbol. 00633 case Expr::ObjCBoxedExprClass: { 00634 Bldr.takeNodes(Pred); 00635 00636 ExplodedNodeSet preVisit; 00637 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this); 00638 00639 ExplodedNodeSet Tmp; 00640 StmtNodeBuilder Bldr2(preVisit, Tmp, *currentBuilderContext); 00641 00642 const Expr *Ex = cast<Expr>(S); 00643 QualType resultType = Ex->getType(); 00644 00645 for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end(); 00646 it != et; ++it) { 00647 ExplodedNode *N = *it; 00648 const LocationContext *LCtx = N->getLocationContext(); 00649 SVal result = 00650 svalBuilder.getConjuredSymbolVal(0, Ex, LCtx, resultType, 00651 currentBuilderContext->getCurrentBlockCount()); 00652 ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result); 00653 Bldr2.generateNode(S, N, state); 00654 } 00655 00656 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this); 00657 Bldr.addNodes(Dst); 00658 break; 00659 } 00660 00661 case Stmt::ArraySubscriptExprClass: 00662 Bldr.takeNodes(Pred); 00663 VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst); 00664 Bldr.addNodes(Dst); 00665 break; 00666 00667 case Stmt::AsmStmtClass: 00668 Bldr.takeNodes(Pred); 00669 VisitAsmStmt(cast<AsmStmt>(S), Pred, Dst); 00670 Bldr.addNodes(Dst); 00671 break; 00672 00673 case Stmt::BlockExprClass: 00674 Bldr.takeNodes(Pred); 00675 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst); 00676 Bldr.addNodes(Dst); 00677 break; 00678 00679 case Stmt::BinaryOperatorClass: { 00680 const BinaryOperator* B = cast<BinaryOperator>(S); 00681 if (B->isLogicalOp()) { 00682 Bldr.takeNodes(Pred); 00683 VisitLogicalExpr(B, Pred, Dst); 00684 Bldr.addNodes(Dst); 00685 break; 00686 } 00687 else if (B->getOpcode() == BO_Comma) { 00688 ProgramStateRef state = Pred->getState(); 00689 Bldr.generateNode(B, Pred, 00690 state->BindExpr(B, Pred->getLocationContext(), 00691 state->getSVal(B->getRHS(), 00692 Pred->getLocationContext()))); 00693 break; 00694 } 00695 00696 Bldr.takeNodes(Pred); 00697 00698 if (AMgr.shouldEagerlyAssume() && 00699 (B->isRelationalOp() || B->isEqualityOp())) { 00700 ExplodedNodeSet Tmp; 00701 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp); 00702 evalEagerlyAssume(Dst, Tmp, cast<Expr>(S)); 00703 } 00704 else 00705 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 00706 00707 Bldr.addNodes(Dst); 00708 break; 00709 } 00710 00711 case Stmt::CallExprClass: 00712 case Stmt::CXXOperatorCallExprClass: 00713 case Stmt::CXXMemberCallExprClass: 00714 case Stmt::UserDefinedLiteralClass: { 00715 Bldr.takeNodes(Pred); 00716 VisitCallExpr(cast<CallExpr>(S), Pred, Dst); 00717 Bldr.addNodes(Dst); 00718 break; 00719 } 00720 00721 case Stmt::CXXCatchStmtClass: { 00722 Bldr.takeNodes(Pred); 00723 VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst); 00724 Bldr.addNodes(Dst); 00725 break; 00726 } 00727 00728 case Stmt::CXXTemporaryObjectExprClass: 00729 case Stmt::CXXConstructExprClass: { 00730 const CXXConstructExpr *C = cast<CXXConstructExpr>(S); 00731 // For block-level CXXConstructExpr, we don't have a destination region. 00732 // Let VisitCXXConstructExpr() create one. 00733 Bldr.takeNodes(Pred); 00734 VisitCXXConstructExpr(C, 0, Pred, Dst); 00735 Bldr.addNodes(Dst); 00736 break; 00737 } 00738 00739 case Stmt::CXXNewExprClass: { 00740 Bldr.takeNodes(Pred); 00741 const CXXNewExpr *NE = cast<CXXNewExpr>(S); 00742 VisitCXXNewExpr(NE, Pred, Dst); 00743 Bldr.addNodes(Dst); 00744 break; 00745 } 00746 00747 case Stmt::CXXDeleteExprClass: { 00748 Bldr.takeNodes(Pred); 00749 const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S); 00750 VisitCXXDeleteExpr(CDE, Pred, Dst); 00751 Bldr.addNodes(Dst); 00752 break; 00753 } 00754 // FIXME: ChooseExpr is really a constant. We need to fix 00755 // the CFG do not model them as explicit control-flow. 00756 00757 case Stmt::ChooseExprClass: { // __builtin_choose_expr 00758 Bldr.takeNodes(Pred); 00759 const ChooseExpr *C = cast<ChooseExpr>(S); 00760 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst); 00761 Bldr.addNodes(Dst); 00762 break; 00763 } 00764 00765 case Stmt::CompoundAssignOperatorClass: 00766 Bldr.takeNodes(Pred); 00767 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); 00768 Bldr.addNodes(Dst); 00769 break; 00770 00771 case Stmt::CompoundLiteralExprClass: 00772 Bldr.takeNodes(Pred); 00773 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst); 00774 Bldr.addNodes(Dst); 00775 break; 00776 00777 case Stmt::BinaryConditionalOperatorClass: 00778 case Stmt::ConditionalOperatorClass: { // '?' operator 00779 Bldr.takeNodes(Pred); 00780 const AbstractConditionalOperator *C 00781 = cast<AbstractConditionalOperator>(S); 00782 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst); 00783 Bldr.addNodes(Dst); 00784 break; 00785 } 00786 00787 case Stmt::CXXThisExprClass: 00788 Bldr.takeNodes(Pred); 00789 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst); 00790 Bldr.addNodes(Dst); 00791 break; 00792 00793 case Stmt::DeclRefExprClass: { 00794 Bldr.takeNodes(Pred); 00795 const DeclRefExpr *DE = cast<DeclRefExpr>(S); 00796 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst); 00797 Bldr.addNodes(Dst); 00798 break; 00799 } 00800 00801 case Stmt::DeclStmtClass: 00802 Bldr.takeNodes(Pred); 00803 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst); 00804 Bldr.addNodes(Dst); 00805 break; 00806 00807 case Stmt::ImplicitCastExprClass: 00808 case Stmt::CStyleCastExprClass: 00809 case Stmt::CXXStaticCastExprClass: 00810 case Stmt::CXXDynamicCastExprClass: 00811 case Stmt::CXXReinterpretCastExprClass: 00812 case Stmt::CXXConstCastExprClass: 00813 case Stmt::CXXFunctionalCastExprClass: 00814 case Stmt::ObjCBridgedCastExprClass: { 00815 Bldr.takeNodes(Pred); 00816 const CastExpr *C = cast<CastExpr>(S); 00817 // Handle the previsit checks. 00818 ExplodedNodeSet dstPrevisit; 00819 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this); 00820 00821 // Handle the expression itself. 00822 ExplodedNodeSet dstExpr; 00823 for (ExplodedNodeSet::iterator i = dstPrevisit.begin(), 00824 e = dstPrevisit.end(); i != e ; ++i) { 00825 VisitCast(C, C->getSubExpr(), *i, dstExpr); 00826 } 00827 00828 // Handle the postvisit checks. 00829 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this); 00830 Bldr.addNodes(Dst); 00831 break; 00832 } 00833 00834 case Expr::MaterializeTemporaryExprClass: { 00835 Bldr.takeNodes(Pred); 00836 const MaterializeTemporaryExpr *Materialize 00837 = cast<MaterializeTemporaryExpr>(S); 00838 if (Materialize->getType()->isRecordType()) 00839 Dst.Add(Pred); 00840 else 00841 CreateCXXTemporaryObject(Materialize, Pred, Dst); 00842 Bldr.addNodes(Dst); 00843 break; 00844 } 00845 00846 case Stmt::InitListExprClass: 00847 Bldr.takeNodes(Pred); 00848 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst); 00849 Bldr.addNodes(Dst); 00850 break; 00851 00852 case Stmt::MemberExprClass: 00853 Bldr.takeNodes(Pred); 00854 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst); 00855 Bldr.addNodes(Dst); 00856 break; 00857 00858 case Stmt::ObjCIvarRefExprClass: 00859 Bldr.takeNodes(Pred); 00860 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst); 00861 Bldr.addNodes(Dst); 00862 break; 00863 00864 case Stmt::ObjCForCollectionStmtClass: 00865 Bldr.takeNodes(Pred); 00866 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst); 00867 Bldr.addNodes(Dst); 00868 break; 00869 00870 case Stmt::ObjCMessageExprClass: { 00871 Bldr.takeNodes(Pred); 00872 // Is this a property access? 00873 const ParentMap &PM = Pred->getLocationContext()->getParentMap(); 00874 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(S); 00875 bool evaluated = false; 00876 00877 if (const PseudoObjectExpr *PO = 00878 dyn_cast_or_null<PseudoObjectExpr>(PM.getParent(S))) { 00879 const Expr *syntactic = PO->getSyntacticForm(); 00880 if (const ObjCPropertyRefExpr *PR = 00881 dyn_cast<ObjCPropertyRefExpr>(syntactic)) { 00882 bool isSetter = ME->getNumArgs() > 0; 00883 VisitObjCMessage(ObjCMessage(ME, PR, isSetter), Pred, Dst); 00884 evaluated = true; 00885 } 00886 else if (isa<BinaryOperator>(syntactic)) { 00887 VisitObjCMessage(ObjCMessage(ME, 0, true), Pred, Dst); 00888 } 00889 } 00890 00891 if (!evaluated) 00892 VisitObjCMessage(ME, Pred, Dst); 00893 00894 Bldr.addNodes(Dst); 00895 break; 00896 } 00897 00898 case Stmt::ObjCAtThrowStmtClass: { 00899 // FIXME: This is not complete. We basically treat @throw as 00900 // an abort. 00901 Bldr.generateNode(S, Pred, Pred->getState()); 00902 break; 00903 } 00904 00905 case Stmt::ReturnStmtClass: 00906 Bldr.takeNodes(Pred); 00907 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst); 00908 Bldr.addNodes(Dst); 00909 break; 00910 00911 case Stmt::OffsetOfExprClass: 00912 Bldr.takeNodes(Pred); 00913 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst); 00914 Bldr.addNodes(Dst); 00915 break; 00916 00917 case Stmt::UnaryExprOrTypeTraitExprClass: 00918 Bldr.takeNodes(Pred); 00919 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), 00920 Pred, Dst); 00921 Bldr.addNodes(Dst); 00922 break; 00923 00924 case Stmt::StmtExprClass: { 00925 const StmtExpr *SE = cast<StmtExpr>(S); 00926 00927 if (SE->getSubStmt()->body_empty()) { 00928 // Empty statement expression. 00929 assert(SE->getType() == getContext().VoidTy 00930 && "Empty statement expression must have void type."); 00931 break; 00932 } 00933 00934 if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) { 00935 ProgramStateRef state = Pred->getState(); 00936 Bldr.generateNode(SE, Pred, 00937 state->BindExpr(SE, Pred->getLocationContext(), 00938 state->getSVal(LastExpr, 00939 Pred->getLocationContext()))); 00940 } 00941 break; 00942 } 00943 00944 case Stmt::UnaryOperatorClass: { 00945 Bldr.takeNodes(Pred); 00946 const UnaryOperator *U = cast<UnaryOperator>(S); 00947 if (AMgr.shouldEagerlyAssume() && (U->getOpcode() == UO_LNot)) { 00948 ExplodedNodeSet Tmp; 00949 VisitUnaryOperator(U, Pred, Tmp); 00950 evalEagerlyAssume(Dst, Tmp, U); 00951 } 00952 else 00953 VisitUnaryOperator(U, Pred, Dst); 00954 Bldr.addNodes(Dst); 00955 break; 00956 } 00957 00958 case Stmt::PseudoObjectExprClass: { 00959 Bldr.takeNodes(Pred); 00960 ProgramStateRef state = Pred->getState(); 00961 const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S); 00962 if (const Expr *Result = PE->getResultExpr()) { 00963 SVal V = state->getSVal(Result, Pred->getLocationContext()); 00964 Bldr.generateNode(S, Pred, 00965 state->BindExpr(S, Pred->getLocationContext(), V)); 00966 } 00967 else 00968 Bldr.generateNode(S, Pred, 00969 state->BindExpr(S, Pred->getLocationContext(), 00970 UnknownVal())); 00971 00972 Bldr.addNodes(Dst); 00973 break; 00974 } 00975 } 00976 } 00977 00978 bool ExprEngine::replayWithoutInlining(ExplodedNode *N, 00979 const LocationContext *CalleeLC) { 00980 const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame(); 00981 const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame(); 00982 assert(CalleeSF && CallerSF); 00983 ExplodedNode *BeforeProcessingCall = 0; 00984 00985 // Find the first node before we started processing the call expression. 00986 while (N) { 00987 ProgramPoint L = N->getLocation(); 00988 BeforeProcessingCall = N; 00989 N = N->pred_empty() ? NULL : *(N->pred_begin()); 00990 00991 // Skip the nodes corresponding to the inlined code. 00992 if (L.getLocationContext()->getCurrentStackFrame() != CallerSF) 00993 continue; 00994 // We reached the caller. Find the node right before we started 00995 // processing the CallExpr. 00996 if (L.isPurgeKind()) 00997 continue; 00998 if (const StmtPoint *SP = dyn_cast<StmtPoint>(&L)) 00999 if (SP->getStmt() == CalleeSF->getCallSite()) 01000 continue; 01001 break; 01002 } 01003 01004 if (!BeforeProcessingCall) 01005 return false; 01006 01007 // TODO: Clean up the unneeded nodes. 01008 01009 // Build an Epsilon node from which we will restart the analyzes. 01010 const Stmt *CE = CalleeSF->getCallSite(); 01011 ProgramPoint NewNodeLoc = 01012 EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE); 01013 // Add the special flag to GDM to signal retrying with no inlining. 01014 // Note, changing the state ensures that we are not going to cache out. 01015 ProgramStateRef NewNodeState = BeforeProcessingCall->getState(); 01016 NewNodeState = NewNodeState->set<ReplayWithoutInlining>((void*)CE); 01017 01018 // Make the new node a successor of BeforeProcessingCall. 01019 bool IsNew = false; 01020 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew); 01021 // We cached out at this point. Caching out is common due to us backtracking 01022 // from the inlined function, which might spawn several paths. 01023 if (!IsNew) 01024 return true; 01025 01026 NewNode->addPredecessor(BeforeProcessingCall, G); 01027 01028 // Add the new node to the work list. 01029 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(), 01030 CalleeSF->getIndex()); 01031 NumTimesRetriedWithoutInlining++; 01032 return true; 01033 } 01034 01035 /// Block entrance. (Update counters). 01036 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L, 01037 NodeBuilderWithSinks &nodeBuilder) { 01038 01039 // FIXME: Refactor this into a checker. 01040 ExplodedNode *pred = nodeBuilder.getContext().getPred(); 01041 01042 if (nodeBuilder.getContext().getCurrentBlockCount() >= AMgr.getMaxVisit()) { 01043 static SimpleProgramPointTag tag("ExprEngine : Block count exceeded"); 01044 const ExplodedNode *Sink = 01045 nodeBuilder.generateNode(pred->getState(), pred, &tag, true); 01046 01047 // Check if we stopped at the top level function or not. 01048 // Root node should have the location context of the top most function. 01049 const LocationContext *CalleeLC = pred->getLocation().getLocationContext(); 01050 const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame(); 01051 const LocationContext *RootLC = 01052 (*G.roots_begin())->getLocation().getLocationContext(); 01053 if (RootLC->getCurrentStackFrame() != CalleeSF) { 01054 Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl()); 01055 01056 // Re-run the call evaluation without inlining it, by storing the 01057 // no-inlining policy in the state and enqueuing the new work item on 01058 // the list. Replay should almost never fail. Use the stats to catch it 01059 // if it does. 01060 if ((!AMgr.NoRetryExhausted && replayWithoutInlining(pred, CalleeLC))) 01061 return; 01062 NumMaxBlockCountReachedInInlined++; 01063 } else 01064 NumMaxBlockCountReached++; 01065 01066 // Make sink nodes as exhausted(for stats) only if retry failed. 01067 Engine.blocksExhausted.push_back(std::make_pair(L, Sink)); 01068 } 01069 } 01070 01071 //===----------------------------------------------------------------------===// 01072 // Branch processing. 01073 //===----------------------------------------------------------------------===// 01074 01075 ProgramStateRef ExprEngine::MarkBranch(ProgramStateRef state, 01076 const Stmt *Terminator, 01077 const LocationContext *LCtx, 01078 bool branchTaken) { 01079 01080 switch (Terminator->getStmtClass()) { 01081 default: 01082 return state; 01083 01084 case Stmt::BinaryOperatorClass: { // '&&' and '||' 01085 01086 const BinaryOperator* B = cast<BinaryOperator>(Terminator); 01087 BinaryOperator::Opcode Op = B->getOpcode(); 01088 01089 assert (Op == BO_LAnd || Op == BO_LOr); 01090 01091 // For &&, if we take the true branch, then the value of the whole 01092 // expression is that of the RHS expression. 01093 // 01094 // For ||, if we take the false branch, then the value of the whole 01095 // expression is that of the RHS expression. 01096 01097 const Expr *Ex = (Op == BO_LAnd && branchTaken) || 01098 (Op == BO_LOr && !branchTaken) 01099 ? B->getRHS() : B->getLHS(); 01100 01101 return state->BindExpr(B, LCtx, UndefinedVal(Ex)); 01102 } 01103 01104 case Stmt::BinaryConditionalOperatorClass: 01105 case Stmt::ConditionalOperatorClass: { // ?: 01106 const AbstractConditionalOperator* C 01107 = cast<AbstractConditionalOperator>(Terminator); 01108 01109 // For ?, if branchTaken == true then the value is either the LHS or 01110 // the condition itself. (GNU extension). 01111 01112 const Expr *Ex; 01113 01114 if (branchTaken) 01115 Ex = C->getTrueExpr(); 01116 else 01117 Ex = C->getFalseExpr(); 01118 01119 return state->BindExpr(C, LCtx, UndefinedVal(Ex)); 01120 } 01121 01122 case Stmt::ChooseExprClass: { // ?: 01123 01124 const ChooseExpr *C = cast<ChooseExpr>(Terminator); 01125 01126 const Expr *Ex = branchTaken ? C->getLHS() : C->getRHS(); 01127 return state->BindExpr(C, LCtx, UndefinedVal(Ex)); 01128 } 01129 } 01130 } 01131 01132 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used 01133 /// to try to recover some path-sensitivity for casts of symbolic 01134 /// integers that promote their values (which are currently not tracked well). 01135 /// This function returns the SVal bound to Condition->IgnoreCasts if all the 01136 // cast(s) did was sign-extend the original value. 01137 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr, 01138 ProgramStateRef state, 01139 const Stmt *Condition, 01140 const LocationContext *LCtx, 01141 ASTContext &Ctx) { 01142 01143 const Expr *Ex = dyn_cast<Expr>(Condition); 01144 if (!Ex) 01145 return UnknownVal(); 01146 01147 uint64_t bits = 0; 01148 bool bitsInit = false; 01149 01150 while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) { 01151 QualType T = CE->getType(); 01152 01153 if (!T->isIntegerType()) 01154 return UnknownVal(); 01155 01156 uint64_t newBits = Ctx.getTypeSize(T); 01157 if (!bitsInit || newBits < bits) { 01158 bitsInit = true; 01159 bits = newBits; 01160 } 01161 01162 Ex = CE->getSubExpr(); 01163 } 01164 01165 // We reached a non-cast. Is it a symbolic value? 01166 QualType T = Ex->getType(); 01167 01168 if (!bitsInit || !T->isIntegerType() || Ctx.getTypeSize(T) > bits) 01169 return UnknownVal(); 01170 01171 return state->getSVal(Ex, LCtx); 01172 } 01173 01174 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term, 01175 NodeBuilderContext& BldCtx, 01176 ExplodedNode *Pred, 01177 ExplodedNodeSet &Dst, 01178 const CFGBlock *DstT, 01179 const CFGBlock *DstF) { 01180 currentBuilderContext = &BldCtx; 01181 01182 // Check for NULL conditions; e.g. "for(;;)" 01183 if (!Condition) { 01184 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF); 01185 NullCondBldr.markInfeasible(false); 01186 NullCondBldr.generateNode(Pred->getState(), true, Pred); 01187 return; 01188 } 01189 01190 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 01191 Condition->getLocStart(), 01192 "Error evaluating branch"); 01193 01194 ExplodedNodeSet CheckersOutSet; 01195 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet, 01196 Pred, *this); 01197 // We generated only sinks. 01198 if (CheckersOutSet.empty()) 01199 return; 01200 01201 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF); 01202 for (NodeBuilder::iterator I = CheckersOutSet.begin(), 01203 E = CheckersOutSet.end(); E != I; ++I) { 01204 ExplodedNode *PredI = *I; 01205 01206 if (PredI->isSink()) 01207 continue; 01208 01209 ProgramStateRef PrevState = Pred->getState(); 01210 SVal X = PrevState->getSVal(Condition, Pred->getLocationContext()); 01211 01212 if (X.isUnknownOrUndef()) { 01213 // Give it a chance to recover from unknown. 01214 if (const Expr *Ex = dyn_cast<Expr>(Condition)) { 01215 if (Ex->getType()->isIntegerType()) { 01216 // Try to recover some path-sensitivity. Right now casts of symbolic 01217 // integers that promote their values are currently not tracked well. 01218 // If 'Condition' is such an expression, try and recover the 01219 // underlying value and use that instead. 01220 SVal recovered = RecoverCastedSymbol(getStateManager(), 01221 PrevState, Condition, 01222 Pred->getLocationContext(), 01223 getContext()); 01224 01225 if (!recovered.isUnknown()) { 01226 X = recovered; 01227 } 01228 } 01229 } 01230 } 01231 01232 const LocationContext *LCtx = PredI->getLocationContext(); 01233 01234 // If the condition is still unknown, give up. 01235 if (X.isUnknownOrUndef()) { 01236 builder.generateNode(MarkBranch(PrevState, Term, LCtx, true), 01237 true, PredI); 01238 builder.generateNode(MarkBranch(PrevState, Term, LCtx, false), 01239 false, PredI); 01240 continue; 01241 } 01242 01243 DefinedSVal V = cast<DefinedSVal>(X); 01244 01245 // Process the true branch. 01246 if (builder.isFeasible(true)) { 01247 if (ProgramStateRef state = PrevState->assume(V, true)) 01248 builder.generateNode(MarkBranch(state, Term, LCtx, true), 01249 true, PredI); 01250 else 01251 builder.markInfeasible(true); 01252 } 01253 01254 // Process the false branch. 01255 if (builder.isFeasible(false)) { 01256 if (ProgramStateRef state = PrevState->assume(V, false)) 01257 builder.generateNode(MarkBranch(state, Term, LCtx, false), 01258 false, PredI); 01259 else 01260 builder.markInfeasible(false); 01261 } 01262 } 01263 currentBuilderContext = 0; 01264 } 01265 01266 /// processIndirectGoto - Called by CoreEngine. Used to generate successor 01267 /// nodes by processing the 'effects' of a computed goto jump. 01268 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) { 01269 01270 ProgramStateRef state = builder.getState(); 01271 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext()); 01272 01273 // Three possibilities: 01274 // 01275 // (1) We know the computed label. 01276 // (2) The label is NULL (or some other constant), or Undefined. 01277 // (3) We have no clue about the label. Dispatch to all targets. 01278 // 01279 01280 typedef IndirectGotoNodeBuilder::iterator iterator; 01281 01282 if (isa<loc::GotoLabel>(V)) { 01283 const LabelDecl *L = cast<loc::GotoLabel>(V).getLabel(); 01284 01285 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) { 01286 if (I.getLabel() == L) { 01287 builder.generateNode(I, state); 01288 return; 01289 } 01290 } 01291 01292 llvm_unreachable("No block with label."); 01293 } 01294 01295 if (isa<loc::ConcreteInt>(V) || isa<UndefinedVal>(V)) { 01296 // Dispatch to the first target and mark it as a sink. 01297 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true); 01298 // FIXME: add checker visit. 01299 // UndefBranches.insert(N); 01300 return; 01301 } 01302 01303 // This is really a catch-all. We don't support symbolics yet. 01304 // FIXME: Implement dispatch for symbolic pointers. 01305 01306 for (iterator I=builder.begin(), E=builder.end(); I != E; ++I) 01307 builder.generateNode(I, state); 01308 } 01309 01310 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path 01311 /// nodes when the control reaches the end of a function. 01312 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC) { 01313 StateMgr.EndPath(BC.Pred->getState()); 01314 ExplodedNodeSet Dst; 01315 getCheckerManager().runCheckersForEndPath(BC, Dst, *this); 01316 Engine.enqueueEndOfFunction(Dst); 01317 } 01318 01319 /// ProcessSwitch - Called by CoreEngine. Used to generate successor 01320 /// nodes by processing the 'effects' of a switch statement. 01321 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) { 01322 typedef SwitchNodeBuilder::iterator iterator; 01323 ProgramStateRef state = builder.getState(); 01324 const Expr *CondE = builder.getCondition(); 01325 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext()); 01326 01327 if (CondV_untested.isUndef()) { 01328 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true); 01329 // FIXME: add checker 01330 //UndefBranches.insert(N); 01331 01332 return; 01333 } 01334 DefinedOrUnknownSVal CondV = cast<DefinedOrUnknownSVal>(CondV_untested); 01335 01336 ProgramStateRef DefaultSt = state; 01337 01338 iterator I = builder.begin(), EI = builder.end(); 01339 bool defaultIsFeasible = I == EI; 01340 01341 for ( ; I != EI; ++I) { 01342 // Successor may be pruned out during CFG construction. 01343 if (!I.getBlock()) 01344 continue; 01345 01346 const CaseStmt *Case = I.getCase(); 01347 01348 // Evaluate the LHS of the case value. 01349 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext()); 01350 assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType())); 01351 01352 // Get the RHS of the case, if it exists. 01353 llvm::APSInt V2; 01354 if (const Expr *E = Case->getRHS()) 01355 V2 = E->EvaluateKnownConstInt(getContext()); 01356 else 01357 V2 = V1; 01358 01359 // FIXME: Eventually we should replace the logic below with a range 01360 // comparison, rather than concretize the values within the range. 01361 // This should be easy once we have "ranges" for NonLVals. 01362 01363 do { 01364 nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1)); 01365 DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state, 01366 CondV, CaseVal); 01367 01368 // Now "assume" that the case matches. 01369 if (ProgramStateRef stateNew = state->assume(Res, true)) { 01370 builder.generateCaseStmtNode(I, stateNew); 01371 01372 // If CondV evaluates to a constant, then we know that this 01373 // is the *only* case that we can take, so stop evaluating the 01374 // others. 01375 if (isa<nonloc::ConcreteInt>(CondV)) 01376 return; 01377 } 01378 01379 // Now "assume" that the case doesn't match. Add this state 01380 // to the default state (if it is feasible). 01381 if (DefaultSt) { 01382 if (ProgramStateRef stateNew = DefaultSt->assume(Res, false)) { 01383 defaultIsFeasible = true; 01384 DefaultSt = stateNew; 01385 } 01386 else { 01387 defaultIsFeasible = false; 01388 DefaultSt = NULL; 01389 } 01390 } 01391 01392 // Concretize the next value in the range. 01393 if (V1 == V2) 01394 break; 01395 01396 ++V1; 01397 assert (V1 <= V2); 01398 01399 } while (true); 01400 } 01401 01402 if (!defaultIsFeasible) 01403 return; 01404 01405 // If we have switch(enum value), the default branch is not 01406 // feasible if all of the enum constants not covered by 'case:' statements 01407 // are not feasible values for the switch condition. 01408 // 01409 // Note that this isn't as accurate as it could be. Even if there isn't 01410 // a case for a particular enum value as long as that enum value isn't 01411 // feasible then it shouldn't be considered for making 'default:' reachable. 01412 const SwitchStmt *SS = builder.getSwitch(); 01413 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts(); 01414 if (CondExpr->getType()->getAs<EnumType>()) { 01415 if (SS->isAllEnumCasesCovered()) 01416 return; 01417 } 01418 01419 builder.generateDefaultCaseNode(DefaultSt); 01420 } 01421 01422 //===----------------------------------------------------------------------===// 01423 // Transfer functions: Loads and stores. 01424 //===----------------------------------------------------------------------===// 01425 01426 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D, 01427 ExplodedNode *Pred, 01428 ExplodedNodeSet &Dst) { 01429 StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext); 01430 01431 ProgramStateRef state = Pred->getState(); 01432 const LocationContext *LCtx = Pred->getLocationContext(); 01433 01434 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 01435 assert(Ex->isGLValue()); 01436 SVal V = state->getLValue(VD, Pred->getLocationContext()); 01437 01438 // For references, the 'lvalue' is the pointer address stored in the 01439 // reference region. 01440 if (VD->getType()->isReferenceType()) { 01441 if (const MemRegion *R = V.getAsRegion()) 01442 V = state->getSVal(R); 01443 else 01444 V = UnknownVal(); 01445 } 01446 01447 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), false, 0, 01448 ProgramPoint::PostLValueKind); 01449 return; 01450 } 01451 if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 01452 assert(!Ex->isGLValue()); 01453 SVal V = svalBuilder.makeIntVal(ED->getInitVal()); 01454 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V)); 01455 return; 01456 } 01457 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 01458 SVal V = svalBuilder.getFunctionPointer(FD); 01459 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), false, 0, 01460 ProgramPoint::PostLValueKind); 01461 return; 01462 } 01463 if (isa<FieldDecl>(D)) { 01464 // FIXME: Compute lvalue of fields. 01465 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, UnknownVal()), 01466 false, 0, ProgramPoint::PostLValueKind); 01467 return; 01468 } 01469 01470 assert (false && 01471 "ValueDecl support for this ValueDecl not implemented."); 01472 } 01473 01474 /// VisitArraySubscriptExpr - Transfer function for array accesses 01475 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A, 01476 ExplodedNode *Pred, 01477 ExplodedNodeSet &Dst){ 01478 01479 const Expr *Base = A->getBase()->IgnoreParens(); 01480 const Expr *Idx = A->getIdx()->IgnoreParens(); 01481 01482 01483 ExplodedNodeSet checkerPreStmt; 01484 getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this); 01485 01486 StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currentBuilderContext); 01487 01488 for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(), 01489 ei = checkerPreStmt.end(); it != ei; ++it) { 01490 const LocationContext *LCtx = (*it)->getLocationContext(); 01491 ProgramStateRef state = (*it)->getState(); 01492 SVal V = state->getLValue(A->getType(), 01493 state->getSVal(Idx, LCtx), 01494 state->getSVal(Base, LCtx)); 01495 assert(A->isGLValue()); 01496 Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), 01497 false, 0, ProgramPoint::PostLValueKind); 01498 } 01499 } 01500 01501 /// VisitMemberExpr - Transfer function for member expressions. 01502 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, 01503 ExplodedNodeSet &TopDst) { 01504 01505 StmtNodeBuilder Bldr(Pred, TopDst, *currentBuilderContext); 01506 ExplodedNodeSet Dst; 01507 Decl *member = M->getMemberDecl(); 01508 if (VarDecl *VD = dyn_cast<VarDecl>(member)) { 01509 assert(M->isGLValue()); 01510 Bldr.takeNodes(Pred); 01511 VisitCommonDeclRefExpr(M, VD, Pred, Dst); 01512 Bldr.addNodes(Dst); 01513 return; 01514 } 01515 01516 FieldDecl *field = dyn_cast<FieldDecl>(member); 01517 if (!field) // FIXME: skipping member expressions for non-fields 01518 return; 01519 01520 Expr *baseExpr = M->getBase()->IgnoreParens(); 01521 ProgramStateRef state = Pred->getState(); 01522 const LocationContext *LCtx = Pred->getLocationContext(); 01523 SVal baseExprVal = state->getSVal(baseExpr, Pred->getLocationContext()); 01524 if (isa<nonloc::LazyCompoundVal>(baseExprVal) || 01525 isa<nonloc::CompoundVal>(baseExprVal) || 01526 // FIXME: This can originate by conjuring a symbol for an unknown 01527 // temporary struct object, see test/Analysis/fields.c: 01528 // (p = getit()).x 01529 isa<nonloc::SymbolVal>(baseExprVal)) { 01530 Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, UnknownVal())); 01531 return; 01532 } 01533 01534 // FIXME: Should we insert some assumption logic in here to determine 01535 // if "Base" is a valid piece of memory? Before we put this assumption 01536 // later when using FieldOffset lvals (which we no longer have). 01537 01538 // For all other cases, compute an lvalue. 01539 SVal L = state->getLValue(field, baseExprVal); 01540 if (M->isGLValue()) 01541 Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, L), false, 0, 01542 ProgramPoint::PostLValueKind); 01543 else { 01544 Bldr.takeNodes(Pred); 01545 evalLoad(Dst, M, M, Pred, state, L); 01546 Bldr.addNodes(Dst); 01547 } 01548 } 01549 01550 /// evalBind - Handle the semantics of binding a value to a specific location. 01551 /// This method is used by evalStore and (soon) VisitDeclStmt, and others. 01552 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, 01553 ExplodedNode *Pred, 01554 SVal location, SVal Val, bool atDeclInit) { 01555 01556 // Do a previsit of the bind. 01557 ExplodedNodeSet CheckedSet; 01558 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val, 01559 StoreE, *this, 01560 ProgramPoint::PostStmtKind); 01561 01562 ExplodedNodeSet TmpDst; 01563 StmtNodeBuilder Bldr(CheckedSet, TmpDst, *currentBuilderContext); 01564 01565 const LocationContext *LC = Pred->getLocationContext(); 01566 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 01567 I!=E; ++I) { 01568 ExplodedNode *PredI = *I; 01569 ProgramStateRef state = PredI->getState(); 01570 01571 if (atDeclInit) { 01572 const VarRegion *VR = 01573 cast<VarRegion>(cast<loc::MemRegionVal>(location).getRegion()); 01574 01575 state = state->bindDecl(VR, Val); 01576 } else { 01577 state = state->bindLoc(location, Val); 01578 } 01579 01580 const MemRegion *LocReg = 0; 01581 if (loc::MemRegionVal *LocRegVal = dyn_cast<loc::MemRegionVal>(&location)) 01582 LocReg = LocRegVal->getRegion(); 01583 01584 const ProgramPoint L = PostStore(StoreE, LC, LocReg, 0); 01585 Bldr.generateNode(L, PredI, state, false); 01586 } 01587 01588 Dst.insert(TmpDst); 01589 } 01590 01591 /// evalStore - Handle the semantics of a store via an assignment. 01592 /// @param Dst The node set to store generated state nodes 01593 /// @param AssignE The assignment expression if the store happens in an 01594 /// assignment. 01595 /// @param LocatioinE The location expression that is stored to. 01596 /// @param state The current simulation state 01597 /// @param location The location to store the value 01598 /// @param Val The value to be stored 01599 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, 01600 const Expr *LocationE, 01601 ExplodedNode *Pred, 01602 ProgramStateRef state, SVal location, SVal Val, 01603 const ProgramPointTag *tag) { 01604 // Proceed with the store. We use AssignE as the anchor for the PostStore 01605 // ProgramPoint if it is non-NULL, and LocationE otherwise. 01606 const Expr *StoreE = AssignE ? AssignE : LocationE; 01607 01608 if (isa<loc::ObjCPropRef>(location)) { 01609 assert(false); 01610 } 01611 01612 // Evaluate the location (checks for bad dereferences). 01613 ExplodedNodeSet Tmp; 01614 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false); 01615 01616 if (Tmp.empty()) 01617 return; 01618 01619 if (location.isUndef()) 01620 return; 01621 01622 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) 01623 evalBind(Dst, StoreE, *NI, location, Val, false); 01624 } 01625 01626 void ExprEngine::evalLoad(ExplodedNodeSet &Dst, 01627 const Expr *NodeEx, 01628 const Expr *BoundEx, 01629 ExplodedNode *Pred, 01630 ProgramStateRef state, 01631 SVal location, 01632 const ProgramPointTag *tag, 01633 QualType LoadTy) 01634 { 01635 assert(!isa<NonLoc>(location) && "location cannot be a NonLoc."); 01636 assert(!isa<loc::ObjCPropRef>(location)); 01637 01638 // Are we loading from a region? This actually results in two loads; one 01639 // to fetch the address of the referenced value and one to fetch the 01640 // referenced value. 01641 if (const TypedValueRegion *TR = 01642 dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) { 01643 01644 QualType ValTy = TR->getValueType(); 01645 if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) { 01646 static SimpleProgramPointTag 01647 loadReferenceTag("ExprEngine : Load Reference"); 01648 ExplodedNodeSet Tmp; 01649 evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state, 01650 location, &loadReferenceTag, 01651 getContext().getPointerType(RT->getPointeeType())); 01652 01653 // Perform the load from the referenced value. 01654 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) { 01655 state = (*I)->getState(); 01656 location = state->getSVal(BoundEx, (*I)->getLocationContext()); 01657 evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy); 01658 } 01659 return; 01660 } 01661 } 01662 01663 evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy); 01664 } 01665 01666 void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst, 01667 const Expr *NodeEx, 01668 const Expr *BoundEx, 01669 ExplodedNode *Pred, 01670 ProgramStateRef state, 01671 SVal location, 01672 const ProgramPointTag *tag, 01673 QualType LoadTy) { 01674 assert(NodeEx); 01675 assert(BoundEx); 01676 // Evaluate the location (checks for bad dereferences). 01677 ExplodedNodeSet Tmp; 01678 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true); 01679 if (Tmp.empty()) 01680 return; 01681 01682 StmtNodeBuilder Bldr(Tmp, Dst, *currentBuilderContext); 01683 if (location.isUndef()) 01684 return; 01685 01686 // Proceed with the load. 01687 for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) { 01688 state = (*NI)->getState(); 01689 const LocationContext *LCtx = (*NI)->getLocationContext(); 01690 01691 if (location.isUnknown()) { 01692 // This is important. We must nuke the old binding. 01693 Bldr.generateNode(NodeEx, *NI, 01694 state->BindExpr(BoundEx, LCtx, UnknownVal()), 01695 false, tag, 01696 ProgramPoint::PostLoadKind); 01697 } 01698 else { 01699 if (LoadTy.isNull()) 01700 LoadTy = BoundEx->getType(); 01701 SVal V = state->getSVal(cast<Loc>(location), LoadTy); 01702 Bldr.generateNode(NodeEx, *NI, 01703 state->bindExprAndLocation(BoundEx, LCtx, location, V), 01704 false, tag, ProgramPoint::PostLoadKind); 01705 } 01706 } 01707 } 01708 01709 void ExprEngine::evalLocation(ExplodedNodeSet &Dst, 01710 const Stmt *NodeEx, 01711 const Stmt *BoundEx, 01712 ExplodedNode *Pred, 01713 ProgramStateRef state, 01714 SVal location, 01715 const ProgramPointTag *tag, 01716 bool isLoad) { 01717 StmtNodeBuilder BldrTop(Pred, Dst, *currentBuilderContext); 01718 // Early checks for performance reason. 01719 if (location.isUnknown()) { 01720 return; 01721 } 01722 01723 ExplodedNodeSet Src; 01724 BldrTop.takeNodes(Pred); 01725 StmtNodeBuilder Bldr(Pred, Src, *currentBuilderContext); 01726 if (Pred->getState() != state) { 01727 // Associate this new state with an ExplodedNode. 01728 // FIXME: If I pass null tag, the graph is incorrect, e.g for 01729 // int *p; 01730 // p = 0; 01731 // *p = 0xDEADBEEF; 01732 // "p = 0" is not noted as "Null pointer value stored to 'p'" but 01733 // instead "int *p" is noted as 01734 // "Variable 'p' initialized to a null pointer value" 01735 01736 // FIXME: why is 'tag' not used instead of etag? 01737 static SimpleProgramPointTag etag("ExprEngine: Location"); 01738 Bldr.generateNode(NodeEx, Pred, state, false, &etag); 01739 } 01740 ExplodedNodeSet Tmp; 01741 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad, 01742 NodeEx, BoundEx, *this); 01743 BldrTop.addNodes(Tmp); 01744 } 01745 01746 std::pair<const ProgramPointTag *, const ProgramPointTag*> 01747 ExprEngine::getEagerlyAssumeTags() { 01748 static SimpleProgramPointTag 01749 EagerlyAssumeTrue("ExprEngine : Eagerly Assume True"), 01750 EagerlyAssumeFalse("ExprEngine : Eagerly Assume False"); 01751 return std::make_pair(&EagerlyAssumeTrue, &EagerlyAssumeFalse); 01752 } 01753 01754 void ExprEngine::evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, 01755 const Expr *Ex) { 01756 StmtNodeBuilder Bldr(Src, Dst, *currentBuilderContext); 01757 01758 for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) { 01759 ExplodedNode *Pred = *I; 01760 // Test if the previous node was as the same expression. This can happen 01761 // when the expression fails to evaluate to anything meaningful and 01762 // (as an optimization) we don't generate a node. 01763 ProgramPoint P = Pred->getLocation(); 01764 if (!isa<PostStmt>(P) || cast<PostStmt>(P).getStmt() != Ex) { 01765 continue; 01766 } 01767 01768 ProgramStateRef state = Pred->getState(); 01769 SVal V = state->getSVal(Ex, Pred->getLocationContext()); 01770 nonloc::SymbolVal *SEV = dyn_cast<nonloc::SymbolVal>(&V); 01771 if (SEV && SEV->isExpression()) { 01772 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags = 01773 getEagerlyAssumeTags(); 01774 01775 // First assume that the condition is true. 01776 if (ProgramStateRef StateTrue = state->assume(*SEV, true)) { 01777 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType()); 01778 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val); 01779 Bldr.generateNode(Ex, Pred, StateTrue, false, tags.first); 01780 } 01781 01782 // Next, assume that the condition is false. 01783 if (ProgramStateRef StateFalse = state->assume(*SEV, false)) { 01784 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType()); 01785 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val); 01786 Bldr.generateNode(Ex, Pred, StateFalse, false, tags.second); 01787 } 01788 } 01789 } 01790 } 01791 01792 void ExprEngine::VisitAsmStmt(const AsmStmt *A, ExplodedNode *Pred, 01793 ExplodedNodeSet &Dst) { 01794 StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext); 01795 // We have processed both the inputs and the outputs. All of the outputs 01796 // should evaluate to Locs. Nuke all of their values. 01797 01798 // FIXME: Some day in the future it would be nice to allow a "plug-in" 01799 // which interprets the inline asm and stores proper results in the 01800 // outputs. 01801 01802 ProgramStateRef state = Pred->getState(); 01803 01804 for (AsmStmt::const_outputs_iterator OI = A->begin_outputs(), 01805 OE = A->end_outputs(); OI != OE; ++OI) { 01806 SVal X = state->getSVal(*OI, Pred->getLocationContext()); 01807 assert (!isa<NonLoc>(X)); // Should be an Lval, or unknown, undef. 01808 01809 if (isa<Loc>(X)) 01810 state = state->bindLoc(cast<Loc>(X), UnknownVal()); 01811 } 01812 01813 Bldr.generateNode(A, Pred, state); 01814 } 01815 01816 //===----------------------------------------------------------------------===// 01817 // Visualization. 01818 //===----------------------------------------------------------------------===// 01819 01820 #ifndef NDEBUG 01821 static ExprEngine* GraphPrintCheckerState; 01822 static SourceManager* GraphPrintSourceManager; 01823 01824 namespace llvm { 01825 template<> 01826 struct DOTGraphTraits<ExplodedNode*> : 01827 public DefaultDOTGraphTraits { 01828 01829 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 01830 01831 // FIXME: Since we do not cache error nodes in ExprEngine now, this does not 01832 // work. 01833 static std::string getNodeAttributes(const ExplodedNode *N, void*) { 01834 01835 #if 0 01836 // FIXME: Replace with a general scheme to tell if the node is 01837 // an error node. 01838 if (GraphPrintCheckerState->isImplicitNullDeref(N) || 01839 GraphPrintCheckerState->isExplicitNullDeref(N) || 01840 GraphPrintCheckerState->isUndefDeref(N) || 01841 GraphPrintCheckerState->isUndefStore(N) || 01842 GraphPrintCheckerState->isUndefControlFlow(N) || 01843 GraphPrintCheckerState->isUndefResult(N) || 01844 GraphPrintCheckerState->isBadCall(N) || 01845 GraphPrintCheckerState->isUndefArg(N)) 01846 return "color=\"red\",style=\"filled\""; 01847 01848 if (GraphPrintCheckerState->isNoReturnCall(N)) 01849 return "color=\"blue\",style=\"filled\""; 01850 #endif 01851 return ""; 01852 } 01853 01854 static std::string getNodeLabel(const ExplodedNode *N, void*){ 01855 01856 std::string sbuf; 01857 llvm::raw_string_ostream Out(sbuf); 01858 01859 // Program Location. 01860 ProgramPoint Loc = N->getLocation(); 01861 01862 switch (Loc.getKind()) { 01863 case ProgramPoint::BlockEntranceKind: { 01864 Out << "Block Entrance: B" 01865 << cast<BlockEntrance>(Loc).getBlock()->getBlockID(); 01866 if (const NamedDecl *ND = 01867 dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) { 01868 Out << " ("; 01869 ND->printName(Out); 01870 Out << ")"; 01871 } 01872 break; 01873 } 01874 01875 case ProgramPoint::BlockExitKind: 01876 assert (false); 01877 break; 01878 01879 case ProgramPoint::CallEnterKind: 01880 Out << "CallEnter"; 01881 break; 01882 01883 case ProgramPoint::CallExitBeginKind: 01884 Out << "CallExitBegin"; 01885 break; 01886 01887 case ProgramPoint::CallExitEndKind: 01888 Out << "CallExitEnd"; 01889 break; 01890 01891 case ProgramPoint::PostStmtPurgeDeadSymbolsKind: 01892 Out << "PostStmtPurgeDeadSymbols"; 01893 break; 01894 01895 case ProgramPoint::PreStmtPurgeDeadSymbolsKind: 01896 Out << "PreStmtPurgeDeadSymbols"; 01897 break; 01898 01899 case ProgramPoint::EpsilonKind: 01900 Out << "Epsilon Point"; 01901 break; 01902 01903 default: { 01904 if (StmtPoint *L = dyn_cast<StmtPoint>(&Loc)) { 01905 const Stmt *S = L->getStmt(); 01906 SourceLocation SLoc = S->getLocStart(); 01907 01908 Out << S->getStmtClassName() << ' ' << (void*) S << ' '; 01909 LangOptions LO; // FIXME. 01910 S->printPretty(Out, 0, PrintingPolicy(LO)); 01911 01912 if (SLoc.isFileID()) { 01913 Out << "\\lline=" 01914 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 01915 << " col=" 01916 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc) 01917 << "\\l"; 01918 } 01919 01920 if (isa<PreStmt>(Loc)) 01921 Out << "\\lPreStmt\\l;"; 01922 else if (isa<PostLoad>(Loc)) 01923 Out << "\\lPostLoad\\l;"; 01924 else if (isa<PostStore>(Loc)) 01925 Out << "\\lPostStore\\l"; 01926 else if (isa<PostLValue>(Loc)) 01927 Out << "\\lPostLValue\\l"; 01928 01929 #if 0 01930 // FIXME: Replace with a general scheme to determine 01931 // the name of the check. 01932 if (GraphPrintCheckerState->isImplicitNullDeref(N)) 01933 Out << "\\|Implicit-Null Dereference.\\l"; 01934 else if (GraphPrintCheckerState->isExplicitNullDeref(N)) 01935 Out << "\\|Explicit-Null Dereference.\\l"; 01936 else if (GraphPrintCheckerState->isUndefDeref(N)) 01937 Out << "\\|Dereference of undefialied value.\\l"; 01938 else if (GraphPrintCheckerState->isUndefStore(N)) 01939 Out << "\\|Store to Undefined Loc."; 01940 else if (GraphPrintCheckerState->isUndefResult(N)) 01941 Out << "\\|Result of operation is undefined."; 01942 else if (GraphPrintCheckerState->isNoReturnCall(N)) 01943 Out << "\\|Call to function marked \"noreturn\"."; 01944 else if (GraphPrintCheckerState->isBadCall(N)) 01945 Out << "\\|Call to NULL/Undefined."; 01946 else if (GraphPrintCheckerState->isUndefArg(N)) 01947 Out << "\\|Argument in call is undefined"; 01948 #endif 01949 01950 break; 01951 } 01952 01953 const BlockEdge &E = cast<BlockEdge>(Loc); 01954 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B" 01955 << E.getDst()->getBlockID() << ')'; 01956 01957 if (const Stmt *T = E.getSrc()->getTerminator()) { 01958 01959 SourceLocation SLoc = T->getLocStart(); 01960 01961 Out << "\\|Terminator: "; 01962 LangOptions LO; // FIXME. 01963 E.getSrc()->printTerminator(Out, LO); 01964 01965 if (SLoc.isFileID()) { 01966 Out << "\\lline=" 01967 << GraphPrintSourceManager->getExpansionLineNumber(SLoc) 01968 << " col=" 01969 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc); 01970 } 01971 01972 if (isa<SwitchStmt>(T)) { 01973 const Stmt *Label = E.getDst()->getLabel(); 01974 01975 if (Label) { 01976 if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) { 01977 Out << "\\lcase "; 01978 LangOptions LO; // FIXME. 01979 C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO)); 01980 01981 if (const Stmt *RHS = C->getRHS()) { 01982 Out << " .. "; 01983 RHS->printPretty(Out, 0, PrintingPolicy(LO)); 01984 } 01985 01986 Out << ":"; 01987 } 01988 else { 01989 assert (isa<DefaultStmt>(Label)); 01990 Out << "\\ldefault:"; 01991 } 01992 } 01993 else 01994 Out << "\\l(implicit) default:"; 01995 } 01996 else if (isa<IndirectGotoStmt>(T)) { 01997 // FIXME 01998 } 01999 else { 02000 Out << "\\lCondition: "; 02001 if (*E.getSrc()->succ_begin() == E.getDst()) 02002 Out << "true"; 02003 else 02004 Out << "false"; 02005 } 02006 02007 Out << "\\l"; 02008 } 02009 02010 #if 0 02011 // FIXME: Replace with a general scheme to determine 02012 // the name of the check. 02013 if (GraphPrintCheckerState->isUndefControlFlow(N)) { 02014 Out << "\\|Control-flow based on\\lUndefined value.\\l"; 02015 } 02016 #endif 02017 } 02018 } 02019 02020 ProgramStateRef state = N->getState(); 02021 Out << "\\|StateID: " << (void*) state.getPtr() 02022 << " NodeID: " << (void*) N << "\\|"; 02023 state->printDOT(Out); 02024 02025 Out << "\\l"; 02026 02027 if (const ProgramPointTag *tag = Loc.getTag()) { 02028 Out << "\\|Tag: " << tag->getTagDescription(); 02029 Out << "\\l"; 02030 } 02031 return Out.str(); 02032 } 02033 }; 02034 } // end llvm namespace 02035 #endif 02036 02037 #ifndef NDEBUG 02038 template <typename ITERATOR> 02039 ExplodedNode *GetGraphNode(ITERATOR I) { return *I; } 02040 02041 template <> ExplodedNode* 02042 GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator> 02043 (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) { 02044 return I->first; 02045 } 02046 #endif 02047 02048 void ExprEngine::ViewGraph(bool trim) { 02049 #ifndef NDEBUG 02050 if (trim) { 02051 std::vector<ExplodedNode*> Src; 02052 02053 // Flush any outstanding reports to make sure we cover all the nodes. 02054 // This does not cause them to get displayed. 02055 for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I) 02056 const_cast<BugType*>(*I)->FlushReports(BR); 02057 02058 // Iterate through the reports and get their nodes. 02059 for (BugReporter::EQClasses_iterator 02060 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) { 02061 ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode()); 02062 if (N) Src.push_back(N); 02063 } 02064 02065 ViewGraph(&Src[0], &Src[0]+Src.size()); 02066 } 02067 else { 02068 GraphPrintCheckerState = this; 02069 GraphPrintSourceManager = &getContext().getSourceManager(); 02070 02071 llvm::ViewGraph(*G.roots_begin(), "ExprEngine"); 02072 02073 GraphPrintCheckerState = NULL; 02074 GraphPrintSourceManager = NULL; 02075 } 02076 #endif 02077 } 02078 02079 void ExprEngine::ViewGraph(ExplodedNode** Beg, ExplodedNode** End) { 02080 #ifndef NDEBUG 02081 GraphPrintCheckerState = this; 02082 GraphPrintSourceManager = &getContext().getSourceManager(); 02083 02084 std::auto_ptr<ExplodedGraph> TrimmedG(G.Trim(Beg, End).first); 02085 02086 if (!TrimmedG.get()) 02087 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n"; 02088 else 02089 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine"); 02090 02091 GraphPrintCheckerState = NULL; 02092 GraphPrintSourceManager = NULL; 02093 #endif 02094 }