From: Ted Kremenek Date: Tue, 11 Sep 2007 17:24:14 +0000 (+0000) Subject: For looking at "dead stores" in declarations, we now check to see X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=ce1cab9fc0b4aec9cdef1b30a14e4ccdca3ac5f1;p=clang For looking at "dead stores" in declarations, we now check to see if the assigned value is a constant expression, e.g.: int x = 0; We then check to see if "x" is ever reassigned later. If so, we don't emit a warning. This is because programmers frequently use defensive programming to make sure a variable has a defined value. git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@41853 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/Analysis/DeadStores.cpp b/Analysis/DeadStores.cpp index e547989f6b..91034e3894 100644 --- a/Analysis/DeadStores.cpp +++ b/Analysis/DeadStores.cpp @@ -18,6 +18,7 @@ #include "clang/AST/CFG.h" #include "clang/Basic/Diagnostic.h" #include "clang/Lex/Preprocessor.h" +#include "clang/AST/ASTContext.h" using namespace clang; @@ -25,8 +26,11 @@ namespace { class DeadStoreObserver : public LiveVariablesObserver { Preprocessor& PP; + ASTContext Ctx; public: - DeadStoreObserver(Preprocessor& pp) : PP(pp) {} + DeadStoreObserver(Preprocessor& pp) : + PP(pp), Ctx(PP.getTargetInfo(), PP.getIdentifierTable()) {} + virtual ~DeadStoreObserver() {} virtual void ObserveStmt(Stmt* S, LiveVariables& L, llvm::BitVector& Live) { @@ -52,12 +56,22 @@ public: for (VarDecl* V = cast(DS->getDecl()); V != NULL ; V = cast_or_null(V->getNextDeclarator())) if (Expr* E = V->getInit()) - if (!L.isLive(Live,V)) { - SourceRange R = E->getSourceRange(); - PP.getDiagnostics().Report(V->getLocation(), - diag::warn_dead_store, 0, 0, - &R,1); - } + if (!L.isLive(Live,V)) + // Special case: check for initializations with constants. + // + // e.g. : int x = 0; + // + // If x is EVER assigned a new value later, don't issue + // a warning. This is because such initialization can be + // due to defensive programming. + if (!E->isConstantExpr(Ctx,NULL) || + L.getVarInfo(V).Kills.size() == 0) { + // Flag a warning. + SourceRange R = E->getSourceRange(); + PP.getDiagnostics().Report(V->getLocation(), + diag::warn_dead_store, 0, 0, + &R,1); + } } } };