[libcxx-commits] [libcxx] [libc++][math] Add constexpr for std::abs() (PR #146633)
Arjun Patel via libcxx-commits
libcxx-commits at lists.llvm.org
Thu Sep 4 12:04:29 PDT 2025
arjunUpatel wrote:
I have been investigating the source to understand why the constant evaluation is failing but have not been able to pin point the why. In fact the more time I spent the more confused I got since it felt like this should work. Here is my understanding so y'all can poke holes and guide me in the right direction.
As @frederick-vs-ja mentioned, the overload that is actually being called is from the "C standard library." I assumed that you meant `<cstdlib>`. `<cstdlib>` includes `<stdlib.h>` which includes `<__math/abs.h>`, the file that defines the `abs` overloads updated in this PR which calls `__builtin_abs`. Note that all the headers I have mentioned here have their sources defined in the `libcxx/include` directory which are the ones I am referring to when I say `x` includes or defines something.
@philnik777 mentioned implementing constexpr support for the builtins. [This support seems to have already been added for abs](https://github.com/llvm/llvm-project/commit/332ac18e318ce0b6bf316d7f35d33d8af4c56fc5)? Static assertions calling `__builtin_abs` seem to be working in the tests associated with the linked pull request. This plus the perceived dependency chain above is really throwing a wrench in my comprehension as it makes it seem like this should be working.
Obviously something is still wrong. My best guess is that the the overload that actually ends up being called is the one that is defined in `libc`. I am just not seeing how we actually end up there.
If the `libc` over is the one being called, my plan is to refactor libc to expose the `abs` overload from `libc/shared/stdlib.h` and define it constexpr. The support functions it currently calls, `libc/src/__support/integer_operations.h`, are already constexpr so constant eval should work after this refactor. The other option would be to just call `__builtin_abs`. In essence, something similar to @Intue's work linked above and ideas shared in [this discussion](https://discourse.llvm.org/t/rfc-make-clang-builtin-math-functions-constexpr-with-llvm-libc-to-support-c-23-constexpr-math-functions/86450)
https://github.com/llvm/llvm-project/pull/146633
More information about the libcxx-commits
mailing list