Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[libc++] Add basic constant folding for std::format #107197

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions 43 libcxx/include/__format/format_functions.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
#define _LIBCPP___FORMAT_FORMAT_FUNCTIONS

#include <__algorithm/clamp.h>
#include <__algorithm/ranges_find_first_of.h>
#include <__chrono/statically_widen.h>
#include <__concepts/convertible_to.h>
#include <__concepts/same_as.h>
#include <__config>
Expand All @@ -36,6 +38,7 @@
#include <__iterator/iterator_traits.h> // iter_value_t
#include <__variant/monostate.h>
#include <array>
#include <optional>
#include <string>
#include <string_view>

Expand Down Expand Up @@ -447,10 +450,47 @@ format_to(_OutIt __out_it, wformat_string<_Args...> __fmt, _Args&&... __args) {
}
# endif

// Try constant folding the format string instead of going through the whole formatting machinery. If there is no
// constant folding no extra code should be emitted (with optimizations enabled) and the function returns nullopt. When
// constant folding is successful, the formatting is performed and the resulting string is returned.
namespace __format {
template <class _CharT>
philnik777 marked this conversation as resolved.
Show resolved Hide resolved
[[nodiscard]] _LIBCPP_HIDE_FROM_ABI optional<basic_string<_CharT>> __try_constant_folding(
philnik777 marked this conversation as resolved.
Show resolved Hide resolved
basic_string_view<_CharT> __fmt,
basic_format_args<basic_format_context<back_insert_iterator<__format::__output_buffer<_CharT>>, _CharT>> __args) {
// Fold strings not containing '{' or '}' to just return the string
if (bool __is_identity = [&] [[__gnu__::__pure__]] // Make sure the compiler knows this call can be eliminated
{ return std::ranges::find_first_of(__fmt, array{'{', '}'}) == __fmt.end(); }();
__builtin_constant_p(__is_identity) && __is_identity)
return basic_string<_CharT>{__fmt};

// Fold '{}' to the appropriate conversion function
if (auto __only_first_arg = __fmt == _LIBCPP_STATICALLY_WIDEN(_CharT, "{}");
__builtin_constant_p(__only_first_arg) && __only_first_arg) {
if (auto __arg = __args.get(0); __builtin_constant_p(__arg.__type_)) {
return std::__visit_format_arg(
[]<class _Tp>(_Tp&& __argument) -> optional<basic_string<_CharT>> {
if constexpr (is_same_v<remove_cvref_t<_Tp>, basic_string_view<_CharT>>) {
return basic_string<_CharT>{__argument};
} else {
return nullopt;
}
},
__arg);
}
}

return nullopt;
}
} // namespace __format

// TODO FMT This needs to be a template or std::to_chars(floating-point) availability markup
// fires too eagerly, see http://llvm.org/PR61563.
template <class = void>
[[nodiscard]] _LIBCPP_ALWAYS_INLINE inline _LIBCPP_HIDE_FROM_ABI string vformat(string_view __fmt, format_args __args) {
auto __result = __format::__try_constant_folding(__fmt, __args);
if (__result.has_value())
return *std::move(__result);
__format::__allocating_buffer<char> __buffer;
std::vformat_to(__buffer.__make_output_iterator(), __fmt, __args);
return string{__buffer.__view()};
Expand All @@ -462,6 +502,9 @@ template <class = void>
template <class = void>
[[nodiscard]] _LIBCPP_ALWAYS_INLINE inline _LIBCPP_HIDE_FROM_ABI wstring
vformat(wstring_view __fmt, wformat_args __args) {
auto __result = __format::__try_constant_folding(__fmt, __args);
if (__result.has_value())
return *std::move(__result);
__format::__allocating_buffer<wchar_t> __buffer;
std::vformat_to(__buffer.__make_output_iterator(), __fmt, __args);
return wstring{__buffer.__view()};
Expand Down
11 changes: 11 additions & 0 deletions 11 libcxx/test/benchmarks/format/format.bench.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,15 @@ BENCHMARK(BM_format_string<char>)->RangeMultiplier(2)->Range(1, 1 << 20);
BENCHMARK(BM_format_string<wchar_t>)->RangeMultiplier(2)->Range(1, 1 << 20);
#endif

template <class CharT>
static void BM_string_without_formatting(benchmark::State& state) {
for (auto _ : state) {
benchmark::DoNotOptimize(std::format(CSTR("Hello, World!")));
}
}
BENCHMARK(BM_string_without_formatting<char>);
#ifndef TEST_HAS_NO_WIDE_CHARACTERS
BENCHMARK(BM_string_without_formatting<wchar_t>);
#endif

BENCHMARK_MAIN();
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.