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 
27 
28 /*
29  * Denorms usually have an exponent biased by 1 so that they flow
30  * smoothly into the smallest normal value with an exponent of
31  * 1. However, m68k 80-bit long doubles includes exponent of zero for
32  * normal values, so denorms use the same value, eliminating the
33  * bias. That is set in s_fmal.c.
34  */
35 
36 #ifndef FLOAT_DENORM_BIAS
37 #define FLOAT_DENORM_BIAS   1
38 #endif
39 
40 /*
41  * A struct dd represents a floating-point number with twice the precision
42  * of a FLOAT_T.  We maintain the invariant that "hi" stores the high-order
43  * bits of the result.
44  */
45 struct dd {
46 	FLOAT_T hi;
47 	FLOAT_T lo;
48 };
49 
50 /*
51  * Compute a+b exactly, returning the exact result in a struct dd.  We assume
52  * that both a and b are finite, but make no assumptions about their relative
53  * magnitudes.
54  */
55 static inline struct dd
dd_add(FLOAT_T a,FLOAT_T b)56 dd_add(FLOAT_T a, FLOAT_T b)
57 {
58 	struct dd ret;
59 	FLOAT_T s;
60 
61 	ret.hi = a + b;
62 	s = ret.hi - a;
63 	ret.lo = (a - (ret.hi - s)) + (b - s);
64 	return (ret);
65 }
66 
67 /*
68  * Compute a+b, with a small tweak:  The least significant bit of the
69  * result is adjusted into a sticky bit summarizing all the bits that
70  * were lost to rounding.  This adjustment negates the effects of double
71  * rounding when the result is added to another number with a higher
72  * exponent.  For an explanation of round and sticky bits, see any reference
73  * on FPU design, e.g.,
74  *
75  *     J. Coonen.  An Implementation Guide to a Proposed Standard for
76  *     Floating-Point Arithmetic.  Computer, vol. 13, no. 1, Jan 1980.
77  */
78 static inline FLOAT_T
add_adjusted(FLOAT_T a,FLOAT_T b)79 add_adjusted(FLOAT_T a, FLOAT_T b)
80 {
81 	struct dd sum;
82 
83 	sum = dd_add(a, b);
84 	if (sum.lo != 0) {
85 		if (!odd_mant(sum.hi))
86 			sum.hi = NEXTAFTER(sum.hi, (FLOAT_T)INFINITY * sum.lo);
87 	}
88 	return (sum.hi);
89 }
90 
91 /*
92  * Compute ldexp(a+b, scale) with a single rounding error. It is assumed
93  * that the result will be subnormal, and care is taken to ensure that
94  * double rounding does not occur.
95  */
96 static inline FLOAT_T
add_and_denormalize(FLOAT_T a,FLOAT_T b,int scale)97 add_and_denormalize(FLOAT_T a, FLOAT_T b, int scale)
98 {
99 	struct dd sum;
100 	int bits_lost;
101 
102 	sum = dd_add(a, b);
103 
104 	/*
105 	 * If we are losing at least two bits of accuracy to denormalization,
106 	 * then the first lost bit becomes a round bit, and we adjust the
107 	 * lowest bit of sum.hi to make it a sticky bit summarizing all the
108 	 * bits in sum.lo. With the sticky bit adjusted, the hardware will
109 	 * break any ties in the correct direction.
110 	 *
111 	 * If we are losing only one bit to denormalization, however, we must
112 	 * break the ties manually.
113 	 */
114 	if (sum.lo != 0) {
115 		bits_lost = -EXPONENT(sum.hi) - scale + FLOAT_DENORM_BIAS;
116 		if ((bits_lost != 1) ^ (int)odd_mant(sum.hi))
117                         sum.hi = NEXTAFTER(sum.hi, (FLOAT_T)INFINITY * sum.lo);
118 	}
119 	return (LDEXP(sum.hi, scale));
120 }
121 
122 /*
123  * Compute a*b exactly, returning the exact result in a struct dd.  We assume
124  * that both a and b are normalized, so no underflow or overflow will occur.
125  * The current rounding mode must be round-to-nearest.
126  */
127 static inline struct dd
dd_mul(FLOAT_T a,FLOAT_T b)128 dd_mul(FLOAT_T a, FLOAT_T b)
129 {
130 	static const FLOAT_T split = SPLIT;
131 	struct dd ret;
132 	FLOAT_T ha, hb, la, lb, p, q;
133 
134 	p = a * split;
135 	ha = a - p;
136 	ha += p;
137 	la = a - ha;
138 
139 	p = b * split;
140 	hb = b - p;
141 	hb += p;
142 	lb = b - hb;
143 
144 	p = ha * hb;
145 	q = ha * lb + la * hb;
146 
147 	ret.hi = p + q;
148 	ret.lo = p - ret.hi + q + la * lb;
149 	return (ret);
150 }
151 
152 #ifdef _WANT_MATH_ERRNO
153 static FLOAT_T
_scalbn_no_errno(FLOAT_T x,int n)154 _scalbn_no_errno(FLOAT_T x, int n)
155 {
156         int save_errno = errno;
157         x = SCALBN(x, n);
158         errno = save_errno;
159         return x;
160 }
161 #else
162 #define _scalbn_no_errno(a,b) SCALBN(a,b)
163 #endif
164 
165 #ifdef __clang__
166 #pragma STDC FP_CONTRACT OFF
167 #endif
168 
169 #if defined(FE_UPWARD) || defined(FE_DOWNWARD) || defined(FE_TOWARDZERO)
170 #define HAS_ROUNDING
171 #endif
172 
173 /*
174  * Fused multiply-add: Compute x * y + z with a single rounding error.
175  *
176  * We use scaling to avoid overflow/underflow, along with the
177  * canonical precision-doubling technique adapted from:
178  *
179  *	Dekker, T.  A Floating-Point Technique for Extending the
180  *	Available Precision.  Numer. Math. 18, 224-242 (1971).
181  */
182 FLOAT_T
FMA(FLOAT_T x,FLOAT_T y,FLOAT_T z)183 FMA(FLOAT_T x, FLOAT_T y, FLOAT_T z)
184 {
185 	FLOAT_T xs, ys, zs, adj;
186 	struct dd xy, r;
187 	int ex, ey, ez;
188 	int spread;
189 
190 	/*
191 	 * Handle special cases. The order of operations and the particular
192 	 * return values here are crucial in handling special cases involving
193 	 * infinities, NaNs, overflows, and signed zeroes correctly.
194 	 */
195         if (!isfinite(z) && isfinite(x) && isfinite(y))
196                 return z + z;
197 	if (!isfinite(x) || !isfinite(y) || !isfinite(z))
198 		return (x * y + z);
199 	if (x == (FLOAT_T) 0.0 || y == (FLOAT_T) 0.0)
200 		return (x * y + z);
201 	if (z == (FLOAT_T) 0.0)
202 		return (x * y);
203 
204 	xs = FREXP(x, &ex);
205 	ys = FREXP(y, &ey);
206 	zs = FREXP(z, &ez);
207 #ifdef HAS_ROUNDING
208 	int oround = fegetround();
209 #endif
210 	spread = ex + ey - ez;
211 
212 	/*
213 	 * If x * y and z are many orders of magnitude apart, the scaling
214 	 * will overflow, so we handle these cases specially.  Rounding
215 	 * modes other than FE_TONEAREST are painful.
216 	 */
217 	if (spread < -FLOAT_MANT_DIG) {
218 #ifdef FE_INEXACT
219 		feraiseexcept(FE_INEXACT);
220 #endif
221 #ifdef FE_UNDERFLOW
222 		if (!isnormal(z))
223 			feraiseexcept(FE_UNDERFLOW);
224 #endif
225 #ifdef HAS_ROUNDING
226 		switch (oround) {
227 		default:
228                         break;
229 #ifdef FE_TOWARDZERO
230 		case FE_TOWARDZERO:
231 			if ((x > (FLOAT_T) 0.0) ^ (y < (FLOAT_T) 0.0) ^ (z < (FLOAT_T) 0.0))
232 				break;
233 			else
234 				return (NEXTAFTER(z, 0));
235 #endif
236 #ifdef FE_DOWNWARD
237 		case FE_DOWNWARD:
238 			if ((x > (FLOAT_T) 0.0) ^ (y < (FLOAT_T) 0.0))
239 				break;
240 			else
241 				return (NEXTAFTER(z, -(FLOAT_T)INFINITY));
242 #endif
243 #ifdef FE_UPWARD
244                 case FE_UPWARD:
245 			if ((x > (FLOAT_T) 0.0) ^ (y < (FLOAT_T) 0.0))
246 				return (NEXTAFTER(z, (FLOAT_T)INFINITY));
247                         break;
248 #endif
249 		}
250 #endif
251                 return (z);
252 	}
253 	if (spread <= FLOAT_MANT_DIG * 2)
254 		zs = _scalbn_no_errno(zs, -spread);
255 	else
256 		zs = COPYSIGN(FLOAT_MIN, zs);
257 
258 #ifdef HAS_ROUNDING
259 	fesetround(FE_TONEAREST);
260 #endif
261 
262 	/*
263 	 * Basic approach for round-to-nearest:
264 	 *
265 	 *     (xy.hi, xy.lo) = x * y		(exact)
266 	 *     (r.hi, r.lo)   = xy.hi + z	(exact)
267 	 *     adj = xy.lo + r.lo		(inexact; low bit is sticky)
268 	 *     result = r.hi + adj		(correctly rounded)
269 	 */
270 	xy = dd_mul(xs, ys);
271 	r = dd_add(xy.hi, zs);
272 
273 	spread = ex + ey;
274 
275 	if (r.hi == (FLOAT_T) 0.0) {
276 		/*
277 		 * When the addends cancel to 0, ensure that the result has
278 		 * the correct sign.
279 		 */
280 #ifdef HAS_ROUNDING
281 		fesetround(oround);
282 #endif
283 		volatile FLOAT_T vzs = zs; /* XXX gcc CSE bug workaround */
284 		return (xy.hi + vzs + _scalbn_no_errno(xy.lo, spread));
285 	}
286 
287 #ifdef HAS_ROUNDING
288 	if (oround != FE_TONEAREST) {
289 		/*
290 		 * There is no need to worry about double rounding in directed
291 		 * rounding modes.
292 		 */
293 		fesetround(oround);
294 		adj = r.lo + xy.lo;
295 		return (_scalbn_no_errno(r.hi + adj, spread));
296 	}
297 #endif
298 
299 	adj = add_adjusted(r.lo, xy.lo);
300 	if (spread + ILOGB(r.hi) > -(FLOAT_MAX_EXP - FLOAT_DENORM_BIAS))
301 		return (_scalbn_no_errno(r.hi + adj, spread));
302 	else
303 		return (add_and_denormalize(r.hi, adj, spread));
304 }
305