r17-4554-gded7c4e851228c added _M_maybe_start_match, a conservative
precheck that regex_search runs at every start position before entering
the executor. It recursively walks the non-consuming front of the NFA
from _M_start, evaluating ^, $ and \b at the current position and
testing each reachable match state against *_M_current. Its cost is
paid again at each of the O(n) start positions, even though apart from
the assertion checks the walk depends only on the pattern:
* Each rejected position costs a fresh recursive walk plus one indirect
(std::function) _M_matches call per reachable first match state.
E.g. for the IPv4 pattern below that is four calls per position
('2' twice, [01], [0-9]). The walk is unmemoized and bounded only by
a depth cap of the NFA size.
* For an anchored pattern like "^abc" it still runs at every remaining
position, only to fail at ^ each time.
* It is disabled entirely in BFS mode and for any regex containing a
backreference anywhere.
This patch instead derives a first-character filter from the pattern
once per _M_search call, so each position costs only a character test:
* As before, _M_search first tries the initial position unfiltered.
Afterwards match_prev_avail is set, so from then on a ^ assertion
can only succeed if multiline is on.
* _M_first_states then walks the epsilon closure of _M_start once and
collects the match states that can consume the first character of a
match at the remaining positions. This is a reachability analysis
that does not depend on the input, not an evaluation of the NFA at a
position, so it needs only a coarse classification of opcodes:
non-consuming states (captures, dummies, alternatives, repeats, and
assertions including lookaheads, which are conservatively treated as
succeeding) are followed, match states are collected, and
accept/backref disable the filter. The one exception is ^ when
multiline is off, which can no longer succeed and so ends its path.
The walk is iterative and linear in the NFA size. Since every NFA
cycle passes through a repeat state, the visited bitmap and walk
stack are only allocated once an alternative or repeat state is
reached, so straight-line prefixes need no allocation.
* The remaining start positions whose character is rejected by the
filter are skipped without calling _M_search_from_first. No match
can start at _M_end when the filter applies, since the accept state
is then not reachable without consuming input. Empty inputs and
matches at the initial position bypass the filter.
* For 8-bit integral character types, the filter's result is cached
per character value in a lazily populated 256-entry table, so after
the first occurrence of a given byte value, testing a position is a
single table load. The table is filled lazily rather than up front
because only character values that occur in the input should be
queried: filling all 256 entries would cost hundreds of matcher calls
per regex_search call, _BracketMatcher's cache only covers 7-bit
values so other values can be expensive to test (e.g. under collate),
and a custom regex_traits might not expect them. For other character
types each position costs one _M_matches call per first match state,
still with no walk.
Compared to the old precheck this means:
* Rejected positions cost a table load (or a few matcher calls) rather
than a recursive NFA walk with matcher calls.
* When the only path to a match starts with a non-multiline ^, e.g.
"^abc" or "^.*", the search now ends right after the initial position
instead of visiting every remaining position.
* The filter also applies in BFS (__polynomial) mode and to regexes
with backreferences, unless a backreference can be reached before the
first character is consumed.
* The old precheck had to correctly combine the assertion,
alternative and repeat semantics at each position, and any mistake
there would silently skip a real match. The new walk evaluates
nothing at a position, and only a non-multiline ^ prunes a path.
The per-character test is the executor's own _M_matches.
All new state is local to _M_search, so the layout of _Executor and the
NFA format are unchanged.
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; master includes the old precheck):
master -O2 patch -O2 master -O3 patch -O3
Email 280.88 ms 240.70 ms 274.27 ms 237.15 ms
URI 233.36 ms 205.35 ms 232.38 ms 200.50 ms
IP 161.54 ms 9.92 ms 148.96 ms 9.29 ms
The IP pattern can only start with a digit, so almost every position is
rejected and the cost per rejection dominates. Averaged over the input
it falls from about 24 ns to about 1.5 ns per byte. The Email and URI
patterns can start with any word character, so most positions still
enter the executor and the gain is smaller.
Calling regex_search separately on each of the file's 206K lines, where
the once-per-call cost of computing the filter matters more:
master -O2 patch -O2 master -O3 patch -O3
Email 293.13 ms 286.93 ms 289.24 ms 282.82 ms
URI 242.05 ms 240.63 ms 242.09 ms 236.94 ms
IP 159.92 ms 84.12 ms 172.57 ms 81.28 ms
PR libstdc++/126274
libstdc++-v3/ChangeLog:
* include/bits/regex_executor.h (_Executor::_M_search_from_first):
Remove _M_maybe_start_match precheck.
(_Executor::_M_maybe_start_match): Remove.
(_Executor::_M_first_states): Declare.
* include/bits/regex_executor.tcc (_Executor::_M_search): After
trying the initial position, skip start positions rejected by a
first-character filter.
(_Executor::_M_first_states): Define.
(_Executor::_M_maybe_start_match): Remove.
Assisted-by: Claude Opus 5.5
---
libstdc++-v3/include/bits/regex_executor.h | 24 +-
libstdc++-v3/include/bits/regex_executor.tcc | 245 +++++++++++--------
2 files changed, 147 insertions(+), 122 deletions(-)
diff --git a/libstdc++-v3/include/bits/regex_executor.h
b/libstdc++-v3/include/bits/regex_executor.h
index 51de0f52113..0e15d722ca6 100644
--- a/libstdc++-v3/include/bits/regex_executor.h
+++ b/libstdc++-v3/include/bits/regex_executor.h
@@ -108,28 +108,6 @@ _GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(_V2)
_M_search_from_first()
{
_M_current = _M_begin;
- // Fast reject for DFS prefix search. regex_search and
- // regex_token_iterator try the pattern at each possible starting
- // position. If the regex can only start with a digit, running the full
- // DFS executor at a space, letter, or punctuation character only builds
- // frames to discover the first match state rejects that character.
- //
- // Example: for the IPv4 pattern
- // (?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])\.){3}...
- // a current input character of 'x' cannot match any first consuming
- // state. _M_maybe_start_match returns false and this starting position
- // is skipped. At '2' it returns true, because at least one branch
- // might match, so the normal executor still decides the complete
- // result.
- //
- // This is intentionally disabled for backreferences. Pruning the
- // search space for DFS reduces the number of frames we build and the
- // time to find an actual match.
- if (_M_search_mode == _Search_mode::_Dfs
- && !_M_nfa._M_has_backref
- && _M_current != _M_end
- && !_M_maybe_start_match(_M_start, 0))
- return false;
return _M_main(_Match_mode::_Prefix);
}
@@ -202,7 +180,7 @@ _GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(_V2)
_M_main_dfs(_Match_mode __match_mode);
bool
- _M_maybe_start_match(_StateIdT, size_t);
+ _M_first_states(_GLIBCXX_STD_C::vector<_StateIdT>&) const;
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 d4f7a2a4bd5..fe9636c9cb6 100644
--- a/libstdc++-v3/include/bits/regex_executor.tcc
+++ b/libstdc++-v3/include/bits/regex_executor.tcc
@@ -45,13 +45,155 @@ namespace __detail
if (_M_flags & regex_constants::match_continuous)
return false;
_M_flags |= regex_constants::match_prev_avail;
- while (_M_begin != _M_end)
+ if (_M_begin == _M_end)
+ return false;
+
+ // Match states that can consume the first character of a match at a
+ // later position.
+ _GLIBCXX_STD_C::vector<_StateIdT> __first;
+ if (!_M_first_states(__first))
{
- ++_M_begin;
- if (_M_search_from_first())
+ // No filter; try every remaining position.
+ while (_M_begin != _M_end)
+ {
+ ++_M_begin;
+ if (_M_search_from_first())
+ return true;
+ }
+ return false;
+ }
+
+ // Skip every remaining starting position whose character is rejected
+ // by all of the first match states, without entering
+ // _M_search_from_first. Since _M_first_states succeeded, no match can
+ // start at _M_end: the accept state is not reachable without consuming
+ // input other than through a non-multiline ^, which can't succeed now
+ // that match_prev_avail is set.
+ if (__first.empty())
+ return false; // e.g. "^abc" or "^.*"
+
+ // Test whether some first match state accepts a character.
+ auto __can_start = [this, &__first](_CharT __c) {
+ for (_StateIdT __i : __first)
+ if (_M_nfa[__i]._M_matches(__c))
return true;
+ return false;
+ };
+
+ // 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)
+ {
+ using _UCharT = typename make_unsigned<_CharT>::type;
+ // Lazy cache: -1 = unknown, 0 = reject, 1 = accept.
+ // Only characters actually seen in the input are queried.
+ signed char __table[256];
+ __builtin_memset(__table, -1, sizeof(__table));
+ while (++_M_begin != _M_end)
+ {
+ const _CharT __c = *_M_begin;
+ signed char& __slot = __table[static_cast<_UCharT>(__c)];
+ if (__slot < 0)
+ __slot = __can_start(__c);
+ if (__slot && _M_search_from_first())
+ return true;
+ }
+ return false;
}
- return false;
+ else
+ {
+ while (++_M_begin != _M_end)
+ if (__can_start(*_M_begin) && _M_search_from_first())
+ return true;
+ return false;
+ }
+ }
+
+ // Collect the match states that can consume the first character of a match
+ // starting at a position other than the initial one, following every path
+ // through the non-consuming states from _M_start. Assertions (including
+ // lookaheads) are treated as always succeeding, except ^ when multiline is
+ // off, which ends that path because ^ can then only succeed at the initial
+ // position. So the result is conservative: a match starting at a
+ // non-initial position can only start at a character accepted by one of
+ // the collected states.
+ //
+ // Return false if the first character of a match can't be characterized
+ // this way, i.e. if the accept state (an empty match) or a backreference
+ // is reachable without consuming input.
+ template<typename _BiIter, typename _Alloc, typename _TraitsT>
+ bool _Executor<_BiIter, _Alloc, _TraitsT>::
+ _M_first_states(_GLIBCXX_STD_C::vector<_StateIdT>& __first) const
+ {
+ const bool __multiline = _M_match_multiline();
+
+ // A cycle in the NFA must pass through an _S_opcode_repeat state, so
+ // the visited bitmap and the stack of pending paths are only needed
+ // (and only allocated) once an alternative or repeat state is seen.
+ // The states before the first such state are not marked visited, but
+ // revisiting them (e.g. via the back edge of a + repeat) is harmless:
+ // the walk then just follows the same straight line to that first
+ // alternative or repeat state, which is marked.
+ _GLIBCXX_STD_C::vector<bool> __visited;
+ _GLIBCXX_STD_C::vector<_StateIdT> __stack;
+ _StateIdT __i = _M_start;
+ while (true)
+ {
+ if (__i == _S_invalid_state_id
+ || (!__visited.empty() && __visited[__i]))
+ {
+ // This path ends here; resume a pending one, if any.
+ if (__stack.empty())
+ break;
+ __i = __stack.back();
+ __stack.pop_back();
+ continue;
+ }
+
+ const auto& __state = _M_nfa[__i];
+ _StateIdT __next = __state._M_next;
+ switch (__state._M_opcode())
+ {
+ case _S_opcode_alternative:
+ case _S_opcode_repeat:
+ if (__visited.empty())
+ {
+ __visited.resize(_M_nfa.size());
+ // Avoid repeated reallocation, which is significant when
+ // searching many short strings.
+ __stack.reserve(8);
+ __first.reserve(8);
+ }
+ __stack.push_back(__state._M_alt);
+ break;
+ case _S_opcode_match:
+ __first.push_back(__i);
+ __next = _S_invalid_state_id;
+ break;
+ case _S_opcode_line_begin_assertion:
+ if (!__multiline)
+ __next = _S_invalid_state_id;
+ break;
+ // States that don't consume input; assertions are assumed to
+ // succeed, which is conservative.
+ case _S_opcode_subexpr_begin:
+ case _S_opcode_subexpr_end:
+ case _S_opcode_line_end_assertion:
+ case _S_opcode_word_boundary:
+ case _S_opcode_subexpr_lookahead:
+ case _S_opcode_dummy:
+ break;
+ default: // accept, backref
+ return false;
+ }
+
+ if (!__visited.empty())
+ __visited[__i] = true;
+ __i = __next;
+ }
+ return true;
}
enum _ExecutorFrameOpcode : unsigned char
@@ -169,101 +311,6 @@ namespace __detail
return _M_has_sol;
}
- // Return whether a prefix search at _M_current might still match after
- // looking only through the non-consuming front of the NFA.
- //
- // This is not a general implementation. It is deliberately small and
- // conservative: when it reaches a construct whose first consuming character
- // is hard to know cheaply, it returns true and lets the normal executor run.
- // The important fast paths are the common negative cases.
- //
- // Examples:
- // * Pattern "[0-9]+" at input 'x': the first _S_opcode_match rejects 'x',
- // so a full DFS search would only allocate/pop frames to fail. Return
- // false and let regex_search advance the starting position.
- //
- // * Pattern "[01]?[0-9]" at input '9': the optional [01] branch rejects,
- // but the skip branch can consume '9'. Return true and let DFS decide
- // the full match.
- //
- // * Pattern "foo|bar" at input 'b': one alternative rejects, the other can
- // start with 'b'. Return true.
- template<typename _BiIter, typename _Alloc, typename _TraitsT>
- bool _Executor<_BiIter, _Alloc, _TraitsT>::
- _M_maybe_start_match(_StateIdT __i, size_t __depth)
- {
- // Depth is bounded by the NFA size so epsilon cycles cannot make the
- // precheck recurse forever. Hitting the bound means "unknown", not
- // "no match", so stay conservative and run the real executor. This is
- // important for patterns such as "(a*)*" where epsilon paths can cycle
- // before a consuming state is reached.
- if (__depth > _M_nfa.size())
- return true;
-
- // An invalid edge is a real dead end for the explored path.
- if (__i == _S_invalid_state_id)
- return false;
-
- const auto& __state = _M_nfa[__i];
- switch (__state._M_opcode())
- {
- case _S_opcode_match:
- return __state._M_matches(*_M_current);
-
- case _S_opcode_accept:
- // Empty matches are possible, so the full executor must decide.
- return true;
-
- case _S_opcode_subexpr_begin:
- case _S_opcode_subexpr_end:
- case _S_opcode_dummy:
- // Captures and dummy states do not consume input, so they cannot
- // affect the first-character decision. Continue along the only
- // successor.
- return _M_maybe_start_match(__state._M_next, __depth + 1);
-
- case _S_opcode_line_begin_assertion:
- // Assertions do not consume characters, but they can reject the
- // current position. For "^abc" at a non-begin position, there is no
- // need to run DFS merely to discover that ^ fails.
- return _M_at_begin()
- && _M_maybe_start_match(__state._M_next, __depth + 1);
-
- case _S_opcode_line_end_assertion:
- // Same idea for "$": if the assertion does not hold here, this
- // starting position cannot match via this path.
- return _M_at_end()
- && _M_maybe_start_match(__state._M_next, __depth + 1);
-
- case _S_opcode_word_boundary:
- // Word-boundary assertions are also checked before the first
- // consuming state. For "\bfoo" in the middle of "xfoo", this path
- // rejects before testing 'f'.
- return _M_word_boundary() == !__state._M_neg
- && _M_maybe_start_match(__state._M_next, __depth + 1);
-
- case _S_opcode_alternative:
- // A branch might match if either arm can start with *_M_current.
- // Example: "foo|bar" at 'b' rejects the "foo" arm but keeps the
- // search because the "bar" arm is viable.
- return _M_maybe_start_match(__state._M_alt, __depth + 1)
- || _M_maybe_start_match(__state._M_next, __depth + 1);
-
- case _S_opcode_repeat:
- // Repeats can either enter the body or skip to the exit, so inspect
- // both paths. This matters for constructs such as "[01]?[0-9]": at
- // '9' the optional first digit can be skipped, while at 'x' both
- // paths reject.
- return _M_maybe_start_match(__state._M_alt, __depth + 1)
- || _M_maybe_start_match(__state._M_next, __depth + 1);
-
- case _S_opcode_backref:
- case _S_opcode_subexpr_lookahead:
- default:
- return true;
- }
- }
-
// ------------------------------------------------------------
//
// BFS mode:
--
2.56.1