clang-tools 22.0.0git
BranchCloneCheck.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
9#include "BranchCloneCheck.h"
10#include "../utils/ASTUtils.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/AST/RecursiveASTVisitor.h"
13#include "clang/ASTMatchers/ASTMatchFinder.h"
14#include "clang/Analysis/CloneDetection.h"
15#include "clang/Lex/Lexer.h"
16
17using namespace clang;
18using namespace clang::ast_matchers;
19
20namespace {
21/// A branch in a switch may consist of several statements; while a branch in
22/// an if/else if/else chain is one statement (which may be a CompoundStmt).
23using SwitchBranch = llvm::SmallVector<const Stmt *, 2>;
24} // anonymous namespace
25
26/// Determines if the bodies of two branches in a switch statements are Type I
27/// clones of each other. This function only examines the body of the branch
28/// and ignores the `case X:` or `default:` at the start of the branch.
29static bool areSwitchBranchesIdentical(const SwitchBranch &LHS,
30 const SwitchBranch &RHS,
31 const ASTContext &Context) {
32 return llvm::equal(LHS, RHS, [&](const Stmt *S1, const Stmt *S2) {
33 // NOTE: We strip goto labels and annotations in addition to stripping
34 // the `case X:` or `default:` labels, but it is very unlikely that this
35 // would cause false positives in real-world code.
36 return tidy::utils::areStatementsIdentical(S1->stripLabelLikeStatements(),
37 S2->stripLabelLikeStatements(),
38 Context);
39 });
40}
41
42static bool isFallthroughSwitchBranch(const SwitchBranch &Branch) {
43 struct SwitchCaseVisitor : RecursiveASTVisitor<SwitchCaseVisitor> {
44 using RecursiveASTVisitor<SwitchCaseVisitor>::DataRecursionQueue;
45
46 bool TraverseLambdaExpr(LambdaExpr *, DataRecursionQueue * = nullptr) {
47 return true; // Ignore lambdas
48 }
49
50 bool TraverseDecl(Decl *) {
51 return true; // No need to check declarations
52 }
53
54 bool TraverseSwitchStmt(SwitchStmt *, DataRecursionQueue * = nullptr) {
55 return true; // Ignore sub-switches
56 }
57
58 // NOLINTNEXTLINE(readability-identifier-naming) - FIXME
59 bool TraverseSwitchCase(SwitchCase *, DataRecursionQueue * = nullptr) {
60 return true; // Ignore cases
61 }
62
63 bool TraverseDefaultStmt(DefaultStmt *, DataRecursionQueue * = nullptr) {
64 return true; // Ignore defaults
65 }
66
67 bool TraverseAttributedStmt(AttributedStmt *S) {
68 if (!S)
69 return true;
70
71 return llvm::all_of(S->getAttrs(), [](const Attr *A) {
72 return !isa<FallThroughAttr>(A);
73 });
74 }
75 } Visitor;
76
77 for (const Stmt *Elem : Branch)
78 if (!Visitor.TraverseStmt(const_cast<Stmt *>(Elem)))
79 return true;
80 return false;
81}
82
83namespace clang::tidy::bugprone {
84
85void BranchCloneCheck::registerMatchers(MatchFinder *Finder) {
86 Finder->addMatcher(
87 ifStmt(unless(allOf(isConstexpr(), isInTemplateInstantiation())),
88 stmt().bind("if"),
89 hasParent(stmt(unless(ifStmt(hasElse(equalsBoundNode("if")))))),
90 hasElse(stmt().bind("else"))),
91 this);
92 Finder->addMatcher(switchStmt().bind("switch"), this);
93 Finder->addMatcher(conditionalOperator().bind("condOp"), this);
94 Finder->addMatcher(
95 ifStmt((hasThen(hasDescendant(ifStmt())))).bind("ifWithDescendantIf"),
96 this);
97}
98
99/// Determines whether two statement trees are identical regarding
100/// operators and symbols.
101///
102/// Exceptions: expressions containing macros or functions with possible side
103/// effects are never considered identical.
104/// Limitations: (t + u) and (u + t) are not considered identical.
105/// t*(u + t) and t*u + t*t are not considered identical.
106///
107static bool isIdenticalStmt(const ASTContext &Ctx, const Stmt *Stmt1,
108 const Stmt *Stmt2, bool IgnoreSideEffects) {
109 if (!Stmt1 || !Stmt2)
110 return !Stmt1 && !Stmt2;
111
112 // If Stmt1 & Stmt2 are of different class then they are not
113 // identical statements.
114 if (Stmt1->getStmtClass() != Stmt2->getStmtClass())
115 return false;
116
117 const auto *Expr1 = dyn_cast<Expr>(Stmt1);
118 const auto *Expr2 = dyn_cast<Expr>(Stmt2);
119
120 if (Expr1 && Expr2) {
121 // If Stmt1 has side effects then don't warn even if expressions
122 // are identical.
123 if (!IgnoreSideEffects && Expr1->HasSideEffects(Ctx) &&
124 Expr2->HasSideEffects(Ctx))
125 return false;
126 // If either expression comes from a macro then don't warn even if
127 // the expressions are identical.
128 if ((Expr1->getExprLoc().isMacroID()) || (Expr2->getExprLoc().isMacroID()))
129 return false;
130
131 // If all children of two expressions are identical, return true.
132 if (!llvm::equal(Expr1->children(), Expr2->children(),
133 [&](const Stmt *S1, const Stmt *S2) {
134 return isIdenticalStmt(Ctx, S1, S2, IgnoreSideEffects);
135 }))
136 return false;
137 }
138
139 switch (Stmt1->getStmtClass()) {
140 default:
141 return false;
142 case Stmt::CallExprClass:
143 case Stmt::ArraySubscriptExprClass:
144 case Stmt::ArraySectionExprClass:
145 case Stmt::OMPArrayShapingExprClass:
146 case Stmt::OMPIteratorExprClass:
147 case Stmt::ImplicitCastExprClass:
148 case Stmt::ParenExprClass:
149 case Stmt::BreakStmtClass:
150 case Stmt::ContinueStmtClass:
151 case Stmt::NullStmtClass:
152 return true;
153 case Stmt::CStyleCastExprClass: {
154 const auto *CastExpr1 = cast<CStyleCastExpr>(Stmt1);
155 const auto *CastExpr2 = cast<CStyleCastExpr>(Stmt2);
156
157 return CastExpr1->getTypeAsWritten() == CastExpr2->getTypeAsWritten();
158 }
159 case Stmt::ReturnStmtClass: {
160 const auto *ReturnStmt1 = cast<ReturnStmt>(Stmt1);
161 const auto *ReturnStmt2 = cast<ReturnStmt>(Stmt2);
162
163 return isIdenticalStmt(Ctx, ReturnStmt1->getRetValue(),
164 ReturnStmt2->getRetValue(), IgnoreSideEffects);
165 }
166 case Stmt::ForStmtClass: {
167 const auto *ForStmt1 = cast<ForStmt>(Stmt1);
168 const auto *ForStmt2 = cast<ForStmt>(Stmt2);
169
170 if (!isIdenticalStmt(Ctx, ForStmt1->getInit(), ForStmt2->getInit(),
171 IgnoreSideEffects))
172 return false;
173 if (!isIdenticalStmt(Ctx, ForStmt1->getCond(), ForStmt2->getCond(),
174 IgnoreSideEffects))
175 return false;
176 if (!isIdenticalStmt(Ctx, ForStmt1->getInc(), ForStmt2->getInc(),
177 IgnoreSideEffects))
178 return false;
179 if (!isIdenticalStmt(Ctx, ForStmt1->getBody(), ForStmt2->getBody(),
180 IgnoreSideEffects))
181 return false;
182 return true;
183 }
184 case Stmt::DoStmtClass: {
185 const auto *DStmt1 = cast<DoStmt>(Stmt1);
186 const auto *DStmt2 = cast<DoStmt>(Stmt2);
187
188 if (!isIdenticalStmt(Ctx, DStmt1->getCond(), DStmt2->getCond(),
189 IgnoreSideEffects))
190 return false;
191 if (!isIdenticalStmt(Ctx, DStmt1->getBody(), DStmt2->getBody(),
192 IgnoreSideEffects))
193 return false;
194 return true;
195 }
196 case Stmt::WhileStmtClass: {
197 const auto *WStmt1 = cast<WhileStmt>(Stmt1);
198 const auto *WStmt2 = cast<WhileStmt>(Stmt2);
199
200 if (!isIdenticalStmt(Ctx, WStmt1->getCond(), WStmt2->getCond(),
201 IgnoreSideEffects))
202 return false;
203 if (!isIdenticalStmt(Ctx, WStmt1->getBody(), WStmt2->getBody(),
204 IgnoreSideEffects))
205 return false;
206 return true;
207 }
208 case Stmt::IfStmtClass: {
209 const auto *IStmt1 = cast<IfStmt>(Stmt1);
210 const auto *IStmt2 = cast<IfStmt>(Stmt2);
211
212 if (!isIdenticalStmt(Ctx, IStmt1->getCond(), IStmt2->getCond(),
213 IgnoreSideEffects))
214 return false;
215 if (!isIdenticalStmt(Ctx, IStmt1->getThen(), IStmt2->getThen(),
216 IgnoreSideEffects))
217 return false;
218 if (!isIdenticalStmt(Ctx, IStmt1->getElse(), IStmt2->getElse(),
219 IgnoreSideEffects))
220 return false;
221 return true;
222 }
223 case Stmt::DeferStmtClass: {
224 const auto *DefStmt1 = cast<DeferStmt>(Stmt1);
225 const auto *DefStmt2 = cast<DeferStmt>(Stmt2);
226 return isIdenticalStmt(Ctx, DefStmt1->getBody(), DefStmt2->getBody(),
227 IgnoreSideEffects);
228 }
229 case Stmt::CompoundStmtClass: {
230 const auto *CompStmt1 = cast<CompoundStmt>(Stmt1);
231 const auto *CompStmt2 = cast<CompoundStmt>(Stmt2);
232 return llvm::equal(CompStmt1->body(), CompStmt2->body(),
233 [&](const Stmt *S1, const Stmt *S2) {
234 return isIdenticalStmt(Ctx, S1, S2, IgnoreSideEffects);
235 });
236 }
237 case Stmt::CompoundAssignOperatorClass:
238 case Stmt::BinaryOperatorClass: {
239 const auto *BinOp1 = cast<BinaryOperator>(Stmt1);
240 const auto *BinOp2 = cast<BinaryOperator>(Stmt2);
241 return BinOp1->getOpcode() == BinOp2->getOpcode();
242 }
243 case Stmt::CharacterLiteralClass: {
244 const auto *CharLit1 = cast<CharacterLiteral>(Stmt1);
245 const auto *CharLit2 = cast<CharacterLiteral>(Stmt2);
246 return CharLit1->getValue() == CharLit2->getValue();
247 }
248 case Stmt::DeclRefExprClass: {
249 const auto *DeclRef1 = cast<DeclRefExpr>(Stmt1);
250 const auto *DeclRef2 = cast<DeclRefExpr>(Stmt2);
251 return DeclRef1->getDecl() == DeclRef2->getDecl();
252 }
253 case Stmt::IntegerLiteralClass: {
254 const auto *IntLit1 = cast<IntegerLiteral>(Stmt1);
255 const auto *IntLit2 = cast<IntegerLiteral>(Stmt2);
256
257 const llvm::APInt I1 = IntLit1->getValue();
258 const llvm::APInt I2 = IntLit2->getValue();
259 if (I1.getBitWidth() != I2.getBitWidth())
260 return false;
261 return I1 == I2;
262 }
263 case Stmt::FloatingLiteralClass: {
264 const auto *FloatLit1 = cast<FloatingLiteral>(Stmt1);
265 const auto *FloatLit2 = cast<FloatingLiteral>(Stmt2);
266 return FloatLit1->getValue().bitwiseIsEqual(FloatLit2->getValue());
267 }
268 case Stmt::StringLiteralClass: {
269 const auto *StringLit1 = cast<StringLiteral>(Stmt1);
270 const auto *StringLit2 = cast<StringLiteral>(Stmt2);
271 return StringLit1->getBytes() == StringLit2->getBytes();
272 }
273 case Stmt::MemberExprClass: {
274 const auto *MemberStmt1 = cast<MemberExpr>(Stmt1);
275 const auto *MemberStmt2 = cast<MemberExpr>(Stmt2);
276 return MemberStmt1->getMemberDecl() == MemberStmt2->getMemberDecl();
277 }
278 case Stmt::UnaryOperatorClass: {
279 const auto *UnaryOp1 = cast<UnaryOperator>(Stmt1);
280 const auto *UnaryOp2 = cast<UnaryOperator>(Stmt2);
281 return UnaryOp1->getOpcode() == UnaryOp2->getOpcode();
282 }
283 }
284}
285
286void BranchCloneCheck::check(const MatchFinder::MatchResult &Result) {
287 const ASTContext &Context = *Result.Context;
288
289 if (const auto *IS = Result.Nodes.getNodeAs<IfStmt>("if")) {
290 const Stmt *Then = IS->getThen();
291 assert(Then && "An IfStmt must have a `then` branch!");
292
293 const Stmt *Else = Result.Nodes.getNodeAs<Stmt>("else");
294 assert(Else && "We only look for `if` statements with an `else` branch!");
295
296 if (!isa<IfStmt>(Else)) {
297 // Just a simple if with no `else if` branch.
298 if (utils::areStatementsIdentical(Then->IgnoreContainers(),
299 Else->IgnoreContainers(), Context)) {
300 diag(IS->getBeginLoc(), "if with identical then and else branches");
301 diag(IS->getElseLoc(), "else branch starts here", DiagnosticIDs::Note);
302 }
303 return;
304 }
305
306 // This is the complicated case when we start an if/else if/else chain.
307 // To find all the duplicates, we collect all the branches into a vector.
308 llvm::SmallVector<const Stmt *, 4> Branches;
309 const IfStmt *Cur = IS;
310 while (true) {
311 // Store the `then` branch.
312 Branches.push_back(Cur->getThen());
313
314 Else = Cur->getElse();
315 // The chain ends if there is no `else` branch.
316 if (!Else)
317 break;
318
319 // Check if there is another `else if`...
320 Cur = dyn_cast<IfStmt>(Else);
321 if (!Cur) {
322 // ...this is just a plain `else` branch at the end of the chain.
323 Branches.push_back(Else);
324 break;
325 }
326 }
327
328 const size_t N = Branches.size();
329 llvm::BitVector KnownAsClone(N);
330
331 for (size_t I = 0; I + 1 < N; I++) {
332 // We have already seen Branches[i] as a clone of an earlier branch.
333 if (KnownAsClone[I])
334 continue;
335
336 int NumCopies = 1;
337
338 for (size_t J = I + 1; J < N; J++) {
339 if (KnownAsClone[J] || !utils::areStatementsIdentical(
340 Branches[I]->IgnoreContainers(),
341 Branches[J]->IgnoreContainers(), Context))
342 continue;
343
344 NumCopies++;
345 KnownAsClone[J] = true;
346
347 if (NumCopies == 2) {
348 // We report the first occurrence only when we find the second one.
349 diag(Branches[I]->getBeginLoc(),
350 "repeated branch body in conditional chain");
351 const SourceLocation End =
352 Lexer::getLocForEndOfToken(Branches[I]->getEndLoc(), 0,
353 *Result.SourceManager, getLangOpts());
354 if (End.isValid())
355 diag(End, "end of the original", DiagnosticIDs::Note);
356 }
357
358 diag(Branches[J]->getBeginLoc(), "clone %0 starts here",
359 DiagnosticIDs::Note)
360 << (NumCopies - 1);
361 }
362 }
363 return;
364 }
365
366 if (const auto *CO = Result.Nodes.getNodeAs<ConditionalOperator>("condOp")) {
367 // We do not try to detect chains of ?: operators.
368 if (utils::areStatementsIdentical(CO->getTrueExpr(), CO->getFalseExpr(),
369 Context))
370 diag(CO->getQuestionLoc(),
371 "conditional operator with identical true and false expressions");
372
373 return;
374 }
375
376 if (const auto *SS = Result.Nodes.getNodeAs<SwitchStmt>("switch")) {
377 const auto *Body = dyn_cast_or_null<CompoundStmt>(SS->getBody());
378
379 // Code like
380 // switch (x) case 0: case 1: foobar();
381 // is legal and calls foobar() if and only if x is either 0 or 1;
382 // but we do not try to distinguish branches in such code.
383 if (!Body)
384 return;
385
386 // We will first collect the branches of the switch statements. For the
387 // sake of simplicity we say that branches are delimited by the SwitchCase
388 // (`case:` or `default:`) children of Body; that is, we ignore `case:` or
389 // `default:` labels embedded inside other statements and we do not follow
390 // the effects of `break` and other manipulation of the control-flow.
391 llvm::SmallVector<SwitchBranch, 4> Branches;
392 for (const Stmt *S : Body->body()) {
393 // If this is a `case` or `default`, we start a new, empty branch.
394 if (isa<SwitchCase>(S))
395 Branches.emplace_back();
396
397 // There may be code before the first branch (which can be dead code
398 // and can be code reached either through goto or through case labels
399 // that are embedded inside e.g. inner compound statements); we do not
400 // store those statements in branches.
401 if (!Branches.empty())
402 Branches.back().push_back(S);
403 }
404
405 auto *End = Branches.end();
406 auto *BeginCurrent = Branches.begin();
407 while (BeginCurrent < End) {
408 if (isFallthroughSwitchBranch(*BeginCurrent)) {
409 ++BeginCurrent;
410 continue;
411 }
412
413 auto *EndCurrent = BeginCurrent + 1;
414 while (EndCurrent < End &&
415 areSwitchBranchesIdentical(*BeginCurrent, *EndCurrent, Context)) {
416 ++EndCurrent;
417 }
418 // At this point the iterator range {BeginCurrent, EndCurrent} contains a
419 // complete family of consecutive identical branches.
420
421 if (EndCurrent == (BeginCurrent + 1)) {
422 // No consecutive identical branches that start on BeginCurrent
423 BeginCurrent = EndCurrent;
424 continue;
425 }
426
427 diag(BeginCurrent->front()->getBeginLoc(),
428 "switch has %0 consecutive identical branches")
429 << std::distance(BeginCurrent, EndCurrent);
430
431 SourceLocation EndLoc = (EndCurrent - 1)->back()->getEndLoc();
432 // If the case statement is generated from a macro, it's SourceLocation
433 // may be invalid, resulting in an assertion failure down the line.
434 // While not optimal, try the begin location in this case, it's still
435 // better then nothing.
436 if (EndLoc.isInvalid())
437 EndLoc = (EndCurrent - 1)->back()->getBeginLoc();
438 if (EndLoc.isMacroID())
439 EndLoc = Context.getSourceManager().getExpansionLoc(EndLoc);
440 EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, *Result.SourceManager,
441 getLangOpts());
442 if (EndLoc.isValid())
443 diag(EndLoc, "last of these clones ends here", DiagnosticIDs::Note);
444 BeginCurrent = EndCurrent;
445 }
446 return;
447 }
448
449 if (const auto *IS = Result.Nodes.getNodeAs<IfStmt>("ifWithDescendantIf")) {
450 const Stmt *Then = IS->getThen();
451 const auto *CS = dyn_cast<CompoundStmt>(Then);
452 if (CS && (!CS->body_empty())) {
453 const auto *InnerIf = dyn_cast<IfStmt>(*CS->body_begin());
454 if (InnerIf && isIdenticalStmt(Context, IS->getCond(), InnerIf->getCond(),
455 /*IgnoreSideEffects=*/false)) {
456 diag(IS->getBeginLoc(), "if with identical inner if statement");
457 diag(InnerIf->getBeginLoc(), "inner if starts here",
458 DiagnosticIDs::Note);
459 }
460 }
461 return;
462 }
463
464 llvm_unreachable("No if statement and no switch statement.");
465}
466
467} // namespace clang::tidy::bugprone
static bool isFallthroughSwitchBranch(const SwitchBranch &Branch)
static bool areSwitchBranchesIdentical(const SwitchBranch &LHS, const SwitchBranch &RHS, const ASTContext &Context)
Determines if the bodies of two branches in a switch statements are Type I clones of each other.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
static bool isIdenticalStmt(const ASTContext &Ctx, const Stmt *Stmt1, const Stmt *Stmt2, bool IgnoreSideEffects)
Determines whether two statement trees are identical regarding operators and symbols.
bool areStatementsIdentical(const Stmt *FirstStmt, const Stmt *SecondStmt, const ASTContext &Context, bool Canonical)
Definition ASTUtils.cpp:89
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//