23 #include "llvm/ADT/BitVector.h" 24 #include "llvm/ADT/SmallString.h" 25 #include "llvm/Support/SaveAndRestore.h" 27 using namespace clang;
40 return ::RecursiveASTVisitor<EHCodeVisitor>::TraverseObjCAtFinallyStmt(S);
45 return ::RecursiveASTVisitor<EHCodeVisitor>::TraverseObjCAtCatchStmt(S);
68 llvm::BitVector reachable;
70 ReachableCode(
const CFG &cfg)
71 : cfg(cfg), reachable(cfg.getNumBlockIDs(),
false) {}
73 void computeReachableBlocks();
75 bool isReachable(
const CFGBlock *block)
const {
81 void ReachableCode::computeReachableBlocks() {
82 if (!cfg.getNumBlockIDs())
86 worklist.push_back(&cfg.getEntry());
88 while (!worklist.empty()) {
89 const CFGBlock *block = worklist.pop_back_val();
90 llvm::BitVector::reference isReachable = reachable[block->
getBlockID()];
97 worklist.push_back(succ);
126 const CheckerBase *Checker;
129 llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
130 std::unique_ptr<ReachableCode> reachableCode;
132 std::unique_ptr<llvm::DenseSet<const VarDecl *>> InEH;
134 enum DeadStoreKind { Standard, Enclosing, DeadIncrement, DeadInit };
137 DeadStoreObs(
const CFG &cfg,
ASTContext &ctx, BugReporter &br,
140 llvm::SmallPtrSet<const VarDecl *, 20> &escaped)
141 : cfg(cfg), Ctx(ctx), BR(br), Checker(checker), AC(ac), Parents(parents),
142 Escaped(escaped), currentBlock(
nullptr) {}
144 ~DeadStoreObs()
override {}
153 EHCodeVisitor
V(*InEH.get());
160 return InEH->count(D);
170 bool Invalid =
false;
177 if (Data.startswith(
"/* iig"))
183 void Report(
const VarDecl *
V, DeadStoreKind dsk,
185 if (Escaped.count(V))
190 if (!reachableCode.get()) {
191 reachableCode.reset(
new ReachableCode(cfg));
192 reachableCode->computeReachableBlocks();
195 if (!reachableCode->isReachable(currentBlock))
202 llvm::raw_svector_ostream os(buf);
203 const char *BugType =
nullptr;
207 BugType =
"Dead initialization";
208 os <<
"Value stored to '" << *V
209 <<
"' during its initialization is never read";
213 BugType =
"Dead increment";
216 if (!BugType) BugType =
"Dead assignment";
217 os <<
"Value stored to '" << *V <<
"' is never read";
227 BR.EmitBasicReport(AC->
getDecl(), Checker, BugType,
"Dead store", os.str(),
242 if (!isLive(Live, VD) &&
244 VD->
hasAttr<ObjCPreciseLifetimeAttr>())) {
246 PathDiagnosticLocation ExLoc =
252 void CheckDeclRef(
const DeclRefExpr *DR,
const Expr *Val, DeadStoreKind dsk,
255 CheckVarDecl(VD, DR, Val, dsk, Live);
284 currentBlock = block;
313 if (
const DeclRefExpr *RhsDR = dyn_cast<DeclRefExpr>(RHS))
314 if (VD == dyn_cast<VarDecl>(RhsDR->getDecl()))
320 : (isIncrement(VD,B) ? DeadIncrement : Standard);
322 CheckVarDecl(VD, DR, B->
getRHS(), dsk, Live);
325 else if (
const UnaryOperator* U = dyn_cast<UnaryOperator>(S)) {
326 if (!U->isIncrementOp() || U->isPrefix())
330 if (!parent || !isa<ReturnStmt>(parent))
335 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex))
336 CheckDeclRef(DR, U, DeadIncrement, Live);
338 else if (
const DeclStmt *DS = dyn_cast<DeclStmt>(S))
341 for (
const auto *DI : DS->decls()) {
342 const auto *V = dyn_cast<
VarDecl>(DI);
354 while (
const FullExpr *FE = dyn_cast<FullExpr>(E))
355 E = FE->getSubExpr();
363 if (isa<CXXConstructExpr>(E))
369 if (!isLive(Live, V) &&
371 !V->
hasAttr<ObjCPreciseLifetimeAttr>()) {
379 if (E->isEvaluatable(Ctx))
383 dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
384 if (
const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
403 PathDiagnosticLocation Loc =
422 llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
424 void operator()(
const Stmt *S) {
428 if (
auto *LE = dyn_cast<LambdaExpr>(S)) {
429 findLambdaReferenceCaptures(LE);
440 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
446 void findLambdaReferenceCaptures(
const LambdaExpr *LE) {
448 llvm::DenseMap<const VarDecl *, FieldDecl *> CaptureFields;
453 if (!C.capturesVariable())
456 VarDecl *VD = C.getCapturedVar();
475 class DeadStoresChecker :
public Checker<check::ASTCodeBody> {
477 void checkASTCodeBody(
const Decl *D, AnalysisManager& mgr,
478 BugReporter &BR)
const {
485 if (FD->isTemplateInstantiation())
489 CFG &cfg = *mgr.getCFG(D);
494 DeadStoreObs A(cfg, BR.getContext(), BR,
this, AC, pmap, FS.Escaped);
495 L->runOnAllBlocks(A);
501 void ento::registerDeadStoresChecker(CheckerManager &mgr) {
502 mgr.registerChecker<DeadStoresChecker>();
505 bool ento::shouldRegisterDeadStoresChecker(
const LangOptions &LO) {
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.
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
bool isConsumedExpr(Expr *E) const
Represents a variable declaration or definition.
const T * getAs() const
Member-template getAs<specific type>'.
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 ...
FullExpr - Represents a "full-expression" node.
SourceLocation getBeginLoc() const LLVM_READONLY
Represents a member of a struct/union/class.
AnalysisDeclContext contains the context data for the function or method under analysis.
bool isReferenceType() const
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Represents Objective-C's @catch statement.
AdjacentBlocks::const_iterator const_succ_iterator
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
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
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...
Represents a single basic block in a source-level CFG.
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.
bool isConstQualified() const
Determine whether this type is const-qualified.
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
Encodes a location in the source.
Expr * getSubExpr() const
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
const Decl * getDecl() const
bool isObjCObjectPointerType() const
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Dataflow Directional Tag Classes.
void VisitBlockStmts(CALLBACK &O) const
bool isValid() const
Return true if this is a valid SourceLocation object.
static const Expr * LookThroughTransitiveAssignmentsAndCommaOperators(const Expr *Ex)
bool isLive(const Stmt *S) const
const Expr * getInit() const
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
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.
SourceLocation getBegin() const
This class handles loading and caching of source files into memory.