Each match state stores its matcher in a std::function<bool(_CharT)>,
so every character test is an indirect call that can't be inlined.
This is most costly in the loops that apply one matcher to many
characters in a row: the greedy single-char loop in _M_greedy_char_loop,
and the first-char filter loop in _M_search.

This patch adds _Executor::_M_visit_matcher, which calls a function
object with the state's matcher as its concrete type when it's one of
the commonly used types: _BracketMatcher (bracket expressions and \w,
\d, \s etc), _CharMatcher (a literal character) or _AnyMatcher (. in
ECMAScript).  Otherwise it passes the std::function itself.  The type
check is done once per loop, not once per character, and the loop body
is instantiated once for each type, so the matcher call can be inlined.

The regex's flags determine which matcher types the compiler could
have produced, so _M_visit_matcher looks only for the non-icase
variants or only for the icase variants, and gives up when collate is
set.  So icase regexes get the fast path too, which is where the icase
rows below improve.

POSIX . (_AnyMatcher with __is_ecma false) isn't handled either.
POSIX grammars are rarely used with std::regex, and since the grammar
is only known at run time, looking for that matcher would add another
instantiation of each loop to every program that uses std::regex,
whether or not it uses a POSIX grammar.

The public std::function::target<T>() isn't suitable for the type
check: when the target has a different type, with RTTI enabled, it
falls back to an indirect call and a type_info comparison, which made
the benchmark below ~55% slower.  So this also adds an internal
std::function::_M_target_if<T>(), which only compares the stored
manager pointer with the address of T's handler and then gets the
target directly.  A failed check is just a pointer comparison.  If the
pointer comparison fails even though the types match (e.g. across
shared libraries with hidden visibility), we just take the normal
std::function call, which is still correct.

For 8-bit character types, _M_search already caches the filter result
for each character value, so each first match state's matcher is called
at most once per character value per search and there's nothing to gain
there.  Name that condition _S_filter_cached
and use _M_visit_matcher in the filter loop only when it's false and
there's a single first match state.  The filter loop for the other
cases, which tests each of the first match states in turn, is moved
into the same function object, _Search_filtered_by.

Doing the same for the per-character call in _M_handle_match was also
tried.  On its own it made regex-benchmark ~7% and icase searches ~9%
slower, and on top of the two loop sites it made no measurable
difference to regex-benchmark, so it's not done.

Benchmark (regex-benchmark's cpp/benchmark.cpp, i.e. sregex_token_iterator
over its 6.8 MB input-text.txt, median of 9 interleaved runs pinned to
one core, x86_64, -O2):

               before     after
      Email  146.46 ms  136.36 ms
      URI    126.53 ms  116.51 ms
      IP       8.94 ms    9.06 ms

The IP pattern has no * or + loop and its first-char filter is cached,
so it is unaffected (the difference is noise).

Microbenchmarks (best of 3x5 runs pinned to one core, -O2; the strings
are 200k chars for the greedy loops and 600k chars for the searches):

                                        before     after
      regex_match [a-z]*              12.79 ms   6.63 ms
      regex_match a*                  10.83 ms   2.23 ms
      regex_match .*                  11.37 ms   3.16 ms
      regex_match [a-z]* icase        12.09 ms   6.63 ms
      regex_match a* icase            30.18 ms  17.21 ms
      regex_match [a-z]* icase wchar 134.70 ms 129.56 ms
      regex_match (?:[a-z][a-z])*     66.23 ms  66.99 ms
      regex_search [a-z]+@[a-z]+\.com 41.06 ms  38.31 ms
        icase                         47.64 ms  46.44 ms
        wchar_t                       70.79 ms  71.84 ms
      regex_search @[a-z]+ wchar_t    11.76 ms  10.06 ms
      regex_match (?:ab)* (BFS)       13.67 ms  14.20 ms

For wchar_t, _BracketMatcher has no per-character cache, so the cost of
the matcher itself dominates and inlining the call to it gains little.

The benchmark binary's text grows by ~1.1KB.

This builds on "Consume greedy single-char regex loops in one step" and
"Use a first-char filter in regex_search", which added the two loops;
without them there's no loop to hoist the type check out of.

libstdc++-v3/ChangeLog:

        * include/bits/std_function.h (function::_M_target_if): New.
        * include/bits/regex_executor.h (_Executor::_M_visit_matcher)
        (_Executor::_S_visit_matcher): Declare.
        (_Executor::_Greedy_scan, _Executor::_Search_filtered_by): Declare.
        (_Executor::_S_filter_cached): New.
        * include/bits/regex_executor.tcc (_Executor::_M_visit_matcher)
        (_Executor::_S_visit_matcher): Define.
        (_Executor::_Greedy_scan, _Executor::_Search_filtered_by): Define.
        (_Executor::_M_search): Use _S_filter_cached.  When it's false,
        use _M_visit_matcher if there's a single first match state, and
        otherwise use _Search_filtered_by.
        (_Executor::_M_greedy_char_loop): Use _M_visit_matcher and
        _Greedy_scan.

Assisted-by: Claude Opus 5.5
---
 libstdc++-v3/include/bits/regex_executor.h   |  23 +++++
 libstdc++-v3/include/bits/regex_executor.tcc | 103 ++++++++++++++++---
 libstdc++-v3/include/bits/std_function.h     |  22 ++++
 3 files changed, 135 insertions(+), 13 deletions(-)

diff --git a/libstdc++-v3/include/bits/regex_executor.h 
b/libstdc++-v3/include/bits/regex_executor.h
index c28c830daaf..ca5d77bfa1e 100644
--- a/libstdc++-v3/include/bits/regex_executor.h
+++ b/libstdc++-v3/include/bits/regex_executor.h
@@ -115,6 +115,23 @@ _GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(_V3)
       _M_search();
 
     private:
+      // Call __fn with the matcher of the match state __state.  If the
+      // matcher has one of the most commonly used types, it is passed as
+      // that type instead of as the type-erased std::function, so that
+      // calls to it from __fn can be inlined.
+      template<typename _Fn>
+       auto
+       _M_visit_matcher(const _State<_CharT>& __state, _Fn __fn) const
+       -> decltype(__fn(__state._M_get_matcher()));
+
+      template<bool __icase, typename _Fn>
+       static auto
+       _S_visit_matcher(const _Matcher<_CharT>& __m, _Fn& __fn)
+       -> decltype(__fn(__m));
+
+      struct _Greedy_scan;
+      struct _Search_filtered_by;
+
       _StateIdT
       _M_rep_once_more(_Match_mode __match_mode, _StateIdT);
 
@@ -182,6 +199,12 @@ _GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(_V3)
       bool
       _M_first_states(_GLIBCXX_STD_C::vector<_StateIdT>&) const;
 
+      // Whether _M_search caches the result of its first-character filter
+      // for each character value.
+      static constexpr bool _S_filter_cached
+       = sizeof(_CharT) == 1 && __CHAR_BIT__ == 8
+         && is_integral<_CharT>::value && !is_same<_CharT, bool>::value;
+
       bool
       _M_main_bfs(_Match_mode __match_mode);
 
diff --git a/libstdc++-v3/include/bits/regex_executor.tcc 
b/libstdc++-v3/include/bits/regex_executor.tcc
index 0c90909256a..a9f1eaab22a 100644
--- a/libstdc++-v3/include/bits/regex_executor.tcc
+++ b/libstdc++-v3/include/bits/regex_executor.tcc
@@ -36,6 +36,86 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
 #pragma GCC diagnostic ignored "-Wc++17-extensions" // if constexpr
 namespace __detail
 {
+  template<typename _BiIter, typename _Alloc, typename _TraitsT>
+  template<typename _Fn>
+    inline auto _Executor<_BiIter, _Alloc, _TraitsT>::
+    _M_visit_matcher(const _State<_CharT>& __state, _Fn __fn) const
+    -> decltype(__fn(__state._M_get_matcher()))
+    {
+      const auto& __m = __state._M_get_matcher();
+      // The flags determine which matcher types the compiler could have
+      // used, so only look for those.
+      const auto __flags = _M_nfa._M_options()
+       & (regex_constants::icase | regex_constants::collate);
+      if (__flags == regex_constants::syntax_option_type())
+       return _S_visit_matcher<false>(__m, __fn);
+      else if (__flags == regex_constants::icase)
+       return _S_visit_matcher<true>(__m, __fn);
+      else
+       return __fn(__m);
+    }
+
+  template<typename _BiIter, typename _Alloc, typename _TraitsT>
+  template<bool __icase, typename _Fn>
+    inline auto _Executor<_BiIter, _Alloc, _TraitsT>::
+    _S_visit_matcher(const _Matcher<_CharT>& __m, _Fn& __fn)
+    -> decltype(__fn(__m))
+    {
+      // The matchers for a bracket expression or character class escape,
+      // a literal character, and . in ECMAScript.  Checking for each of
+      // these is just a pointer comparison.
+      using _BracketM = _BracketMatcher<_TraitsT, __icase, false>;
+      using _CharM = _CharMatcher<_TraitsT, __icase, false>;
+      using _AnyM = _AnyMatcher<_TraitsT, true, __icase, false>;
+
+      if (const auto* __p = __m.template _M_target_if<_BracketM>())
+       return __fn(*__p);
+      if (const auto* __p = __m.template _M_target_if<_CharM>())
+       return __fn(*__p);
+      if (const auto* __p = __m.template _M_target_if<_AnyM>())
+       return __fn(*__p);
+      return __fn(__m);
+    }
+
+  // Advance from _M_cur for as long as the matcher accepts the next character,
+  // returning the final position.
+  template<typename _BiIter, typename _Alloc, typename _TraitsT>
+    struct _Executor<_BiIter, _Alloc, _TraitsT>::_Greedy_scan
+    {
+      _BiIter _M_cur;
+      _BiIter _M_end;
+
+      template<typename _MatcherT>
+       _BiIter
+       operator()(const _MatcherT& __m) const
+       {
+         _BiIter __cur = _M_cur;
+         while (__cur != _M_end && __m(*__cur))
+           ++__cur;
+         return __cur;
+       }
+    };
+
+  // Search for a match starting after _M_begin, skipping over every starting
+  // position whose character is rejected by the given first-character filter
+  // (a matcher, or another predicate on characters).
+  template<typename _BiIter, typename _Alloc, typename _TraitsT>
+    struct _Executor<_BiIter, _Alloc, _TraitsT>::_Search_filtered_by
+    {
+      _Executor* _M_executor;
+
+      template<typename _Pred>
+       bool
+       operator()(const _Pred& __can_start) const
+       {
+         _Executor& __e = *_M_executor;
+         while (++__e._M_begin != __e._M_end)
+           if (__can_start(*__e._M_begin) && __e._M_search_from_first())
+             return true;
+         return false;
+       }
+    };
+
   template<typename _BiIter, typename _Alloc, typename _TraitsT>
     bool _Executor<_BiIter, _Alloc, _TraitsT>::
     _M_search()
@@ -72,6 +152,10 @@ namespace __detail
       if (__first.empty())
        return false; // e.g. "^abc" or "^.*"
 
+      if constexpr (!_S_filter_cached)
+       if (__first.size() == 1)
+         return _M_visit_matcher(_M_nfa[__first[0]], 
_Search_filtered_by{this});
+
       // Test whether some first match state accepts a character.
       auto __can_start = [this, &__first](_CharT __c) {
        for (_StateIdT __i : __first)
@@ -82,10 +166,10 @@ namespace __detail
 
       // For 8-bit characters, cache __can_start per character value, so
       // each value is tested at most once per search.
-      if constexpr (sizeof(_CharT) == 1 && __CHAR_BIT__ == 8
-                   && is_integral<_CharT>::value
-                   && !is_same<_CharT, bool>::value)
+      if constexpr (_S_filter_cached)
        {
+         // The matchers are called at most once per character value, so
+         // there's nothing to gain from _M_visit_matcher here.
          using _UCharT = typename make_unsigned<_CharT>::type;
          // Lazy cache: -1 = unknown, 0 = reject, 1 = accept.
          // Only characters actually seen in the input are queried.
@@ -103,12 +187,7 @@ namespace __detail
          return false;
        }
       else
-       {
-         while (++_M_begin != _M_end)
-           if (__can_start(*_M_begin) && _M_search_from_first())
-             return true;
-         return false;
-       }
+       return _Search_filtered_by{this}(__can_start);
     }
 
   // Collect the match states that can consume the first character of a match
@@ -450,10 +529,8 @@ namespace __detail
     {
       const auto& __state = _M_nfa[__i];
       const auto& __body = _M_nfa[__state._M_alt];
-      const _BiIter __end = _M_end;
-      _BiIter __cur = _M_current;
-      while (__cur != __end && __body._M_matches(*__cur))
-       ++__cur;
+      const _BiIter __cur
+       = _M_visit_matcher(__body, _Greedy_scan{_M_current, _M_end});
       if (__cur != _M_current)
        {
          _M_frames.emplace_back(_S_fopcode_greedy_char_loop_bound, __i,
diff --git a/libstdc++-v3/include/bits/std_function.h 
b/libstdc++-v3/include/bits/std_function.h
index 0ae858354c0..6a5581df16a 100644
--- a/libstdc++-v3/include/bits/std_function.h
+++ b/libstdc++-v3/include/bits/std_function.h
@@ -652,6 +652,28 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
        }
       /// @}
 
+      /// @cond undocumented
+      // Like target<_Functor>(), but recognizes only a target that was
+      // stored by this specialization's handler for _Functor in the same
+      // program image, and never compares type_info.  It is therefore
+      // cheap when it fails, but may return null even if
+      // target<_Functor>() wouldn't.  For internal use by the library.
+      template<typename _Functor>
+       const _Functor*
+       _M_target_if() const noexcept
+       {
+         if (_M_manager == &_Handler<_Functor>::_M_manager)
+           {
+             // A direct call, so this inlines to a load or address 
computation.
+             _Any_data __ptr;
+             _Handler<_Functor>::_M_manager(__ptr, _M_functor,
+                                            __get_functor_ptr);
+             return __ptr._M_access<const _Functor*>();
+           }
+         return nullptr;
+       }
+      /// @endcond
+
     private:
       using _Invoker_type = _Res (*)(const _Any_data&, _ArgTypes&&...);
       _Invoker_type _M_invoker = nullptr;
-- 
2.56.1


Reply via email to