DeadStoresChecker.cpp revision 9c378f705405d37f49795d5e915989de774fe11f
1//==- DeadStoresChecker.cpp - Check for stores to dead variables -*- 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 DeadStores, a flow-sensitive checker that looks for 11// stores to variables that are no longer live. 12// 13//===----------------------------------------------------------------------===// 14 15#include "ClangSACheckers.h" 16#include "clang/StaticAnalyzer/Core/Checker.h" 17#include "clang/Analysis/Analyses/LiveVariables.h" 18#include "clang/Analysis/Visitors/CFGRecStmtVisitor.h" 19#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 20#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 21#include "clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h" 22#include "clang/Basic/Diagnostic.h" 23#include "clang/AST/ASTContext.h" 24#include "clang/AST/ParentMap.h" 25#include "llvm/ADT/SmallPtrSet.h" 26 27using namespace clang; 28using namespace ento; 29 30namespace { 31 32// FIXME: Eventually migrate into its own file, and have it managed by 33// AnalysisManager. 34class ReachableCode { 35 const CFG &cfg; 36 llvm::BitVector reachable; 37public: 38 ReachableCode(const CFG &cfg) 39 : cfg(cfg), reachable(cfg.getNumBlockIDs(), false) {} 40 41 void computeReachableBlocks(); 42 43 bool isReachable(const CFGBlock *block) const { 44 return reachable[block->getBlockID()]; 45 } 46}; 47} 48 49void ReachableCode::computeReachableBlocks() { 50 if (!cfg.getNumBlockIDs()) 51 return; 52 53 SmallVector<const CFGBlock*, 10> worklist; 54 worklist.push_back(&cfg.getEntry()); 55 56 while (!worklist.empty()) { 57 const CFGBlock *block = worklist.back(); 58 worklist.pop_back(); 59 llvm::BitVector::reference isReachable = reachable[block->getBlockID()]; 60 if (isReachable) 61 continue; 62 isReachable = true; 63 for (CFGBlock::const_succ_iterator i = block->succ_begin(), 64 e = block->succ_end(); i != e; ++i) 65 if (const CFGBlock *succ = *i) 66 worklist.push_back(succ); 67 } 68} 69 70namespace { 71class DeadStoreObs : public LiveVariables::Observer { 72 const CFG &cfg; 73 ASTContext &Ctx; 74 BugReporter& BR; 75 ParentMap& Parents; 76 llvm::SmallPtrSet<const VarDecl*, 20> Escaped; 77 llvm::OwningPtr<ReachableCode> reachableCode; 78 const CFGBlock *currentBlock; 79 80 enum DeadStoreKind { Standard, Enclosing, DeadIncrement, DeadInit }; 81 82public: 83 DeadStoreObs(const CFG &cfg, ASTContext &ctx, 84 BugReporter& br, ParentMap& parents, 85 llvm::SmallPtrSet<const VarDecl*, 20> &escaped) 86 : cfg(cfg), Ctx(ctx), BR(br), Parents(parents), 87 Escaped(escaped), currentBlock(0) {} 88 89 virtual ~DeadStoreObs() {} 90 91 void Report(const VarDecl *V, DeadStoreKind dsk, 92 SourceLocation L, SourceRange R) { 93 if (Escaped.count(V)) 94 return; 95 96 // Compute reachable blocks within the CFG for trivial cases 97 // where a bogus dead store can be reported because itself is unreachable. 98 if (!reachableCode.get()) { 99 reachableCode.reset(new ReachableCode(cfg)); 100 reachableCode->computeReachableBlocks(); 101 } 102 103 if (!reachableCode->isReachable(currentBlock)) 104 return; 105 106 const std::string &name = V->getNameAsString(); 107 108 const char* BugType = 0; 109 std::string msg; 110 111 switch (dsk) { 112 default: 113 assert(false && "Impossible dead store type."); 114 115 case DeadInit: 116 BugType = "Dead initialization"; 117 msg = "Value stored to '" + name + 118 "' during its initialization is never read"; 119 break; 120 121 case DeadIncrement: 122 BugType = "Dead increment"; 123 case Standard: 124 if (!BugType) BugType = "Dead assignment"; 125 msg = "Value stored to '" + name + "' is never read"; 126 break; 127 128 case Enclosing: 129 // Don't report issues in this case, e.g.: "if (x = foo())", 130 // where 'x' is unused later. We have yet to see a case where 131 // this is a real bug. 132 return; 133 } 134 135 BR.EmitBasicReport(BugType, "Dead store", msg, L, R); 136 } 137 138 void CheckVarDecl(const VarDecl *VD, const Expr *Ex, const Expr *Val, 139 DeadStoreKind dsk, 140 const LiveVariables::LivenessValues &Live) { 141 142 if (!VD->hasLocalStorage()) 143 return; 144 // Reference types confuse the dead stores checker. Skip them 145 // for now. 146 if (VD->getType()->getAs<ReferenceType>()) 147 return; 148 149 if (!Live.isLive(VD) && 150 !(VD->getAttr<UnusedAttr>() || VD->getAttr<BlocksAttr>())) 151 Report(VD, dsk, Ex->getSourceRange().getBegin(), 152 Val->getSourceRange()); 153 } 154 155 void CheckDeclRef(const DeclRefExpr *DR, const Expr *Val, DeadStoreKind dsk, 156 const LiveVariables::LivenessValues& Live) { 157 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) 158 CheckVarDecl(VD, DR, Val, dsk, Live); 159 } 160 161 bool isIncrement(VarDecl *VD, const BinaryOperator* B) { 162 if (B->isCompoundAssignmentOp()) 163 return true; 164 165 const Expr *RHS = B->getRHS()->IgnoreParenCasts(); 166 const BinaryOperator* BRHS = dyn_cast<BinaryOperator>(RHS); 167 168 if (!BRHS) 169 return false; 170 171 const DeclRefExpr *DR; 172 173 if ((DR = dyn_cast<DeclRefExpr>(BRHS->getLHS()->IgnoreParenCasts()))) 174 if (DR->getDecl() == VD) 175 return true; 176 177 if ((DR = dyn_cast<DeclRefExpr>(BRHS->getRHS()->IgnoreParenCasts()))) 178 if (DR->getDecl() == VD) 179 return true; 180 181 return false; 182 } 183 184 virtual void observeStmt(const Stmt *S, const CFGBlock *block, 185 const LiveVariables::LivenessValues &Live) { 186 187 currentBlock = block; 188 189 // Skip statements in macros. 190 if (S->getLocStart().isMacroID()) 191 return; 192 193 // Only cover dead stores from regular assignments. ++/-- dead stores 194 // have never flagged a real bug. 195 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) { 196 if (!B->isAssignmentOp()) return; // Skip non-assignments. 197 198 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(B->getLHS())) 199 if (VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 200 // Special case: check for assigning null to a pointer. 201 // This is a common form of defensive programming. 202 QualType T = VD->getType(); 203 if (T->isPointerType() || T->isObjCObjectPointerType()) { 204 if (B->getRHS()->isNullPointerConstant(Ctx, 205 Expr::NPC_ValueDependentIsNull)) 206 return; 207 } 208 209 Expr *RHS = B->getRHS()->IgnoreParenCasts(); 210 // Special case: self-assignments. These are often used to shut up 211 // "unused variable" compiler warnings. 212 if (DeclRefExpr *RhsDR = dyn_cast<DeclRefExpr>(RHS)) 213 if (VD == dyn_cast<VarDecl>(RhsDR->getDecl())) 214 return; 215 216 // Otherwise, issue a warning. 217 DeadStoreKind dsk = Parents.isConsumedExpr(B) 218 ? Enclosing 219 : (isIncrement(VD,B) ? DeadIncrement : Standard); 220 221 CheckVarDecl(VD, DR, B->getRHS(), dsk, Live); 222 } 223 } 224 else if (const UnaryOperator* U = dyn_cast<UnaryOperator>(S)) { 225 if (!U->isIncrementOp() || U->isPrefix()) 226 return; 227 228 const Stmt *parent = Parents.getParentIgnoreParenCasts(U); 229 if (!parent || !isa<ReturnStmt>(parent)) 230 return; 231 232 const Expr *Ex = U->getSubExpr()->IgnoreParenCasts(); 233 234 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) 235 CheckDeclRef(DR, U, DeadIncrement, Live); 236 } 237 else if (const DeclStmt *DS = dyn_cast<DeclStmt>(S)) 238 // Iterate through the decls. Warn if any initializers are complex 239 // expressions that are not live (never used). 240 for (DeclStmt::const_decl_iterator DI=DS->decl_begin(), DE=DS->decl_end(); 241 DI != DE; ++DI) { 242 243 VarDecl *V = dyn_cast<VarDecl>(*DI); 244 245 if (!V) 246 continue; 247 248 if (V->hasLocalStorage()) { 249 // Reference types confuse the dead stores checker. Skip them 250 // for now. 251 if (V->getType()->getAs<ReferenceType>()) 252 return; 253 254 if (Expr *E = V->getInit()) { 255 while (ExprWithCleanups *exprClean = dyn_cast<ExprWithCleanups>(E)) 256 E = exprClean->getSubExpr(); 257 258 // Don't warn on C++ objects (yet) until we can show that their 259 // constructors/destructors don't have side effects. 260 if (isa<CXXConstructExpr>(E)) 261 return; 262 263 // A dead initialization is a variable that is dead after it 264 // is initialized. We don't flag warnings for those variables 265 // marked 'unused'. 266 if (!Live.isLive(V) && V->getAttr<UnusedAttr>() == 0) { 267 // Special case: check for initializations with constants. 268 // 269 // e.g. : int x = 0; 270 // 271 // If x is EVER assigned a new value later, don't issue 272 // a warning. This is because such initialization can be 273 // due to defensive programming. 274 if (E->isConstantInitializer(Ctx, false)) 275 return; 276 277 if (DeclRefExpr *DRE=dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 278 if (VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 279 // Special case: check for initialization from constant 280 // variables. 281 // 282 // e.g. extern const int MyConstant; 283 // int x = MyConstant; 284 // 285 if (VD->hasGlobalStorage() && 286 VD->getType().isConstQualified()) 287 return; 288 // Special case: check for initialization from scalar 289 // parameters. This is often a form of defensive 290 // programming. Non-scalars are still an error since 291 // because it more likely represents an actual algorithmic 292 // bug. 293 if (isa<ParmVarDecl>(VD) && VD->getType()->isScalarType()) 294 return; 295 } 296 297 Report(V, DeadInit, V->getLocation(), E->getSourceRange()); 298 } 299 } 300 } 301 } 302 } 303}; 304 305} // end anonymous namespace 306 307//===----------------------------------------------------------------------===// 308// Driver function to invoke the Dead-Stores checker on a CFG. 309//===----------------------------------------------------------------------===// 310 311namespace { 312class FindEscaped : public CFGRecStmtDeclVisitor<FindEscaped>{ 313 CFG *cfg; 314public: 315 FindEscaped(CFG *c) : cfg(c) {} 316 317 CFG& getCFG() { return *cfg; } 318 319 llvm::SmallPtrSet<const VarDecl*, 20> Escaped; 320 321 void VisitUnaryOperator(UnaryOperator* U) { 322 // Check for '&'. Any VarDecl whose value has its address-taken we 323 // treat as escaped. 324 Expr *E = U->getSubExpr()->IgnoreParenCasts(); 325 if (U->getOpcode() == UO_AddrOf) 326 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 327 if (VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 328 Escaped.insert(VD); 329 return; 330 } 331 Visit(E); 332 } 333}; 334} // end anonymous namespace 335 336 337//===----------------------------------------------------------------------===// 338// DeadStoresChecker 339//===----------------------------------------------------------------------===// 340 341namespace { 342class DeadStoresChecker : public Checker<check::ASTCodeBody> { 343public: 344 void checkASTCodeBody(const Decl *D, AnalysisManager& mgr, 345 BugReporter &BR) const { 346 if (LiveVariables *L = mgr.getLiveVariables(D)) { 347 CFG &cfg = *mgr.getCFG(D); 348 ParentMap &pmap = mgr.getParentMap(D); 349 FindEscaped FS(&cfg); 350 FS.getCFG().VisitBlockStmts(FS); 351 DeadStoreObs A(cfg, BR.getContext(), BR, pmap, FS.Escaped); 352 L->runOnAllBlocks(A); 353 } 354 } 355}; 356} 357 358void ento::registerDeadStoresChecker(CheckerManager &mgr) { 359 mgr.registerChecker<DeadStoresChecker>(); 360} 361