1 /* Round to integer generic implementation.
2 Copyright (C) 2019-2023 Free Software Foundation, Inc.
3 This file is part of the GNU C Library
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
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 Library General Public License for more details.
15 You should have received a copy of the GNU Library General Public
16 License along with the GNU C Library; see the file COPYING.LIB. If
17 not, see <https://www.gnu.org/licenses/>. */
19 #ifndef _ROUND_TO_INTEGER_H
20 #define _ROUND_TO_INTEGER_H
22 #include <fenv_private.h>
35 set_fenv_mode (enum round_mode mode
)
39 /* Save current FPU rounding mode and inexact state. */
40 fe
= fegetenv_register ();
45 __fesetround_inline_nocheck (FE_UPWARD
);
48 __fesetround_inline_nocheck (FE_DOWNWARD
);
52 __fesetround_inline_nocheck (FE_TOWARDZERO
);
55 /* Disable FE_INEXACT exception */
56 reset_fpscr_bit (FPSCR_XE
);
65 reset_fenv_mode (fenv_t fe
, enum round_mode mode
)
70 __builtin_mtfsf (0xff, fe
);
78 round_to_integer_float (enum round_mode mode
, float x
)
80 /* Ensure sNaN input is converted to qNaN. */
81 if (__glibc_unlikely (isnan (x
)))
84 if (fabs (x
) > 0x1p
+23)
89 fenv_t fe
= set_fenv_mode (mode
);
92 /* IEEE 1003.1 round function. IEEE specifies "round to the nearest
93 integer value, rounding halfway cases away from zero, regardless of
94 the current rounding mode." However PowerPC Architecture defines
95 "Round to Nearest" as "Choose the best approximation. In case of a
96 tie, choose the one that is even (least significant bit o).".
97 So we can't use the PowerPC "Round to Nearest" mode. Instead we set
98 "Round toward Zero" mode and round by adding +-0.5 before rounding
99 to the integer value. */
114 reset_fenv_mode (fe
, mode
);
120 round_to_integer_double (enum round_mode mode
, double x
)
122 /* Ensure sNaN input is converted to qNaN. */
123 if (__glibc_unlikely (isnan (x
)))
126 if (fabs (x
) > 0x1p
+52)
131 /* Save current FPU rounding mode and inexact state. */
132 fenv_t fe
= set_fenv_mode (mode
);
149 reset_fenv_mode (fe
, mode
);