[libc-commits] [PATCH] D142696: [libc] Check pointer equality in strcmp, strncmp, and memcmp

Dylan Li via Phabricator via libc-commits libc-commits at lists.llvm.org
Fri Jan 27 01:28:59 PST 2023


squidgyberries created this revision.
squidgyberries added a reviewer: libc-project.
squidgyberries added a project: libc-project.
Herald added subscribers: libc-commits, ecnelises, tschuett.
Herald added a project: All.
squidgyberries requested review of this revision.

Check if left and right point to the same location before looping through the bytes.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D142696

Files:
  libc/src/string/memory_utils/memcmp_implementations.h
  libc/src/string/memory_utils/strcmp_implementations.h


Index: libc/src/string/memory_utils/strcmp_implementations.h
===================================================================
--- libc/src/string/memory_utils/strcmp_implementations.h
+++ libc/src/string/memory_utils/strcmp_implementations.h
@@ -16,6 +16,9 @@
 template <typename Comp>
 constexpr static int strcmp_implementation(const char *left, const char *right,
                                            Comp &&comp) {
+  if (left == right)
+    return 0;
+
   // TODO: Look at benefits for comparing words at a time.
   for (; *left && !comp(*left, *right); ++left, ++right)
     ;
@@ -29,6 +32,9 @@
   if (n == 0)
     return 0;
 
+  if (left == right)
+    return 0;
+
   // TODO: Look at benefits for comparing words at a time.
   for (; n > 1; --n, ++left, ++right) {
     char lc = *left;
Index: libc/src/string/memory_utils/memcmp_implementations.h
===================================================================
--- libc/src/string/memory_utils/memcmp_implementations.h
+++ libc/src/string/memory_utils/memcmp_implementations.h
@@ -22,6 +22,9 @@
 namespace __llvm_libc {
 [[maybe_unused]] LIBC_INLINE MemcmpReturnType
 inline_memcmp_embedded_tiny(CPtr p1, CPtr p2, size_t count) {
+  if (p1 == p2)
+    return MemcmpReturnType::ZERO();
+
   LLVM_LIBC_LOOP_NOUNROLL
   for (size_t offset = 0; offset < count; ++offset)
     if (auto value = generic::Memcmp<1>::block(p1 + offset, p2 + offset))


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D142696.492660.patch
Type: text/x-patch
Size: 1415 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/libc-commits/attachments/20230127/4cb5baef/attachment.bin>


More information about the libc-commits mailing list