[cfe-dev] [llvm-dev] Should isnan be optimized out in fast-math mode?

Jorg Brown via cfe-dev cfe-dev at lists.llvm.org
Mon Sep 20 11:23:43 PDT 2021

On Wed, Sep 8, 2021 at 1:58 PM Joerg Sonnenberger via llvm-dev <
llvm-dev at lists.llvm.org> wrote:

> On Wed, Sep 08, 2021 at 06:04:08PM +0000, Chris Tetreault via llvm-dev
> wrote:
> > As a developer (who always reads the docs and generally makes good life
> > choices), if I turn on -ffast-math, I want the compiler to produce the
> > fastest possible floating point math code possible, floating point
> > semantics be darned. Given this viewpoint, my opinion on this topic is
> > that the compiler should do whatever it wants, given the constraints of
> > the documented behavior of NaN.
> There is a huge different between optimisations that assume NaN is not
> present and breaking checks for them. I'm not convinced at all that
> constant-folding isnan to false will actually speed up real world code.

I am.

Here's the first 20ish lines of the code in question, which you can see in
full at
https://github.com/abseil/abseil-cpp/blob/master/absl/strings/numbers.cc :

size_t numbers_internal::SixDigitsToBuffer(double d, char* const buffer) {
"IEEE-754/IEC-559 support only");

char* out = buffer; // we write data to out

if (std::isnan(d)) {
strcpy(out, "nan"); // NOLINT(runtime/printf)
return 3;
if (d == 0) { // +0 and -0 are handled here
if (std::signbit(d)) *out++ = '-';
*out++ = '0';
*out = 0;
return out - buffer;
if (d < 0) {
*out++ = '-';
d = -d;
if (std::isinf(d)) {
strcpy(out, "inf"); // NOLINT(runtime/printf)
return out + 3 - buffer;

This routine formats a double-precision floating-point number as 6 digits,
the same way "%g" would do it.  The calls to std::isnan and std::isinf are
a measurable slowdown.

(In fact, as a result of this discussion I'm realizing that the call to
isinf can be replaced with a comparison with positive infinity, since
negative infinity is not a possibility here.  Patch in progress...)

-- Jorg
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20210920/446ef75a/attachment-0001.html>

More information about the cfe-dev mailing list