[libcxx-commits] [libcxx] [libc++] Support sorting consteval-only ranges (PR #134623)

A. Jiang via libcxx-commits libcxx-commits at lists.llvm.org
Fri Apr 25 00:34:33 PDT 2025


================
@@ -912,30 +900,63 @@ using __sort_is_specialized_in_library _LIBCPP_NODEBUG = __is_any_of<
     long double>;
 
 template <class _AlgPolicy, class _Type, __enable_if_t<__sort_is_specialized_in_library<_Type>::value, int> = 0>
-_LIBCPP_HIDE_FROM_ABI void __sort_dispatch(_Type* __first, _Type* __last, __less<>&) {
-  __less<_Type> __comp;
-  std::__sort<__less<_Type>&, _Type*>(__first, __last, __comp);
+_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void __sort_dispatch(_Type* __first, _Type* __last, __less<>&) {
+#if _LIBCPP_STD_VER >= 20
+  if (std::is_constant_evaluated()) {
+    auto __depth_limit = static_cast<ptrdiff_t>(2 * std::__bit_log2(static_cast<size_t>(__last - __first)));
+    std::__introsort<_ClassicAlgPolicy, ranges::less, _Type*, __use_branchless_sort<ranges::less, _Type*>>(
+        __first, __last, ranges::less{}, __depth_limit);
+  } else
+#endif
----------------
frederick-vs-ja wrote:

> OK, IMO this is CWG issue territory. It can't be that `consteval` goes this viral. This basically means that we can't have non-`constexpr` code in `constexpr` functions, which is simply not acceptable.

The crux is the combination of non-constant `consteval` operations and non-`constexpr` functions. Currently non-`constexpr` functions, along with non-template non-lambda non-defaulted `constexpr` functions, are never immediate-escalated. Perhaps it's also possible to escalate some non-`constexpr` functions to "error-on-call-only" things.

However, is it a bad thing to use `__introsort` in constant evaluation? If not, it seems plausible to mark it and its depended functions `_LIBCPP_CONSTEXPR_SINCE_CXX20`.

https://github.com/llvm/llvm-project/pull/134623


More information about the libcxx-commits mailing list