[clang-tools-extra] [clang-tidy] Add readability-redundant-override check (PR #242955)

Richard Thomson via cfe-commits cfe-commits at lists.llvm.org
Sun Nov 15 19:53:10 PST 2026


https://github.com/LegalizeAdulthood created https://github.com/llvm/llvm-project/pull/242955

Find overrides that only forward to an inherited implementation. Support inline definitions and paired removal of header declarations and out-of-line definitions.

Restrict removal to public methods inherited publicly. Preserve cases that affect access, contracts, overload resolution, copies, or known member-pointer uses, and never offer partial fixes.

Add documentation and regression coverage, including compilation of fixed code under native and Linux targets.

Fixes #27431.

>From 411ec7bb117b4d005c9b1e065d35e6db307b75c5 Mon Sep 17 00:00:00 2001
From: Richard <legalize at xmission.com>
Date: Sun, 15 Nov 2026 20:52:38 -0700
Subject: [PATCH] [clang-tidy] Add readability-redundant-override check

Find overrides that only forward to an inherited implementation.
Support inline definitions and paired removal of header declarations
and out-of-line definitions.

Restrict removal to public methods inherited publicly. Preserve cases
that affect access, contracts, overload resolution, copies, or known
member-pointer uses, and never offer partial fixes.

Add documentation and regression coverage, including compilation of
fixed code under native and Linux targets.

Fixes #27431.
---
 .../clang-tidy/readability/CMakeLists.txt     |   1 +
 .../readability/ReadabilityTidyModule.cpp     |   3 +
 .../readability/RedundantOverrideCheck.cpp    | 223 +++++++++++
 .../readability/RedundantOverrideCheck.h      |  40 ++
 clang-tools-extra/docs/ReleaseNotes.md        |   7 +
 .../docs/clang-tidy/checks/list.md            |   1 +
 .../checks/readability/redundant-override.md  |  59 +++
 .../Inputs/redundant-override/header.h        |  24 ++
 .../readability/redundant-override-cxx98.cpp  |  13 +
 .../readability/redundant-override-header.cpp |  20 +
 .../readability/redundant-override.cpp        | 370 ++++++++++++++++++
 11 files changed, 761 insertions(+)
 create mode 100644 clang-tools-extra/clang-tidy/readability/RedundantOverrideCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/readability/RedundantOverrideCheck.h
 create mode 100644 clang-tools-extra/docs/clang-tidy/checks/readability/redundant-override.md
 create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/redundant-override/header.h
 create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override-cxx98.cpp
 create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override-header.cpp
 create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override.cpp

diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
index 11cadf9f398792..f3a94a7cc30258 100644
--- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
@@ -47,6 +47,7 @@ add_clang_library(clangTidyReadabilityModule STATIC
   RedundantLambdaParameterListCheck.cpp
   RedundantMemberInitCheck.cpp
   RedundantNestedIfCheck.cpp
+  RedundantOverrideCheck.cpp
   RedundantParenthesesCheck.cpp
   RedundantPreprocessorCheck.cpp
   RedundantQualifiedAliasCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
index 0592ae5f1bf606..8dbedbd7d643e1 100644
--- a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
@@ -49,6 +49,7 @@
 #include "RedundantLambdaParameterListCheck.h"
 #include "RedundantMemberInitCheck.h"
 #include "RedundantNestedIfCheck.h"
+#include "RedundantOverrideCheck.h"
 #include "RedundantParenthesesCheck.h"
 #include "RedundantPreprocessorCheck.h"
 #include "RedundantQualifiedAliasCheck.h"
@@ -153,6 +154,8 @@ class ReadabilityModule : public ClangTidyModule {
         "readability-redundant-member-init");
     CheckFactories.registerCheck<RedundantNestedIfCheck>(
         "readability-redundant-nested-if");
+    CheckFactories.registerCheck<RedundantOverrideCheck>(
+        "readability-redundant-override");
     CheckFactories.registerCheck<RedundantParenthesesCheck>(
         "readability-redundant-parentheses");
     CheckFactories.registerCheck<RedundantPreprocessorCheck>(
diff --git a/clang-tools-extra/clang-tidy/readability/RedundantOverrideCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantOverrideCheck.cpp
new file mode 100644
index 00000000000000..93ad5a8c618344
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/readability/RedundantOverrideCheck.cpp
@@ -0,0 +1,223 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "RedundantOverrideCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Attr.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/AST/ExprCXX.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+#include "llvm/ADT/STLExtras.h"
+#include <algorithm>
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+static bool isForwardingType(QualType Type) {
+  return Type->isVoidType() || Type->isReferenceType() ||
+         (Type->isScalarType() && !Type.isVolatileQualified());
+}
+
+static bool hasAdditionalInterface(const CXXMethodDecl *Method) {
+  for (const FunctionDecl *Redecl : Method->redecls()) {
+    if (Redecl->getBeginLoc().isMacroID() || Redecl->getEndLoc().isMacroID())
+      return true;
+    if (llvm::any_of(Redecl->attrs(),
+                     [](const Attr *A) { return !isa<OverrideAttr>(A); }))
+      return true;
+    if (llvm::any_of(Redecl->parameters(), [](const ParmVarDecl *P) {
+          return P->hasDefaultArg() || P->hasAttrs() ||
+                 !isForwardingType(P->getType());
+        }))
+      return true;
+  }
+  return false;
+}
+
+static bool hasOtherOverloads(const CXXRecordDecl *Record,
+                              const CXXMethodDecl *Method) {
+  return llvm::any_of(
+      Record->lookup(Method->getDeclName()), [Method](const NamedDecl *D) {
+        return D->getCanonicalDecl() != Method->getCanonicalDecl();
+      });
+}
+
+static const CXXMethodDecl *getRedundantBase(const CXXMethodDecl *Method,
+                                             ASTContext &Context) {
+  const CXXRecordDecl *Record = Method->getParent();
+  if (Method->size_overridden_methods() != 1 || Method->isPureVirtual() ||
+      !Method->getDeclName().isIdentifier() || Record->isDependentContext() ||
+      isa<ClassTemplateSpecializationDecl>(Record) ||
+      Method->getTemplatedKind() != FunctionDecl::TK_NonTemplate ||
+      Record->getNumBases() != 1 || Record->hasAttrs() ||
+      hasAdditionalInterface(Method))
+    return nullptr;
+
+  const CXXMethodDecl *Base = *Method->begin_overridden_methods();
+  const CXXBaseSpecifier &Inheritance = *Record->bases_begin();
+  const CXXRecordDecl *BaseRecord = Inheritance.getType()->getAsCXXRecordDecl();
+  if (!BaseRecord || Inheritance.isVirtual() || Base->isPureVirtual() ||
+      Base->getAccess() != AS_public ||
+      isa<ClassTemplateSpecializationDecl>(BaseRecord) ||
+      BaseRecord->hasAttrs() ||
+      BaseRecord->getCanonicalDecl() != Base->getParent()->getCanonicalDecl() ||
+      hasAdditionalInterface(Base) || hasOtherOverloads(Record, Method) ||
+      hasOtherOverloads(BaseRecord, Base))
+    return nullptr;
+
+  // Removing the override must preserve access through the derived class,
+  // including access restricted by protected or private inheritance.
+  const AccessSpecifier InheritedAccess =
+      std::max(Base->getAccess(), Inheritance.getAccessSpecifier());
+  if (InheritedAccess != AS_public || Method->getAccess() != InheritedAccess ||
+      !Context.hasSameType(Method->getType(), Base->getType()) ||
+      !isForwardingType(Method->getReturnType()) ||
+      Method->isConstexpr() != Base->isConstexpr() ||
+      Method->isConsteval() != Base->isConsteval())
+    return nullptr;
+
+  const auto *MethodType = Method->getType()->castAs<FunctionProtoType>();
+  const auto *BaseType = Base->getType()->castAs<FunctionProtoType>();
+  if (MethodType->isVariadic() || MethodType->hasDynamicExceptionSpec() ||
+      MethodType->getExceptionSpecType() != BaseType->getExceptionSpecType() ||
+      isUnresolvedExceptionSpec(MethodType->getExceptionSpecType()) ||
+      MethodType->canThrow() == CT_Dependent ||
+      MethodType->canThrow() != BaseType->canThrow())
+    return nullptr;
+
+  const auto *Body = dyn_cast<CompoundStmt>(Method->getBody());
+  if (!Body || Body->size() != 1)
+    return nullptr;
+  const Stmt *Statement = Body->body_front();
+  const Expr *Expression = nullptr;
+  if (const auto *Return = dyn_cast<ReturnStmt>(Statement))
+    Expression = Return->getRetValue();
+  else if (Method->getReturnType()->isVoidType())
+    Expression = dyn_cast<Expr>(Statement);
+  if (!Expression)
+    return nullptr;
+
+  const auto *Call =
+      dyn_cast<CXXMemberCallExpr>(Expression->IgnoreParenImpCasts());
+  if (!Call || !Call->getMethodDecl() || Call->getExprLoc().isMacroID() ||
+      Call->getMethodDecl()->getCanonicalDecl() != Base->getCanonicalDecl() ||
+      Call->getNumArgs() != Method->getNumParams())
+    return nullptr;
+  const auto *Member =
+      dyn_cast<MemberExpr>(Call->getCallee()->IgnoreParenImpCasts());
+  if (!Member || !Member->hasQualifier() ||
+      !isa<CXXThisExpr>(
+          Call->getImplicitObjectArgument()->IgnoreParenImpCasts()))
+    return nullptr;
+  for (unsigned I = 0; I != Call->getNumArgs(); ++I) {
+    const auto *Argument =
+        dyn_cast<DeclRefExpr>(Call->getArg(I)->IgnoreParenImpCasts());
+    if (!Argument || Argument->getLocation().isMacroID() ||
+        Argument->getDecl() != Method->getParamDecl(I))
+      return nullptr;
+  }
+  return Base;
+}
+
+static bool getRemovalRanges(const CXXMethodDecl *Method,
+                             const SourceManager &SM,
+                             const LangOptions &LangOpts,
+                             SmallVectorImpl<CharSourceRange> &Ranges) {
+  for (const FunctionDecl *Redecl : Method->redecls()) {
+    const SourceRange Range = Redecl->getSourceRange();
+    if (Range.isInvalid() || Range.getBegin().isMacroID() ||
+        Range.getEnd().isMacroID() || SM.isInSystemHeader(Range.getBegin()))
+      return false;
+    // A shared declaration such as "void f(), g();" cannot be removed whole.
+    for (const Decl *Other : Redecl->getLexicalDeclContext()->decls())
+      if (Other->getCanonicalDecl() != Redecl->getCanonicalDecl() &&
+          Other->getBeginLoc() == Range.getBegin())
+        return false;
+
+    CharSourceRange FileRange = Lexer::makeFileCharRange(
+        CharSourceRange::getTokenRange(Range), SM, LangOpts);
+    if (FileRange.isInvalid())
+      return false;
+    if (!Redecl->doesThisDeclarationHaveABody()) {
+      const SourceLocation AfterSemicolon = Lexer::findLocationAfterToken(
+          Range.getEnd(), tok::semi, SM, LangOpts,
+          /*SkipTrailingWhitespaceAndNewLine=*/false);
+      if (AfterSemicolon.isInvalid())
+        return false;
+      FileRange.setEnd(AfterSemicolon);
+    }
+    SourceLocation Loc = FileRange.getBegin();
+    while (Loc < FileRange.getEnd()) {
+      Token Tok;
+      if (Lexer::getRawToken(Loc, Tok, SM, LangOpts,
+                             /*IgnoreWhiteSpace=*/true))
+        return false;
+      if (Tok.getLocation() >= FileRange.getEnd())
+        break;
+      if (Tok.isOneOf(tok::hash, tok::eof))
+        return false;
+      Loc = Tok.getEndLoc();
+    }
+    Ranges.push_back(FileRange);
+  }
+  return true;
+}
+
+bool RedundantOverrideCheck::isLanguageVersionSupported(
+    const LangOptions &LangOpts) const {
+  return LangOpts.CPlusPlus;
+}
+
+std::optional<TraversalKind>
+RedundantOverrideCheck::getCheckTraversalKind() const {
+  return TK_IgnoreUnlessSpelledInSource;
+}
+
+void RedundantOverrideCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(cxxMethodDecl(isDefinition(), isVirtual(),
+                                   unless(cxxDestructorDecl()),
+                                   hasBody(compoundStmt(statementCountIs(1))))
+                         .bind("method"),
+                     this);
+  Finder->addMatcher(declRefExpr(to(cxxMethodDecl().bind("referenced-method"))),
+                     this);
+}
+
+void RedundantOverrideCheck::check(const MatchFinder::MatchResult &Result) {
+  if (const auto *Reference =
+          Result.Nodes.getNodeAs<CXXMethodDecl>("referenced-method")) {
+    // A pointer-to-member or its type can depend on the derived declaration.
+    ReferencedMethods.insert(Reference->getCanonicalDecl());
+    return;
+  }
+  const auto *Method = Result.Nodes.getNodeAs<CXXMethodDecl>("method");
+  if (getRedundantBase(Method, *Result.Context))
+    Candidates.push_back(Method);
+}
+
+void RedundantOverrideCheck::onEndOfTranslationUnit() {
+  for (const CXXMethodDecl *Method : Candidates) {
+    if (ReferencedMethods.contains(Method->getCanonicalDecl()) ||
+        Method->getLocation().isMacroID())
+      continue;
+    SmallVector<CharSourceRange, 2> Ranges;
+    if (!getRemovalRanges(Method, Method->getASTContext().getSourceManager(),
+                          getLangOpts(), Ranges))
+      continue;
+    const auto Diag = diag(Method->getLocation(), "redundant override of %0")
+                      << *Method->begin_overridden_methods();
+    for (CharSourceRange Range : Ranges)
+      Diag << FixItHint::CreateRemoval(Range);
+  }
+  Candidates.clear();
+  ReferencedMethods.clear();
+}
+
+} // namespace clang::tidy::readability
diff --git a/clang-tools-extra/clang-tidy/readability/RedundantOverrideCheck.h b/clang-tools-extra/clang-tidy/readability/RedundantOverrideCheck.h
new file mode 100644
index 00000000000000..f325097e96021a
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/readability/RedundantOverrideCheck.h
@@ -0,0 +1,40 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_REDUNDANTOVERRIDECHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_REDUNDANTOVERRIDECHECK_H
+
+#include "../ClangTidyCheck.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallVector.h"
+
+namespace clang::tidy::readability {
+
+/// Finds overrides that only forward to the inherited implementation without
+/// changing its interface.
+///
+/// For the user-facing documentation see:
+/// https://clang.llvm.org/extra/clang-tidy/checks/readability/redundant-override.html
+class RedundantOverrideCheck : public ClangTidyCheck {
+public:
+  using ClangTidyCheck::ClangTidyCheck;
+  bool isLanguageVersionSupported(const LangOptions &LangOpts) const override;
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+  void onEndOfTranslationUnit() override;
+
+private:
+  std::optional<TraversalKind> getCheckTraversalKind() const override;
+
+  SmallVector<const CXXMethodDecl *, 8> Candidates;
+  llvm::SmallPtrSet<const CXXMethodDecl *, 8> ReferencedMethods;
+};
+
+} // namespace clang::tidy::readability
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_REDUNDANTOVERRIDECHECK_H
diff --git a/clang-tools-extra/docs/ReleaseNotes.md b/clang-tools-extra/docs/ReleaseNotes.md
index b6774370511feb..b5ddec9e413341 100644
--- a/clang-tools-extra/docs/ReleaseNotes.md
+++ b/clang-tools-extra/docs/ReleaseNotes.md
@@ -174,6 +174,13 @@ infrastructure are described first, followed by tool-specific sections.
   Finds uses of `#pragma comment` and, for `lib` or `linker` comments, suggests
   using the build system for improved portability.
 
+- New {doc}`readability-redundant-override
+  <clang-tidy/checks/readability/redundant-override>` check.
+
+  Removes overrides that only forward to an inherited implementation
+  without changing its interface, including declarations and out-of-line
+  definitions in different files.
+
 - New {doc}`readability-redundant-zero-initializer
   <clang-tidy/checks/readability/redundant-zero-initializer>` check.
 
diff --git a/clang-tools-extra/docs/clang-tidy/checks/list.md b/clang-tools-extra/docs/clang-tidy/checks/list.md
index ec20c380131852..c17a3cde342b9e 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/list.md
+++ b/clang-tools-extra/docs/clang-tidy/checks/list.md
@@ -427,6 +427,7 @@ readability/*
 | {doc}`readability-redundant-lambda-parameter-list <readability/redundant-lambda-parameter-list>` | Yes |
 | {doc}`readability-redundant-member-init <readability/redundant-member-init>` | Yes |
 | {doc}`readability-redundant-nested-if <readability/redundant-nested-if>` | Yes |
+| {doc}`readability/redundant-override` | Yes |
 | {doc}`readability-redundant-parentheses <readability/redundant-parentheses>` | Yes |
 | {doc}`readability-redundant-preprocessor <readability/redundant-preprocessor>` |  |
 | {doc}`readability-redundant-qualified-alias <readability/redundant-qualified-alias>` | Yes |
diff --git a/clang-tools-extra/docs/clang-tidy/checks/readability/redundant-override.md b/clang-tools-extra/docs/clang-tidy/checks/readability/redundant-override.md
new file mode 100644
index 00000000000000..c1722c1e3154b0
--- /dev/null
+++ b/clang-tools-extra/docs/clang-tidy/checks/readability/redundant-override.md
@@ -0,0 +1,59 @@
+```{title} clang-tidy - readability-redundant-override
+```
+
+# readability-redundant-override
+
+Finds virtual overrides that only forward their arguments to the inherited
+implementation on the same object, without changing its interface.
+
+For example:
+
+```c++
+struct Base {
+  virtual void f() {}
+};
+
+struct Derived : Base {
+  void f() override { Base::f(); }
+};
+```
+
+becomes:
+
+```c++
+struct Base {
+  virtual void f() {}
+};
+
+struct Derived : Base {};
+```
+
+Both inline definitions and out-of-line definitions are supported. When an
+override is declared in a header and defined in a source file, the fix
+removes both declarations. The check skips an override if any declaration
+or definition cannot be safely removed, including shared declarations and
+ranges containing preprocessor directives. It never offers a partial fix.
+
+Access is compared after accounting for the inheritance access specifier.
+Only public methods inherited publicly are considered for removal.
+Non-public methods and non-public inheritance are preserved. Even matching
+non-public access can change access from code in the base class when an
+override is removed.
+
+The check is deliberately conservative. It requires one non-virtual direct
+base class declaring the overridden method, a single forwarding call, and
+unchanged function types and exception specifications. It does not diagnose
+overrides involving:
+
+- Pure virtual base methods, `final`, or additional attributes.
+- Default arguments or overload sets that would affect name lookup.
+- Class objects passed or returned by value, or changed argument order or
+  expressions.
+- Templates, multiple inheritance, or virtual inheritance.
+- Macro-generated declarations or forwarding calls.
+- References to the overriding method that can observe its member-pointer
+  identity or type in the analyzed translation unit.
+
+As with removing any member function, uses outside the analyzed translation
+unit and binary compatibility require review. All affected translation
+units should be rebuilt after applying the fix.
diff --git a/clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/redundant-override/header.h b/clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/redundant-override/header.h
new file mode 100644
index 00000000000000..7a61a56f7fa2d2
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/redundant-override/header.h
@@ -0,0 +1,24 @@
+#ifndef REDUNDANT_OVERRIDE_HEADER_H
+#define REDUNDANT_OVERRIDE_HEADER_H
+
+struct HeaderBase {
+  virtual void f() {}
+  virtual int value(int n) const { return n; }
+};
+
+struct HeaderDerived : HeaderBase {
+  void f() override;
+  int value(int n) const override;
+};
+// CHECK-FIXES: struct HeaderDerived : HeaderBase {
+// CHECK-FIXES-NOT: f()
+// CHECK-FIXES-NOT: value(
+// CHECK-FIXES: };
+
+struct HeaderVisibility : protected HeaderBase {
+  void f() override;
+};
+// CHECK-FIXES: struct HeaderVisibility : protected HeaderBase {
+// CHECK-FIXES-NEXT: void f() override;
+
+#endif
diff --git a/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override-cxx98.cpp b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override-cxx98.cpp
new file mode 100644
index 00000000000000..01c99b610b5ebd
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override-cxx98.cpp
@@ -0,0 +1,13 @@
+// RUN: %check_clang_tidy -std=c++98 %s readability-redundant-override %t
+// RUN: %clang_cc1 -std=c++98 -fsyntax-only %t.cpp
+
+struct Base {
+  virtual void f() {}
+};
+struct Derived : Base {
+  virtual void f() { Base::f(); }
+};
+// CHECK-MESSAGES: :[[@LINE-2]]:16: warning: redundant override
+// CHECK-FIXES: struct Derived : Base {
+// CHECK-FIXES-NOT: f()
+// CHECK-FIXES: };
diff --git a/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override-header.cpp b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override-header.cpp
new file mode 100644
index 00000000000000..be83baf7fdfa53
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override-header.cpp
@@ -0,0 +1,20 @@
+// RUN: %check_clang_tidy -check-header %S/Inputs/redundant-override/header.h \
+// RUN:   %s readability-redundant-override %t
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -I%t.cpp.headers %t.cpp
+
+#include "header.h"
+
+void HeaderDerived::f() { HeaderBase::f(); }
+// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: redundant override
+// CHECK-FIXES-NOT: void HeaderDerived::f()
+int HeaderDerived::value(int n) const { return HeaderBase::value(n); }
+// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: redundant override
+// CHECK-FIXES-NOT: int HeaderDerived::value(
+
+void HeaderVisibility::f() { HeaderBase::f(); }
+// CHECK-FIXES: void HeaderVisibility::f() { HeaderBase::f(); }
+
+void use(HeaderDerived &object) {
+  object.f();
+  object.value(1);
+}
diff --git a/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override.cpp b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override.cpp
new file mode 100644
index 00000000000000..d29275f942f927
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override.cpp
@@ -0,0 +1,370 @@
+// RUN: %check_clang_tidy %s readability-redundant-override %t
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only %t.cpp
+// RUN: %check_clang_tidy %s readability-redundant-override %t-linux -- -- -target x86_64-unknown-linux-gnu
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -std=c++11 -fsyntax-only %t-linux.cpp
+
+struct Base {
+  virtual void f() {}
+};
+
+struct Inline : Base {
+  void f() override { Base::f(); }
+};
+// CHECK-MESSAGES: :[[@LINE-2]]:8: warning: redundant override
+// CHECK-FIXES: struct Inline : Base {
+// CHECK-FIXES-NOT: f()
+// CHECK-FIXES: };
+
+struct VoidReturn : Base {
+  void f() override { return Base::f(); }
+};
+// CHECK-MESSAGES: :[[@LINE-2]]:8: warning: redundant override
+// CHECK-FIXES: struct VoidReturn : Base {
+// CHECK-FIXES-NOT: f()
+// CHECK-FIXES: };
+
+struct ValueBase {
+  virtual int f(int value, const int &other) const { return value + other; }
+};
+struct Value : ValueBase {
+  int f(int value, const int &other) const override {
+    return ValueBase::f(value, other);
+  }
+};
+// CHECK-MESSAGES: :[[@LINE-4]]:7: warning: redundant override
+// CHECK-FIXES: struct Value : ValueBase {
+// CHECK-FIXES-NOT: f(
+// CHECK-FIXES: };
+
+struct RefBase {
+  virtual int &f(int &value) { return value; }
+};
+struct Reference : RefBase {
+  int &f(int &value) override { return RefBase::f(value); }
+};
+// CHECK-MESSAGES: :[[@LINE-2]]:8: warning: redundant override
+// CHECK-FIXES: struct Reference : RefBase {
+// CHECK-FIXES-NOT: f(
+// CHECK-FIXES: };
+
+struct SourceDefinition : Base {
+  void f() override;
+};
+void SourceDefinition::f() { Base::f(); }
+// CHECK-MESSAGES: :[[@LINE-1]]:24: warning: redundant override
+// CHECK-FIXES: struct SourceDefinition : Base {
+// CHECK-FIXES-NOT: f()
+// CHECK-FIXES: };
+// CHECK-FIXES-NOT: SourceDefinition::f
+
+// Compare access after accounting for inheritance, not just the two methods.
+struct SameProtected : protected Base {
+protected:
+  void f() override { Base::f(); }
+};
+// CHECK-FIXES: struct SameProtected : protected Base {
+// CHECK-FIXES-NEXT: protected:
+// CHECK-FIXES-NEXT: void f() override { Base::f(); }
+// CHECK-FIXES: };
+
+struct SamePrivate : private Base {
+private:
+  void f() override { Base::f(); }
+};
+// CHECK-FIXES: struct SamePrivate : private Base {
+// CHECK-FIXES-NEXT: private:
+// CHECK-FIXES-NEXT: void f() override { Base::f(); }
+// CHECK-FIXES: };
+
+struct Narrowed : Base {
+protected:
+  void f() override { Base::f(); }
+};
+// CHECK-FIXES: struct Narrowed : Base {
+// CHECK-FIXES: void f() override { Base::f(); }
+
+struct Published : protected Base {
+  void f() override { Base::f(); }
+};
+// CHECK-FIXES: struct Published : protected Base {
+// CHECK-FIXES-NEXT: void f() override { Base::f(); }
+
+struct ProtectedBase {
+protected:
+  virtual void f() {}
+};
+struct Widened : ProtectedBase {
+  void f() override { ProtectedBase::f(); }
+};
+// CHECK-FIXES: struct Widened : ProtectedBase {
+// CHECK-FIXES-NEXT: void f() override { ProtectedBase::f(); }
+
+struct PrivatePublished : private Base {
+  void f() override { Base::f(); }
+};
+// CHECK-FIXES: struct PrivatePublished : private Base {
+// CHECK-FIXES-NEXT: void f() override { Base::f(); }
+
+struct Final : Base {
+  void f() final { Base::f(); }
+};
+// CHECK-FIXES: void f() final { Base::f(); }
+
+struct PureBase {
+  virtual void f() = 0;
+};
+void PureBase::f() {}
+struct Concrete : PureBase {
+  void f() override { PureBase::f(); }
+};
+// CHECK-FIXES: void f() override { PureBase::f(); }
+
+struct DefaultBase {
+  virtual int f(int value = 1) { return value; }
+};
+struct Defaults : DefaultBase {
+  int f(int value = 2) override { return DefaultBase::f(value); }
+};
+// CHECK-FIXES: int f(int value = 2) override { return DefaultBase::f(value); }
+
+struct DifferentNoexcept : Base {
+  void f() noexcept override { Base::f(); }
+};
+// CHECK-FIXES: void f() noexcept override { Base::f(); }
+
+struct Attributed : Base {
+  __attribute__((noinline)) void f() override { Base::f(); }
+};
+// CHECK-FIXES: __attribute__((noinline)) void f() override { Base::f(); }
+
+struct OverloadedBase {
+  virtual void f() {}
+  void f(int) {}
+};
+struct HidesOverload : OverloadedBase {
+  void f() override { OverloadedBase::f(); }
+};
+// CHECK-FIXES: void f() override { OverloadedBase::f(); }
+
+struct OwnOverload : Base {
+  void f() override { Base::f(); }
+  void f(int) {}
+};
+// CHECK-FIXES: void f() override { Base::f(); }
+
+struct Observed : Base {
+  void f() override { Base::f(); }
+};
+// CHECK-FIXES: struct Observed : Base {
+// CHECK-FIXES-NEXT: void f() override { Base::f(); }
+auto MemberPointer = &Observed::f;
+
+struct Copyable {};
+struct CopyBase {
+  virtual void f(Copyable) {}
+};
+struct ExtraCopy : CopyBase {
+  void f(Copyable value) override { CopyBase::f(value); }
+};
+// CHECK-FIXES: void f(Copyable value) override { CopyBase::f(value); }
+
+struct ResultBase {
+  virtual Copyable f() { return {}; }
+};
+struct ExtraResult : ResultBase {
+  Copyable f() override { return ResultBase::f(); }
+};
+// CHECK-FIXES: Copyable f() override { return ResultBase::f(); }
+
+struct ExtraWork : Base {
+  void f() override {
+    Base::f();
+    Base::f();
+  }
+};
+// CHECK-FIXES: struct ExtraWork : Base {
+// CHECK-FIXES-NEXT: void f() override {
+// CHECK-FIXES-NEXT: Base::f();
+// CHECK-FIXES-NEXT: Base::f();
+
+struct ChangedArgument : ValueBase {
+  int f(int value, const int &other) const override {
+    return ValueBase::f(value + 1, other);
+  }
+};
+// CHECK-FIXES: return ValueBase::f(value + 1, other);
+
+struct EmptyBase {};
+struct MultipleBases : Base, EmptyBase {
+  void f() override { Base::f(); }
+};
+// CHECK-FIXES: struct MultipleBases : Base, EmptyBase {
+// CHECK-FIXES-NEXT: void f() override { Base::f(); }
+
+struct VirtualBase : virtual Base {
+  void f() override { Base::f(); }
+};
+// CHECK-FIXES: struct VirtualBase : virtual Base {
+// CHECK-FIXES-NEXT: void f() override { Base::f(); }
+
+template <typename T> struct Template : Base {
+  void f() override { Base::f(); }
+};
+// CHECK-FIXES: void f() override { Base::f(); }
+Template<int> Instantiated;
+
+// Shared declarations must not result in only the definition being removed.
+struct Shared : Base {
+  void f() override, g();
+};
+void Shared::f() { Base::f(); }
+// CHECK-FIXES: void f() override, g();
+// CHECK-FIXES: void Shared::f() { Base::f(); }
+
+struct PrivateNarrowed : Base {
+private:
+  void f() override { Base::f(); }
+};
+// CHECK-FIXES: struct PrivateNarrowed : Base {
+// CHECK-FIXES: void f() override { Base::f(); }
+
+struct SameProtectedMember : ProtectedBase {
+protected:
+  void f() override { ProtectedBase::f(); }
+};
+// CHECK-FIXES: struct SameProtectedMember : ProtectedBase {
+// CHECK-FIXES-NEXT: protected:
+// CHECK-FIXES-NEXT: void f() override { ProtectedBase::f(); }
+// CHECK-FIXES: };
+
+struct PrivateBase {
+  friend struct PrivateForward;
+
+private:
+  virtual void f() {}
+};
+struct PrivateForward : PrivateBase {
+private:
+  void f() override { PrivateBase::f(); }
+};
+// CHECK-FIXES: void f() override { PrivateBase::f(); }
+
+struct OtherObject : Base {
+  Base other;
+  void f() override { other.Base::f(); }
+};
+// CHECK-FIXES: void f() override { other.Base::f(); }
+
+struct ObservedBefore : Base {
+  void f() override;
+};
+auto EarlierPointer = &ObservedBefore::f;
+void ObservedBefore::f() { Base::f(); }
+// CHECK-FIXES: auto EarlierPointer = &ObservedBefore::f;
+// CHECK-FIXES-NEXT: void ObservedBefore::f() { Base::f(); }
+
+struct IndirectBase {
+  virtual void f() {}
+};
+struct Indirect : IndirectBase {
+  void (IndirectBase::*target)() = &IndirectBase::f;
+  void f() override { (this->*target)(); }
+};
+// CHECK-FIXES: void f() override { (this->*target)(); }
+
+#define FORWARD Base::f()
+struct MacroBody : Base {
+  void f() override { FORWARD; }
+};
+// CHECK-FIXES: void f() override { FORWARD; }
+
+#define METHOD_DECL void f() override;
+struct MacroDeclaration : Base {
+  METHOD_DECL
+};
+void MacroDeclaration::f() { Base::f(); }
+// CHECK-FIXES: METHOD_DECL
+// CHECK-FIXES: void MacroDeclaration::f() { Base::f(); }
+
+struct ConditionalBody : Base {
+  void f() override {
+#if 1
+    Base::f();
+#else
+    Base::f();
+    Base::f();
+#endif
+  }
+};
+// CHECK-FIXES: struct ConditionalBody : Base {
+// CHECK-FIXES-NEXT: void f() override {
+// CHECK-FIXES-NEXT: #if 1
+// CHECK-FIXES-NEXT: Base::f();
+
+struct InheritedDefaults : DefaultBase {
+  int f(int value) override { return DefaultBase::f(value); }
+};
+// CHECK-FIXES: int f(int value) override { return DefaultBase::f(value); }
+
+struct CovariantBase {
+  virtual CovariantBase *f() { return this; }
+};
+struct Covariant : CovariantBase {
+  Covariant *f() override { return static_cast<Covariant *>(CovariantBase::f()); }
+};
+// CHECK-FIXES: Covariant *f() override { return static_cast<Covariant *>(CovariantBase::f()); }
+
+struct ParameterBase {
+  virtual void f(int) {}
+};
+struct AnnotatedParameter : ParameterBase {
+  void f(int value __attribute__((annotate("parameter")))) override {
+    ParameterBase::f(value);
+  }
+};
+// CHECK-FIXES: void f(int value __attribute__((annotate("parameter")))) override {
+// CHECK-FIXES-NEXT: ParameterBase::f(value);
+
+// Equal protected access does not preserve access from the base class itself.
+struct AccessBase {
+protected:
+  virtual void f() {}
+
+public:
+  template <typename T> static auto accessible(T &object)
+      -> decltype(object.f(), char());
+  static int accessible(...);
+};
+struct AccessDerived : AccessBase {
+protected:
+  void f() override { AccessBase::f(); }
+};
+// CHECK-FIXES: void f() override { AccessBase::f(); }
+using AccessResult =
+    decltype(AccessBase::accessible(*static_cast<AccessDerived *>(nullptr)));
+static_assert(sizeof(AccessResult) == sizeof(int), "preserve protected access");
+
+// A semicolon after a definition is a separate empty declaration.
+// clang-format off
+struct Trailing : Base {
+  void f() override { Base::f(); }
+  // Keep the comment with the following empty declaration.
+  ;
+};
+// clang-format on
+// CHECK-MESSAGES: :[[@LINE-5]]:8: warning: redundant override
+// CHECK-FIXES: struct Trailing : Base {
+// CHECK-FIXES-NOT: f()
+// CHECK-FIXES: // Keep the comment with the following empty declaration.
+// CHECK-FIXES-NEXT: ;
+// CHECK-FIXES-NEXT: };
+
+// Ordinary calls continue to resolve to the inherited method after fixing.
+void use() {
+  Inline().f();
+  VoidReturn().f();
+  SourceDefinition().f();
+  int value = 0;
+  Value().f(value, value);
+  Reference().f(value);
+}



More information about the cfe-commits mailing list