25#include "llvm/ADT/BitVector.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/Support/SaveAndRestore.h"
38 llvm::DenseSet<const VarDecl *> &S;
40 bool TraverseObjCAtFinallyStmt(ObjCAtFinallyStmt *S)
override {
41 SaveAndRestore inFinally(inEH,
true);
42 return DynamicRecursiveASTVisitor::TraverseObjCAtFinallyStmt(S);
45 bool TraverseObjCAtCatchStmt(ObjCAtCatchStmt *S)
override {
46 SaveAndRestore inCatch(inEH,
true);
47 return DynamicRecursiveASTVisitor::TraverseObjCAtCatchStmt(S);
50 bool TraverseCXXCatchStmt(CXXCatchStmt *S)
override {
51 SaveAndRestore inCatch(inEH,
true);
52 return TraverseStmt(S->getHandlerBlock());
55 bool VisitDeclRefExpr(DeclRefExpr *DR)
override {
57 if (
const VarDecl *D = dyn_cast<VarDecl>(DR->
getDecl()))
62 EHCodeVisitor(llvm::DenseSet<const VarDecl *> &S) :
70 llvm::BitVector reachable;
72 ReachableCode(
const CFG &cfg)
73 : cfg(cfg), reachable(cfg.getNumBlockIDs(),
false) {}
75 void computeReachableBlocks();
77 bool isReachable(
const CFGBlock *block)
const {
83void ReachableCode::computeReachableBlocks() {
87 SmallVector<const CFGBlock*, 10> worklist;
90 while (!worklist.empty()) {
91 const CFGBlock *block = worklist.pop_back_val();
92 llvm::BitVector::reference isReachable = reachable[block->
getBlockID()];
97 for (
const CFGBlock *succ : block->
succs())
99 worklist.push_back(succ);
111 if (Op == BO_Assign || Op == BO_Comma) {
121class DeadStoresChecker :
public Checker<check::ASTCodeBody> {
123 bool ShowFixIts =
false;
124 bool WarnForDeadNestedAssignments =
true;
126 void checkASTCodeBody(
const Decl *D, AnalysisManager &Mgr,
127 BugReporter &BR)
const;
130class DeadStoreObs :
public LiveVariables::Observer {
134 const DeadStoresChecker *Checker;
135 AnalysisDeclContext* AC;
137 llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
138 std::unique_ptr<ReachableCode> reachableCode;
139 const CFGBlock *currentBlock;
140 std::unique_ptr<llvm::DenseSet<const VarDecl *>> InEH;
142 enum DeadStoreKind { Standard, Enclosing, DeadIncrement, DeadInit };
145 DeadStoreObs(
const CFG &cfg, ASTContext &ctx, BugReporter &br,
146 const DeadStoresChecker *checker, AnalysisDeclContext *ac,
148 llvm::SmallPtrSet<const VarDecl *, 20> &escaped,
149 bool warnForDeadNestedAssignments)
150 : cfg(cfg), Ctx(ctx), BR(br), Checker(checker), AC(ac), Parents(parents),
151 Escaped(escaped), currentBlock(
nullptr) {}
153 ~DeadStoreObs()
override {}
155 bool isLive(
const LiveVariables::LivenessValues &Live,
const VarDecl *D) {
161 InEH.reset(
new llvm::DenseSet<const VarDecl *>());
162 EHCodeVisitor
V(*InEH);
169 return InEH->count(D);
172 bool isSuppressed(SourceRange R) {
174 SourceLocation Loc =
R.getBegin();
186 if (
Data.starts_with(
"/* iig"))
192 void Report(
const VarDecl *
V, DeadStoreKind dsk,
193 PathDiagnosticLocation L, SourceRange R) {
194 if (Escaped.count(
V))
199 if (!reachableCode) {
200 reachableCode.reset(
new ReachableCode(cfg));
201 reachableCode->computeReachableBlocks();
204 if (!reachableCode->isReachable(currentBlock))
211 llvm::raw_svector_ostream os(buf);
212 const char *BugType =
nullptr;
214 SmallVector<FixItHint, 1> Fixits;
218 BugType =
"Dead initialization";
219 os <<
"Value stored to '" << *
V
220 <<
"' during its initialization is never read";
222 ASTContext &ACtx =
V->getASTContext();
223 if (Checker->ShowFixIts) {
224 if (
V->getInit()->HasSideEffects(ACtx,
232 V->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
233 SM, LO)->getEndLoc();
242 BugType =
"Dead increment";
245 if (!BugType) BugType =
"Dead assignment";
246 os <<
"Value stored to '" << *
V <<
"' is never read";
251 if (!Checker->WarnForDeadNestedAssignments)
253 BugType =
"Dead nested assignment";
254 os <<
"Although the value stored to '" << *
V
255 <<
"' is used in the enclosing expression, the value is never "
256 "actually read from '"
262 os.str(), L, R, Fixits);
265 void CheckVarDecl(
const VarDecl *VD,
const Expr *Ex,
const Expr *Val,
267 const LiveVariables::LivenessValues &Live) {
276 if (!isLive(Live, VD) &&
278 VD->
hasAttr<ObjCPreciseLifetimeAttr>())) {
280 PathDiagnosticLocation ExLoc =
286 void CheckDeclRef(
const DeclRefExpr *DR,
const Expr *Val, DeadStoreKind dsk,
287 const LiveVariables::LivenessValues& Live) {
288 if (
const VarDecl *VD = dyn_cast<VarDecl>(DR->
getDecl()))
289 CheckVarDecl(VD, DR, Val, dsk, Live);
292 bool isIncrement(VarDecl *VD,
const BinaryOperator* B) {
297 const BinaryOperator* BRHS = dyn_cast<BinaryOperator>(RHS);
302 const DeclRefExpr *DR;
315 void observeStmt(
const Stmt *S,
const CFGBlock *block,
316 const LiveVariables::LivenessValues &Live)
override {
318 currentBlock = block;
326 if (
const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
330 if (VarDecl *VD = dyn_cast<VarDecl>(DR->
getDecl())) {
346 if (
const DeclRefExpr *RhsDR = dyn_cast<DeclRefExpr>(RHS))
347 if (VD == dyn_cast<VarDecl>(RhsDR->getDecl()))
353 : (isIncrement(VD,B) ? DeadIncrement : Standard);
355 CheckVarDecl(VD, DR, B->
getRHS(), dsk, Live);
358 else if (
const UnaryOperator* U = dyn_cast<UnaryOperator>(S)) {
359 if (!U->isIncrementOp() || U->isPrefix())
368 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex))
371 else if (
const DeclStmt *DS = dyn_cast<DeclStmt>(S))
374 for (
const auto *DI : DS->decls()) {
375 const auto *
V = dyn_cast<VarDecl>(DI);
380 if (
V->hasLocalStorage()) {
383 if (
V->getType()->getAs<ReferenceType>())
386 if (
const Expr *E =
V->getInit()) {
387 while (
const FullExpr *FE = dyn_cast<FullExpr>(E))
388 E = FE->getSubExpr();
402 if (!isLive(Live,
V) &&
403 !
V->hasAttr<UnusedAttr>() &&
404 !
V->hasAttr<ObjCPreciseLifetimeAttr>()) {
417 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
418 if (
const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
443 PathDiagnosticLocation Loc =
445 Report(
V, DeadInit, Loc,
V->getInit()->getSourceRange());
454 bool isConstant(
const InitListExpr *Candidate)
const {
457 return llvm::all_of(Candidate->
inits(), [
this](
const Expr *
Init) {
458 return isConstant(Init->IgnoreParenCasts());
463 bool isConstant(
const Expr *E)
const {
469 if (
const auto *ILE = dyn_cast<InitListExpr>(E)) {
470 return isConstant(ILE);
486 llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
488 void operator()(
const Stmt *S) {
492 if (
auto *LE = dyn_cast<LambdaExpr>(S)) {
493 findLambdaReferenceCaptures(LE);
497 const UnaryOperator *U = dyn_cast<UnaryOperator>(S);
504 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
505 if (
const VarDecl *VD = dyn_cast<VarDecl>(DR->
getDecl()))
510 void findLambdaReferenceCaptures(
const LambdaExpr *LE) {
511 const CXXRecordDecl *LambdaClass =
LE->getLambdaClass();
512 llvm::DenseMap<const ValueDecl *, FieldDecl *> CaptureFields;
513 FieldDecl *ThisCaptureField;
516 for (
const LambdaCapture &
C :
LE->captures()) {
517 if (!
C.capturesVariable())
520 ValueDecl *VD =
C.getCapturedVar();
521 const FieldDecl *FD = CaptureFields[VD];
538void DeadStoresChecker::checkASTCodeBody(
const Decl *D, AnalysisManager &mgr,
539 BugReporter &BR)
const {
545 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
546 if (FD->isTemplateInstantiation())
549 if (LiveVariables *L = mgr.
getAnalysis<LiveVariables>(D)) {
550 CFG &cfg = *mgr.
getCFG(D);
555 DeadStoreObs A(cfg, BR.
getContext(), BR,
this, AC, pmap, FS.Escaped,
556 WarnForDeadNestedAssignments);
557 L->runOnAllBlocks(A);
561void ento::registerDeadStoresChecker(CheckerManager &Mgr) {
565 Chk->WarnForDeadNestedAssignments =
566 AnOpts.getCheckerBooleanOption(Chk,
"WarnForDeadNestedAssignments");
568 AnOpts.getCheckerBooleanOption(Chk,
"ShowFixIts");
571bool ento::shouldRegisterDeadStoresChecker(
const CheckerManager &mgr) {
Defines the clang::ASTContext interface.
static const Expr * LookThroughTransitiveAssignmentsAndCommaOperators(const Expr *Ex)
Defines the SourceManager interface.
SourceManager & getSourceManager()
const LangOptions & getLangOpts() const
const Decl * getDecl() const
A builtin binary operation expression such as "x + y" or "x <= y".
static bool isAssignmentOp(Opcode Opc)
static bool isCompoundAssignmentOp(Opcode Opc)
unsigned getBlockID() const
void VisitBlockStmts(Callback &O) const
unsigned getNumBlockIDs() const
Returns the total number of BlockIDs allocated (which start at 0).
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
This represents one expression.
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
ArrayRef< Expr * > inits() const
static std::optional< Token > findNextToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeComments=false)
Finds the token that comes right after the given location.
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
bool isLive(const Expr *E) const
bool isConsumedExpr(Expr *E) const
Stmt * getParentIgnoreParenCasts(Stmt *) const
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
bool isConstQualified() const
Determine whether this type is const-qualified.
bool isValid() const
Return true if this is a valid SourceLocation object.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
SourceLocation getBeginLoc() const LLVM_READONLY
bool isPointerType() const
bool isReferenceType() const
bool isScalarType() const
bool isObjCObjectPointerType() const
const T * getAs() const
Member-template getAs<specific type>'.
Expr * getSubExpr() const
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
AnalysisDeclContext * getAnalysisDeclContext(const Decl *D)
T * getAnalysis(Decl const *D)
ParentMap & getParentMap(Decl const *D)
CFG * getCFG(Decl const *D)
const SourceManager & getSourceManager()
ASTContext & getContext()
void EmitBasicReport(const Decl *DeclWithIssue, const CheckerFrontend *Checker, StringRef BugName, StringRef BugCategory, StringRef BugStr, PathDiagnosticLocation Loc, ArrayRef< SourceRange > Ranges={}, ArrayRef< FixItHint > Fixits={})
const AnalyzerOptions & getAnalyzerOptions() const
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
static PathDiagnosticLocation create(const Decl *D, const SourceManager &SM)
Create a location corresponding to the given declaration.
const char *const UnusedCode
bool CheckDeclRef(InterpState &S, CodePtr OpPC, const DeclRefExpr *DR)
We aleady know the given DeclRefExpr is invalid for some reason, now figure out why and print appropr...
bool LE(InterpState &S, CodePtr OpPC)
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
U cast(CodeGen::Address addr)