afc27c
commit 5e0a7ecb6629461b28adc1a5aabcc0ede122f201
afc27c
Author: Wilco Dijkstra <wdijkstr@arm.com>
afc27c
Date:   Wed Jun 12 11:38:52 2019 +0100
afc27c
afc27c
    Improve performance of strstr
afc27c
    
afc27c
    This patch significantly improves performance of strstr using a novel
afc27c
    modified Horspool algorithm.  Needles up to size 256 use a bad-character
afc27c
    table indexed by hashed pairs of characters to quickly skip past mismatches.
afc27c
    Long needles use a self-adapting filtering step to avoid comparing the whole
afc27c
    needle repeatedly.
afc27c
    
afc27c
    By limiting the needle length to 256, the shift table only requires 8 bits
afc27c
    per entry, lowering preprocessing overhead and minimizing cache effects.
afc27c
    This limit also implies worst-case performance is linear.
afc27c
    
afc27c
    Small needles up to size 3 use a dedicated linear search.  Very long needles
afc27c
    use the Two-Way algorithm.
afc27c
    
afc27c
    The performance gain using the improved bench-strstr on Cortex-A72 is 5.8
afc27c
    times basic_strstr and 3.7 times twoway_strstr.
afc27c
    
afc27c
    Tested against GLIBC testsuite, randomized tests and the GNULIB strstr test
afc27c
    (https://git.savannah.gnu.org/cgit/gnulib.git/tree/tests/test-strstr.c).
afc27c
    
afc27c
    Reviewed-by: Szabolcs Nagy <szabolcs.nagy@arm.com>
afc27c
    
afc27c
            * string/str-two-way.h (two_way_short_needle): Add inline to avoid
afc27c
            warning.
afc27c
            (two_way_long_needle): Block inlining.
afc27c
            * string/strstr.c (strstr2): Add new function.
afc27c
            (strstr3): Likewise.
afc27c
            (STRSTR): Completely rewrite strstr to improve performance.
afc27c
afc27c
diff --git a/string/str-two-way.h b/string/str-two-way.h
afc27c
index 523d946c59412e1f..358959bef0fd6f74 100644
afc27c
--- a/string/str-two-way.h
afc27c
+++ b/string/str-two-way.h
afc27c
@@ -221,7 +221,7 @@ critical_factorization (const unsigned char *needle, size_t needle_len,
afc27c
    most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching.
afc27c
    If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
afc27c
    HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching.  */
afc27c
-static RETURN_TYPE
afc27c
+static inline RETURN_TYPE
afc27c
 two_way_short_needle (const unsigned char *haystack, size_t haystack_len,
afc27c
 		      const unsigned char *needle, size_t needle_len)
afc27c
 {
afc27c
@@ -382,8 +382,11 @@ two_way_short_needle (const unsigned char *haystack, size_t haystack_len,
afc27c
    and sublinear performance O(HAYSTACK_LEN / NEEDLE_LEN) is possible.
afc27c
    If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
afc27c
    HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching, and
afc27c
-   sublinear performance is not possible.  */
afc27c
-static RETURN_TYPE
afc27c
+   sublinear performance is not possible.
afc27c
+
afc27c
+   Since this function is large and complex, block inlining to avoid
afc27c
+   slowing down the common case of small needles.  */
afc27c
+__attribute__((noinline)) static RETURN_TYPE
afc27c
 two_way_long_needle (const unsigned char *haystack, size_t haystack_len,
afc27c
 		     const unsigned char *needle, size_t needle_len)
afc27c
 {
afc27c
diff --git a/string/strstr.c b/string/strstr.c
afc27c
index f74d7189ed1319f6..7ffb18ab4285b060 100644
afc27c
--- a/string/strstr.c
afc27c
+++ b/string/strstr.c
afc27c
@@ -16,29 +16,17 @@
afc27c
    License along with the GNU C Library; if not, see
afc27c
    <http://www.gnu.org/licenses/>.  */
afc27c
 
afc27c
-/* This particular implementation was written by Eric Blake, 2008.  */
afc27c
-
afc27c
 #ifndef _LIBC
afc27c
 # include <config.h>
afc27c
 #endif
afc27c
 
afc27c
-/* Specification of strstr.  */
afc27c
 #include <string.h>
afc27c
 
afc27c
-#include <stdbool.h>
afc27c
-
afc27c
-#ifndef _LIBC
afc27c
-# define __builtin_expect(expr, val)   (expr)
afc27c
-#endif
afc27c
-
afc27c
 #define RETURN_TYPE char *
afc27c
 #define AVAILABLE(h, h_l, j, n_l)			\
afc27c
   (((j) + (n_l) <= (h_l)) \
afc27c
    || ((h_l) += __strnlen ((void*)((h) + (h_l)), (n_l) + 512), \
afc27c
        (j) + (n_l) <= (h_l)))
afc27c
-#define CHECK_EOL (1)
afc27c
-#define RET0_IF_0(a) if (!a) goto ret0
afc27c
-#define FASTSEARCH(S,C,N) (void*) strchr ((void*)(S), (C))
afc27c
 #include "str-two-way.h"
afc27c
 
afc27c
 #undef strstr
afc27c
@@ -47,47 +35,128 @@
afc27c
 #define STRSTR strstr
afc27c
 #endif
afc27c
 
afc27c
-/* Return the first occurrence of NEEDLE in HAYSTACK.  Return HAYSTACK
afc27c
-   if NEEDLE is empty, otherwise NULL if NEEDLE is not found in
afc27c
-   HAYSTACK.  */
afc27c
-char *
afc27c
-STRSTR (const char *haystack, const char *needle)
afc27c
+static inline char *
afc27c
+strstr2 (const unsigned char *hs, const unsigned char *ne)
afc27c
 {
afc27c
-  size_t needle_len; /* Length of NEEDLE.  */
afc27c
-  size_t haystack_len; /* Known minimum length of HAYSTACK.  */
afc27c
-
afc27c
-  /* Handle empty NEEDLE special case.  */
afc27c
-  if (needle[0] == '\0')
afc27c
-    return (char *) haystack;
afc27c
+  uint32_t h1 = (ne[0] << 16) | ne[1];
afc27c
+  uint32_t h2 = 0;
afc27c
+  for (int c = hs[0]; h1 != h2 && c != 0; c = *++hs)
afc27c
+      h2 = (h2 << 16) | c;
afc27c
+  return h1 == h2 ? (char *)hs - 2 : NULL;
afc27c
+}
afc27c
 
afc27c
-  /* Skip until we find the first matching char from NEEDLE.  */
afc27c
-  haystack = strchr (haystack, needle[0]);
afc27c
-  if (haystack == NULL || needle[1] == '\0')
afc27c
-    return (char *) haystack;
afc27c
+static inline char *
afc27c
+strstr3 (const unsigned char *hs, const unsigned char *ne)
afc27c
+{
afc27c
+  uint32_t h1 = ((uint32_t)ne[0] << 24) | (ne[1] << 16) | (ne[2] << 8);
afc27c
+  uint32_t h2 = 0;
afc27c
+  for (int c = hs[0]; h1 != h2 && c != 0; c = *++hs)
afc27c
+      h2 = (h2 | c) << 8;
afc27c
+  return h1 == h2 ? (char *)hs - 3 : NULL;
afc27c
+}
afc27c
 
afc27c
-  /* Ensure HAYSTACK length is at least as long as NEEDLE length.
afc27c
-     Since a match may occur early on in a huge HAYSTACK, use strnlen
afc27c
+/* Hash character pairs so a small shift table can be used.  All bits of
afc27c
+   p[0] are included, but not all bits from p[-1].  So if two equal hashes
afc27c
+   match on p[-1], p[0] matches too.  Hash collisions are harmless and result
afc27c
+   in smaller shifts.  */
afc27c
+#define hash2(p) (((size_t)(p)[0] - ((size_t)(p)[-1] << 3)) % sizeof (shift))
afc27c
+
afc27c
+/* Fast strstr algorithm with guaranteed linear-time performance.
afc27c
+   Small needles up to size 3 use a dedicated linear search.  Longer needles
afc27c
+   up to size 256 use a novel modified Horspool algorithm.  It hashes pairs
afc27c
+   of characters to quickly skip past mismatches.  The main search loop only
afc27c
+   exits if the last 2 characters match, avoiding unnecessary calls to memcmp
afc27c
+   and allowing for a larger skip if there is no match.  A self-adapting
afc27c
+   filtering check is used to quickly detect mismatches in long needles.
afc27c
+   By limiting the needle length to 256, the shift table can be reduced to 8
afc27c
+   bits per entry, lowering preprocessing overhead and minimizing cache effects.
afc27c
+   The limit also implies worst-case performance is linear.
afc27c
+   Needles larger than 256 characters use the linear-time Two-Way algorithm.  */
afc27c
+char *
afc27c
+STRSTR (const char *haystack, const char *needle)
afc27c
+{
afc27c
+  const unsigned char *hs = (const unsigned char *) haystack;
afc27c
+  const unsigned char *ne = (const unsigned char *) needle;
afc27c
+
afc27c
+  /* Handle short needle special cases first.  */
afc27c
+  if (ne[0] == '\0')
afc27c
+    return (char *)hs;
afc27c
+  hs = (const unsigned char *)strchr ((const char*)hs, ne[0]);
afc27c
+  if (hs == NULL || ne[1] == '\0')
afc27c
+    return (char*)hs;
afc27c
+  if (ne[2] == '\0')
afc27c
+    return strstr2 (hs, ne);
afc27c
+  if (ne[3] == '\0')
afc27c
+    return strstr3 (hs, ne);
afc27c
+
afc27c
+  /* Ensure haystack length is at least as long as needle length.
afc27c
+     Since a match may occur early on in a huge haystack, use strnlen
afc27c
      and read ahead a few cachelines for improved performance.  */
afc27c
-  needle_len = strlen (needle);
afc27c
-  haystack_len = __strnlen (haystack, needle_len + 256);
afc27c
-  if (haystack_len < needle_len)
afc27c
+  size_t ne_len = strlen ((const char*)ne);
afc27c
+  size_t hs_len = __strnlen ((const char*)hs, ne_len | 512);
afc27c
+  if (hs_len < ne_len)
afc27c
     return NULL;
afc27c
 
afc27c
-  /* Check whether we have a match.  This improves performance since we avoid
afc27c
-     the initialization overhead of the two-way algorithm.  */
afc27c
-  if (memcmp (haystack, needle, needle_len) == 0)
afc27c
-    return (char *) haystack;
afc27c
-
afc27c
-  /* Perform the search.  Abstract memory is considered to be an array
afc27c
-     of 'unsigned char' values, not an array of 'char' values.  See
afc27c
-     ISO C 99 section 6.2.6.1.  */
afc27c
-  if (needle_len < LONG_NEEDLE_THRESHOLD)
afc27c
-    return two_way_short_needle ((const unsigned char *) haystack,
afc27c
-				 haystack_len,
afc27c
-				 (const unsigned char *) needle, needle_len);
afc27c
-  return two_way_long_needle ((const unsigned char *) haystack, haystack_len,
afc27c
-			      (const unsigned char *) needle, needle_len);
afc27c
+  /* Check whether we have a match.  This improves performance since we
afc27c
+     avoid initialization overheads.  */
afc27c
+  if (memcmp (hs, ne, ne_len) == 0)
afc27c
+    return (char *) hs;
afc27c
+
afc27c
+  /* Use Two-Way algorithm for very long needles.  */
afc27c
+  if (__glibc_unlikely (ne_len > 256))
afc27c
+    return two_way_long_needle (hs, hs_len, ne, ne_len);
afc27c
+
afc27c
+  const unsigned char *end = hs + hs_len - ne_len;
afc27c
+  uint8_t shift[256];
afc27c
+  size_t tmp, shift1;
afc27c
+  size_t m1 = ne_len - 1;
afc27c
+  size_t offset = 0;
afc27c
+
afc27c
+  /* Initialize bad character shift hash table.  */
afc27c
+  memset (shift, 0, sizeof (shift));
afc27c
+  for (int i = 1; i < m1; i++)
afc27c
+    shift[hash2 (ne + i)] = i;
afc27c
+  /* Shift1 is the amount we can skip after matching the hash of the
afc27c
+     needle end but not the full needle.  */
afc27c
+  shift1 = m1 - shift[hash2 (ne + m1)];
afc27c
+  shift[hash2 (ne + m1)] = m1;
afc27c
+
afc27c
+  while (1)
afc27c
+    {
afc27c
+      if (__glibc_unlikely (hs > end))
afc27c
+	{
afc27c
+	  end += __strnlen ((const char*)end + m1 + 1, 2048);
afc27c
+	  if (hs > end)
afc27c
+	    return NULL;
afc27c
+	}
afc27c
+
afc27c
+      /* Skip past character pairs not in the needle.  */
afc27c
+      do
afc27c
+	{
afc27c
+	  hs += m1;
afc27c
+	  tmp = shift[hash2 (hs)];
afc27c
+	}
afc27c
+      while (tmp == 0 && hs <= end);
afc27c
+
afc27c
+      /* If the match is not at the end of the needle, shift to the end
afc27c
+	 and continue until we match the hash of the needle end.  */
afc27c
+      hs -= tmp;
afc27c
+      if (tmp < m1)
afc27c
+	continue;
afc27c
+
afc27c
+      /* Hash of the last 2 characters matches.  If the needle is long,
afc27c
+	 try to quickly filter out mismatches.  */
afc27c
+      if (m1 < 15 || memcmp (hs + offset, ne + offset, 8) == 0)
afc27c
+	{
afc27c
+	  if (memcmp (hs, ne, m1) == 0)
afc27c
+	    return (void *) hs;
afc27c
+
afc27c
+	  /* Adjust filter offset when it doesn't find the mismatch.  */
afc27c
+	  offset = (offset >= 8 ? offset : m1) - 8;
afc27c
+	}
afc27c
+
afc27c
+      /* Skip based on matching the hash of the needle end.  */
afc27c
+      hs += shift1;
afc27c
+    }
afc27c
 }
afc27c
 libc_hidden_builtin_def (strstr)
afc27c
-
afc27c
-#undef LONG_NEEDLE_THRESHOLD