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

via libc-commits libc-commits at lists.llvm.org
Thu Mar 6 08:03:42 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); }
----------------
lntue wrote:

Ok, so spec-wise, `ffs` and `stdc_first_trailing_one` are identical:

`ffs`: https://man7.org/linux/man-pages/man3/ffs.3.html
```
These functions return the position of the first bit set, or 0 if
       no bits are set in i.
```

`stdc_first_trailing_one`: https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3096.pdf
```
Returns the least significant index of the first 1 bit in value, plus 1. If it is not found, this function
returns 0.
```

The problem is that our current implementation for `first_trailing_one` is not correct:
https://github.com/llvm/llvm-project/blob/main/libc/src/__support/math_extras.h#L149

It should check 0 instead of `max()`.

Can you fix the `first_trailing_one` implementation and their tests, and use that for `ffs` also?  Thanks!

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


More information about the libc-commits mailing list