math: use '#pragma STDC FENV_ACCESS ON' when fenv is accessed
[musl] / src / math / fmal.c
1 /* origin: FreeBSD /usr/src/lib/msun/src/s_fmal.c */
2 /*-
3  * Copyright (c) 2005-2011 David Schultz <das@FreeBSD.ORG>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28
29 #include "libm.h"
30 #if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024
31 long double fmal(long double x, long double y, long double z)
32 {
33         return fma(x, y, z);
34 }
35 #elif (LDBL_MANT_DIG == 64 || LDBL_MANT_DIG == 113) && LDBL_MAX_EXP == 16384
36 #include <fenv.h>
37
38 /*
39  * A struct dd represents a floating-point number with twice the precision
40  * of a long double.  We maintain the invariant that "hi" stores the high-order
41  * bits of the result.
42  */
43 struct dd {
44         long double hi;
45         long double lo;
46 };
47
48 /*
49  * Compute a+b exactly, returning the exact result in a struct dd.  We assume
50  * that both a and b are finite, but make no assumptions about their relative
51  * magnitudes.
52  */
53 static inline struct dd dd_add(long double a, long double b)
54 {
55         struct dd ret;
56         long double s;
57
58         ret.hi = a + b;
59         s = ret.hi - a;
60         ret.lo = (a - (ret.hi - s)) + (b - s);
61         return (ret);
62 }
63
64 /*
65  * Compute a+b, with a small tweak:  The least significant bit of the
66  * result is adjusted into a sticky bit summarizing all the bits that
67  * were lost to rounding.  This adjustment negates the effects of double
68  * rounding when the result is added to another number with a higher
69  * exponent.  For an explanation of round and sticky bits, see any reference
70  * on FPU design, e.g.,
71  *
72  *     J. Coonen.  An Implementation Guide to a Proposed Standard for
73  *     Floating-Point Arithmetic.  Computer, vol. 13, no. 1, Jan 1980.
74  */
75 static inline long double add_adjusted(long double a, long double b)
76 {
77         struct dd sum;
78         union IEEEl2bits u;
79
80         sum = dd_add(a, b);
81         if (sum.lo != 0) {
82                 u.e = sum.hi;
83                 if ((u.bits.manl & 1) == 0)
84                         sum.hi = nextafterl(sum.hi, INFINITY * sum.lo);
85         }
86         return (sum.hi);
87 }
88
89 /*
90  * Compute ldexp(a+b, scale) with a single rounding error. It is assumed
91  * that the result will be subnormal, and care is taken to ensure that
92  * double rounding does not occur.
93  */
94 static inline long double add_and_denormalize(long double a, long double b, int scale)
95 {
96         struct dd sum;
97         int bits_lost;
98         union IEEEl2bits u;
99
100         sum = dd_add(a, b);
101
102         /*
103          * If we are losing at least two bits of accuracy to denormalization,
104          * then the first lost bit becomes a round bit, and we adjust the
105          * lowest bit of sum.hi to make it a sticky bit summarizing all the
106          * bits in sum.lo. With the sticky bit adjusted, the hardware will
107          * break any ties in the correct direction.
108          *
109          * If we are losing only one bit to denormalization, however, we must
110          * break the ties manually.
111          */
112         if (sum.lo != 0) {
113                 u.e = sum.hi;
114                 bits_lost = -u.bits.exp - scale + 1;
115                 if (bits_lost != 1 ^ (int)(u.bits.manl & 1))
116                         sum.hi = nextafterl(sum.hi, INFINITY * sum.lo);
117         }
118         return scalbnl(sum.hi, scale);
119 }
120
121 /*
122  * Compute a*b exactly, returning the exact result in a struct dd.  We assume
123  * that both a and b are normalized, so no underflow or overflow will occur.
124  * The current rounding mode must be round-to-nearest.
125  */
126 static inline struct dd dd_mul(long double a, long double b)
127 {
128 #if LDBL_MANT_DIG == 64
129         static const long double split = 0x1p32L + 1.0;
130 #elif LDBL_MANT_DIG == 113
131         static const long double split = 0x1p57L + 1.0;
132 #endif
133         struct dd ret;
134         long double ha, hb, la, lb, p, q;
135
136         p = a * split;
137         ha = a - p;
138         ha += p;
139         la = a - ha;
140
141         p = b * split;
142         hb = b - p;
143         hb += p;
144         lb = b - hb;
145
146         p = ha * hb;
147         q = ha * lb + la * hb;
148
149         ret.hi = p + q;
150         ret.lo = p - ret.hi + q + la * lb;
151         return (ret);
152 }
153
154 /*
155  * Fused multiply-add: Compute x * y + z with a single rounding error.
156  *
157  * We use scaling to avoid overflow/underflow, along with the
158  * canonical precision-doubling technique adapted from:
159  *
160  *      Dekker, T.  A Floating-Point Technique for Extending the
161  *      Available Precision.  Numer. Math. 18, 224-242 (1971).
162  */
163 long double fmal(long double x, long double y, long double z)
164 {
165         #pragma STDC FENV_ACCESS ON
166         long double xs, ys, zs, adj;
167         struct dd xy, r;
168         int oround;
169         int ex, ey, ez;
170         int spread;
171
172         /*
173          * Handle special cases. The order of operations and the particular
174          * return values here are crucial in handling special cases involving
175          * infinities, NaNs, overflows, and signed zeroes correctly.
176          */
177         if (!isfinite(x) || !isfinite(y))
178                 return (x * y + z);
179         if (!isfinite(z))
180                 return (z);
181         if (x == 0.0 || y == 0.0)
182                 return (x * y + z);
183         if (z == 0.0)
184                 return (x * y);
185
186         xs = frexpl(x, &ex);
187         ys = frexpl(y, &ey);
188         zs = frexpl(z, &ez);
189         oround = fegetround();
190         spread = ex + ey - ez;
191
192         /*
193          * If x * y and z are many orders of magnitude apart, the scaling
194          * will overflow, so we handle these cases specially.  Rounding
195          * modes other than FE_TONEAREST are painful.
196          */
197         if (spread < -LDBL_MANT_DIG) {
198 #ifdef FE_INEXACT
199                 feraiseexcept(FE_INEXACT);
200 #endif
201 #ifdef FE_UNDERFLOW
202                 if (!isnormal(z))
203                         feraiseexcept(FE_UNDERFLOW);
204 #endif
205                 switch (oround) {
206                 default: /* FE_TONEAREST */
207                         return (z);
208 #ifdef FE_TOWARDZERO
209                 case FE_TOWARDZERO:
210                         if (x > 0.0 ^ y < 0.0 ^ z < 0.0)
211                                 return (z);
212                         else
213                                 return (nextafterl(z, 0));
214 #endif
215 #ifdef FE_DOWNWARD
216                 case FE_DOWNWARD:
217                         if (x > 0.0 ^ y < 0.0)
218                                 return (z);
219                         else
220                                 return (nextafterl(z, -INFINITY));
221 #endif
222 #ifdef FE_UPWARD
223                 case FE_UPWARD:
224                         if (x > 0.0 ^ y < 0.0)
225                                 return (nextafterl(z, INFINITY));
226                         else
227                                 return (z);
228 #endif
229                 }
230         }
231         if (spread <= LDBL_MANT_DIG * 2)
232                 zs = scalbnl(zs, -spread);
233         else
234                 zs = copysignl(LDBL_MIN, zs);
235
236         fesetround(FE_TONEAREST);
237
238         /*
239          * Basic approach for round-to-nearest:
240          *
241          *     (xy.hi, xy.lo) = x * y           (exact)
242          *     (r.hi, r.lo)   = xy.hi + z       (exact)
243          *     adj = xy.lo + r.lo               (inexact; low bit is sticky)
244          *     result = r.hi + adj              (correctly rounded)
245          */
246         xy = dd_mul(xs, ys);
247         r = dd_add(xy.hi, zs);
248
249         spread = ex + ey;
250
251         if (r.hi == 0.0) {
252                 /*
253                  * When the addends cancel to 0, ensure that the result has
254                  * the correct sign.
255                  */
256                 fesetround(oround);
257                 volatile long double vzs = zs; /* XXX gcc CSE bug workaround */
258                 return xy.hi + vzs + scalbnl(xy.lo, spread);
259         }
260
261         if (oround != FE_TONEAREST) {
262                 /*
263                  * There is no need to worry about double rounding in directed
264                  * rounding modes.
265                  */
266                 fesetround(oround);
267                 adj = r.lo + xy.lo;
268                 return scalbnl(r.hi + adj, spread);
269         }
270
271         adj = add_adjusted(r.lo, xy.lo);
272         if (spread + ilogbl(r.hi) > -16383)
273                 return scalbnl(r.hi + adj, spread);
274         else
275                 return add_and_denormalize(r.hi, adj, spread);
276 }
277 #endif