[libcxx-commits] [libcxx] [libc++] Simplify the definition of string::operator== (PR #95000)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Mon Jun 10 08:21:16 PDT 2024


https://github.com/ldionne created https://github.com/llvm/llvm-project/pull/95000

Instead of hardcoding a loop for small strings, always call char_traits::compare which ends up desugaring to __builtin_memcmp.

Note that the original code dates back 11 years, when we didn't lower to intrinsics in `char_traits::compare`.

Fixes #94222

>From 1378d62e6cb41bbeca473b5b254452b078c300b0 Mon Sep 17 00:00:00 2001
From: Louis Dionne <ldionne.2 at gmail.com>
Date: Mon, 10 Jun 2024 11:16:03 -0400
Subject: [PATCH] [libc++] Simplify the definition of string::operator==

Instead of hardcoding a loop for small strings, always call
char_traits::compare which ends up desugaring to __builtin_memcmp.

Note that the original code dates back 11 years, when we didn't
lower to intrinsics in `char_traits::compare`.

Fixes #94222
---
 libcxx/include/string | 13 +++----------
 1 file changed, 3 insertions(+), 10 deletions(-)

diff --git a/libcxx/include/string b/libcxx/include/string
index 1db803e822d72..5301f8a87d9bb 100644
--- a/libcxx/include/string
+++ b/libcxx/include/string
@@ -3746,17 +3746,10 @@ template <class _Allocator>
 inline _LIBCPP_CONSTEXPR_SINCE_CXX20 _LIBCPP_HIDE_FROM_ABI bool
 operator==(const basic_string<char, char_traits<char>, _Allocator>& __lhs,
            const basic_string<char, char_traits<char>, _Allocator>& __rhs) _NOEXCEPT {
-  size_t __lhs_sz = __lhs.size();
-  if (__lhs_sz != __rhs.size())
+  size_t __sz = __lhs.size();
+  if (__sz != __rhs.size())
     return false;
-  const char* __lp = __lhs.data();
-  const char* __rp = __rhs.data();
-  if (__lhs.__is_long())
-    return char_traits<char>::compare(__lp, __rp, __lhs_sz) == 0;
-  for (; __lhs_sz != 0; --__lhs_sz, ++__lp, ++__rp)
-    if (*__lp != *__rp)
-      return false;
-  return true;
+  return char_traits<char>::compare(__lhs.data(), __rhs.data(), __sz) == 0;
 }
 
 #if _LIBCPP_STD_VER <= 17



More information about the libcxx-commits mailing list