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#include "llvm/Support/Casting.h"
24using SwitchBranch = llvm::SmallVector<const Stmt *, 2>;
31 const SwitchBranch &RHS,
32 const ASTContext &Context) {
33 if (LHS.size() != RHS.size())
36 for (
size_t I = 0, Size = LHS.size(); I < Size; I++) {
41 RHS[I]->stripLabelLikeStatements(),
54 bool TraverseLambdaExpr(LambdaExpr *, DataRecursionQueue * =
nullptr) {
58 bool TraverseDecl(
Decl *) {
62 bool TraverseSwitchStmt(SwitchStmt *, DataRecursionQueue * =
nullptr) {
66 bool TraverseSwitchCase(SwitchCase *, DataRecursionQueue * =
nullptr) {
70 bool TraverseDefaultStmt(DefaultStmt *, DataRecursionQueue * =
nullptr) {
74 bool TraverseAttributedStmt(AttributedStmt *S) {
78 for (
const Attr *A : S->getAttrs()) {
79 if (isa<FallThroughAttr>(A))
87 for (
const Stmt *Elem : Branch) {
88 if (!Visitor.TraverseStmt(
const_cast<Stmt *
>(Elem)))
98 ifStmt(unless(allOf(isConstexpr(), isInTemplateInstantiation())),
100 hasParent(stmt(unless(ifStmt(hasElse(equalsBoundNode(
"if")))))),
101 hasElse(stmt().bind(
"else"))),
103 Finder->addMatcher(switchStmt().bind(
"switch"),
this);
104 Finder->addMatcher(conditionalOperator().bind(
"condOp"),
this);
106 ifStmt((hasThen(hasDescendant(ifStmt())))).bind(
"ifWithDescendantIf"),
119 const Stmt *Stmt2,
bool IgnoreSideEffects) {
121 if (!Stmt1 || !Stmt2)
122 return !Stmt1 && !Stmt2;
126 if (Stmt1->getStmtClass() != Stmt2->getStmtClass())
129 const auto *Expr1 = dyn_cast<Expr>(Stmt1);
130 const auto *Expr2 = dyn_cast<Expr>(Stmt2);
132 if (Expr1 && Expr2) {
135 if (!IgnoreSideEffects && Expr1->HasSideEffects(Ctx) &&
136 Expr2->HasSideEffects(Ctx))
140 if ((Expr1->getExprLoc().isMacroID()) || (Expr2->getExprLoc().isMacroID()))
144 Expr::const_child_iterator I1 = Expr1->child_begin();
145 Expr::const_child_iterator I2 = Expr2->child_begin();
146 while (I1 != Expr1->child_end() && I2 != Expr2->child_end()) {
154 if (I1 != Expr1->child_end())
156 if (I2 != Expr2->child_end())
160 switch (Stmt1->getStmtClass()) {
163 case Stmt::CallExprClass:
164 case Stmt::ArraySubscriptExprClass:
165 case Stmt::ArraySectionExprClass:
166 case Stmt::OMPArrayShapingExprClass:
167 case Stmt::OMPIteratorExprClass:
168 case Stmt::ImplicitCastExprClass:
169 case Stmt::ParenExprClass:
170 case Stmt::BreakStmtClass:
171 case Stmt::ContinueStmtClass:
172 case Stmt::NullStmtClass:
174 case Stmt::CStyleCastExprClass: {
175 const auto *CastExpr1 = cast<CStyleCastExpr>(Stmt1);
176 const auto *CastExpr2 = cast<CStyleCastExpr>(Stmt2);
178 return CastExpr1->getTypeAsWritten() == CastExpr2->getTypeAsWritten();
180 case Stmt::ReturnStmtClass: {
181 const auto *ReturnStmt1 = cast<ReturnStmt>(Stmt1);
182 const auto *ReturnStmt2 = cast<ReturnStmt>(Stmt2);
185 ReturnStmt2->getRetValue(), IgnoreSideEffects);
187 case Stmt::ForStmtClass: {
188 const auto *ForStmt1 = cast<ForStmt>(Stmt1);
189 const auto *ForStmt2 = cast<ForStmt>(Stmt2);
205 case Stmt::DoStmtClass: {
206 const auto *DStmt1 = cast<DoStmt>(Stmt1);
207 const auto *DStmt2 = cast<DoStmt>(Stmt2);
217 case Stmt::WhileStmtClass: {
218 const auto *WStmt1 = cast<WhileStmt>(Stmt1);
219 const auto *WStmt2 = cast<WhileStmt>(Stmt2);
229 case Stmt::IfStmtClass: {
230 const auto *IStmt1 = cast<IfStmt>(Stmt1);
231 const auto *IStmt2 = cast<IfStmt>(Stmt2);
244 case Stmt::CompoundStmtClass: {
245 const auto *CompStmt1 = cast<CompoundStmt>(Stmt1);
246 const auto *CompStmt2 = cast<CompoundStmt>(Stmt2);
248 if (CompStmt1->size() != CompStmt2->size())
251 if (!llvm::all_of(llvm::zip(CompStmt1->body(), CompStmt2->body()),
252 [&Ctx, IgnoreSideEffects](
253 std::tuple<const Stmt *, const Stmt *> stmtPair) {
254 const Stmt *stmt0 = std::get<0>(stmtPair);
255 const Stmt *stmt1 = std::get<1>(stmtPair);
256 return isIdenticalStmt(Ctx, stmt0, stmt1,
264 case Stmt::CompoundAssignOperatorClass:
265 case Stmt::BinaryOperatorClass: {
266 const auto *BinOp1 = cast<BinaryOperator>(Stmt1);
267 const auto *BinOp2 = cast<BinaryOperator>(Stmt2);
268 return BinOp1->getOpcode() == BinOp2->getOpcode();
270 case Stmt::CharacterLiteralClass: {
271 const auto *CharLit1 = cast<CharacterLiteral>(Stmt1);
272 const auto *CharLit2 = cast<CharacterLiteral>(Stmt2);
273 return CharLit1->getValue() == CharLit2->getValue();
275 case Stmt::DeclRefExprClass: {
276 const auto *DeclRef1 = cast<DeclRefExpr>(Stmt1);
277 const auto *DeclRef2 = cast<DeclRefExpr>(Stmt2);
278 return DeclRef1->getDecl() == DeclRef2->getDecl();
280 case Stmt::IntegerLiteralClass: {
281 const auto *IntLit1 = cast<IntegerLiteral>(Stmt1);
282 const auto *IntLit2 = cast<IntegerLiteral>(Stmt2);
284 llvm::APInt I1 = IntLit1->getValue();
285 llvm::APInt I2 = IntLit2->getValue();
286 if (I1.getBitWidth() != I2.getBitWidth())
290 case Stmt::FloatingLiteralClass: {
291 const auto *FloatLit1 = cast<FloatingLiteral>(Stmt1);
292 const auto *FloatLit2 = cast<FloatingLiteral>(Stmt2);
293 return FloatLit1->getValue().bitwiseIsEqual(FloatLit2->getValue());
295 case Stmt::StringLiteralClass: {
296 const auto *StringLit1 = cast<StringLiteral>(Stmt1);
297 const auto *StringLit2 = cast<StringLiteral>(Stmt2);
298 return StringLit1->getBytes() == StringLit2->getBytes();
300 case Stmt::MemberExprClass: {
301 const auto *MemberStmt1 = cast<MemberExpr>(Stmt1);
302 const auto *MemberStmt2 = cast<MemberExpr>(Stmt2);
303 return MemberStmt1->getMemberDecl() == MemberStmt2->getMemberDecl();
305 case Stmt::UnaryOperatorClass: {
306 const auto *UnaryOp1 = cast<UnaryOperator>(Stmt1);
307 const auto *UnaryOp2 = cast<UnaryOperator>(Stmt2);
308 return UnaryOp1->getOpcode() == UnaryOp2->getOpcode();
314 const ASTContext &Context = *Result.Context;
316 if (
const auto *IS = Result.Nodes.getNodeAs<IfStmt>(
"if")) {
317 const Stmt *Then = IS->getThen();
318 assert(Then &&
"An IfStmt must have a `then` branch!");
320 const Stmt *Else = Result.Nodes.getNodeAs<Stmt>(
"else");
321 assert(Else &&
"We only look for `if` statements with an `else` branch!");
323 if (!isa<IfStmt>(Else)) {
326 Else->IgnoreContainers(), Context)) {
327 diag(IS->getBeginLoc(),
"if with identical then and else branches");
328 diag(IS->getElseLoc(),
"else branch starts here", DiagnosticIDs::Note);
335 llvm::SmallVector<const Stmt *, 4>
Branches;
336 const IfStmt *Cur = IS;
341 Else = Cur->getElse();
347 Cur = dyn_cast<IfStmt>(Else);
356 llvm::BitVector KnownAsClone(N);
358 for (
size_t I = 0; I + 1 < N; I++) {
365 for (
size_t J = I + 1; J < N; J++) {
368 Branches[J]->IgnoreContainers(), Context))
372 KnownAsClone[J] =
true;
374 if (NumCopies == 2) {
377 "repeated branch body in conditional chain");
379 Lexer::getLocForEndOfToken(
Branches[I]->getEndLoc(), 0,
382 diag(End,
"end of the original", DiagnosticIDs::Note);
386 diag(
Branches[J]->getBeginLoc(),
"clone %0 starts here",
394 if (
const auto *CO = Result.Nodes.getNodeAs<ConditionalOperator>(
"condOp")) {
398 diag(CO->getQuestionLoc(),
399 "conditional operator with identical true and false expressions");
404 if (
const auto *SS = Result.Nodes.getNodeAs<SwitchStmt>(
"switch")) {
405 const auto *Body = dyn_cast_or_null<CompoundStmt>(SS->getBody());
419 llvm::SmallVector<SwitchBranch, 4>
Branches;
420 for (
const Stmt *S : Body->body()) {
422 if (isa<SwitchCase>(S))
434 auto *BeginCurrent =
Branches.begin();
435 while (BeginCurrent < End) {
441 auto *EndCurrent = BeginCurrent + 1;
442 while (EndCurrent < End &&
449 if (EndCurrent == (BeginCurrent + 1)) {
451 BeginCurrent = EndCurrent;
455 diag(BeginCurrent->front()->getBeginLoc(),
456 "switch has %0 consecutive identical branches")
457 <<
static_cast<int>(std::distance(BeginCurrent, EndCurrent));
459 SourceLocation EndLoc = (EndCurrent - 1)->back()->getEndLoc();
464 if (EndLoc.isInvalid())
465 EndLoc = (EndCurrent - 1)->back()->getBeginLoc();
466 if (EndLoc.isMacroID())
467 EndLoc = Context.getSourceManager().getExpansionLoc(EndLoc);
468 EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, *Result.SourceManager,
470 if (EndLoc.isValid()) {
471 diag(EndLoc,
"last of these clones ends here", DiagnosticIDs::Note);
473 BeginCurrent = EndCurrent;
478 if (
const auto *IS = Result.Nodes.getNodeAs<IfStmt>(
"ifWithDescendantIf")) {
479 const Stmt *Then = IS->getThen();
480 auto CS = dyn_cast<CompoundStmt>(Then);
481 if (CS && (!CS->body_empty())) {
482 const auto *InnerIf = dyn_cast<IfStmt>(*CS->body_begin());
483 if (InnerIf &&
isIdenticalStmt(Context, IS->getCond(), InnerIf->getCond(),
485 diag(IS->getBeginLoc(),
"if with identical inner if statement");
486 diag(InnerIf->getBeginLoc(),
"inner if starts here",
487 DiagnosticIDs::Note);
493 llvm_unreachable(
"No if statement and no switch statement.");
const FunctionDecl * Decl
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.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
const LangOptions & getLangOpts() const
Returns the language options from the context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
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)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//