[libcxx-commits] [PATCH] D125958: Use __libcpp_clz for a tighter __log2i function

Hans Wennborg via Phabricator via libcxx-commits libcxx-commits at lists.llvm.org
Thu May 19 02:49:13 PDT 2022


hans created this revision.
hans added reviewers: nilayvaish, ldionne, libc++.
Herald added a project: All.
hans requested review of this revision.
Herald added a project: libc++.
Herald added a subscriber: libcxx-commits.
Herald added 1 blocking reviewer(s): libc++.

While looking at D113413 <https://reviews.llvm.org/D113413> I noticed that __log2i could perhaps be improved to be both slightly smaller and faster.

I'm not familiar with how to run benchmarks for this if there are any, but https://godbolt.org/z/48KT3z5Tj looks like an improvement to me.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125958

Files:
  libcxx/include/__algorithm/sort.h


Index: libcxx/include/__algorithm/sort.h
===================================================================
--- libcxx/include/__algorithm/sort.h
+++ libcxx/include/__algorithm/sort.h
@@ -14,6 +14,7 @@
 #include <__algorithm/min_element.h>
 #include <__algorithm/partial_sort.h>
 #include <__algorithm/unwrap_iter.h>
+#include <__bits>
 #include <__config>
 #include <__utility/swap.h>
 #include <memory>
@@ -498,6 +499,15 @@
 
 template <typename _Number>
 inline _LIBCPP_HIDE_FROM_ABI _Number __log2i(_Number __n) {
+  if (__n == 0)
+    return 0;
+  if (sizeof(__n) <= sizeof(unsigned))
+    return sizeof(unsigned) * __CHAR_BIT__ - 1 - __libcpp_clz(static_cast<unsigned>(__n));
+  if (sizeof(__n) <= sizeof(unsigned long))
+    return sizeof(unsigned long) * __CHAR_BIT__ - 1 - __libcpp_clz(static_cast<unsigned long>(__n));
+  if (sizeof(__n) <= sizeof(unsigned long long))
+    return sizeof(unsigned long long) * __CHAR_BIT__ - 1 - __libcpp_clz(static_cast<unsigned long long>(__n));
+
   _Number __log2 = 0;
   while (__n > 1) {
     __log2++;


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D125958.430617.patch
Type: text/x-patch
Size: 1053 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/libcxx-commits/attachments/20220519/e175ce89/attachment.bin>


More information about the libcxx-commits mailing list