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