1 /* lround function.  PowerPC32 version.
2    Copyright (C) 2004-2021 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4 
5    The GNU C Library is free software; you can redistribute it and/or
6    modify it under the terms of the GNU Lesser General Public
7    License as published by the Free Software Foundation; either
8    version 2.1 of the License, or (at your option) any later version.
9 
10    The GNU C Library is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Lesser General Public License for more details.
14 
15    You should have received a copy of the GNU Lesser General Public
16    License along with the GNU C Library; if not, see
17    <https://www.gnu.org/licenses/>.  */
18 
19 #define lroundf __redirect_lroundf
20 #define __lroundf __redirect___lroundf
21 #include <math.h>
22 #undef lroundf
23 #undef __lroundf
24 #include <libm-alias-float.h>
25 #include <libm-alias-double.h>
26 
27 long int
__lround(double x)28 __lround (double x)
29 {
30 #ifdef _ARCH_PWR5X
31   x = round (x);
32 #else
33   /* Ieee 1003.1 lround function.  ieee specifies "round to the nearest
34      integer value, rounding halfway cases away from zero, regardless of
35      the current rounding mode."  however powerpc architecture defines
36      "round to nearest" as "choose the best approximation. in case of a
37      tie, choose the one that is even (least significant bit o).".
38      so we can't use the powerpc "round to nearest" mode. instead we set
39      "round toward zero" mode and round by adding +-0.5 before rounding
40      to the integer value.  it is necessary to detect when x is
41      (+-)0x1.fffffffffffffp-2 because adding +-0.5 in this case will
42      cause an erroneous shift, carry and round.  we simply return 0 if
43      0.5 > x > -0.5.  */
44 
45   double ax = fabs (x);
46 
47   if (ax < 0.5)
48     return 0;
49 
50   if (x >= 0x7fffffff.8p0 || x <= -0x80000000.8p0)
51     x = (x < 0.0) ? -0x1p+52 : 0x1p+52;
52   else
53     {
54       /* Test whether an integer to avoid spurious "inexact".  */
55       double t = ax + 0x1p+52;
56       t = t - 0x1p+52;
57       if (ax != t)
58         {
59 	  ax = ax + 0.5;
60 	  if (x < 0.0)
61 	    ax = -fabs (ax);
62 	  x = ax;
63         }
64     }
65 #endif
66   /* Force evaluation of values larger than long int, so invalid
67      exceptions are raise.  */
68   long long int ret;
69   asm ("fctiwz %0, %1" : "=d" (ret) : "d" (x));
70   return ret;
71 }
72 #ifndef __lround
73 libm_alias_double (__lround, lround)
74 
75 strong_alias (__lround, __lroundf)
76 libm_alias_float (__lround, lround)
77 #endif
78