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