A greedy single-character loop calls the same std::function for every
character in the run. So does the first-character filter when it has
one candidate and no per-character cache. Identify the matcher once
before entering either loop so the compiler can inline the call.
_M_visit_matcher passes a literal, bracket, or ECMAScript dot matcher
to the loop as its concrete type. Other matchers, including collating
matchers and POSIX dot, use the stored std::function. This limits the
number of loop instantiations. Trying the same dispatch in
_M_handle_match, where it would run per character, gave no benefit.
Use a manager-pointer comparison rather than std::function::target<T>:
on a miss, target<T> can make an indirect call and compare type_info.
Using target<T> made the benchmark below about 55% slower. A manager
pointer can differ across shared libraries even for the same type; a
miss simply selects the ordinary std::function call.
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 matcher
itself dominates and inlining the call to it gains little.
The benchmark binary's text grows by ~1.1KB.
libstdc++-v3/ChangeLog:
* include/bits/std_function.h (_Function_handler::_M_get_pointer):
Make public via using-declaration.
(function::_M_fast_target): New.
* include/bits/regex_executor.h (_Executor::_M_visit_matcher)
(_Executor::_S_visit_matcher): Declare.
(_Executor::_Greedy_scan, _Executor::_Search_filtered_by): Declare.
* 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 _M_visit_matcher when the filter isn't
cached and 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 | 16 +++
libstdc++-v3/include/bits/regex_executor.tcc | 105 ++++++++++++++++---
libstdc++-v3/include/bits/std_function.h | 16 +++
3 files changed, 123 insertions(+), 14 deletions(-)
diff --git a/libstdc++-v3/include/bits/regex_executor.h
b/libstdc++-v3/include/bits/regex_executor.h
index c28c830daaf..bbe68c4798c 100644
--- a/libstdc++-v3/include/bits/regex_executor.h
+++ b/libstdc++-v3/include/bits/regex_executor.h
@@ -115,6 +115,22 @@ _GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(_V3)
_M_search();
private:
+ // Dispatch once for the whole loop in __fn. Pass the concrete matcher
+ // when recognized, so its calls can be inlined; otherwise pass the
+ // stored std::function.
+ 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);
diff --git a/libstdc++-v3/include/bits/regex_executor.tcc
b/libstdc++-v3/include/bits/regex_executor.tcc
index 5b2e01b1b1e..a179fddbf53 100644
--- a/libstdc++-v3/include/bits/regex_executor.tcc
+++ b/libstdc++-v3/include/bits/regex_executor.tcc
@@ -36,6 +36,67 @@ _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();
+ // Only probe for specializations consistent with the regex flags.
+ const auto __opts = _M_nfa._M_options();
+ if (!(__opts & regex_constants::collate))
+ {
+ if (__opts & regex_constants::icase)
+ return _S_visit_matcher<true>(__m, __fn);
+ else
+ return _S_visit_matcher<false>(__m, __fn);
+ }
+ 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))
+ {
+ // Leave POSIX . to std::function to avoid instantiating another
+ // version of each loop.
+ constexpr bool __collate = false;
+ constexpr bool __is_ecma = true;
+ using _BracketM = _BracketMatcher<_TraitsT, __icase, __collate>;
+ using _CharM = _CharMatcher<_TraitsT, __icase, __collate>;
+ using _AnyM = _AnyMatcher<_TraitsT, __is_ecma, __icase, __collate>;
+
+ if (const auto* __p = __m.template _M_fast_target<_BracketM>())
+ return __fn(*__p);
+ if (const auto* __p = __m.template _M_fast_target<_CharM>())
+ return __fn(*__p);
+ if (const auto* __p = __m.template _M_fast_target<_AnyM>())
+ return __fn(*__p);
+ return __fn(__m);
+ }
+
+ // The initial position has already been tried. Search the remaining
+ // positions whose first character passes the filter.
+ 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()
@@ -67,6 +128,11 @@ namespace __detail
if (__first.empty())
return false;
+ // For 8-bit characters, cache __can_start per character value.
+ constexpr bool __use_filter_cache
+ = sizeof(_CharT) == 1 && __CHAR_BIT__ == 8
+ && is_integral<_CharT>::value && !is_same<_CharT, bool>::value;
+
auto __can_start = [this, &__first](_CharT __c) {
for (_StateIdT __i : __first)
if (_M_nfa[__i]._M_matches(__c))
@@ -74,11 +140,9 @@ namespace __detail
return false;
};
- // For 8-bit characters, cache __can_start per character value.
- if constexpr (sizeof(_CharT) == 1 && __CHAR_BIT__ == 8
- && is_integral<_CharT>::value
- && !is_same<_CharT, bool>::value)
+ if constexpr (__use_filter_cache)
{
+ // Only cache misses need a matcher call.
using _UCharT = typename make_unsigned<_CharT>::type;
// -1 = unknown, 0 = reject, 1 = accept. Fill on demand to avoid
// testing values absent from the input; uncached bracket matches
@@ -96,13 +160,10 @@ namespace __detail
}
return false;
}
+ else if (__first.size() == 1)
+ return _M_visit_matcher(_M_nfa[__first[0]], _Search_filtered_by{this});
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 candidate first match states by walking the NFA from _M_start
@@ -412,6 +473,24 @@ namespace __detail
return _S_invalid_state_id;
}
+ // Return the end of the longest run accepted by the matcher.
+ 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;
+ }
+ };
+
// 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.
@@ -426,10 +505,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..38ace123404 100644
--- a/libstdc++-v3/include/bits/std_function.h
+++ b/libstdc++-v3/include/bits/std_function.h
@@ -268,6 +268,8 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
using _Base = _Function_base::_Base_manager<_Functor>;
public:
+ using _Base::_M_get_pointer;
+
static bool
_M_manager(_Any_data& __dest, const _Any_data& __source,
_Manager_operation __op)
@@ -652,6 +654,20 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
}
/// @}
+ /// @cond undocumented
+ // Compare only manager pointers. Unlike target<_Functor>(), this can
+ // miss a target stored by another shared library. Callers must have
+ // a fallback for that case.
+ template<typename _Functor>
+ const _Functor*
+ _M_fast_target() const noexcept
+ {
+ if (_M_manager == &_Handler<_Functor>::_M_manager)
+ return _Handler<_Functor>::_M_get_pointer(_M_functor);
+ return nullptr;
+ }
+ /// @endcond
+
private:
using _Invoker_type = _Res (*)(const _Any_data&, _ArgTypes&&...);
_Invoker_type _M_invoker = nullptr;
--
2.56.1