clang-tools 24.0.0git
RedundantBranchConditionCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "../utils/Aliasing.h"
11#include "../utils/LexerUtils.h"
12#include "clang/AST/ASTContext.h"
13#include "clang/AST/ParentMapContext.h"
14#include "clang/AST/StmtCXX.h"
15#include "clang/ASTMatchers/ASTMatchFinder.h"
16#include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
17#include "clang/Lex/Lexer.h"
18
19using namespace clang::ast_matchers;
21
22namespace clang::tidy::bugprone {
23
24static const char CondVarStr[] = "cond_var";
25static const char OuterIfStr[] = "outer_if";
26static const char InnerIfStr[] = "inner_if";
27static const char OuterIfVar1Str[] = "outer_if_var1";
28static const char OuterIfVar2Str[] = "outer_if_var2";
29static const char InnerIfVar1Str[] = "inner_if_var1";
30static const char InnerIfVar2Str[] = "inner_if_var2";
31static const char FuncStr[] = "func";
32
33/// Returns whether `Var` is changed in range (`PrevS`..`NextS`).
34static bool isChangedBefore(const Stmt *S, const Stmt *NextS, const Stmt *PrevS,
35 const VarDecl *Var, ASTContext *Context) {
36 ExprMutationAnalyzer MutAn(*S, *Context);
37 const auto &SM = Context->getSourceManager();
38 const Stmt *MutS = MutAn.findMutation(Var);
39 return MutS &&
40 SM.isBeforeInTranslationUnit(PrevS->getEndLoc(),
41 MutS->getBeginLoc()) &&
42 SM.isBeforeInTranslationUnit(MutS->getEndLoc(), NextS->getBeginLoc());
43}
44
45/// Returns the outermost loop that encloses `S` and is itself enclosed by
46/// `Outer`, or null if there is no such loop. The walk passes through
47/// declarations, such as a variable initialized by a lambda, but stops at the
48/// enclosing function.
49static const Stmt *getOutermostLoopBetween(const Stmt *S, const Stmt *Outer,
50 ASTContext *Context) {
51 const Stmt *Loop = nullptr;
52 // getParents() returns only the direct parents of a node, usually exactly
53 // one, so the walk calls it once per level.
54 DynTypedNodeList Parents = Context->getParents(*S);
55 while (!Parents.empty()) {
56 const DynTypedNode Parent = Parents[0];
57 if (Parent.get<FunctionDecl>())
58 break;
59 if (const auto *ParentStmt = Parent.get<Stmt>()) {
60 if (ParentStmt == Outer)
61 break;
62 if (isa<ForStmt, WhileStmt, DoStmt, CXXForRangeStmt>(ParentStmt))
63 Loop = ParentStmt;
64 }
65 Parents = Context->getParents(Parent);
66 }
67 return Loop;
68}
69
71 const auto ImmutableVar =
72 varDecl(anyOf(parmVarDecl(), hasLocalStorage()), hasType(isInteger()),
73 unless(hasType(isVolatileQualified())))
74 .bind(CondVarStr);
75 Finder->addMatcher(
76 ifStmt(
77 hasCondition(anyOf(
78 declRefExpr(hasDeclaration(ImmutableVar)).bind(OuterIfVar1Str),
79 binaryOperator(hasOperatorName("&&"),
80 forEach(declRefExpr(hasDeclaration(ImmutableVar))
81 .bind(OuterIfVar2Str))))),
82 hasThen(hasDescendant(
83 ifStmt(hasCondition(anyOf(
84 declRefExpr(hasDeclaration(
85 varDecl(equalsBoundNode(CondVarStr))))
86 .bind(InnerIfVar1Str),
87 binaryOperator(
88 hasAnyOperatorName("&&", "||"),
89 hasEitherOperand(
90 declRefExpr(hasDeclaration(varDecl(
91 equalsBoundNode(CondVarStr))))
92 .bind(InnerIfVar2Str))))))
93 .bind(InnerIfStr))),
94 forFunction(functionDecl().bind(FuncStr)))
95 .bind(OuterIfStr),
96 this);
97 // FIXME: Handle longer conjunctive and disjunctive clauses.
98}
99
101 const MatchFinder::MatchResult &Result) {
102 const auto *OuterIf = Result.Nodes.getNodeAs<IfStmt>(OuterIfStr);
103 const auto *InnerIf = Result.Nodes.getNodeAs<IfStmt>(InnerIfStr);
104 const auto *CondVar = Result.Nodes.getNodeAs<VarDecl>(CondVarStr);
105 const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>(FuncStr);
106
107 const DeclRefExpr *OuterIfVar = nullptr, *InnerIfVar = nullptr;
108 if (const auto *Inner = Result.Nodes.getNodeAs<DeclRefExpr>(InnerIfVar1Str))
109 InnerIfVar = Inner;
110 else
111 InnerIfVar = Result.Nodes.getNodeAs<DeclRefExpr>(InnerIfVar2Str);
112 if (const auto *Outer = Result.Nodes.getNodeAs<DeclRefExpr>(OuterIfVar1Str))
113 OuterIfVar = Outer;
114 else
115 OuterIfVar = Result.Nodes.getNodeAs<DeclRefExpr>(OuterIfVar2Str);
116
117 if (OuterIfVar && InnerIfVar) {
118 if (isChangedBefore(OuterIf->getThen(), InnerIfVar, OuterIfVar, CondVar,
119 Result.Context))
120 return;
121
122 if (isChangedBefore(OuterIf->getCond(), InnerIfVar, OuterIfVar, CondVar,
123 Result.Context))
124 return;
125 }
126
127 // Inside a loop, a mutation anywhere in the loop runs before the inner
128 // condition is evaluated again, even if it comes later in the source.
129 const Stmt *Loop = getOutermostLoopBetween(InnerIf, OuterIf, Result.Context);
130 if (Loop &&
131 ExprMutationAnalyzer(*Loop, *Result.Context).findMutation(CondVar))
132 return;
133
134 // If the variable has an alias then it can be changed by that alias as well.
135 // FIXME: could potentially support tracking pointers and references in the
136 // future to improve catching true positives through aliases.
137 if (hasPtrOrReferenceInFunc(Func, CondVar))
138 return;
139
140 const auto Diag = diag(InnerIf->getBeginLoc(), "redundant condition %0")
141 << CondVar;
142
143 // For standalone condition variables and for "or" binary operations we simply
144 // remove the inner `if`.
145 const auto *BinOpCond =
146 dyn_cast<BinaryOperator>(InnerIf->getCond()->IgnoreParenImpCasts());
147
148 if (isa<DeclRefExpr>(InnerIf->getCond()->IgnoreParenImpCasts()) ||
149 (BinOpCond && BinOpCond->getOpcode() == BO_LOr)) {
150 const SourceLocation IfBegin = InnerIf->getBeginLoc();
151 const Stmt *Body = InnerIf->getThen();
152 const Expr *OtherSide = nullptr;
153 if (BinOpCond) {
154 const auto *LeftDRE =
155 dyn_cast<DeclRefExpr>(BinOpCond->getLHS()->IgnoreParenImpCasts());
156 if (LeftDRE && LeftDRE->getDecl() == CondVar)
157 OtherSide = BinOpCond->getRHS();
158 else
159 OtherSide = BinOpCond->getLHS();
160 }
161
162 SourceLocation IfEnd = Body->getBeginLoc().getLocWithOffset(-1);
163
164 // For compound statements also remove the left brace.
165 if (isa<CompoundStmt>(Body))
166 IfEnd = Body->getBeginLoc();
167
168 // If the other side has side effects then keep it.
169 if (OtherSide && OtherSide->HasSideEffects(*Result.Context)) {
170 const SourceLocation BeforeOtherSide =
171 OtherSide->getBeginLoc().getLocWithOffset(-1);
172 if (const auto NextToken = utils::lexer::findNextTokenSkippingComments(
173 OtherSide->getEndLoc(), *Result.SourceManager, getLangOpts())) {
174 const SourceLocation AfterOtherSide = NextToken->getLocation();
175 Diag << FixItHint::CreateRemoval(
176 CharSourceRange::getTokenRange(IfBegin, BeforeOtherSide))
177 << FixItHint::CreateInsertion(AfterOtherSide, ";")
178 << FixItHint::CreateRemoval(
179 CharSourceRange::getTokenRange(AfterOtherSide, IfEnd));
180 }
181 } else {
182 Diag << FixItHint::CreateRemoval(
183 CharSourceRange::getTokenRange(IfBegin, IfEnd));
184 }
185
186 // For compound statements also remove the right brace at the end.
187 if (isa<CompoundStmt>(Body))
188 Diag << FixItHint::CreateRemoval(
189 CharSourceRange::getTokenRange(Body->getEndLoc(), Body->getEndLoc()));
190
191 // For "and" binary operations we remove the "and" operation with the
192 // condition variable from the inner if.
193 } else {
194 const auto *CondOp =
195 cast<BinaryOperator>(InnerIf->getCond()->IgnoreParenImpCasts());
196 const auto *LeftDRE =
197 dyn_cast<DeclRefExpr>(CondOp->getLHS()->IgnoreParenImpCasts());
198 if (LeftDRE && LeftDRE->getDecl() == CondVar) {
199 const SourceLocation BeforeRHS =
200 CondOp->getRHS()->getBeginLoc().getLocWithOffset(-1);
201 Diag << FixItHint::CreateRemoval(CharSourceRange::getTokenRange(
202 CondOp->getLHS()->getBeginLoc(), BeforeRHS));
203 } else if (const auto NextToken =
205 CondOp->getLHS()->getEndLoc(), *Result.SourceManager,
206 getLangOpts())) {
207 const SourceLocation AfterLHS = NextToken->getLocation();
208 Diag << FixItHint::CreateRemoval(CharSourceRange::getTokenRange(
209 AfterLHS, CondOp->getRHS()->getEndLoc()));
210 }
211 }
212}
213
214} // namespace clang::tidy::bugprone
bool hasPtrOrReferenceInFunc(const Decl *Func, const ValueDecl *Var)
Returns whether Var has a pointer or reference in Func.
Definition Aliasing.cpp:84
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
static const Stmt * getOutermostLoopBetween(const Stmt *S, const Stmt *Outer, ASTContext *Context)
Returns the outermost loop that encloses S and is itself enclosed by Outer, or null if there is no su...
static bool isChangedBefore(const Stmt *S, const Stmt *NextS, const Stmt *PrevS, const VarDecl *Var, ASTContext *Context)
Returns whether Var is changed in range (PrevS..NextS).
std::optional< Token > findNextTokenSkippingComments(SourceLocation Start, const SourceManager &SM, const LangOptions &LangOpts)
Definition LexerUtils.h:114
bool hasPtrOrReferenceInFunc(const Decl *Func, const ValueDecl *Var)
Returns whether Var has a pointer or reference in Func.
Definition Aliasing.cpp:84