1 /*
2  * Copyright (C) 1995-2011 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19 
20 /**
21  * @file
22  * @brief    tarval floating point calculations
23  * @date     2003
24  * @author   Mathias Heil
25  */
26 #include "config.h"
27 
28 #include "fltcalc.h"
29 #include "strcalc.h"
30 #include "error.h"
31 
32 #include <math.h>
33 #include <inttypes.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <assert.h>
38 #include <stdbool.h>
39 
40 #include "xmalloc.h"
41 
42 /*
43  * portability stuff (why do we even care about the msvc people with their C89?)
44  */
45 
46 
string_to_long_double(const char * str)47 static long double string_to_long_double(const char *str)
48 {
49 #if __STDC_VERSION__ >= 199901L || _POSIX_C_SOURCE >= 200112L
50 	return strtold(str, NULL);
51 #else
52 	return strtod(str, NULL);
53 #endif
54 }
55 
my_isnan(long double val)56 static bool my_isnan(long double val)
57 {
58 #if __STDC_VERSION__ >= 199901L
59 	return isnan(val);
60 #else
61 	/* hopefully the compiler does not optimize aggressively (=incorrect) */
62 	return val != val;
63 #endif
64 }
65 
my_isinf(long double val)66 static bool my_isinf(long double val)
67 {
68 #if __STDC_VERSION__ >= 199901L
69 	return isinf(val);
70 #else
71 	/* hopefully the compiler does not optimize aggressively (=incorrect) */
72 	return my_isnan(val-val) && !my_isnan(val);
73 #endif
74 }
75 
76 /** The number of extra precision rounding bits */
77 #define ROUNDING_BITS 2
78 
79 typedef union {
80 	struct {
81 #ifdef WORDS_BIGENDIAN
82 		uint32_t high;
83 #else
84 		uint32_t low;
85 #endif
86 		uint32_t mid;
87 #ifdef WORDS_BIGENDIAN
88 		uint32_t low;
89 #else
90 		uint32_t high;
91 #endif
92 	} val_ld12;
93 	struct {
94 #ifdef WORDS_BIGENDIAN
95 		uint32_t high;
96 #else
97 		uint32_t low;
98 #endif
99 #ifdef WORDS_BIGENDIAN
100 		uint32_t low;
101 #else
102 		uint32_t high;
103 #endif
104 	} val_ld8;
105 	volatile long double d;
106 } value_t;
107 
108 #define CLEAR_BUFFER(buffer) memset(buffer, 0, calc_buffer_size)
109 
110 /* our floating point value */
111 struct fp_value {
112 	float_descriptor_t desc;
113 	unsigned char clss;
114 	char sign;
115 	char value[1];        /* exp[value_size] + mant[value_size] */
116 };
117 
118 #define _exp(a)  &((a)->value[0])
119 #define _mant(a) &((a)->value[value_size])
120 
121 #define _save_result(x) memcpy((x), sc_get_buffer(), value_size)
122 #define _shift_right(x, y, res) sc_shr((x), (y), value_size*4, 0, (res))
123 #define _shift_left(x, y, res) sc_shl((x), (y), value_size*4, 0, (res))
124 
125 
126 #ifdef FLTCALC_DEBUG
127 #  define DEBUGPRINTF(x) printf x
128 #else
129 #  define DEBUGPRINTF(x) ((void)0)
130 #endif
131 
132 #ifdef FLTCALC_TRACE_CALC
133 #  define TRACEPRINTF(x) printf x
134 #else
135 #  define TRACEPRINTF(x) ((void)0)
136 #endif
137 
138 /** A temporal buffer. */
139 static fp_value *calc_buffer = NULL;
140 
141 /** Current rounding mode.*/
142 static fc_rounding_mode_t rounding_mode;
143 
144 static int calc_buffer_size;
145 static int value_size;
146 static int max_precision;
147 
148 /** Exact flag. */
149 static int fc_exact = 1;
150 
151 /** pack machine-like */
pack(const fp_value * int_float,void * packed)152 static void *pack(const fp_value *int_float, void *packed)
153 {
154 	char     *shift_val;
155 	char     *temp;
156 	fp_value *val_buffer;
157 	int      pos;
158 
159 	temp      = (char*) alloca(value_size);
160 	shift_val = (char*) alloca(value_size);
161 
162 	switch ((value_class_t)int_float->clss) {
163 	case FC_NAN:
164 		val_buffer = (fp_value*) alloca(calc_buffer_size);
165 		fc_get_qnan(&int_float->desc, val_buffer);
166 		int_float = val_buffer;
167 		break;
168 
169 	case FC_INF:
170 		val_buffer = (fp_value*) alloca(calc_buffer_size);
171 		fc_get_plusinf(&int_float->desc, val_buffer);
172 		val_buffer->sign = int_float->sign;
173 		int_float = val_buffer;
174 		break;
175 
176 	default:
177 		break;
178 	}
179 	assert(int_float->desc.explicit_one <= 1);
180 
181 	/* pack sign: move it to the left after exponent AND mantissa */
182 	sc_val_from_ulong(int_float->sign, temp);
183 
184 	pos = int_float->desc.exponent_size + int_float->desc.mantissa_size + int_float->desc.explicit_one;
185 	sc_val_from_ulong(pos, NULL);
186 	_shift_left(temp, sc_get_buffer(), packed);
187 
188 	/* pack exponent: move it to the left after mantissa */
189 	pos = int_float->desc.mantissa_size + int_float->desc.explicit_one;
190 	sc_val_from_ulong(pos, shift_val);
191 	_shift_left(_exp(int_float), shift_val, temp);
192 
193 	/* combine sign|exponent */
194 	sc_or(temp, packed, packed);
195 
196 	/* extract mantissa */
197 	/* remove rounding bits */
198 	sc_val_from_ulong(ROUNDING_BITS, shift_val);
199 	_shift_right(_mant(int_float), shift_val, temp);
200 
201 	/* remove leading 1 (or 0 if denormalized) */
202 	sc_max_from_bits(pos, 0, shift_val); /* all mantissa bits are 1's */
203 	sc_and(temp, shift_val, temp);
204 
205 	/* combine sign|exponent|mantissa */
206 	sc_or(temp, packed, packed);
207 
208 	return packed;
209 }
210 
211 /**
212  * Normalize a fp_value.
213  *
214  * @return non-zero if result is exact
215  */
normalize(const fp_value * in_val,fp_value * out_val,int sticky)216 static int normalize(const fp_value *in_val, fp_value *out_val, int sticky)
217 {
218 	int exact = 1;
219 	int hsb;
220 	char lsb, guard, round, round_dir = 0;
221 	char *temp = (char*) alloca(value_size);
222 
223 	/* save rounding bits at the end */
224 	hsb = ROUNDING_BITS + in_val->desc.mantissa_size - sc_get_highest_set_bit(_mant(in_val)) - 1;
225 
226 	if (in_val != out_val)   {
227 		out_val->sign = in_val->sign;
228 		out_val->desc = in_val->desc;
229 	}
230 
231 	out_val->clss = FC_NORMAL;
232 
233 	/* mantissa all zeros, so zero exponent (because of explicit one) */
234 	if (hsb == ROUNDING_BITS + in_val->desc.mantissa_size)   {
235 		sc_val_from_ulong(0, _exp(out_val));
236 		hsb = -1;
237 	}
238 
239 	/* shift the first 1 into the left of the radix point (i.e. hsb == -1) */
240 	if (hsb < -1)   {
241 		/* shift right */
242 		sc_val_from_ulong(-hsb-1, temp);
243 
244 		_shift_right(_mant(in_val), temp, _mant(out_val));
245 
246 		/* remember if some bits were shifted away */
247 		if (sc_had_carry()) {
248 			exact = 0;
249 			sticky = 1;
250 		}
251 		sc_add(_exp(in_val), temp, _exp(out_val));
252 	} else if (hsb > -1) {
253 		/* shift left */
254 		sc_val_from_ulong(hsb+1, temp);
255 
256 		_shift_left(_mant(in_val), temp, _mant(out_val));
257 
258 		sc_sub(_exp(in_val), temp, _exp(out_val));
259 	}
260 
261 	/* check for exponent underflow */
262 	if (sc_is_negative(_exp(out_val)) || sc_is_zero(_exp(out_val))) {
263 		DEBUGPRINTF(("Exponent underflow!\n"));
264 		/* exponent underflow */
265 		/* shift the mantissa right to have a zero exponent */
266 		sc_val_from_ulong(1, temp);
267 		sc_sub(temp, _exp(out_val), NULL);
268 
269 		_shift_right(_mant(out_val), sc_get_buffer(), _mant(out_val));
270 		if (sc_had_carry()) {
271 			exact  = 0;
272 			sticky = 1;
273 		}
274 		/* denormalized means exponent of zero */
275 		sc_val_from_ulong(0, _exp(out_val));
276 
277 		out_val->clss = FC_SUBNORMAL;
278 	}
279 
280 	/* perform rounding by adding a value that clears the guard bit and the round bit
281 	 * and either causes a carry to round up or not */
282 	/* get the last 3 bits of the value */
283 	lsb = sc_sub_bits(_mant(out_val), out_val->desc.mantissa_size + ROUNDING_BITS, 0) & 0x7;
284 	guard = (lsb&0x2)>>1;
285 	round = lsb&0x1;
286 
287 	switch (rounding_mode) {
288 	case FC_TONEAREST:
289 		/* round to nearest representable value, if in doubt choose the version
290 		 * with lsb == 0 */
291 		round_dir = guard && (sticky || round || lsb>>2);
292 		break;
293 	case FC_TOPOSITIVE:
294 		/* if positive: round to one if the exact value is bigger, else to zero */
295 		round_dir = (!out_val->sign && (guard || round || sticky));
296 		break;
297 	case FC_TONEGATIVE:
298 		/* if negative: round to one if the exact value is bigger, else to zero */
299 		round_dir = (out_val->sign && (guard || round || sticky));
300 		break;
301 	case FC_TOZERO:
302 		/* always round to 0 (chopping mode) */
303 		round_dir = 0;
304 		break;
305 	}
306 	DEBUGPRINTF(("Rounding (s%d, l%d, g%d, r%d, s%d) %s\n", out_val->sign, lsb>>2, guard, round, sticky, (round_dir)?"up":"down"));
307 
308 	if (round_dir == 1) {
309 		guard = (round^guard)<<1;
310 		lsb = !(round || guard)<<2 | guard | round;
311 	} else {
312 		lsb = -((guard<<1) | round);
313 	}
314 
315 	/* add the rounded value */
316 	if (lsb != 0) {
317 		sc_val_from_long(lsb, temp);
318 		sc_add(_mant(out_val), temp, _mant(out_val));
319 		exact = 0;
320 	}
321 
322 	/* could have rounded down to zero */
323 	if (sc_is_zero(_mant(out_val)) && (out_val->clss == FC_SUBNORMAL))
324 		out_val->clss = FC_ZERO;
325 
326 	/* check for rounding overflow */
327 	hsb = ROUNDING_BITS + out_val->desc.mantissa_size - sc_get_highest_set_bit(_mant(out_val)) - 1;
328 	if ((out_val->clss != FC_SUBNORMAL) && (hsb < -1)) {
329 		sc_val_from_ulong(1, temp);
330 		_shift_right(_mant(out_val), temp, _mant(out_val));
331 		if (exact && sc_had_carry())
332 			exact = 0;
333 		sc_add(_exp(out_val), temp, _exp(out_val));
334 	} else if ((out_val->clss == FC_SUBNORMAL) && (hsb == -1)) {
335 		/* overflow caused the mantissa to be normal again,
336 		 * so adapt the exponent accordingly */
337 		sc_val_from_ulong(1, temp);
338 		sc_add(_exp(out_val), temp, _exp(out_val));
339 
340 		out_val->clss = FC_NORMAL;
341 	}
342 	/* no further rounding is needed, because rounding overflow means
343 	 * the carry of the original rounding was propagated all the way
344 	 * up to the bit left of the radix point. This implies the bits
345 	 * to the right are all zeros (rounding is +1) */
346 
347 	/* check for exponent overflow */
348 	sc_val_from_ulong((1 << out_val->desc.exponent_size) - 1, temp);
349 	if (sc_comp(_exp(out_val), temp) != -1) {
350 		DEBUGPRINTF(("Exponent overflow!\n"));
351 		/* exponent overflow, reaction depends on rounding method:
352 		 *
353 		 * mode        | sign of value |  result
354 		 *--------------------------------------------------------------
355 		 * TO_NEAREST  |      +        |   +inf
356 		 *             |      -        |   -inf
357 		 *--------------------------------------------------------------
358 		 * TO_POSITIVE |      +        |   +inf
359 		 *             |      -        |   smallest representable value
360 		 *--------------------------------------------------------------
361 		 * TO_NEAGTIVE |      +        |   largest representable value
362 		 *             |      -        |   -inf
363 		 *--------------------------------------------------------------
364 		 * TO_ZERO     |      +        |   largest representable value
365 		 *             |      -        |   smallest representable value
366 		 *--------------------------------------------------------------*/
367 		if (out_val->sign == 0) {
368 			/* value is positive */
369 			switch (rounding_mode) {
370 			case FC_TONEAREST:
371 			case FC_TOPOSITIVE:
372 				out_val->clss = FC_INF;
373 				break;
374 
375 			case FC_TONEGATIVE:
376 			case FC_TOZERO:
377 				fc_get_max(&out_val->desc, out_val);
378 			}
379 		} else {
380 			/* value is negative */
381 			switch (rounding_mode) {
382 			case FC_TONEAREST:
383 			case FC_TONEGATIVE:
384 				out_val->clss = FC_INF;
385 				break;
386 
387 			case FC_TOPOSITIVE:
388 			case FC_TOZERO:
389 				fc_get_min(&out_val->desc, out_val);
390 			}
391 		}
392 	}
393 	return exact;
394 }
395 
396 /**
397  * Operations involving NaN's must return NaN.
398  * They are NOT exact.
399  */
400 #define handle_NAN(a, b, result) \
401 do {                                                      \
402   if (a->clss == FC_NAN) {                                \
403     if (a != result) memcpy(result, a, calc_buffer_size); \
404     fc_exact = 0;                                         \
405     return;                                               \
406   }                                                       \
407   if (b->clss == FC_NAN) {                                \
408     if (b != result) memcpy(result, b, calc_buffer_size); \
409     fc_exact = 0;                                         \
410     return;                                               \
411   }                                                       \
412 }while (0)
413 
414 
415 /**
416  * calculate a + b, where a is the value with the bigger exponent
417  */
_fadd(const fp_value * a,const fp_value * b,fp_value * result)418 static void _fadd(const fp_value *a, const fp_value *b, fp_value *result)
419 {
420 	char *temp;
421 	char *exp_diff;
422 
423 	char sign, res_sign;
424 	char sticky;
425 
426 	fc_exact = 1;
427 
428 	handle_NAN(a, b, result);
429 
430 	/* make sure result has a descriptor */
431 	if (result != a && result != b)
432 		result->desc = a->desc;
433 
434 	/* determine if this is an addition or subtraction */
435 	sign = a->sign ^ b->sign;
436 
437 	/* produce NaN on inf - inf */
438 	if (sign && (a->clss == FC_INF) && (b->clss == FC_INF)) {
439 		fc_exact = 0;
440 		fc_get_qnan(&a->desc, result);
441 		return;
442 	}
443 
444 	temp     = (char*) alloca(value_size);
445 	exp_diff = (char*) alloca(value_size);
446 
447 	/* get exponent difference */
448 	sc_sub(_exp(a), _exp(b), exp_diff);
449 
450 	/* initially set sign to be the sign of a, special treatment of subtraction
451 	 * when exponents are equal is required though.
452 	 * Also special care about the sign is needed when the mantissas are equal
453 	 * (+/- 0 ?) */
454 	if (sign && sc_val_to_long(exp_diff) == 0) {
455 		switch (sc_comp(_mant(a), _mant(b))) {
456 		case 1:  /* a > b */
457 			res_sign = a->sign;  /* abs(a) is bigger and a is negative */
458 			break;
459 		case 0:  /* a == b */
460 			res_sign = (rounding_mode == FC_TONEGATIVE);
461 			break;
462 		case -1: /* a < b */
463 			res_sign = b->sign; /* abs(b) is bigger and b is negative */
464 			break;
465 		default:
466 			/* can't be reached */
467 			res_sign = 0;
468 			break;
469 		}
470 	}
471 	else
472 		res_sign = a->sign;
473 	result->sign = res_sign;
474 
475 	/* sign has been taken care of, check for special cases */
476 	if (a->clss == FC_ZERO || b->clss == FC_INF) {
477 		if (b != result)
478 			memcpy(result, b, calc_buffer_size);
479 		fc_exact = b->clss == FC_NORMAL;
480 		result->sign = res_sign;
481 		return;
482 	}
483 	if (b->clss == FC_ZERO || a->clss == FC_INF) {
484 		if (a != result)
485 			memcpy(result, a, calc_buffer_size);
486 		fc_exact = a->clss == FC_NORMAL;
487 		result->sign = res_sign;
488 		return;
489 	}
490 
491 	/* shift the smaller value to the right to align the radix point */
492 	/* subnormals have their radix point shifted to the right,
493 	 * take care of this first */
494 	if ((b->clss == FC_SUBNORMAL) && (a->clss != FC_SUBNORMAL)) {
495 		sc_val_from_ulong(1, temp);
496 		sc_sub(exp_diff, temp, exp_diff);
497 	}
498 
499 	_shift_right(_mant(b), exp_diff, temp);
500 	sticky = sc_had_carry();
501 	fc_exact &= !sticky;
502 
503 	if (sticky && sign) {
504 		/* if subtracting a little more than the represented value or adding a little
505 		 * more than the represented value to a negative value this, in addition to the
506 		 * still set sticky bit, takes account of the 'little more' */
507 		char *temp1 = (char*) alloca(calc_buffer_size);
508 		sc_val_from_ulong(1, temp1);
509 		sc_add(temp, temp1, temp);
510 	}
511 
512 	if (sign) {
513 		if (sc_comp(_mant(a), temp) == -1)
514 			sc_sub(temp, _mant(a), _mant(result));
515 		else
516 			sc_sub(_mant(a), temp, _mant(result));
517 	} else {
518 		sc_add(_mant(a), temp, _mant(result));
519 	}
520 
521 	/* _normalize expects a 'normal' radix point, adding two subnormals
522 	 * results in a subnormal radix point -> shifting before normalizing */
523 	if ((a->clss == FC_SUBNORMAL) && (b->clss == FC_SUBNORMAL)) {
524 		sc_val_from_ulong(1, NULL);
525 		_shift_left(_mant(result), sc_get_buffer(), _mant(result));
526 	}
527 
528 	/* resulting exponent is the bigger one */
529 	memmove(_exp(result), _exp(a), value_size);
530 
531 	fc_exact &= normalize(result, result, sticky);
532 }
533 
534 /**
535  * calculate a * b
536  */
_fmul(const fp_value * a,const fp_value * b,fp_value * result)537 static void _fmul(const fp_value *a, const fp_value *b, fp_value *result)
538 {
539 	int sticky;
540 	char *temp;
541 	char res_sign;
542 
543 	fc_exact = 1;
544 
545 	handle_NAN(a, b, result);
546 
547 	temp = (char*) alloca(value_size);
548 
549 	if (result != a && result != b)
550 		result->desc = a->desc;
551 
552 	result->sign = res_sign = a->sign ^ b->sign;
553 
554 	/* produce NaN on 0 * inf */
555 	if (a->clss == FC_ZERO) {
556 		if (b->clss == FC_INF) {
557 			fc_get_qnan(&a->desc, result);
558 			fc_exact = 0;
559 		} else {
560 			if (a != result)
561 				memcpy(result, a, calc_buffer_size);
562 			result->sign = res_sign;
563 		}
564 		return;
565 	}
566 	if (b->clss == FC_ZERO) {
567 		if (a->clss == FC_INF) {
568 			fc_get_qnan(&a->desc, result);
569 			fc_exact = 0;
570 		} else {
571 			if (b != result)
572 				memcpy(result, b, calc_buffer_size);
573 			result->sign = res_sign;
574 		}
575 		return;
576 	}
577 
578 	if (a->clss == FC_INF) {
579 		fc_exact = 0;
580 		if (a != result)
581 			memcpy(result, a, calc_buffer_size);
582 		result->sign = res_sign;
583 		return;
584 	}
585 	if (b->clss == FC_INF) {
586 		fc_exact = 0;
587 		if (b != result)
588 			memcpy(result, b, calc_buffer_size);
589 		result->sign = res_sign;
590 		return;
591 	}
592 
593 	/* exp = exp(a) + exp(b) - excess */
594 	sc_add(_exp(a), _exp(b), _exp(result));
595 
596 	sc_val_from_ulong((1 << (a->desc.exponent_size - 1)) - 1, temp);
597 	sc_sub(_exp(result), temp, _exp(result));
598 
599 	/* mixed normal, subnormal values introduce an error of 1, correct it */
600 	if ((a->clss == FC_SUBNORMAL) ^ (b->clss == FC_SUBNORMAL)) {
601 		sc_val_from_ulong(1, temp);
602 		sc_add(_exp(result), temp, _exp(result));
603 	}
604 
605 	sc_mul(_mant(a), _mant(b), _mant(result));
606 
607 	/* realign result: after a multiplication the digits right of the radix
608 	 * point are the sum of the factors' digits after the radix point. As all
609 	 * values are normalized they both have the same amount of these digits,
610 	 * which has to be restored by proper shifting
611 	 * because of the rounding bits */
612 	sc_val_from_ulong(ROUNDING_BITS + result->desc.mantissa_size, temp);
613 
614 	_shift_right(_mant(result), temp, _mant(result));
615 	sticky = sc_had_carry();
616 	fc_exact &= !sticky;
617 
618 	fc_exact &= normalize(result, result, sticky);
619 }
620 
621 /**
622  * calculate a / b
623  */
_fdiv(const fp_value * a,const fp_value * b,fp_value * result)624 static void _fdiv(const fp_value *a, const fp_value *b, fp_value *result)
625 {
626 	int sticky;
627 	char *temp, *dividend;
628 	char res_sign;
629 
630 	fc_exact = 1;
631 
632 	handle_NAN(a, b, result);
633 
634 	temp = (char*) alloca(value_size);
635 	dividend = (char*) alloca(value_size);
636 
637 	if (result != a && result != b)
638 		result->desc = a->desc;
639 
640 	result->sign = res_sign = a->sign ^ b->sign;
641 
642 	/* produce FC_NAN on 0/0 and inf/inf */
643 	if (a->clss == FC_ZERO) {
644 		if (b->clss == FC_ZERO) {
645 			/* 0/0 -> NaN */
646 			fc_get_qnan(&a->desc, result);
647 			fc_exact = 0;
648 		} else {
649 			/* 0/x -> a */
650 			if (a != result)
651 				memcpy(result, a, calc_buffer_size);
652 			result->sign = res_sign;
653 		}
654 		return;
655 	}
656 
657 	if (b->clss == FC_INF) {
658 		fc_exact = 0;
659 		if (a->clss == FC_INF) {
660 			/* inf/inf -> NaN */
661 			fc_get_qnan(&a->desc, result);
662 		} else {
663 			/* x/inf -> 0 */
664 			sc_val_from_ulong(0, NULL);
665 			_save_result(_exp(result));
666 			_save_result(_mant(result));
667 			result->clss = FC_ZERO;
668 		}
669 		return;
670 	}
671 
672 	if (a->clss == FC_INF) {
673 		fc_exact = 0;
674 		/* inf/x -> inf */
675 		if (a != result)
676 			memcpy(result, a, calc_buffer_size);
677 		result->sign = res_sign;
678 		return;
679 	}
680 	if (b->clss == FC_ZERO) {
681 		fc_exact = 0;
682 		/* division by zero */
683 		if (result->sign)
684 			fc_get_minusinf(&a->desc, result);
685 		else
686 			fc_get_plusinf(&a->desc, result);
687 		return;
688 	}
689 
690 	/* exp = exp(a) - exp(b) + excess - 1*/
691 	sc_sub(_exp(a), _exp(b), _exp(result));
692 	sc_val_from_ulong((1 << (a->desc.exponent_size - 1)) - 2, temp);
693 	sc_add(_exp(result), temp, _exp(result));
694 
695 	/* mixed normal, subnormal values introduce an error of 1, correct it */
696 	if ((a->clss == FC_SUBNORMAL) ^ (b->clss == FC_SUBNORMAL)) {
697 		sc_val_from_ulong(1, temp);
698 		sc_add(_exp(result), temp, _exp(result));
699 	}
700 
701 	/* mant(res) = mant(a) / 1/2mant(b) */
702 	/* to gain more bits of precision in the result the dividend could be
703 	 * shifted left, as this operation does not loose bits. This would not
704 	 * fit into the integer precision, but due to the rounding bits (which
705 	 * are always zero because the values are all normalized) the divisor
706 	 * can be shifted right instead to achieve the same result */
707 	sc_val_from_ulong(ROUNDING_BITS + result->desc.mantissa_size, temp);
708 
709 	_shift_left(_mant(a), temp, dividend);
710 
711 	{
712 		char *divisor = (char*) alloca(calc_buffer_size);
713 		sc_val_from_ulong(1, divisor);
714 		_shift_right(_mant(b), divisor, divisor);
715 		sc_div(dividend, divisor, _mant(result));
716 		sticky = sc_had_carry();
717 		fc_exact &= !sticky;
718 	}
719 
720 	fc_exact &= normalize(result, result, sticky);
721 }
722 
723 #if 0
724 static void _power_of_ten(int exp, float_descriptor_t *desc, char *result)
725 {
726 	char *build;
727 	char *temp;
728 
729 	/* positive sign */
730 	result->sign = 0;
731 
732 	/* set new descriptor (else result is supposed to already have one) */
733 	if (desc != NULL)
734 		result->desc = *desc;
735 
736 	build = alloca(value_size);
737 	temp = alloca(value_size);
738 
739 	sc_val_from_ulong((1 << (result->desc.exponent_size - 1)) - 1, _exp(result));
740 
741 	if (exp > 0) {
742 		/* temp is value of ten now */
743 		sc_val_from_ulong(10, NULL);
744 		_save_result(temp);
745 
746 		for (exp--; exp > 0; exp--) {
747 			_save_result(build);
748 			sc_mul(build, temp, NULL);
749 		}
750 		_save_result(build);
751 
752 		/* temp is amount of left shift needed to put the value left of the radix point */
753 		sc_val_from_ulong(result->desc.mantissa_size + ROUNDING_BITS, temp);
754 
755 		_shift_left(build, temp, _mant(result));
756 
757 		_normalize(result, result, 0);
758 	}
759 }
760 #endif
761 
762 /**
763  * Truncate the fractional part away.
764  *
765  * This does not clip to any integer range.
766  */
_trunc(const fp_value * a,fp_value * result)767 static void _trunc(const fp_value *a, fp_value *result)
768 {
769 	/*
770 	 * When exponent == 0 all bits left of the radix point
771 	 * are the integral part of the value. For 15bit exp_size
772 	 * this would require a left shift of max. 16383 bits which
773 	 * is too much.
774 	 * But it is enough to ensure that no bit right of the radix
775 	 * point remains set. This restricts the interesting
776 	 * exponents to the interval [0, mant_size-1].
777 	 * Outside this interval the truncated value is either 0 or
778 	 * it does not have fractional parts.
779 	 */
780 
781 	int exp_bias, exp_val;
782 	char *temp;
783 
784 	/* fixme: can be exact */
785 	fc_exact = 0;
786 
787 	temp = (char*) alloca(value_size);
788 
789 	if (a != result) {
790 		result->desc = a->desc;
791 		result->clss = a->clss;
792 	}
793 
794 	exp_bias = (1 << (a->desc.exponent_size - 1)) - 1;
795 	exp_val  = sc_val_to_long(_exp(a)) - exp_bias;
796 
797 	if (exp_val < 0) {
798 		sc_val_from_ulong(0, NULL);
799 		_save_result(_exp(result));
800 		_save_result(_mant(result));
801 		result->clss = FC_ZERO;
802 
803 		return;
804 	}
805 
806 	if (exp_val > (long)a->desc.mantissa_size) {
807 		if (a != result)
808 			memcpy(result, a, calc_buffer_size);
809 
810 		return;
811 	}
812 
813 	/* set up a proper mask to delete all bits right of the
814 	 * radix point if the mantissa had been shifted until exp == 0 */
815 	sc_max_from_bits(1 + exp_val, 0, temp);
816 	sc_val_from_long(a->desc.mantissa_size - exp_val + 2, NULL);
817 	_shift_left(temp, sc_get_buffer(), temp);
818 
819 	/* and the mask and return the result */
820 	sc_and(_mant(a), temp, _mant(result));
821 
822 	if (a != result) {
823 		memcpy(_exp(result), _exp(a), value_size);
824 		result->sign = a->sign;
825 	}
826 }
827 
828 /********
829  * functions defined in fltcalc.h
830  ********/
fc_get_buffer(void)831 const void *fc_get_buffer(void)
832 {
833 	return calc_buffer;
834 }
835 
fc_get_buffer_length(void)836 int fc_get_buffer_length(void)
837 {
838 	return calc_buffer_size;
839 }
840 
fc_val_from_str(const char * str,size_t len,const float_descriptor_t * desc,void * result)841 void *fc_val_from_str(const char *str, size_t len,
842                       const float_descriptor_t *desc, void *result)
843 {
844 	char *buffer;
845 
846 	/* XXX excuse of an implementation to make things work */
847 	long double        val;
848 	fp_value          *tmp = (fp_value*) alloca(calc_buffer_size);
849 	float_descriptor_t tmp_desc;
850 
851 	buffer = (char*) alloca(len+1);
852 	memcpy(buffer, str, len);
853 	buffer[len] = '\0';
854 	val = string_to_long_double(buffer);
855 
856 	DEBUGPRINTF(("val_from_str(%s)\n", str));
857 	tmp_desc.exponent_size = 15;
858 	tmp_desc.mantissa_size = 63;
859 	tmp_desc.explicit_one  = 1;
860 	fc_val_from_ieee754(val, &tmp_desc, tmp);
861 
862 	return fc_cast(tmp, desc, (fp_value*) result);
863 }
864 
fc_val_from_ieee754(long double l,const float_descriptor_t * desc,fp_value * result)865 fp_value *fc_val_from_ieee754(long double l, const float_descriptor_t *desc,
866                               fp_value *result)
867 {
868 	char    *temp;
869 	int      bias_res, bias_val, mant_val;
870 	value_t  srcval;
871 	char     sign;
872 	uint32_t exponent, mantissa0, mantissa1;
873 	size_t   long_double_size = sizeof(long double);
874 
875 	srcval.d = l;
876 	bias_res = ((1 << (desc->exponent_size - 1)) - 1);
877 
878 	if (long_double_size == 8) {
879 		mant_val  = 52;
880 		bias_val  = 0x3ff;
881 		sign      = (srcval.val_ld8.high & 0x80000000) != 0;
882 		exponent  = (srcval.val_ld8.high & 0x7FF00000) >> 20;
883 		mantissa0 = srcval.val_ld8.high & 0x000FFFFF;
884 		mantissa1 = srcval.val_ld8.low;
885 	} else {
886 		/* we assume an x86-like 80bit representation of the value... */
887 		assert(sizeof(long double)==12 || sizeof(long double)==16);
888 		mant_val  = 63;
889 		bias_val  = 0x3fff;
890 		sign      = (srcval.val_ld12.high & 0x00008000) != 0;
891 		exponent  = (srcval.val_ld12.high & 0x00007FFF) ;
892 		mantissa0 = srcval.val_ld12.mid;
893 		mantissa1 = srcval.val_ld12.low;
894 	}
895 
896 	if (result == NULL)
897 		result = calc_buffer;
898 	temp = (char*) alloca(value_size);
899 
900 	/* CLEAR the buffer, else some bits might be uninitialized */
901 	memset(result, 0, fc_get_buffer_length());
902 
903 	result->desc = *desc;
904 	result->clss = FC_NORMAL;
905 	result->sign = sign;
906 
907 	/* sign and flag suffice to identify NaN or inf, no exponent/mantissa
908 	 * encoding is needed. the function can return immediately in these cases */
909 	if (my_isnan(l)) {
910 		result->clss = FC_NAN;
911 		TRACEPRINTF(("val_from_float resulted in NAN\n"));
912 		return result;
913 	} else if (my_isinf(l)) {
914 		result->clss = FC_INF;
915 		TRACEPRINTF(("val_from_float resulted in %sINF\n", (result->sign == 1) ? "-" : ""));
916 		return result;
917 	}
918 
919 	/* build exponent, because input and output exponent and mantissa sizes may differ
920 	 * this looks more complicated than it is: unbiased input exponent + output bias,
921 	 * minus the mantissa difference which is added again later when the output float
922 	 * becomes normalized */
923 	sc_val_from_long((exponent - bias_val + bias_res) - (mant_val - desc->mantissa_size), _exp(result));
924 
925 	/* build mantissa representation */
926 	if (exponent != 0) {
927 		/* insert the hidden bit */
928 		sc_val_from_ulong(1, temp);
929 		sc_val_from_ulong(mant_val + ROUNDING_BITS, NULL);
930 		_shift_left(temp, sc_get_buffer(), NULL);
931 	}
932 	else {
933 		sc_val_from_ulong(0, NULL);
934 	}
935 
936 	_save_result(_mant(result));
937 
938 	/* bits from the upper word */
939 	sc_val_from_ulong(mantissa0, temp);
940 	sc_val_from_ulong(34, NULL);
941 	_shift_left(temp, sc_get_buffer(), temp);
942 	sc_or(_mant(result), temp, _mant(result));
943 
944 	/* bits from the lower word */
945 	sc_val_from_ulong(mantissa1, temp);
946 	sc_val_from_ulong(ROUNDING_BITS, NULL);
947 	_shift_left(temp, sc_get_buffer(), temp);
948 	sc_or(_mant(result), temp, _mant(result));
949 
950 	/* _normalize expects the radix point to be normal, so shift mantissa of subnormal
951 	 * origin one to the left */
952 	if (exponent == 0) {
953 		sc_val_from_ulong(1, NULL);
954 		_shift_left(_mant(result), sc_get_buffer(), _mant(result));
955 	}
956 
957 	normalize(result, result, 0);
958 
959 	TRACEPRINTF(("val_from_float results in %s\n", fc_print(result, temp, calc_buffer_size, FC_PACKED)));
960 
961 	return result;
962 }
963 
fc_val_to_ieee754(const fp_value * val)964 long double fc_val_to_ieee754(const fp_value *val)
965 {
966 	fp_value *value;
967 	fp_value *temp = NULL;
968 
969 	unsigned byte_offset;
970 
971 	uint32_t sign;
972 	uint32_t exponent;
973 	uint32_t mantissa0;
974 	uint32_t mantissa1;
975 
976 	value_t           buildval;
977 	float_descriptor_t desc;
978 	unsigned          mantissa_size;
979 
980 	size_t            long_double_size = sizeof(long double);
981 
982 	if (long_double_size == 8) {
983 		desc.exponent_size = 11;
984 		desc.mantissa_size = 52;
985 		desc.explicit_one  = 0;
986 	} else {
987 		desc.exponent_size = 15;
988 		desc.mantissa_size = 63;
989 		desc.explicit_one  = 1;
990 	}
991 	mantissa_size = desc.mantissa_size + desc.explicit_one;
992 
993 	temp = (fp_value*) alloca(calc_buffer_size);
994 	value = fc_cast(val, &desc, temp);
995 
996 	sign = value->sign;
997 
998 	/* @@@ long double exponent is 15bit, so the use of sc_val_to_long should not
999 	 * lead to wrong results */
1000 	exponent = sc_val_to_long(_exp(value)) ;
1001 
1002 	sc_val_from_ulong(ROUNDING_BITS, NULL);
1003 	_shift_right(_mant(value), sc_get_buffer(), _mant(value));
1004 
1005 	mantissa0 = 0;
1006 	mantissa1 = 0;
1007 
1008 	for (byte_offset = 0; byte_offset < 4; byte_offset++)
1009 		mantissa1 |= sc_sub_bits(_mant(value), mantissa_size, byte_offset) << (byte_offset << 3);
1010 
1011 	for (; (byte_offset<<3) < desc.mantissa_size; byte_offset++)
1012 		mantissa0 |= sc_sub_bits(_mant(value), mantissa_size, byte_offset) << ((byte_offset - 4) << 3);
1013 
1014 	if (long_double_size == 8) {
1015 		mantissa0 &= 0x000FFFFF;  /* get rid of garbage */
1016 		buildval.val_ld8.high = sign << 31;
1017 		buildval.val_ld8.high |= exponent << 20;
1018 		buildval.val_ld8.high |= mantissa0;
1019 		buildval.val_ld8.low = mantissa1;
1020 	} else {
1021 		buildval.val_ld12.high = sign << 15;
1022 		buildval.val_ld12.high |= exponent;
1023 		buildval.val_ld12.mid = mantissa0;
1024 		buildval.val_ld12.low = mantissa1;
1025 	}
1026 
1027 	TRACEPRINTF(("val_to_float: %d-%x-%x%x\n", sign, exponent, mantissa0, mantissa1));
1028 	return buildval.d;
1029 }
1030 
fc_cast(const fp_value * value,const float_descriptor_t * desc,fp_value * result)1031 fp_value *fc_cast(const fp_value *value, const float_descriptor_t *desc,
1032                   fp_value *result)
1033 {
1034 	char *temp;
1035 	int exp_offset, val_bias, res_bias;
1036 
1037 	if (result == NULL) result = calc_buffer;
1038 	temp = (char*) alloca(value_size);
1039 
1040 	if (value->desc.exponent_size == desc->exponent_size &&
1041 		value->desc.mantissa_size == desc->mantissa_size &&
1042 		value->desc.explicit_one  == desc->explicit_one) {
1043 		if (value != result)
1044 			memcpy(result, value, calc_buffer_size);
1045 		return result;
1046 	}
1047 
1048 	if (value->clss == FC_NAN) {
1049 		if (sc_get_highest_set_bit(_mant(value)) == value->desc.mantissa_size + 1)
1050 			return fc_get_qnan(desc, result);
1051 		else
1052 			return fc_get_snan(desc, result);
1053 	}
1054 	else if (value->clss == FC_INF) {
1055 		if (value->sign == 0)
1056 			return fc_get_plusinf(desc, result);
1057 		else
1058 			return fc_get_minusinf(desc, result);
1059 	}
1060 
1061 	/* set the descriptor of the new value */
1062 	result->desc = *desc;
1063 	result->clss = value->clss;
1064 	result->sign = value->sign;
1065 
1066 	/* when the mantissa sizes differ normalizing has to shift to align it.
1067 	 * this would change the exponent, which is unwanted. So calculate this
1068 	 * offset and add it */
1069 	val_bias = (1 << (value->desc.exponent_size - 1)) - 1;
1070 	res_bias = (1 << (desc->exponent_size - 1)) - 1;
1071 
1072 	exp_offset = (res_bias - val_bias) - (value->desc.mantissa_size - desc->mantissa_size);
1073 	sc_val_from_long(exp_offset, temp);
1074 	sc_add(_exp(value), temp, _exp(result));
1075 
1076 	/* _normalize expects normalized radix point */
1077 	if (value->clss == FC_SUBNORMAL) {
1078 		sc_val_from_ulong(1, NULL);
1079 		_shift_left(_mant(value), sc_get_buffer(), _mant(result));
1080 	} else if (value != result) {
1081 		memcpy(_mant(result), _mant(value), value_size);
1082 	} else {
1083 		memmove(_mant(result), _mant(value), value_size);
1084 	}
1085 
1086 	normalize(result, result, 0);
1087 	TRACEPRINTF(("Cast results in %s\n", fc_print(result, temp, value_size, FC_PACKED)));
1088 	return result;
1089 }
1090 
fc_get_max(const float_descriptor_t * desc,fp_value * result)1091 fp_value *fc_get_max(const float_descriptor_t *desc, fp_value *result)
1092 {
1093 	if (result == NULL) result = calc_buffer;
1094 
1095 	result->desc = *desc;
1096 	result->clss = FC_NORMAL;
1097 	result->sign = 0;
1098 
1099 	sc_val_from_ulong((1 << desc->exponent_size) - 2, _exp(result));
1100 
1101 	sc_max_from_bits(desc->mantissa_size + 1, 0, _mant(result));
1102 	sc_val_from_ulong(ROUNDING_BITS, NULL);
1103 	_shift_left(_mant(result), sc_get_buffer(), _mant(result));
1104 
1105 	return result;
1106 }
1107 
fc_get_min(const float_descriptor_t * desc,fp_value * result)1108 fp_value *fc_get_min(const float_descriptor_t *desc, fp_value *result)
1109 {
1110 	if (result == NULL) result = calc_buffer;
1111 
1112 	fc_get_max(desc, result);
1113 	result->sign = 1;
1114 
1115 	return result;
1116 }
1117 
fc_get_snan(const float_descriptor_t * desc,fp_value * result)1118 fp_value *fc_get_snan(const float_descriptor_t *desc, fp_value *result)
1119 {
1120 	if (result == NULL) result = calc_buffer;
1121 
1122 	result->desc = *desc;
1123 	result->clss = FC_NAN;
1124 	result->sign = 0;
1125 
1126 	sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1127 
1128 	/* signaling NaN has non-zero mantissa with msb not set */
1129 	sc_val_from_ulong(1, _mant(result));
1130 
1131 	return result;
1132 }
1133 
fc_get_qnan(const float_descriptor_t * desc,fp_value * result)1134 fp_value *fc_get_qnan(const float_descriptor_t *desc, fp_value *result)
1135 {
1136 	if (result == NULL) result = calc_buffer;
1137 
1138 	result->desc = *desc;
1139 	result->clss = FC_NAN;
1140 	result->sign = 0;
1141 
1142 	sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1143 
1144 	/* quiet NaN has the msb of the mantissa set, so shift one there */
1145 	sc_val_from_ulong(1, _mant(result));
1146 	/* mantissa_size >+< 1 because of two extra rounding bits */
1147 	sc_val_from_ulong(desc->mantissa_size + 1, NULL);
1148 	_shift_left(_mant(result), sc_get_buffer(), _mant(result));
1149 
1150 	return result;
1151 }
1152 
fc_get_plusinf(const float_descriptor_t * desc,fp_value * result)1153 fp_value *fc_get_plusinf(const float_descriptor_t *desc, fp_value *result)
1154 {
1155 	char *mant;
1156 
1157 	if (result == NULL) result = calc_buffer;
1158 
1159 	result->desc = *desc;
1160 	result->clss = FC_INF;
1161 	result->sign = 0;
1162 
1163 	sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1164 
1165 	mant = _mant(result);
1166 	sc_val_from_ulong(0, mant);
1167 	if (desc->explicit_one) {
1168 		sc_set_bit_at(mant, result->desc.mantissa_size + ROUNDING_BITS);
1169 	}
1170 
1171 	return result;
1172 }
1173 
fc_get_minusinf(const float_descriptor_t * desc,fp_value * result)1174 fp_value *fc_get_minusinf(const float_descriptor_t *desc, fp_value *result)
1175 {
1176 	if (result == NULL) result = calc_buffer;
1177 
1178 	fc_get_plusinf(desc, result);
1179 	result->sign = 1;
1180 
1181 	return result;
1182 }
1183 
fc_comp(const fp_value * val_a,const fp_value * val_b)1184 int fc_comp(const fp_value *val_a, const fp_value *val_b)
1185 {
1186 	int mul = 1;
1187 
1188 	/*
1189 	 * shortcut: if both values are identical, they are either
1190 	 * Unordered if NaN or equal
1191 	 */
1192 	if (val_a == val_b)
1193 		return val_a->clss == FC_NAN ? 2 : 0;
1194 
1195 	/* unordered if one is a NaN */
1196 	if (val_a->clss == FC_NAN || val_b->clss == FC_NAN)
1197 		return 2;
1198 
1199 	/* zero is equal independent of sign */
1200 	if ((val_a->clss == FC_ZERO) && (val_b->clss == FC_ZERO))
1201 		return 0;
1202 
1203 	/* different signs make compare easy */
1204 	if (val_a->sign != val_b->sign)
1205 		return (val_a->sign == 0) ? (1) : (-1);
1206 
1207 	mul = val_a->sign ? -1 : 1;
1208 
1209 	/* both infinity means equality */
1210 	if ((val_a->clss == FC_INF) && (val_b->clss == FC_INF))
1211 		return 0;
1212 
1213 	/* infinity is bigger than the rest */
1214 	if (val_a->clss == FC_INF)
1215 		return  1 * mul;
1216 	if (val_b->clss == FC_INF)
1217 		return -1 * mul;
1218 
1219 	/* check first exponent, that mantissa if equal */
1220 	switch (sc_comp(_exp(val_a), _exp(val_b))) {
1221 	case -1:
1222 		return -1 * mul;
1223 	case  1:
1224 		return  1 * mul;
1225 	case  0:
1226 		return sc_comp(_mant(val_a), _mant(val_b)) * mul;
1227 	default:
1228 		return 2;
1229 	}
1230 }
1231 
fc_is_zero(const fp_value * a)1232 int fc_is_zero(const fp_value *a)
1233 {
1234 	return a->clss == FC_ZERO;
1235 }
1236 
fc_is_negative(const fp_value * a)1237 int fc_is_negative(const fp_value *a)
1238 {
1239 	return a->sign;
1240 }
1241 
fc_is_inf(const fp_value * a)1242 int fc_is_inf(const fp_value *a)
1243 {
1244 	return a->clss == FC_INF;
1245 }
1246 
fc_is_nan(const fp_value * a)1247 int fc_is_nan(const fp_value *a)
1248 {
1249 	return a->clss == FC_NAN;
1250 }
1251 
fc_is_subnormal(const fp_value * a)1252 int fc_is_subnormal(const fp_value *a)
1253 {
1254 	return a->clss == FC_SUBNORMAL;
1255 }
1256 
fc_print(const fp_value * val,char * buf,int buflen,unsigned base)1257 char *fc_print(const fp_value *val, char *buf, int buflen, unsigned base)
1258 {
1259 	char *mul_1;
1260 	long double flt_val;
1261 
1262 	mul_1 = (char*) alloca(calc_buffer_size);
1263 
1264 	switch (base) {
1265 	case FC_DEC:
1266 		switch ((value_class_t)val->clss) {
1267 		case FC_INF:
1268 			snprintf(buf, buflen, "%cINF", val->sign ? '-' : '+');
1269 			break;
1270 		case FC_NAN:
1271 			snprintf(buf, buflen, "NaN");
1272 			break;
1273 		case FC_ZERO:
1274 			snprintf(buf, buflen, "0.0");
1275 			break;
1276 		default:
1277 			flt_val = fc_val_to_ieee754(val);
1278 			/* XXX 30 is arbitrary */
1279 			snprintf(buf, buflen, "%.30LE", flt_val);
1280 		}
1281 		break;
1282 
1283 	case FC_HEX:
1284 		switch ((value_class_t)val->clss) {
1285 		case FC_INF:
1286 			snprintf(buf, buflen, "%cINF", val->sign ? '-' : '+');
1287 			break;
1288 		case FC_NAN:
1289 			snprintf(buf, buflen, "NaN");
1290 			break;
1291 		case FC_ZERO:
1292 			snprintf(buf, buflen, "0.0");
1293 			break;
1294 		default:
1295 			flt_val = fc_val_to_ieee754(val);
1296 			snprintf(buf, buflen, "%LA", flt_val);
1297 		}
1298 		break;
1299 
1300 	case FC_PACKED:
1301 	default:
1302 		snprintf(buf, buflen, "%s", sc_print(pack(val, mul_1), value_size*4, SC_HEX, 0));
1303 		buf[buflen - 1] = '\0';
1304 		break;
1305 	}
1306 	return buf;
1307 }
1308 
fc_sub_bits(const fp_value * value,unsigned num_bits,unsigned byte_ofs)1309 unsigned char fc_sub_bits(const fp_value *value, unsigned num_bits, unsigned byte_ofs)
1310 {
1311 	/* this is used to cache the packed version of the value */
1312 	static char *packed_value = NULL;
1313 
1314 	if (packed_value == NULL) packed_value = XMALLOCN(char, value_size);
1315 
1316 	if (value != NULL)
1317 		pack(value, packed_value);
1318 
1319 	return sc_sub_bits(packed_value, num_bits, byte_ofs);
1320 }
1321 
1322 /* Returns non-zero if the mantissa is zero, i.e. 1.0Exxx */
fc_zero_mantissa(const fp_value * value)1323 int fc_zero_mantissa(const fp_value *value)
1324 {
1325 	return sc_get_lowest_set_bit(_mant(value)) == ROUNDING_BITS + value->desc.mantissa_size;
1326 }
1327 
1328 /* Returns the exponent of a value. */
fc_get_exponent(const fp_value * value)1329 int fc_get_exponent(const fp_value *value)
1330 {
1331 	int exp_bias = (1 << (value->desc.exponent_size - 1)) - 1;
1332 	return sc_val_to_long(_exp(value)) - exp_bias;
1333 }
1334 
1335 /* Return non-zero if a given value can be converted lossless into another precision */
fc_can_lossless_conv_to(const fp_value * value,const float_descriptor_t * desc)1336 int fc_can_lossless_conv_to(const fp_value *value, const float_descriptor_t *desc)
1337 {
1338 	int v;
1339 	int exp_bias;
1340 
1341 	/* handle some special cases first */
1342 	switch (value->clss) {
1343 	case FC_ZERO:
1344 	case FC_INF:
1345 	case FC_NAN:
1346 		return 1;
1347 	default:
1348 		break;
1349 	}
1350 
1351 	/* check if the exponent can be encoded: note, 0 and all ones are reserved for the exponent */
1352 	exp_bias = (1 << (desc->exponent_size - 1)) - 1;
1353 	v = fc_get_exponent(value) + exp_bias;
1354 	if (0 < v && v < (1 << desc->exponent_size) - 1) {
1355 		/* exponent can be encoded, now check the mantissa */
1356 		v = value->desc.mantissa_size + ROUNDING_BITS - sc_get_lowest_set_bit(_mant(value));
1357 		return v <= (int)desc->mantissa_size;
1358 	}
1359 	return 0;
1360 }
1361 
1362 
fc_set_rounding_mode(fc_rounding_mode_t mode)1363 fc_rounding_mode_t fc_set_rounding_mode(fc_rounding_mode_t mode)
1364 {
1365 	if (mode == FC_TONEAREST || mode == FC_TOPOSITIVE || mode == FC_TONEGATIVE || mode == FC_TOZERO)
1366 		rounding_mode = mode;
1367 
1368 	return rounding_mode;
1369 }
1370 
fc_get_rounding_mode(void)1371 fc_rounding_mode_t fc_get_rounding_mode(void)
1372 {
1373 	return rounding_mode;
1374 }
1375 
init_fltcalc(int precision)1376 void init_fltcalc(int precision)
1377 {
1378 	if (calc_buffer == NULL) {
1379 		/* does nothing if already init */
1380 		if (precision == 0) precision = FC_DEFAULT_PRECISION;
1381 
1382 		init_strcalc(precision + 2 + ROUNDING_BITS);
1383 
1384 		/* needs additionally rounding bits, one bit as explicit 1., and one for
1385 		 * addition overflow */
1386 		max_precision = sc_get_precision() - (2 + ROUNDING_BITS);
1387 		if (max_precision < precision)
1388 			printf("WARNING: not enough precision available, using %d\n", max_precision);
1389 
1390 		rounding_mode    = FC_TONEAREST;
1391 		value_size       = sc_get_buffer_length();
1392 		calc_buffer_size = sizeof(fp_value) + 2*value_size - 1;
1393 
1394 		calc_buffer = (fp_value*) xmalloc(calc_buffer_size);
1395 		memset(calc_buffer, 0, calc_buffer_size);
1396 		DEBUGPRINTF(("init fltcalc:\n\tVALUE_SIZE = %d\ntCALC_BUFFER_SIZE = %d\n\tcalc_buffer = %p\n\n", value_size, calc_buffer_size, calc_buffer));
1397 	}
1398 }
1399 
finish_fltcalc(void)1400 void finish_fltcalc (void)
1401 {
1402 	free(calc_buffer); calc_buffer = NULL;
1403 }
1404 
1405 #ifdef FLTCALC_TRACE_CALC
1406 static char buffer[100];
1407 #endif
1408 
1409 /* definition of interface functions */
fc_add(const fp_value * a,const fp_value * b,fp_value * result)1410 fp_value *fc_add(const fp_value *a, const fp_value *b, fp_value *result)
1411 {
1412 	if (result == NULL) result = calc_buffer;
1413 
1414 	TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1415 	TRACEPRINTF(("+ %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1416 
1417 	/* make the value with the bigger exponent the first one */
1418 	if (sc_comp(_exp(a), _exp(b)) == -1)
1419 		_fadd(b, a, result);
1420 	else
1421 		_fadd(a, b, result);
1422 
1423 	TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1424 	return result;
1425 }
1426 
fc_sub(const fp_value * a,const fp_value * b,fp_value * result)1427 fp_value *fc_sub(const fp_value *a, const fp_value *b, fp_value *result)
1428 {
1429 	fp_value *temp;
1430 
1431 	if (result == NULL) result = calc_buffer;
1432 
1433 	TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1434 	TRACEPRINTF(("- %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1435 
1436 	temp = (fp_value*) alloca(calc_buffer_size);
1437 	memcpy(temp, b, calc_buffer_size);
1438 	temp->sign = !b->sign;
1439 	if (sc_comp(_exp(a), _exp(temp)) == -1)
1440 		_fadd(temp, a, result);
1441 	else
1442 		_fadd(a, temp, result);
1443 
1444 	TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1445 	return result;
1446 }
1447 
fc_mul(const fp_value * a,const fp_value * b,fp_value * result)1448 fp_value *fc_mul(const fp_value *a, const fp_value *b, fp_value *result)
1449 {
1450 	if (result == NULL) result = calc_buffer;
1451 
1452 	TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1453 	TRACEPRINTF(("* %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1454 
1455 	_fmul(a, b, result);
1456 
1457 	TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1458 	return result;
1459 }
1460 
fc_div(const fp_value * a,const fp_value * b,fp_value * result)1461 fp_value *fc_div(const fp_value *a, const fp_value *b, fp_value *result)
1462 {
1463 	if (result == NULL) result = calc_buffer;
1464 
1465 	TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1466 	TRACEPRINTF(("/ %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1467 
1468 	_fdiv(a, b, result);
1469 
1470 	TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1471 	return result;
1472 }
1473 
fc_neg(const fp_value * a,fp_value * result)1474 fp_value *fc_neg(const fp_value *a, fp_value *result)
1475 {
1476 	if (result == NULL) result = calc_buffer;
1477 
1478 	TRACEPRINTF(("- %s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1479 
1480 	if (a != result)
1481 		memcpy(result, a, calc_buffer_size);
1482 	result->sign = !a->sign;
1483 
1484 	TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1485 	return result;
1486 }
1487 
fc_int(const fp_value * a,fp_value * result)1488 fp_value *fc_int(const fp_value *a, fp_value *result)
1489 {
1490 	if (result == NULL) result = calc_buffer;
1491 
1492 	TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1493 	TRACEPRINTF(("truncated to integer "));
1494 
1495 	_trunc(a, result);
1496 
1497 	TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1498 	return result;
1499 }
1500 
fc_rnd(const fp_value * a,fp_value * result)1501 fp_value *fc_rnd(const fp_value *a, fp_value *result)
1502 {
1503 	(void)a;
1504 	(void)result;
1505 	TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1506 	TRACEPRINTF(("rounded to integer "));
1507 
1508 	panic("not yet implemented");
1509 }
1510 
1511 /*
1512  * convert a floating point value into an sc value ...
1513  */
fc_flt2int(const fp_value * a,void * result,ir_mode * dst_mode)1514 int fc_flt2int(const fp_value *a, void *result, ir_mode *dst_mode)
1515 {
1516 	if (a->clss == FC_NORMAL) {
1517 		int exp_bias = (1 << (a->desc.exponent_size - 1)) - 1;
1518 		int exp_val  = sc_val_to_long(_exp(a)) - exp_bias;
1519 		int shift, highest;
1520 		int mantissa_size;
1521 		int tgt_bits;
1522 
1523 		if (a->sign && !mode_is_signed(dst_mode)) {
1524 			/* FIXME: for now we cannot convert this */
1525 			return 0;
1526 		}
1527 
1528 		tgt_bits = get_mode_size_bits(dst_mode);
1529 		if (mode_is_signed(dst_mode))
1530 			--tgt_bits;
1531 
1532 		assert(exp_val >= 0 && "floating point value not integral before fc_flt2int() call");
1533 		mantissa_size = a->desc.mantissa_size + ROUNDING_BITS;
1534 		shift         = exp_val - mantissa_size;
1535 
1536 		if (tgt_bits < mantissa_size + 1)
1537 			tgt_bits = mantissa_size + 1;
1538 		if (shift > 0) {
1539 			sc_shlI(_mant(a),  shift, tgt_bits, 0, result);
1540 		} else {
1541 			sc_shrI(_mant(a), -shift, tgt_bits, 0, result);
1542 		}
1543 
1544 		/* check for overflow */
1545 		highest = sc_get_highest_set_bit(result);
1546 
1547 		if (mode_is_signed(dst_mode)) {
1548 			if (highest == sc_get_lowest_set_bit(result)) {
1549 				/* need extra test for MIN_INT */
1550 				if (highest >= (int) get_mode_size_bits(dst_mode)) {
1551 					/* FIXME: handle overflow */
1552 					return 0;
1553 				}
1554 			} else {
1555 				if (highest >= (int) get_mode_size_bits(dst_mode) - 1) {
1556 					/* FIXME: handle overflow */
1557 					return 0;
1558 				}
1559 			}
1560 		} else {
1561 			if (highest >= (int) get_mode_size_bits(dst_mode)) {
1562 				/* FIXME: handle overflow */
1563 				return 0;
1564 			}
1565 		}
1566 
1567 		if (a->sign)
1568 			sc_neg(result, result);
1569 
1570 		return 1;
1571 	} else if (a->clss == FC_ZERO) {
1572 		sc_zero(result);
1573 		return 1;
1574 	}
1575 	return 0;
1576 }
1577 
fc_is_exact(void)1578 int fc_is_exact(void)
1579 {
1580 	return fc_exact;
1581 }
1582