[clang-tools-extra] [clang-tidy] detect redundant uses of LLVM's cast, dyn_cast (PR #189274)

Henrik G. Olsson via cfe-commits cfe-commits at lists.llvm.org
Sun Mar 29 13:57:24 PDT 2026


================
@@ -0,0 +1,131 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 "RedundantCastingCheck.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/ExprCXX.h"
+#include "clang/AST/TemplateBase.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Lex/Lexer.h"
+#include "llvm/ADT/STLExtras.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::llvm_check {
+
+namespace {
+AST_MATCHER(Expr, isMacroID) { return Node.getExprLoc().isMacroID(); }
+AST_MATCHER_P(OverloadExpr, hasAnyUnresolvedName, ArrayRef<StringRef>, Names) {
+  auto DeclName = Node.getName();
+  if (!DeclName.isIdentifier())
+    return false;
+  const IdentifierInfo *II = DeclName.getAsIdentifierInfo();
+  return llvm::any_of(Names, [II](StringRef Name) { return II->isStr(Name); });
+}
+} // namespace
+
+static StringRef FunctionNames[] = {
+    "cast",     "cast_or_null",     "cast_if_present",
+    "dyn_cast", "dyn_cast_or_null", "dyn_cast_if_present"};
+
+void RedundantCastingCheck::registerMatchers(MatchFinder *Finder) {
+  auto AnyCalleeName = [](ArrayRef<StringRef> CalleeName) {
+    return allOf(unless(isMacroID()), unless(cxxMemberCallExpr()),
+                 callee(expr(ignoringImpCasts(
+                     declRefExpr(to(namedDecl(hasAnyName(CalleeName))),
+                                 hasAnyTemplateArgumentLoc(anything()))
+                         .bind("callee")))));
+  };
+  auto AnyCalleeNameInUninstantiatedTemplate =
+      [](ArrayRef<StringRef> CalleeName) {
+        return allOf(unless(isMacroID()), unless(cxxMemberCallExpr()),
+                     callee(expr(ignoringImpCasts(
+                         unresolvedLookupExpr(hasAnyUnresolvedName(CalleeName))
----------------
hnrklssn wrote:

It's for this test case:
```c++
template <typename T>
void testCastTemplateTrigger1(T* value) {
  T *a15 = llvm::cast<T>(value);
  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: redundant use of 'cast' [llvm-redundant-casting]
  // CHECK-MESSAGES: :[[@LINE-2]]:26: note: source expression 'value' has type 'T *'
  // CHECK-FIXES: T *a15 = value;
  (void)a15;
}
```
We don't know what type `T` is, but we know that it's `T` on both sides, so it's still redundant.

https://github.com/llvm/llvm-project/pull/189274


More information about the cfe-commits mailing list