From: Don Hinton Date: Fri, 5 Apr 2019 13:59:24 +0000 (+0000) Subject: [llvm] Add isa_and_nonnull X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=50b9c082418364308df98396ee7eb70ab26565b0;p=llvm [llvm] Add isa_and_nonnull Summary: Add new ``isa_and_nonnull<>`` operator that works just like the ``isa<>`` operator, except that it allows for a null pointer as an argument (which it then returns false). Reviewers: lattner, aaron.ballman, greened Reviewed By: lattner Subscribers: hubert.reinterpretcast, llvm-commits Tags: #llvm Differential Revision: https://reviews.llvm.org/D60291 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@357761 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/docs/ProgrammersManual.rst b/docs/ProgrammersManual.rst index adb23bd5ac2..75b6239375a 100644 --- a/docs/ProgrammersManual.rst +++ b/docs/ProgrammersManual.rst @@ -164,6 +164,12 @@ rarely have to include this file directly). efficient to use the ``InstVisitor`` class to dispatch over the instruction type directly. +``isa_and_nonnull<>``: + The ``isa_and_nonnull<>`` operator works just like the ``isa<>`` operator, + except that it allows for a null pointer as an argument (which it then + returns false). This can sometimes be useful, allowing you to combine several + null checks into one. + ``cast_or_null<>``: The ``cast_or_null<>`` operator works just like the ``cast<>`` operator, except that it allows for a null pointer as an argument (which it then diff --git a/include/llvm/Support/Casting.h b/include/llvm/Support/Casting.h index cddee3642fa..46bdedb04cf 100644 --- a/include/llvm/Support/Casting.h +++ b/include/llvm/Support/Casting.h @@ -143,6 +143,16 @@ template LLVM_NODISCARD inline bool isa(const Y &Val) { typename simplify_type::SimpleType>::doit(Val); } +// isa_and_nonnull - Functionally identical to isa, except that a null value +// is accepted. +// +template +LLVM_NODISCARD inline bool isa_and_nonnull(const Y &Val) { + if (!Val) + return false; + return isa(Val); +} + //===----------------------------------------------------------------------===// // cast Support Templates //===----------------------------------------------------------------------===// diff --git a/unittests/Support/Casting.cpp b/unittests/Support/Casting.cpp index 368ca17ef7c..bcdaca94a3c 100644 --- a/unittests/Support/Casting.cpp +++ b/unittests/Support/Casting.cpp @@ -118,6 +118,12 @@ TEST(CastingTest, isa) { EXPECT_TRUE(isa(B4)); } +TEST(CastingTest, isa_and_nonnull) { + EXPECT_TRUE(isa_and_nonnull(B2)); + EXPECT_TRUE(isa_and_nonnull(B4)); + EXPECT_FALSE(isa_and_nonnull(fub())); +} + TEST(CastingTest, cast) { foo &F1 = cast(B1); EXPECT_NE(&F1, null_foo);