For a greedy single-character repeat such as \w+, r17-4555-ga0b77a14fed845
avoids a DFS dispatch per character but still pushes two frames: one to
retry the exit and one to restore the repeat count.

Consume the longest run first.  Two frames suffice for the whole run:
one holds its starting position and the other holds the next shorter
exit to try.  This preserves greedy backtracking order.  The repeat
needs no count to guard against empty iterations: its body consumes
one character or fails.

Move _Executor from inline namespace _V2 to _V3.  GCC 16's _V2 executor
doesn't recognize the new frame opcodes; when linking objects built with
both sets of headers, its _M_dfs must not be paired with the new
_M_handle_repeat.

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 has no * or + loop.  On 1.2M regex_search calls with
inputs up to 19 characters, Email improved by about 27%, foo|bar and abc
were unchanged, and IPv4 was 2-5% slower.

        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 | 97 ++++++++++++++------
 3 files changed, 73 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 97787a0e565..5b2e01b1b1e 100644
--- a/libstdc++-v3/include/bits/regex_executor.tcc
+++ b/libstdc++-v3/include/bits/regex_executor.tcc
@@ -192,6 +192,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
@@ -410,29 +412,33 @@ 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.
+  // For a greedy repeat -> match -> repeat, try the longest run first.
+  // Two frames record all remaining exits: the lower frame holds the start
+  // of the run and the upper frame walks back one character at a time.
+  //
+  // The body cannot return to __i without consuming a character.  Any
+  // cycle that re-enters __i without consuming input must take the exit
+  // and pass through another repeat with its own count.  So this repeat
+  // doesn't need _M_rep_count[__i] to break cycles.
   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
@@ -452,16 +458,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);
+             // Try the exit only if repeating doesn't give a solution.
+             _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
        {
@@ -890,6 +898,37 @@ namespace __detail
            case _S_fopcode_decrement_rep_count:
              _M_rep_count[__frame._M_state_id].second--;
              break;
+
+           case _S_fopcode_greedy_char_loop:
+             // Retry the exit one character earlier.  The bound frame stays
+             // on the stack until we find a solution or reach the run's start.
+             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