24 #include "llvm/ADT/BitVector.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/Support/SaveAndRestore.h"
28 using namespace clang;
41 return ::RecursiveASTVisitor<EHCodeVisitor>::TraverseObjCAtFinallyStmt(S);
46 return ::RecursiveASTVisitor<EHCodeVisitor>::TraverseObjCAtCatchStmt(S);
69 llvm::BitVector reachable;
71 ReachableCode(
const CFG &cfg)
72 : cfg(cfg), reachable(cfg.getNumBlockIDs(),
false) {}
74 void computeReachableBlocks();
76 bool isReachable(
const CFGBlock *block)
const {
82 void ReachableCode::computeReachableBlocks() {
83 if (!cfg.getNumBlockIDs())
87 worklist.push_back(&cfg.getEntry());
89 while (!worklist.empty()) {
90 const CFGBlock *block = worklist.pop_back_val();
91 llvm::BitVector::reference isReachable = reachable[block->
getBlockID()];
98 worklist.push_back(succ);
130 llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
131 std::unique_ptr<ReachableCode> reachableCode;
133 std::unique_ptr<llvm::DenseSet<const VarDecl *>> InEH;
135 enum DeadStoreKind { Standard, Enclosing, DeadIncrement, DeadInit };
141 llvm::SmallPtrSet<const VarDecl *, 20> &escaped)
142 : cfg(cfg), Ctx(ctx), BR(br),
Checker(checker), AC(ac), Parents(parents),
143 Escaped(escaped), currentBlock(nullptr) {}
145 ~DeadStoreObs()
override {}
154 EHCodeVisitor V(*InEH.get());
155 V.TraverseStmt(AC->getBody());
161 return InEH->count(D);
164 void Report(
const VarDecl *V, DeadStoreKind dsk,
166 if (Escaped.count(V))
171 if (!reachableCode.get()) {
172 reachableCode.reset(
new ReachableCode(cfg));
173 reachableCode->computeReachableBlocks();
176 if (!reachableCode->isReachable(currentBlock))
180 llvm::raw_svector_ostream os(buf);
185 BugType =
"Dead initialization";
186 os <<
"Value stored to '" << *V
187 <<
"' during its initialization is never read";
191 BugType =
"Dead increment";
193 if (!BugType) BugType =
"Dead assignment";
194 os <<
"Value stored to '" << *V <<
"' is never read";
204 BR.EmitBasicReport(AC->getDecl(),
Checker, BugType,
"Dead store", os.str(),
219 if (!isLive(Live, VD) &&
220 !(VD->hasAttr<UnusedAttr>() || VD->hasAttr<BlocksAttr>() ||
221 VD->hasAttr<ObjCPreciseLifetimeAttr>())) {
225 Report(VD, dsk, ExLoc, Val->getSourceRange());
229 void CheckDeclRef(
const DeclRefExpr *DR,
const Expr *Val, DeadStoreKind dsk,
232 CheckVarDecl(VD, DR, Val, dsk, Live);
261 currentBlock = block;
264 if (S->getLocStart().isMacroID())
290 if (
const DeclRefExpr *RhsDR = dyn_cast<DeclRefExpr>(RHS))
291 if (VD == dyn_cast<VarDecl>(RhsDR->getDecl()))
295 DeadStoreKind dsk = Parents.isConsumedExpr(B)
297 : (isIncrement(VD,B) ? DeadIncrement : Standard);
299 CheckVarDecl(VD, DR, B->
getRHS(), dsk, Live);
302 else if (
const UnaryOperator* U = dyn_cast<UnaryOperator>(S)) {
303 if (!U->isIncrementOp() || U->isPrefix())
306 const Stmt *parent = Parents.getParentIgnoreParenCasts(U);
307 if (!parent || !isa<ReturnStmt>(parent))
312 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex))
313 CheckDeclRef(DR, U, DeadIncrement, Live);
315 else if (
const DeclStmt *DS = dyn_cast<DeclStmt>(S))
318 for (
const auto *DI : DS->decls()) {
319 const auto *V = dyn_cast<
VarDecl>(DI);
324 if (V->hasLocalStorage()) {
330 if (
const Expr *
E = V->getInit()) {
332 dyn_cast<ExprWithCleanups>(
E))
333 E = exprClean->getSubExpr();
341 if (isa<CXXConstructExpr>(
E))
347 if (!isLive(Live, V) &&
348 !V->hasAttr<UnusedAttr>() &&
349 !V->hasAttr<ObjCPreciseLifetimeAttr>()) {
357 if (
E->isEvaluatable(Ctx))
361 dyn_cast<DeclRefExpr>(
E->IgnoreParenCasts()))
362 if (
const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
383 Report(V, DeadInit, Loc,
E->getSourceRange());
400 llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
402 void operator()(
const Stmt *S) {
406 if (
auto *LE = dyn_cast<LambdaExpr>(S)) {
407 findLambdaReferenceCaptures(LE);
418 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
424 void findLambdaReferenceCaptures(
const LambdaExpr *LE) {
426 llvm::DenseMap<const VarDecl *, FieldDecl *> CaptureFields;
431 if (!
C.capturesVariable())
453 class DeadStoresChecker :
public Checker<check::ASTCodeBody> {
463 if (FD->isTemplateInstantiation())
472 DeadStoreObs A(cfg, BR.
getContext(), BR,
this, AC, pmap, FS.Escaped);
473 L->runOnAllBlocks(A);
Defines the clang::ASTContext interface.
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
A (possibly-)qualified type.
succ_iterator succ_begin()
capture_range captures() const
Retrieve this lambda's captures.
Describes the capture of a variable or of this, or of a C++1y init-capture.
VarDecl - An instance of this class is created to represent a variable declaration or definition...
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
static bool isAssignmentOp(Opcode Opc)
bool isScalarType() const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
bool isReferenceType() const
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
AnalysisDeclContext contains the context data for the function or method under analysis.
Represents Objective-C's @catch statement.
ASTContext & getContext()
Stmt * getHandlerBlock() const
A builtin binary operation expression such as "x + y" or "x <= y".
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
static PathDiagnosticLocation create(const Decl *D, const SourceManager &SM)
Create a location corresponding to the given declaration.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
A class that does preordor or postorder depth-first traversal on the entire Clang AST and visits each...
AnalysisDeclContext * getAnalysisDeclContext(const Decl *D)
CFGBlock - Represents a single basic block in a source-level CFG.
Expr - This represents one expression.
void VisitBlockStmts(CALLBACK &O) const
CFG - Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt...
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Expr * getSubExpr() const
unsigned getBlockID() const
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
CFG * getCFG(Decl const *D)
BugReporter is a utility class for generating PathDiagnostics for analysis.
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
CHECKER * registerChecker()
Used to register checkers.
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
ParentMap & getParentMap(Decl const *D)
void getCaptureFields(llvm::DenseMap< const VarDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
AdjacentBlocks::const_iterator const_succ_iterator
static const Expr * LookThroughTransitiveAssignmentsAndCommaOperators(const Expr *Ex)
detail::InMemoryDirectory::const_iterator E
const T * getAs() const
Member-template getAs<specific type>'.
Base for LValueReferenceType and RValueReferenceType.
bool isLive(const Stmt *S) const
Represents Objective-C's @finally statement.
Represents a C++ struct/union/class.
static bool isCompoundAssignmentOp(Opcode Opc)
bool isObjCObjectPointerType() const
CXXCatchStmt - This represents a C++ catch block.
A reference to a declared variable, function, enum, etc.
A trivial tuple used to represent a source range.
bool isConstQualified() const
Determine whether this type is const-qualified.
T * getAnalysis(Decl const *D)
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
bool hasLocalStorage() const
hasLocalStorage - Returns true if a variable with function scope is a non-static local variable...
bool isPointerType() const