[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
Wed Oct 29 06:57:12 PDT 2025


https://github.com/philnik777 updated https://github.com/llvm/llvm-project/pull/165228

>From bc25e03d5b9c077df08c1a8dad28f3fbe819e937 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..cb344c8c918c2 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) && (!defined(_LIBCPP_CLANG_VER) || _LIBCPP_CLANG_VER >= 2101)
+  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) && (!defined(_LIBCPP_CLANG_VER) || _LIBCPP_CLANG_VER >= 2101)
+  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