[libcxx-commits] [libcxx] [libc++] Add constant folding for optimized std::find variants (PR #96491)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Thu Jul 4 11:14:15 PDT 2024


================
@@ -132,6 +132,19 @@ _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _Tp* __constexpr_memchr(_Tp*
   static_assert(sizeof(_Tp) == 1 && __libcpp_is_trivially_equality_comparable<_Tp, _Up>::value,
                 "Calling memchr on non-trivially equality comparable types is unsafe.");
 
+  if (__builtin_constant_p(__count) && __builtin_constant_p(__value)) {
+    for (; __count; --__count) {
+      if (!__builtin_constant_p(*__str))
+        break;
+      if (*__str == __value)
+        return __str;
+      ++__str;
+    }
+  }
+
+  if (__builtin_constant_p(__count) && __count == 0)
+    return nullptr;
+
   if (__libcpp_is_constant_evaluated()) {
----------------
ldionne wrote:

I think we can get rid of this branch since `__builtin_constant_p` is always true inside a constant expression. IOW, the code path above is always taken when `__libcpp_is_constant_evaluated()` is true, so the branch below is basically dead now.

https://github.com/llvm/llvm-project/pull/96491


More information about the libcxx-commits mailing list