[libc-commits] [libc] [libc] implement `strings/ffs` (PR #129892)

via libc-commits libc-commits at lists.llvm.org
Wed Mar 5 18:46:55 PST 2025


================
@@ -0,0 +1,17 @@
+//===-- Implementation of ffs ---------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "src/strings/ffs.h"
+#include "src/__support/common.h"
+#include "src/__support/macros/config.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+LLVM_LIBC_FUNCTION(int, ffs, (int i)) { return __builtin_ffs(i); }
----------------
c8ef wrote:

>From GCC:
> Built-in Function: int __builtin_ctz (unsigned int x)
Returns the number of trailing 0-bits in x, starting at the least significant bit position. **If x is 0, the result is undefined.**
> Built-in Function: int __builtin_ffs (int x)
Returns one plus the index of the least significant 1-bit of x, or if x is zero, returns zero.
> Built-in Function: int __builtin_ctzg (...)
Similar to __builtin_ctz, except the argument is type-generic unsigned integer (standard, extended or bit-precise) and there is optional second argument with int type. No integral argument promotions are performed on the first argument. **If two arguments are specified, and first argument is 0, the result is the second argument. If only one argument is specified and it is 0, the result is undefined.**

Perhaps that's why the `ffs` function includes a `cmov` instruction. Would using `__builtin_ffs` be a better alternative?

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


More information about the libc-commits mailing list