[libc-commits] [libc] [libc][stdfix] Implement `countlsfx` functions (PR #114318)

via libc-commits libc-commits at lists.llvm.org
Sat Nov 2 19:44:09 PDT 2024


================
@@ -142,6 +160,25 @@ template <typename T> LIBC_INLINE constexpr T abs(T x) {
   }
 }
 
+template <typename T>
+LIBC_INLINE constexpr cpp::enable_if_t<cpp::is_fixed_point_v<T>, int>
+countls(T x) {
+  using FXRep = FXRep<T>;
+  using BitType = typename FXRep::StorageType;
+  constexpr int CONTAIN_LEN = cpp::numeric_limits<BitType>::digits;
+  constexpr int PADDING_LEN = CONTAIN_LEN - FXRep::VALUE_LEN;
+
+  if constexpr (FXRep::SIGN_LEN != 0) {
+    if (x < 0) {
+      x = -(x + FXRep::EPS());
----------------
duncpro wrote:

After thinking about it. You're right. This is equivalent to bitwise complement. 

I also found this function in `fx_bits.h`.

https://github.com/llvm/llvm-project/blob/f71e13eb354d6a02710ceec254e8c399c60ffdbf/libc/src/__support/fixed_point/fx_bits.h#L143-L150

Assuming that `static_cast` and `bit_cast` are free, this is one less operation than the current way I do it.

So `static_cast` should be free, as it seems its only used as a type hint here.
I think `bit_cast` is free by definition.

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


More information about the libc-commits mailing list