[libcxx-commits] [libcxx] [libc++] Use saturation builtins directly for {add, sub}_sat (PR #165228)
Nikolas Klauser via libcxx-commits
libcxx-commits at lists.llvm.org
Mon Oct 27 03:27:29 PDT 2025
https://github.com/philnik777 created https://github.com/llvm/llvm-project/pull/165228
This doesn't improve performance for the most part, since the compiler is able to fold our current implementation into the same builtin. However, it does significantly reduce the amount of code the compiler has to sift through, reducing compile times a bit.
>From 7aae5c2ab8af8df1448016d4324302d5bf58883a Mon Sep 17 00:00:00 2001
From: Nikolas Klauser <nikolasklauser at berlin.de>
Date: Mon, 27 Oct 2025 11:19:45 +0100
Subject: [PATCH] [libc++] Use saturation builtins directly for {add,sub}_sat
---
libcxx/include/__numeric/saturation_arithmetic.h | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/libcxx/include/__numeric/saturation_arithmetic.h b/libcxx/include/__numeric/saturation_arithmetic.h
index 9bd3af12c9572..39b3fc6465ae4 100644
--- a/libcxx/include/__numeric/saturation_arithmetic.h
+++ b/libcxx/include/__numeric/saturation_arithmetic.h
@@ -30,6 +30,9 @@ _LIBCPP_BEGIN_NAMESPACE_STD
template <__signed_or_unsigned_integer _Tp>
_LIBCPP_HIDE_FROM_ABI constexpr _Tp __add_sat(_Tp __x, _Tp __y) noexcept {
+#if __has_builtin(__builtin_elementwise_add_sat)
+ return __builtin_elementwise_add_sat(__x, __y);
+#else
if (_Tp __sum; !__builtin_add_overflow(__x, __y, std::addressof(__sum)))
return __sum;
// Handle overflow
@@ -44,10 +47,14 @@ _LIBCPP_HIDE_FROM_ABI constexpr _Tp __add_sat(_Tp __x, _Tp __y) noexcept {
// Overflows if (x < 0 && y < 0)
return std::numeric_limits<_Tp>::min();
}
+#endif
}
template <__signed_or_unsigned_integer _Tp>
_LIBCPP_HIDE_FROM_ABI constexpr _Tp __sub_sat(_Tp __x, _Tp __y) noexcept {
+#if __has_builtin(__builtin_elementwise_sub_sat)
+ return __builtin_elementwise_sub_sat(__x, __y);
+#else
if (_Tp __sub; !__builtin_sub_overflow(__x, __y, std::addressof(__sub)))
return __sub;
// Handle overflow
@@ -63,6 +70,7 @@ _LIBCPP_HIDE_FROM_ABI constexpr _Tp __sub_sat(_Tp __x, _Tp __y) noexcept {
// Overflows if (x < 0 && y > 0)
return std::numeric_limits<_Tp>::min();
}
+#endif
}
template <__signed_or_unsigned_integer _Tp>
More information about the libcxx-commits
mailing list