Avoid undefined behaviour in ibm128 implementation of llroundl (BZ #29488)
authorAurelien Jarno <aurelien@aurel32.net>
Sun, 9 Oct 2022 22:39:33 +0000 (00:39 +0200)
committerAurelien Jarno <aurelien@aurel32.net>
Mon, 24 Oct 2022 18:48:02 +0000 (20:48 +0200)
Detecting an overflow edge case depended on signed overflow of a long
long. Replace the additions and the overflow checks by
__builtin_add_overflow().

Reviewed-by: Tulio Magno Quites Machado Filho <tuliom@linux.ibm.com>
sysdeps/ieee754/ldbl-128ibm/s_llroundl.c

index d85154e..d8c0de1 100644 (file)
@@ -66,38 +66,35 @@ __llroundl (long double x)
       /* Peg at max/min values, assuming that the above conversions do so.
          Strictly speaking, we can return anything for values that overflow,
          but this is more useful.  */
-      res = hi + lo;
-
-      /* This is just sign(hi) == sign(lo) && sign(res) != sign(hi).  */
-      if (__glibc_unlikely (((~(hi ^ lo) & (res ^ hi)) < 0)))
+      if (__glibc_unlikely (__builtin_add_overflow (hi, lo, &res)))
        goto overflow;
 
       xh -= lo;
       ldbl_canonicalize (&xh, &xl);
 
-      hi = res;
       if (xh > 0.5)
        {
-         res += 1;
+         if (__glibc_unlikely (__builtin_add_overflow (res, 1, &res)))
+           goto overflow;
        }
       else if (xh == 0.5)
        {
          if (xl > 0.0 || (xl == 0.0 && res >= 0))
-           res += 1;
+           if (__glibc_unlikely (__builtin_add_overflow (res, 1, &res)))
+             goto overflow;
        }
       else if (-xh > 0.5)
        {
-         res -= 1;
+         if (__glibc_unlikely (__builtin_add_overflow (res, -1, &res)))
+           goto overflow;
        }
       else if (-xh == 0.5)
        {
          if (xl < 0.0 || (xl == 0.0 && res <= 0))
-           res -= 1;
+           if (__glibc_unlikely (__builtin_add_overflow (res, -1, &res)))
+             goto overflow;
        }
 
-      if (__glibc_unlikely (((~(hi ^ (res - hi)) & (res ^ hi)) < 0)))
-       goto overflow;
-
       return res;
     }
   else