[libcxx-commits] [libcxx] [libc++] Improve performance of std::midpoint for small types (PR #192804)

via libcxx-commits libcxx-commits at lists.llvm.org
Sat Apr 18 11:09:34 PDT 2026


https://github.com/serge-sans-paille created https://github.com/llvm/llvm-project/pull/192804

None

>From 693e6b7739d5ee0a05c888a94a1805053a74cf1a Mon Sep 17 00:00:00 2001
From: serge-sans-paille <sguelton at mozilla.com>
Date: Sat, 18 Apr 2026 20:08:10 +0200
Subject: [PATCH] [libc++] Improve performance of std::midpoint for small types

---
 libcxx/include/__numeric/midpoint.h | 15 ++++++++++-----
 1 file changed, 10 insertions(+), 5 deletions(-)

diff --git a/libcxx/include/__numeric/midpoint.h b/libcxx/include/__numeric/midpoint.h
index d8e73ab8cad36..7c3f8cc8bd8f9 100644
--- a/libcxx/include/__numeric/midpoint.h
+++ b/libcxx/include/__numeric/midpoint.h
@@ -36,14 +36,19 @@ template <class _Tp>
 [[nodiscard]]
 _LIBCPP_HIDE_FROM_ABI constexpr _Tp midpoint(_Tp __a, _Tp __b) noexcept _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK {
   using _Up                = make_unsigned_t<_Tp>;
-  constexpr _Up __bitshift = numeric_limits<_Up>::digits - 1;
+  if constexpr(sizeof(_Tp) < sizeof(unsigned)) {
+    return (static_cast<unsigned>(__a) + static_cast<unsigned>(__b)) / 2;
+  }
+  else {
+    constexpr _Up __bitshift = numeric_limits<_Up>::digits - 1;
 
-  _Up __diff     = _Up(__b) - _Up(__a);
-  _Up __sign_bit = __b < __a;
+    _Up __diff     = _Up(__b) - _Up(__a);
+    _Up __sign_bit = __b < __a;
 
-  _Up __half_diff = (__diff / 2) + (__sign_bit << __bitshift) + (__sign_bit & __diff);
+    _Up __half_diff = (__diff / 2) + (__sign_bit << __bitshift) + (__sign_bit & __diff);
 
-  return __a + __half_diff;
+    return __a + __half_diff;
+  }
 }
 
 template <class _Tp>



More information about the libcxx-commits mailing list