[llvm] Add isa_or_null<> to Casting.h (PR #104682)

Braden Helmer via llvm-commits llvm-commits at lists.llvm.org
Sat Aug 17 11:55:17 PDT 2024


https://github.com/bradenhelmer created https://github.com/llvm/llvm-project/pull/104682

Implements isa_or_null<> as suggested in #50305.

>From c8a27d1d5cace96f8eb4bd28a3d16413129a68ce Mon Sep 17 00:00:00 2001
From: Braden Helmer <bradenhelmeraus at gmail.com>
Date: Sat, 17 Aug 2024 14:53:08 -0400
Subject: [PATCH] Add isa_or_null<> to Casting.h

---
 llvm/docs/ReleaseNotes.rst          | 2 ++
 llvm/include/llvm/Support/Casting.h | 7 +++++++
 llvm/unittests/Support/Casting.cpp  | 8 ++++++++
 3 files changed, 17 insertions(+)

diff --git a/llvm/docs/ReleaseNotes.rst b/llvm/docs/ReleaseNotes.rst
index 42c0ad976089f7..f71b145d128b71 100644
--- a/llvm/docs/ReleaseNotes.rst
+++ b/llvm/docs/ReleaseNotes.rst
@@ -180,6 +180,8 @@ Changes to Sanitizers
 Other Changes
 -------------
 
+* A template for 'isa_or_null<>' has been added to the casting operations in support.
+
 External Open Source Projects Using LLVM 19
 ===========================================
 
diff --git a/llvm/include/llvm/Support/Casting.h b/llvm/include/llvm/Support/Casting.h
index 14a32ccd0e0dc9..cb39381285cd7a 100644
--- a/llvm/include/llvm/Support/Casting.h
+++ b/llvm/include/llvm/Support/Casting.h
@@ -683,6 +683,13 @@ template <typename... X, class Y>
   return isa_and_present<X...>(Val);
 }
 
+// isa_or_null<X> - Returns true if the value is null or matches the list of
+// types provided.
+template <typename... To, typename From>
+[[nodiscard]] inline bool isa_or_null(const From &Val) {
+  return !detail::isPresent(Val) || isa<To...>(Val);
+}
+
 /// cast_if_present<X> - Functionally identical to cast, except that a null
 /// value is accepted.
 template <class X, class Y>
diff --git a/llvm/unittests/Support/Casting.cpp b/llvm/unittests/Support/Casting.cpp
index a128cedaf3988d..8fee7d037e3c5b 100644
--- a/llvm/unittests/Support/Casting.cpp
+++ b/llvm/unittests/Support/Casting.cpp
@@ -162,6 +162,14 @@ TEST(CastingTest, isa_and_nonnull) {
   EXPECT_FALSE(isa_and_nonnull<foo>(fub()));
 }
 
+TEST(CastingTest, isa_or_null) {
+  EXPECT_TRUE(isa_or_null<foo>(B1));
+  EXPECT_TRUE(isa_or_null<foo>(B2));
+  EXPECT_TRUE(isa_or_null<foo>(B3));
+  EXPECT_TRUE(isa_or_null<foo>(B4));
+  EXPECT_TRUE(isa_or_null<foo>(fub()));
+}
+
 TEST(CastingTest, cast) {
   foo &F1 = cast<foo>(B1);
   EXPECT_NE(&F1, null_foo);



More information about the llvm-commits mailing list