[libc] [llvm] Improve qsort (PR #120450)

Lukas Bergdoll via llvm-commits llvm-commits at lists.llvm.org
Wed Dec 18 13:51:03 PST 2024


================
@@ -27,11 +27,46 @@
 namespace LIBC_NAMESPACE_DECL {
 namespace internal {
 
+template <typename A, typename F> void sort_inst(A &array, const F &is_less) {
 #if LIBC_QSORT_IMPL == LIBC_QSORT_QUICK_SORT
-constexpr auto sort = quick_sort;
+  quick_sort(array, is_less);
 #elif LIBC_QSORT_IMPL == LIBC_QSORT_HEAP_SORT
-constexpr auto sort = heap_sort;
+  heap_sort(array, is_less);
 #endif
+}
+
+template <typename F>
+void unstable_sort(void *array, size_t array_len, size_t elem_size,
+                   const F &is_less) {
+  if (array == nullptr || array_len == 0 || elem_size == 0) {
+    return;
+  }
+
+  uint8_t *array_base = reinterpret_cast<uint8_t *>(array);
+
+  switch (elem_size) {
+  case 4: {
+    auto arr_fixed_size = internal::ArrayFixedSize<4>(array_base, array_len);
+    sort_inst(arr_fixed_size, is_less);
+    return;
+  }
+  case 8: {
+    auto arr_fixed_size = internal::ArrayFixedSize<8>(array_base, array_len);
+    sort_inst(arr_fixed_size, is_less);
+    return;
+  }
+  case 16: {
+    auto arr_fixed_size = internal::ArrayFixedSize<16>(array_base, array_len);
+    sort_inst(arr_fixed_size, is_less);
+    return;
+  }
----------------
Voultapher wrote:

If all you care about is binary-size over everything we should probably configure it to use heap_sort only, more or less same algorithmic guarantees, but slower but also much smaller. It's what the Rust stdlib [does](https://github.com/rust-lang/rust/pull/129587).

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


More information about the llvm-commits mailing list