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());
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";
194 if (!BugType) BugType =
"Dead assignment";
195 os <<
"Value stored to '" << *V <<
"' is never read";
220 if (!isLive(Live, VD) &&
222 VD->
hasAttr<ObjCPreciseLifetimeAttr>())) {
230 void CheckDeclRef(
const DeclRefExpr *DR,
const Expr *Val, DeadStoreKind dsk,
233 CheckVarDecl(VD, DR, Val, dsk, Live);
262 currentBlock = block;
291 if (
const DeclRefExpr *RhsDR = dyn_cast<DeclRefExpr>(RHS))
292 if (VD == dyn_cast<VarDecl>(RhsDR->getDecl()))
298 : (isIncrement(VD,B) ? DeadIncrement : Standard);
300 CheckVarDecl(VD, DR, B->
getRHS(), dsk, Live);
303 else if (
const UnaryOperator* U = dyn_cast<UnaryOperator>(S)) {
304 if (!U->isIncrementOp() || U->isPrefix())
308 if (!parent || !isa<ReturnStmt>(parent))
313 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex))
314 CheckDeclRef(DR, U, DeadIncrement, Live);
316 else if (
const DeclStmt *DS = dyn_cast<DeclStmt>(S))
319 for (
const auto *DI : DS->decls()) {
320 const auto *V = dyn_cast<
VarDecl>(DI);
333 dyn_cast<ExprWithCleanups>(E))
334 E = exprClean->getSubExpr();
342 if (isa<CXXConstructExpr>(E))
348 if (!isLive(Live, V) &&
350 !V->
hasAttr<ObjCPreciseLifetimeAttr>()) {
358 if (E->isEvaluatable(Ctx))
362 dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
363 if (
const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
384 Report(V, DeadInit, Loc, E->getSourceRange());
401 llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
403 void operator()(
const Stmt *S) {
407 if (
auto *LE = dyn_cast<LambdaExpr>(S)) {
408 findLambdaReferenceCaptures(LE);
419 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
425 void findLambdaReferenceCaptures(
const LambdaExpr *LE) {
427 llvm::DenseMap<const VarDecl *, FieldDecl *> CaptureFields;
432 if (!C.capturesVariable())
435 VarDecl *VD = C.getCapturedVar();
454 class DeadStoresChecker :
public Checker<check::ASTCodeBody> {
464 if (FD->isTemplateInstantiation())
473 DeadStoreObs A(cfg, BR.
getContext(), BR,
this, AC, pmap, FS.Escaped);
474 L->runOnAllBlocks(A);
Defines the clang::ASTContext interface.
Represents a function declaration or definition.
A (possibly-)qualified type.
Stmt * getBody() const
Get the body of the Declaration.
succ_iterator succ_begin()
Stmt - This represents one statement.
unsigned getBlockID() const
Decl - This represents one declaration (or definition), e.g.
Stmt * getHandlerBlock() const
Describes the capture of a variable or of this, or of a C++1y init-capture.
bool isConsumedExpr(Expr *E) const
Represents a variable declaration or definition.
const T * getAs() const
Member-template getAs<specific type>'.
Represents an expression – generally a full-expression – that introduces cleanups to be run at the ...
static bool isAssignmentOp(Opcode Opc)
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Represents a member of a struct/union/class.
AnalysisDeclContext contains the context data for the function or method under analysis.
bool isReferenceType() const
Represents Objective-C's @catch statement.
AdjacentBlocks::const_iterator const_succ_iterator
ASTContext & getContext()
A builtin binary operation expression such as "x + y" or "x <= y".
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
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...
bool isScalarType() const
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
AnalysisDeclContext * getAnalysisDeclContext(const Decl *D)
Represents a single basic block in a source-level CFG.
Expr - This represents one expression.
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt...
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
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)
CHECKER * registerChecker(AT... Args)
Used to register checkers.
bool isConstQualified() const
Determine whether this type is const-qualified.
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.
Expr * getSubExpr() const
SourceLocation getLocStart() const LLVM_READONLY
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
ParentMap & getParentMap(Decl const *D)
const Decl * getDecl() const
bool isObjCObjectPointerType() const
Dataflow Directional Tag Classes.
void VisitBlockStmts(CALLBACK &O) const
static const Expr * LookThroughTransitiveAssignmentsAndCommaOperators(const Expr *Ex)
bool isLive(const Stmt *S) const
const Expr * getInit() const
Base for LValueReferenceType and RValueReferenceType.
Represents Objective-C's @finally statement.
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...
SourceManager & getSourceManager()
Represents a C++ struct/union/class.
static bool isCompoundAssignmentOp(Opcode Opc)
CXXCatchStmt - This represents a C++ catch block.
capture_range captures() const
Retrieve this lambda's captures.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Stmt * getParentIgnoreParenCasts(Stmt *) const
A reference to a declared variable, function, enum, etc.
bool isPointerType() const
A trivial tuple used to represent a source range.
void EmitBasicReport(const Decl *DeclWithIssue, const CheckerBase *Checker, StringRef BugName, StringRef BugCategory, StringRef BugStr, PathDiagnosticLocation Loc, ArrayRef< SourceRange > Ranges=None)
T * getAnalysis(Decl const *D)