r17-4555-ga0b77a14fed845 added _M_match_simple_repeat_body, which for
the common DFS NFA shape repeat -> match -> repeat (produced by X* and
X+ where X matches a single character, e.g. \w+ or [^\s?#]*) consumes
the body match state directly from _M_handle_repeat instead of going
through the generic state dispatch.  But that only removes one dispatch
per character: each iteration still saves an exit fallback frame and a
restore_rep_count frame and updates _M_rep_count, which is the bulk of
the per-character cost.

This patch replaces it with a proper greedy loop:

 * When a greedy repeat has this shape, _M_greedy_char_loop consumes
   the longest run of matching characters up front and continues with
   the repeat's exit.  The remaining exits, one character shorter each
   time down to the start position, are recorded by just two frames per
   loop rather than two per character: an _S_fopcode_greedy_char_loop
   frame holding the exit state and next exit position to try, on top
   of an _S_fopcode_greedy_char_loop_bound frame holding the start
   position.  _M_dfs unwinds them, honoring _M_has_sol like
   _S_fopcode_fallback_next.

 * This explores the same paths in the same order as the generic code.
   _M_rep_count[__i] is not needed: entering the body immediately
   consumes a character or fails, so in the generic code __i can never
   be re-entered at the same position while its restore_rep_count frame
   is active (its count can never reach 2).  Any epsilon cycle through
   the repeat goes through another repeat, which still tracks its count.

Since this changes the members and behavior of _Executor, and the
previous executor changes were backported to the GCC 16 branch with
_Executor in the inline namespace _V2, this patch moves _Executor to
a new inline namespace _V3.  Otherwise, code compiled against the GCC
16 headers and linked with code compiled against these headers could
end up with ODR-violating mixed _Executor member definitions, e.g. a
GCC 16 _M_dfs calling this patch's _M_handle_repeat, which pushes
frame opcodes the GCC 16 _M_dfs does not know about.

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):

               before -O2  after -O2  before -O3  after -O3
      Email     222.38 ms  149.09 ms   225.95 ms  153.45 ms
      URI       186.91 ms  127.59 ms   191.12 ms  129.62 ms
      IP          9.05 ms    9.21 ms     9.97 ms    9.49 ms

The IP pattern contains no * or +, so it is unaffected (differences
are noise).  On a short-string benchmark (1.2M regex_search calls on
inputs of up to 19 characters) the email pattern improved by ~27%,
"foo|bar" and "abc" were unchanged, and IPv4 was 2-5% slower in both
rounds.  The cause of the latter is unclear: the parent already did the
same shape check on each visit to a greedy repeat, so it is probably a
code layout or inlining effect.

Gaps and possible follow-ups:

 * Non-greedy X*? could be handled similarly: each time its frame is
   popped, consume one more character and retry the exit.
 * Each loop character still costs an indirect std::function call via
   _M_matches.  The next commit addresses this.

        PR libstdc++/126274

libstdc++-v3/ChangeLog:

        * include/bits/regex.h (_Executor): Move forward declaration
        to inline namespace _V3.
        * include/bits/regex_executor.h (_Executor): Move to inline
        namespace _V3.
        (_Executor::_M_match_simple_repeat_body): Remove.
        (_Executor::_M_greedy_char_loop): Declare.
        * include/bits/regex_executor.tcc (_ExecutorFrameOpcode): Add
        _S_fopcode_greedy_char_loop and _S_fopcode_greedy_char_loop_bound.
        (_Executor::_M_match_simple_repeat_body): Remove.
        (_Executor::_M_greedy_char_loop): Define.
        (_Executor::_M_handle_repeat): Use it for greedy repeats whose body
        is a single match state looping back to the repeat.
        (_Executor::_M_dfs): Handle the new frame opcodes.

Assisted-by: Claude Opus 5.5
---
 libstdc++-v3/include/bits/regex.h            |   4 +-
 libstdc++-v3/include/bits/regex_executor.h   |   6 +-
 libstdc++-v3/include/bits/regex_executor.tcc | 107 ++++++++++++++-----
 3 files changed, 83 insertions(+), 34 deletions(-)

diff --git a/libstdc++-v3/include/bits/regex.h 
b/libstdc++-v3/include/bits/regex.h
index 92aa6ec2210..916ab6e7d73 100644
--- a/libstdc++-v3/include/bits/regex.h
+++ b/libstdc++-v3/include/bits/regex.h
@@ -61,10 +61,10 @@ namespace __detail
                      _RegexExecutorPolicy                 __policy,
                      bool                                 __match_mode);
 
-_GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(_V2)
+_GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(_V3)
   template<typename, typename, typename>
     class _Executor;
-_GLIBCXX_END_INLINE_ABI_NAMESPACE(_V2)
+_GLIBCXX_END_INLINE_ABI_NAMESPACE(_V3)
 
   template<typename _Tp>
     struct __is_contiguous_iter : false_type { };
diff --git a/libstdc++-v3/include/bits/regex_executor.h 
b/libstdc++-v3/include/bits/regex_executor.h
index 0e15d722ca6..c28c830daaf 100644
--- a/libstdc++-v3/include/bits/regex_executor.h
+++ b/libstdc++-v3/include/bits/regex_executor.h
@@ -44,7 +44,7 @@ namespace __detail
   template<typename _BiIter, bool _Trivial = 
is_trivially_copyable<_BiIter>::value>
     struct _ExecutorFrame;
 
-_GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(_V2)
+_GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(_V3)
   /**
    * @brief Takes a regex and an input string and does the matching.
    *
@@ -119,7 +119,7 @@ _GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(_V2)
       _M_rep_once_more(_Match_mode __match_mode, _StateIdT);
 
       _StateIdT
-      _M_match_simple_repeat_body(_StateIdT, _StateIdT);
+      _M_greedy_char_loop(_StateIdT);
 
       template<_Search_mode __search_mode>
       _StateIdT
@@ -298,7 +298,7 @@ _GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(_V2)
       // Do we have a solution so far?
       bool                                                  _M_has_sol;
     };
-_GLIBCXX_END_INLINE_ABI_NAMESPACE(_V2)
+_GLIBCXX_END_INLINE_ABI_NAMESPACE(_V3)
 
  ///@} regex-detail
 } // namespace __detail
diff --git a/libstdc++-v3/include/bits/regex_executor.tcc 
b/libstdc++-v3/include/bits/regex_executor.tcc
index fe9636c9cb6..0c90909256a 100644
--- a/libstdc++-v3/include/bits/regex_executor.tcc
+++ b/libstdc++-v3/include/bits/regex_executor.tcc
@@ -207,6 +207,8 @@ namespace __detail
     _S_fopcode_restore_cur_results,
     _S_fopcode_restore_rep_count,
     _S_fopcode_decrement_rep_count,
+    _S_fopcode_greedy_char_loop,
+    _S_fopcode_greedy_char_loop_bound,
   };
 
 #pragma GCC diagnostic push
@@ -425,29 +427,42 @@ namespace __detail
       return _S_invalid_state_id;
     }
 
-  // Try to consume the common repeat body shape
-  //   repeat -> match -> repeat
-  // without going through the generic state dispatch again.
+  // Greedy DFS loop over a repeat whose body is a single match state, i.e.
+  // the NFA shape  repeat -> match -> repeat  produced by X* and X+ where X
+  // matches one character (e.g. \w+, [^\s?#]*, a*).
+  //
+  // Instead of visiting the repeat and the match state once per character,
+  // and saving an exit fallback frame and a repeat count frame each time,
+  // consume the longest run of matching characters up front and try the
+  // exit after it.  The remaining exits, one character shorter each time,
+  // are recorded by a single _S_fopcode_greedy_char_loop frame (on top of a
+  // _S_fopcode_greedy_char_loop_bound frame holding the start position)
+  // which is unwound in _M_dfs.  This explores the same paths in the same
+  // order as the generic code.
+  //
+  // _M_rep_count[__i] is not needed: entering the body immediately consumes a
+  // character or fails, so in the generic code __i can never be re-entered at
+  // the same position while its repeat-count frame is active, and any epsilon
+  // cycle through __i must pass through another repeat that tracks its count.
   template<typename _BiIter, typename _Alloc, typename _TraitsT>
-#ifdef __OPTIMIZE__
-    [[__gnu__::__always_inline__]]
-#endif
-    inline _StateIdT _Executor<_BiIter, _Alloc, _TraitsT>::
-    _M_match_simple_repeat_body(_StateIdT __next, _StateIdT __repeat)
+    _StateIdT _Executor<_BiIter, _Alloc, _TraitsT>::
+    _M_greedy_char_loop(_StateIdT __i)
     {
-      if (__next == _S_invalid_state_id)
-       return _S_invalid_state_id;
-
-      const auto& __state = _M_nfa[__next];
-      if (__state._M_opcode() != _S_opcode_match
-         || __state._M_next != __repeat)
-       return __next;
-
-      if (_M_current == _M_end || !__state._M_matches(*_M_current))
-       return _S_invalid_state_id;
-
-      ++_M_current;
-      return __repeat;
+      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;
+      if (__cur != _M_current)
+       {
+         _M_frames.emplace_back(_S_fopcode_greedy_char_loop_bound, __i,
+                                _M_current);
+         _M_frames.emplace_back(_S_fopcode_greedy_char_loop, __state._M_next,
+                                std::prev(__cur));
+         _M_current = __cur;
+       }
+      return __state._M_next;
     }
 
   // _M_alt branch is "match once more", while _M_next is "get me out
@@ -467,16 +482,18 @@ namespace __detail
       if (!__state._M_neg)
        {
          if constexpr (__search_mode == _Search_mode::_Dfs)
-           // If it's DFS executor and already accepted, we're done.
-           _M_frames.emplace_back(_S_fopcode_fallback_next, __state._M_next,
-                                  _M_current);
+           {
+             const auto& __body = _M_nfa[__state._M_alt];
+             if (__body._M_opcode() == _S_opcode_match
+                 && __body._M_next == __i)
+               return _M_greedy_char_loop(__i);
+             // If it's DFS executor and already accepted, we're done.
+             _M_frames.emplace_back(_S_fopcode_fallback_next, __state._M_next,
+                                    _M_current);
+           }
          else
            _M_frames.emplace_back(_S_fopcode_next, __state._M_next);
-         _StateIdT __next = _M_rep_once_more(__match_mode, __i);
-         if constexpr (__search_mode == _Search_mode::_Dfs)
-           return _M_match_simple_repeat_body(__next, __i);
-         else
-           return __next;
+         return _M_rep_once_more(__match_mode, __i);
        }
       else // Non-greedy mode
        {
@@ -905,6 +922,38 @@ namespace __detail
            case _S_fopcode_decrement_rep_count:
              _M_rep_count[__frame._M_state_id].second--;
              break;
+
+           case _S_fopcode_greedy_char_loop:
+             // Try the exit of the greedy loop at __frame._M_pos, and record
+             // the next shorter one unless we've reached the start position
+             // saved in the bound frame below.  See _M_greedy_char_loop.
+             if constexpr (__search_mode == _Search_mode::_Dfs)
+               {
+                 __glibcxx_assert(!_M_frames.empty()
+                                  && _M_frames.back()._M_op
+                                     == _S_fopcode_greedy_char_loop_bound);
+                 if (_M_has_sol)
+                   {
+                     _M_frames.pop_back();
+                     break;
+                   }
+                 if (__frame._M_pos == _M_frames.back()._M_pos)
+                   _M_frames.pop_back();
+                 else
+                   _M_frames.emplace_back(_S_fopcode_greedy_char_loop,
+                                          __frame._M_state_id,
+                                          std::prev(__frame._M_pos));
+                 _M_current = __frame._M_pos;
+                 __next = __frame._M_state_id;
+               }
+             else
+               __glibcxx_assert(false);
+             break;
+
+           case _S_fopcode_greedy_char_loop_bound:
+             // Always consumed by the _S_fopcode_greedy_char_loop case.
+             __glibcxx_assert(false);
+             break;
            }
        }
     }
-- 
2.56.1


Reply via email to