2 * Copyright (C) 1995-2008 University of Karlsruhe. All right reserved.
4 * This file is part of libFirm.
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.
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.
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
22 * @brief tarval floating point calculations
24 * @author Mathias Heil
35 #include <math.h> /* need isnan() and isinf() (will be changed)*/
36 /* undef some reused constants defined by math.h */
41 #ifdef HAVE_INTTYPES_H
42 # include <inttypes.h>
55 /** The number of extra precesion rounding bits */
56 #define ROUNDING_BITS 2
58 typedef uint32_t UINT32;
60 #ifdef HAVE_LONG_DOUBLE
61 #ifdef WORDS_BIGENDIAN
68 volatile long double d;
77 volatile long double d;
81 #ifdef WORDS_BIGENDIAN
100 #define CLEAR_BUFFER(buffer) memset(buffer, 0, calc_buffer_size)
102 /* our floating point value */
104 ieee_descriptor_t desc;
106 char value[1]; /* exp[value_size] + mant[value_size] */
109 #define _exp(a) &((a)->value[0])
110 #define _mant(a) &((a)->value[value_size])
112 #define _save_result(x) memcpy((x), sc_get_buffer(), value_size)
113 #define _shift_right(x, y, res) sc_shr((x), (y), value_size*4, 0, (res))
114 #define _shift_left(x, y, res) sc_shl((x), (y), value_size*4, 0, (res))
118 # define DEBUGPRINTF(x) printf x
120 # define DEBUGPRINTF(x) ((void)0)
123 #ifdef FLTCALC_TRACE_CALC
124 # define TRACEPRINTF(x) printf x
126 # define TRACEPRINTF(x) ((void)0)
129 /** The immediate precision. */
130 static unsigned immediate_prec = 0;
132 /** A temporal buffer. */
133 static fp_value *calc_buffer = NULL;
135 /** Current rounding mode.*/
136 static fc_rounding_mode_t rounding_mode;
138 static int calc_buffer_size;
139 static int value_size;
140 static int max_precision;
143 static int fc_exact = 1;
146 static void fail_char(const char *str, unsigned int len, int pos) {
148 printf("ERROR: Unexpected character '%c'\n", *(str + pos));
150 printf("ERROR: Unexpected end of string\n");
151 while (len-- && *str) printf("%c", *str++); printf("\n");
152 while (pos--) printf(" "); printf("^\n");
153 /* the front end has to to check constant strings */
158 /** pack machine-like */
159 static void *pack(const fp_value *int_float, void *packed) {
162 fp_value *val_buffer;
165 temp = alloca(value_size);
166 shift_val = alloca(value_size);
168 switch ((value_class_t)int_float->desc.clss) {
170 val_buffer = alloca(calc_buffer_size);
171 fc_get_qnan(&int_float->desc, val_buffer);
172 int_float = val_buffer;
176 val_buffer = alloca(calc_buffer_size);
177 fc_get_plusinf(&int_float->desc, val_buffer);
178 val_buffer->sign = int_float->sign;
179 int_float = val_buffer;
185 /* pack sign: move it to the left after exponent AND mantissa */
186 sc_val_from_ulong(int_float->sign, temp);
188 pos = int_float->desc.exponent_size + int_float->desc.mantissa_size + int_float->desc.explicit_one;
189 sc_val_from_ulong(pos, NULL);
190 _shift_left(temp, sc_get_buffer(), packed);
192 /* pack exponent: move it to the left after mantissa */
193 pos = int_float->desc.mantissa_size + int_float->desc.explicit_one;
194 sc_val_from_ulong(pos, shift_val);
195 _shift_left(_exp(int_float), shift_val, temp);
197 /* combine sign|exponent */
198 sc_or(temp, packed, packed);
200 /* extract mantissa */
201 /* remove rounding bits */
202 sc_val_from_ulong(ROUNDING_BITS, shift_val);
203 _shift_right(_mant(int_float), shift_val, temp);
205 /* remove leading 1 (or 0 if denormalized) */
206 sc_max_from_bits(pos, 0, shift_val); /* all mantissa bits are 1's */
207 sc_and(temp, shift_val, temp);
209 /* combine sign|exponent|mantissa */
210 sc_or(temp, packed, packed);
216 * Normalize a fp_value.
218 * @return non-zero if result is exact
220 static int normalize(const fp_value *in_val, fp_value *out_val, int sticky) {
223 char lsb, guard, round, round_dir = 0;
224 char *temp = alloca(value_size);
226 /* save rounding bits at the end */
227 hsb = ROUNDING_BITS + in_val->desc.mantissa_size - sc_get_highest_set_bit(_mant(in_val)) - 1;
229 if (in_val != out_val) {
230 out_val->sign = in_val->sign;
231 memcpy(&out_val->desc, &in_val->desc, sizeof(out_val->desc));
234 out_val->desc.clss = NORMAL;
236 /* mantissa all zeros, so zero exponent (because of explicit one) */
237 if (hsb == ROUNDING_BITS + in_val->desc.mantissa_size) {
238 sc_val_from_ulong(0, _exp(out_val));
242 /* shift the first 1 into the left of the radix point (i.e. hsb == -1) */
245 sc_val_from_ulong(-hsb-1, temp);
247 _shift_right(_mant(in_val), temp, _mant(out_val));
249 /* remember if some bits were shifted away */
250 if (sc_had_carry()) {
254 sc_add(_exp(in_val), temp, _exp(out_val));
255 } else if (hsb > -1) {
257 sc_val_from_ulong(hsb+1, temp);
259 _shift_left(_mant(in_val), temp, _mant(out_val));
261 sc_sub(_exp(in_val), temp, _exp(out_val));
264 /* check for exponent underflow */
265 if (sc_is_negative(_exp(out_val)) || sc_is_zero(_exp(out_val))) {
266 DEBUGPRINTF(("Exponent underflow!\n"));
267 /* exponent underflow */
268 /* shift the mantissa right to have a zero exponent */
269 sc_val_from_ulong(1, temp);
270 sc_sub(temp, _exp(out_val), NULL);
272 _shift_right(_mant(out_val), sc_get_buffer(), _mant(out_val));
273 if (sc_had_carry()) {
277 /* denormalized means exponent of zero */
278 sc_val_from_ulong(0, _exp(out_val));
280 out_val->desc.clss = SUBNORMAL;
283 /* perform rounding by adding a value that clears the guard bit and the round bit
284 * and either causes a carry to round up or not */
285 /* get the last 3 bits of the value */
286 lsb = sc_sub_bits(_mant(out_val), out_val->desc.mantissa_size + ROUNDING_BITS, 0) & 0x7;
287 guard = (lsb&0x2)>>1;
290 switch (rounding_mode) {
292 /* round to nearest representable value, if in doubt choose the version
294 round_dir = guard && (sticky || round || lsb>>2);
297 /* if positive: round to one if the exact value is bigger, else to zero */
298 round_dir = (!out_val->sign && (guard || round || sticky));
301 /* if negative: round to one if the exact value is bigger, else to zero */
302 round_dir = (out_val->sign && (guard || round || sticky));
305 /* always round to 0 (chopping mode) */
309 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"));
311 if (round_dir == 1) {
312 guard = (round^guard)<<1;
313 lsb = !(round || guard)<<2 | guard | round;
315 lsb = -((guard<<1) | round);
318 /* add the rounded value */
320 sc_val_from_long(lsb, temp);
321 sc_add(_mant(out_val), temp, _mant(out_val));
325 /* could have rounded down to zero */
326 if (sc_is_zero(_mant(out_val)) && (out_val->desc.clss == SUBNORMAL))
327 out_val->desc.clss = ZERO;
329 /* check for rounding overflow */
330 hsb = ROUNDING_BITS + out_val->desc.mantissa_size - sc_get_highest_set_bit(_mant(out_val)) - 1;
331 if ((out_val->desc.clss != SUBNORMAL) && (hsb < -1)) {
332 sc_val_from_ulong(1, temp);
333 _shift_right(_mant(out_val), temp, _mant(out_val));
334 if (exact && sc_had_carry())
336 sc_add(_exp(out_val), temp, _exp(out_val));
337 } else if ((out_val->desc.clss == SUBNORMAL) && (hsb == -1)) {
338 /* overflow caused the mantissa to be normal again,
339 * so adapt the exponent accordingly */
340 sc_val_from_ulong(1, temp);
341 sc_add(_exp(out_val), temp, _exp(out_val));
343 out_val->desc.clss = NORMAL;
345 /* no further rounding is needed, because rounding overflow means
346 * the carry of the original rounding was propagated all the way
347 * up to the bit left of the radix point. This implies the bits
348 * to the right are all zeros (rounding is +1) */
350 /* check for exponent overflow */
351 sc_val_from_ulong((1 << out_val->desc.exponent_size) - 1, temp);
352 if (sc_comp(_exp(out_val), temp) != -1) {
353 DEBUGPRINTF(("Exponent overflow!\n"));
354 /* exponent overflow, reaction depends on rounding method:
356 * mode | sign of value | result
357 *--------------------------------------------------------------
358 * TO_NEAREST | + | +inf
360 *--------------------------------------------------------------
361 * TO_POSITIVE | + | +inf
362 * | - | smallest representable value
363 *--------------------------------------------------------------
364 * TO_NEAGTIVE | + | largest representable value
366 *--------------------------------------------------------------
367 * TO_ZERO | + | largest representable value
368 * | - | smallest representable value
369 *--------------------------------------------------------------*/
370 if (out_val->sign == 0) {
371 /* value is positive */
372 switch (rounding_mode) {
375 out_val->desc.clss = INF;
380 fc_get_max(&out_val->desc, out_val);
383 /* value is negative */
384 switch (rounding_mode) {
387 out_val->desc.clss = INF;
392 fc_get_min(&out_val->desc, out_val);
400 * Operations involving NaN's must return NaN
402 #define handle_NAN(a, b, result) \
404 if (a->desc.clss == NAN) { \
405 if (a != result) memcpy(result, a, calc_buffer_size); \
408 if (b->desc.clss == NAN) { \
409 if (b != result) memcpy(result, b, calc_buffer_size); \
416 * calculate a + b, where a is the value with the bigger exponent
418 static void _fadd(const fp_value *a, const fp_value *b, fp_value *result) {
427 handle_NAN(a, b, result);
429 /* make sure result has a descriptor */
430 if (result != a && result != b)
431 result->desc = a->desc;
433 /* determine if this is an addition or subtraction */
434 sign = a->sign ^ b->sign;
436 /* produce NaN on inf - inf */
437 if (sign && (a->desc.clss == INF) && (b->desc.clss == INF)) {
438 fc_get_qnan(&a->desc, result);
442 temp = alloca(value_size);
443 exp_diff = alloca(value_size);
445 /* get exponent difference */
446 sc_sub(_exp(a), _exp(b), exp_diff);
448 /* initially set sign to be the sign of a, special treatment of subtraction
449 * when exponents are equal is required though.
450 * Also special care about the sign is needed when the mantissas are equal
452 if (sign && sc_val_to_long(exp_diff) == 0) {
453 switch (sc_comp(_mant(a), _mant(b))) {
455 res_sign = a->sign; /* abs(a) is bigger and a is negative */
458 res_sign = (rounding_mode == FC_TONEGATIVE);
461 res_sign = b->sign; /* abs(b) is bigger and b is negative */
464 /* can't be reached */
471 result->sign = res_sign;
473 /* sign has been taken care of, check for special cases */
474 if (a->desc.clss == ZERO || b->desc.clss == INF) {
476 memcpy(result, b, calc_buffer_size);
477 result->sign = res_sign;
480 if (b->desc.clss == ZERO || a->desc.clss == INF) {
482 memcpy(result, a, calc_buffer_size);
483 result->sign = res_sign;
487 /* shift the smaller value to the right to align the radix point */
488 /* subnormals have their radix point shifted to the right,
489 * take care of this first */
490 if ((b->desc.clss == SUBNORMAL) && (a->desc.clss != SUBNORMAL)) {
491 sc_val_from_ulong(1, temp);
492 sc_sub(exp_diff, temp, exp_diff);
495 _shift_right(_mant(b), exp_diff, temp);
496 sticky = sc_had_carry();
499 if (sticky && sign) {
500 /* if subtracting a little more than the represented value or adding a little
501 * more than the represented value to a negative value this, in addition to the
502 * still set sticky bit, takes account of the 'little more' */
503 char *temp1 = alloca(calc_buffer_size);
504 sc_val_from_ulong(1, temp1);
505 sc_add(temp, temp1, temp);
509 if (sc_comp(_mant(a), temp) == -1)
510 sc_sub(temp, _mant(a), _mant(result));
512 sc_sub(_mant(a), temp, _mant(result));
514 sc_add(_mant(a), temp, _mant(result));
517 /* _normalize expects a 'normal' radix point, adding two subnormals
518 * results in a subnormal radix point -> shifting before normalizing */
519 if ((a->desc.clss == SUBNORMAL) && (b->desc.clss == SUBNORMAL)) {
520 sc_val_from_ulong(1, NULL);
521 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
524 /* resulting exponent is the bigger one */
525 memmove(_exp(result), _exp(a), value_size);
527 fc_exact &= normalize(result, result, sticky);
533 static void _fmul(const fp_value *a, const fp_value *b, fp_value *result) {
540 handle_NAN(a, b, result);
542 temp = alloca(value_size);
544 if (result != a && result != b)
545 result->desc = a->desc;
547 result->sign = res_sign = a->sign ^ b->sign;
549 /* produce NaN on 0 * inf */
550 if (a->desc.clss == ZERO) {
551 if (b->desc.clss == INF)
552 fc_get_qnan(&a->desc, result);
555 memcpy(result, a, calc_buffer_size);
556 result->sign = res_sign;
560 if (b->desc.clss == ZERO) {
561 if (a->desc.clss == INF)
562 fc_get_qnan(&a->desc, result);
565 memcpy(result, b, calc_buffer_size);
566 result->sign = res_sign;
571 if (a->desc.clss == INF) {
573 memcpy(result, a, calc_buffer_size);
574 result->sign = res_sign;
577 if (b->desc.clss == INF) {
579 memcpy(result, b, calc_buffer_size);
580 result->sign = res_sign;
584 /* exp = exp(a) + exp(b) - excess */
585 sc_add(_exp(a), _exp(b), _exp(result));
587 sc_val_from_ulong((1 << (a->desc.exponent_size - 1)) - 1, temp);
588 sc_sub(_exp(result), temp, _exp(result));
590 /* mixed normal, subnormal values introduce an error of 1, correct it */
591 if ((a->desc.clss == SUBNORMAL) ^ (b->desc.clss == SUBNORMAL)) {
592 sc_val_from_ulong(1, temp);
593 sc_add(_exp(result), temp, _exp(result));
596 sc_mul(_mant(a), _mant(b), _mant(result));
598 /* realign result: after a multiplication the digits right of the radix
599 * point are the sum of the factors' digits after the radix point. As all
600 * values are normalized they both have the same amount of these digits,
601 * which has to be restored by proper shifting
602 * because of the rounding bits */
603 sc_val_from_ulong(ROUNDING_BITS + result->desc.mantissa_size, temp);
605 _shift_right(_mant(result), temp, _mant(result));
606 sticky = sc_had_carry();
609 fc_exact &= normalize(result, result, sticky);
615 static void _fdiv(const fp_value *a, const fp_value *b, fp_value *result) {
617 char *temp, *dividend;
622 handle_NAN(a, b, result);
624 temp = alloca(value_size);
625 dividend = alloca(value_size);
627 if (result != a && result != b)
628 result->desc = a->desc;
630 result->sign = res_sign = a->sign ^ b->sign;
632 /* produce NAN on 0/0 and inf/inf */
633 if (a->desc.clss == ZERO) {
634 if (b->desc.clss == ZERO)
636 fc_get_qnan(&a->desc, result);
640 memcpy(result, a, calc_buffer_size);
641 result->sign = res_sign;
646 if (b->desc.clss == INF) {
647 if (a->desc.clss == INF)
649 fc_get_qnan(&a->desc, result);
652 sc_val_from_ulong(0, NULL);
653 _save_result(_exp(result));
654 _save_result(_mant(result));
655 result->desc.clss = ZERO;
660 if (a->desc.clss == INF) {
663 memcpy(result, a, calc_buffer_size);
664 result->sign = res_sign;
667 if (b->desc.clss == ZERO) {
668 /* division by zero */
670 fc_get_minusinf(&a->desc, result);
672 fc_get_plusinf(&a->desc, result);
676 /* exp = exp(a) - exp(b) + excess - 1*/
677 sc_sub(_exp(a), _exp(b), _exp(result));
678 sc_val_from_ulong((1 << (a->desc.exponent_size - 1)) - 2, temp);
679 sc_add(_exp(result), temp, _exp(result));
681 /* mixed normal, subnormal values introduce an error of 1, correct it */
682 if ((a->desc.clss == SUBNORMAL) ^ (b->desc.clss == SUBNORMAL)) {
683 sc_val_from_ulong(1, temp);
684 sc_add(_exp(result), temp, _exp(result));
687 /* mant(res) = mant(a) / 1/2mant(b) */
688 /* to gain more bits of precision in the result the dividend could be
689 * shifted left, as this operation does not loose bits. This would not
690 * fit into the integer precision, but due to the rounding bits (which
691 * are always zero because the values are all normalized) the divisor
692 * can be shifted right instead to achieve the same result */
693 sc_val_from_ulong(ROUNDING_BITS + result->desc.mantissa_size, temp);
695 _shift_left(_mant(a), temp, dividend);
698 char *divisor = alloca(calc_buffer_size);
699 sc_val_from_ulong(1, divisor);
700 _shift_right(_mant(b), divisor, divisor);
701 sc_div(dividend, divisor, _mant(result));
702 sticky = sc_had_carry();
706 fc_exact &= normalize(result, result, sticky);
710 static void _power_of_ten(int exp, ieee_descriptor_t *desc, char *result) {
717 /* set new descriptor (else result is supposed to already have one) */
719 result->desc = *desc;
721 build = alloca(value_size);
722 temp = alloca(value_size);
724 sc_val_from_ulong((1 << (result->desc.exponent_size - 1)) - 1, _exp(result));
727 /* temp is value of ten now */
728 sc_val_from_ulong(10, NULL);
731 for (exp--; exp > 0; exp--) {
733 sc_mul(build, temp, NULL);
737 /* temp is amount of left shift needed to put the value left of the radix point */
738 sc_val_from_ulong(result->desc.mantissa_size + ROUNDING_BITS, temp);
740 _shift_left(build, temp, _mant(result));
742 _normalize(result, result, 0);
748 * Truncate the fractional part away.
750 * This does not clip to any integer range.
752 static void _trunc(const fp_value *a, fp_value *result) {
754 * When exponent == 0 all bits left of the radix point
755 * are the integral part of the value. For 15bit exp_size
756 * this would require a left shift of max. 16383 bits which
758 * But it is enough to ensure that no bit right of the radix
759 * point remains set. This restricts the interesting
760 * exponents to the interval [0, mant_size-1].
761 * Outside this interval the truncated value is either 0 or
762 * it does not have fractional parts.
765 int exp_bias, exp_val;
768 /* fixme: can be exact */
771 temp = alloca(value_size);
774 result->desc = a->desc;
776 exp_bias = (1 << (a->desc.exponent_size - 1)) - 1;
777 exp_val = sc_val_to_long(_exp(a)) - exp_bias;
780 sc_val_from_ulong(0, NULL);
781 _save_result(_exp(result));
782 _save_result(_mant(result));
783 result->desc.clss = ZERO;
788 if (exp_val > a->desc.mantissa_size) {
790 memcpy(result, a, calc_buffer_size);
795 /* set up a proper mask to delete all bits right of the
796 * radix point if the mantissa had been shifted until exp == 0 */
797 sc_max_from_bits(1 + exp_val, 0, temp);
798 sc_val_from_long(a->desc.mantissa_size - exp_val + 2, NULL);
799 _shift_left(temp, sc_get_buffer(), temp);
801 /* and the mask and return the result */
802 sc_and(_mant(a), temp, _mant(result));
804 if (a != result) memcpy(_exp(result), _exp(a), value_size);
808 * functions defined in fltcalc.h
810 const void *fc_get_buffer(void) {
814 int fc_get_buffer_length(void) {
815 return calc_buffer_size;
818 void *fc_val_from_str(const char *str, unsigned int len, const ieee_descriptor_t *desc, void *result) {
830 int exp_int, hsb, state;
835 char *mant_str, *exp_val, *power_val;
838 if (result == NULL) result = calc_buffer;
840 exp_val = alloca(value_size);
841 power_val = alloca(calc_buffer_size);
842 mant_str = alloca((len)?(len):(strlen(str)));
844 result->desc.exponent_size = desc->exponent_size;
845 result->desc.mantissa_size = desc->mantissa_size;
846 result->desc.explicit_one = desc->explicit_one;
847 result->desc.clss = NORMAL;
854 while (len == 0 || str-old_str < len) {
870 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
877 state = RIGHT_OF_DOT;
888 fail_char(old_str, len, str - old_str);
894 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
895 mant_str[pos++] = *(str++);
899 state = RIGHT_OF_DOT;
910 mant_str[pos] = '\0';
914 fail_char(old_str, len, str - old_str);
920 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
921 mant_str[pos++] = *(str++);
932 mant_str[pos] = '\0';
936 fail_char(old_str, len, str - old_str);
946 if (*(str-1) != 'e' && *(str-1) != 'E') fail_char(old_str, len, str - old_str);
950 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
951 mant_str[pos] = '\0';
958 fail_char(old_str, len, str - old_str);
964 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
969 case '\0': goto done;
972 fail_char(old_str, len, str - old_str);
975 } /* switch(state) */
978 sc_val_from_str(mant_str, strlen(mant_str), _mant(result));
980 /* shift to put value left of radix point */
981 sc_val_from_ulong(mant_size + ROUNDING_BITS, exp_val);
983 _shift_left(_mant(result), exp_val, _mant(result));
985 sc_val_from_ulong((1 << (exp_size - 1)) - 1, _exp(result));
987 _normalize(result, result, 0);
989 if (state == EXPONENT) {
990 exp_int -= atoi(str-pos);
993 _power_of_ten(exp_int, &result->desc, power_val);
995 _fdiv(result, power_val, result);
999 /* XXX excuse of an implementation to make things work */
1001 fp_value *tmp = alloca(calc_buffer_size);
1002 ieee_descriptor_t tmp_desc;
1005 #ifdef HAVE_LONG_DOUBLE
1006 val = strtold(str, NULL);
1007 DEBUGPRINTF(("val_from_str(%s)\n", str));
1008 tmp_desc.exponent_size = 15;
1009 tmp_desc.mantissa_size = 63;
1010 tmp_desc.explicit_one = 1;
1011 tmp_desc.clss = NORMAL;
1012 fc_val_from_ieee754(val, &tmp_desc, tmp);
1014 val = strtod(str, NULL);
1015 DEBUGPRINTF(("val_from_str(%s)\n", str));
1016 tmp_desc.exponent_size = 11;
1017 tmp_desc.mantissa_size = 52;
1018 tmp_desc.explicit_one = 0;
1019 tmp_desc.clss = NORMAL;
1020 fc_val_from_ieee754(val, &tmp_desc, tmp);
1021 #endif /* HAVE_LONG_DOUBLE */
1022 return fc_cast(tmp, desc, result);
1026 fp_value *fc_val_from_ieee754(LLDBL l, const ieee_descriptor_t *desc, fp_value *result) {
1028 int bias_res, bias_val, mant_val;
1030 UINT32 sign, exponent, mantissa0, mantissa1;
1033 bias_res = ((1 << (desc->exponent_size - 1)) - 1);
1035 #ifdef HAVE_LONG_DOUBLE
1038 sign = (srcval.val.high & 0x00008000) != 0;
1039 exponent = (srcval.val.high & 0x00007FFF) ;
1040 mantissa0 = srcval.val.mid;
1041 mantissa1 = srcval.val.low;
1042 #else /* no long double */
1045 sign = (srcval.val.high & 0x80000000) != 0;
1046 exponent = (srcval.val.high & 0x7FF00000) >> 20;
1047 mantissa0 = srcval.val.high & 0x000FFFFF;
1048 mantissa1 = srcval.val.low;
1051 #ifdef HAVE_LONG_DOUBLE
1052 TRACEPRINTF(("val_from_float(%.8X%.8X%.8X)\n", ((int*)&l)[2], ((int*)&l)[1], ((int*)&l)[0]));/* srcval.val.high, srcval.val.mid, srcval.val.low)); */
1053 DEBUGPRINTF(("(%d-%.4X-%.8X%.8X)\n", sign, exponent, mantissa0, mantissa1));
1055 TRACEPRINTF(("val_from_float(%.8X%.8X)\n", srcval.val.high, srcval.val.low));
1056 DEBUGPRINTF(("(%d-%.3X-%.5X%.8X)\n", sign, exponent, mantissa0, mantissa1));
1059 if (result == NULL) result = calc_buffer;
1060 temp = alloca(value_size);
1062 /* CLEAR the buffer, else some bits might be uninitialized */
1063 memset(result, 0, fc_get_buffer_length());
1065 result->desc.exponent_size = desc->exponent_size;
1066 result->desc.mantissa_size = desc->mantissa_size;
1067 result->desc.explicit_one = desc->explicit_one;
1070 result->sign = sign;
1072 /* sign and flag suffice to identify NaN or inf, no exponent/mantissa
1073 * encoding is needed. the function can return immediately in these cases */
1075 result->desc.clss = NAN;
1076 TRACEPRINTF(("val_from_float resulted in NAN\n"));
1079 else if (isinf(l)) {
1080 result->desc.clss = INF;
1081 TRACEPRINTF(("val_from_float resulted in %sINF\n", (result->sign == 1) ? "-" : ""));
1085 /* build exponent, because input and output exponent and mantissa sizes may differ
1086 * this looks more complicated than it is: unbiased input exponent + output bias,
1087 * minus the mantissa difference which is added again later when the output float
1088 * becomes normalized */
1089 sc_val_from_long((exponent - bias_val + bias_res) - (mant_val - desc->mantissa_size), _exp(result));
1091 /* build mantissa representation */
1092 if (exponent != 0) {
1093 /* insert the hidden bit */
1094 sc_val_from_ulong(1, temp);
1095 sc_val_from_ulong(mant_val + ROUNDING_BITS, NULL);
1096 _shift_left(temp, sc_get_buffer(), NULL);
1099 sc_val_from_ulong(0, NULL);
1102 _save_result(_mant(result));
1104 /* bits from the upper word */
1105 sc_val_from_ulong(mantissa0, temp);
1106 sc_val_from_ulong(34, NULL);
1107 _shift_left(temp, sc_get_buffer(), temp);
1108 sc_or(_mant(result), temp, _mant(result));
1110 /* bits from the lower word */
1111 sc_val_from_ulong(mantissa1, temp);
1112 sc_val_from_ulong(ROUNDING_BITS, NULL);
1113 _shift_left(temp, sc_get_buffer(), temp);
1114 sc_or(_mant(result), temp, _mant(result));
1116 /* _normalize expects the radix point to be normal, so shift mantissa of subnormal
1117 * origin one to the left */
1118 if (exponent == 0) {
1119 sc_val_from_ulong(1, NULL);
1120 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1123 normalize(result, result, 0);
1125 TRACEPRINTF(("val_from_float results in %s\n", fc_print(result, temp, calc_buffer_size, FC_PACKED)));
1130 LLDBL fc_val_to_ieee754(const fp_value *val) {
1132 fp_value *temp = NULL;
1142 ieee_descriptor_t desc;
1144 #ifdef HAVE_LONG_DOUBLE
1145 desc.exponent_size = 15;
1146 desc.mantissa_size = 63;
1147 desc.explicit_one = 1;
1150 desc.exponent_size = 11;
1151 desc.mantissa_size = 52;
1152 desc.explicit_one = 0;
1156 temp = alloca(calc_buffer_size);
1157 value = fc_cast(val, &desc, temp);
1161 /* @@@ long double exponent is 15bit, so the use of sc_val_to_long should not
1162 * lead to wrong results */
1163 exponent = sc_val_to_long(_exp(value)) ;
1165 sc_val_from_ulong(ROUNDING_BITS, NULL);
1166 _shift_right(_mant(value), sc_get_buffer(), _mant(value));
1171 for (byte_offset = 0; byte_offset < 4; byte_offset++)
1172 mantissa1 |= sc_sub_bits(_mant(value), desc.mantissa_size, byte_offset) << (byte_offset<<3);
1174 for (; (byte_offset<<3) < desc.mantissa_size; byte_offset++)
1175 mantissa0 |= sc_sub_bits(_mant(value), desc.mantissa_size, byte_offset) << ((byte_offset-4)<<3);
1177 #ifdef HAVE_LONG_DOUBLE
1178 buildval.val.high = sign << 15;
1179 buildval.val.high |= exponent;
1180 buildval.val.mid = mantissa0;
1181 buildval.val.low = mantissa1;
1182 #else /* no long double */
1183 mantissa0 &= 0x000FFFFF; /* get rid of garbage */
1184 buildval.val.high = sign << 31;
1185 buildval.val.high |= exponent << 20;
1186 buildval.val.high |= mantissa0;
1187 buildval.val.low = mantissa1;
1190 TRACEPRINTF(("val_to_float: %d-%x-%x%x\n", sign, exponent, mantissa0, mantissa1));
1194 fp_value *fc_cast(const fp_value *value, const ieee_descriptor_t *desc, fp_value *result) {
1196 int exp_offset, val_bias, res_bias;
1198 if (result == NULL) result = calc_buffer;
1199 temp = alloca(value_size);
1201 if (value->desc.exponent_size == desc->exponent_size &&
1202 value->desc.mantissa_size == desc->mantissa_size &&
1203 value->desc.explicit_one == desc->explicit_one) {
1204 if (value != result)
1205 memcpy(result, value, calc_buffer_size);
1209 if (value->desc.clss == NAN) {
1210 if (sc_get_highest_set_bit(_mant(value)) == value->desc.mantissa_size + 1)
1211 return fc_get_qnan(desc, result);
1213 return fc_get_snan(desc, result);
1216 /* set the descriptor of the new value */
1217 result->desc.exponent_size = desc->exponent_size;
1218 result->desc.mantissa_size = desc->mantissa_size;
1219 result->desc.explicit_one = desc->explicit_one;
1220 result->desc.clss = value->desc.clss;
1222 result->sign = value->sign;
1224 /* when the mantissa sizes differ normalizing has to shift to align it.
1225 * this would change the exponent, which is unwanted. So calculate this
1226 * offset and add it */
1227 val_bias = (1 << (value->desc.exponent_size - 1)) - 1;
1228 res_bias = (1 << (desc->exponent_size - 1)) - 1;
1230 exp_offset = (res_bias - val_bias) - (value->desc.mantissa_size - desc->mantissa_size);
1231 sc_val_from_long(exp_offset, temp);
1232 sc_add(_exp(value), temp, _exp(result));
1234 /* _normalize expects normalized radix point */
1235 if (value->desc.clss == SUBNORMAL) {
1236 sc_val_from_ulong(1, NULL);
1237 _shift_left(_mant(value), sc_get_buffer(), _mant(result));
1238 } else if (value != result) {
1239 memcpy(_mant(result), _mant(value), value_size);
1241 memmove(_mant(result), _mant(value), value_size);
1244 normalize(result, result, 0);
1245 TRACEPRINTF(("Cast results in %s\n", fc_print(result, temp, value_size, FC_PACKED)));
1249 fp_value *fc_get_max(const ieee_descriptor_t *desc, fp_value *result) {
1250 if (result == NULL) result = calc_buffer;
1252 result->desc.exponent_size = desc->exponent_size;
1253 result->desc.mantissa_size = desc->mantissa_size;
1254 result->desc.explicit_one = desc->explicit_one;
1255 result->desc.clss = NORMAL;
1259 sc_val_from_ulong((1 << desc->exponent_size) - 2, _exp(result));
1261 sc_max_from_bits(desc->mantissa_size + 1, 0, _mant(result));
1262 sc_val_from_ulong(ROUNDING_BITS, NULL);
1263 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1268 fp_value *fc_get_min(const ieee_descriptor_t *desc, fp_value *result) {
1269 if (result == NULL) result = calc_buffer;
1271 fc_get_max(desc, result);
1277 fp_value *fc_get_snan(const ieee_descriptor_t *desc, fp_value *result) {
1278 if (result == NULL) result = calc_buffer;
1280 result->desc.exponent_size = desc->exponent_size;
1281 result->desc.mantissa_size = desc->mantissa_size;
1282 result->desc.explicit_one = desc->explicit_one;
1283 result->desc.clss = NAN;
1287 sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1289 /* signaling NaN has non-zero mantissa with msb not set */
1290 sc_val_from_ulong(1, _mant(result));
1295 fp_value *fc_get_qnan(const ieee_descriptor_t *desc, fp_value *result) {
1296 if (result == NULL) result = calc_buffer;
1298 result->desc.exponent_size = desc->exponent_size;
1299 result->desc.mantissa_size = desc->mantissa_size;
1300 result->desc.explicit_one = desc->explicit_one;
1301 result->desc.clss = NAN;
1305 sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1307 /* quiet NaN has the msb of the mantissa set, so shift one there */
1308 sc_val_from_ulong(1, _mant(result));
1309 /* mantissa_size >+< 1 because of two extra rounding bits */
1310 sc_val_from_ulong(desc->mantissa_size + 1, NULL);
1311 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1316 fp_value *fc_get_plusinf(const ieee_descriptor_t *desc, fp_value *result) {
1317 if (result == NULL) result = calc_buffer;
1319 result->desc.exponent_size = desc->exponent_size;
1320 result->desc.mantissa_size = desc->mantissa_size;
1321 result->desc.explicit_one = desc->explicit_one;
1322 result->desc.clss = NORMAL;
1326 sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1328 sc_val_from_ulong(0, _mant(result));
1333 fp_value *fc_get_minusinf(const ieee_descriptor_t *desc, fp_value *result) {
1334 if (result == NULL) result = calc_buffer;
1336 fc_get_plusinf(desc, result);
1342 int fc_comp(const fp_value *val_a, const fp_value *val_b) {
1346 * shortcut: if both values are identical, they are either
1347 * Unordered if NaN or equal
1350 return val_a->desc.clss == NAN ? 2 : 0;
1352 /* unordered if one is a NaN */
1353 if (val_a->desc.clss == NAN || val_b->desc.clss == NAN)
1356 /* zero is equal independent of sign */
1357 if ((val_a->desc.clss == ZERO) && (val_b->desc.clss == ZERO))
1360 /* different signs make compare easy */
1361 if (val_a->sign != val_b->sign)
1362 return (val_a->sign == 0) ? (1) : (-1);
1364 mul = val_a->sign ? -1 : 1;
1366 /* both infinity means equality */
1367 if ((val_a->desc.clss == INF) && (val_b->desc.clss == INF))
1370 /* infinity is bigger than the rest */
1371 if (val_a->desc.clss == INF)
1373 if (val_b->desc.clss == INF)
1376 /* check first exponent, that mantissa if equal */
1377 switch (sc_comp(_exp(val_a), _exp(val_b))) {
1383 return sc_comp(_mant(val_a), _mant(val_b)) * mul;
1389 int fc_is_zero(const fp_value *a) {
1390 return a->desc.clss == ZERO;
1393 int fc_is_negative(const fp_value *a) {
1397 int fc_is_inf(const fp_value *a) {
1398 return a->desc.clss == INF;
1401 int fc_is_nan(const fp_value *a) {
1402 return a->desc.clss == NAN;
1405 int fc_is_subnormal(const fp_value *a) {
1406 return a->desc.clss == SUBNORMAL;
1409 char *fc_print(const fp_value *val, char *buf, int buflen, unsigned base) {
1412 mul_1 = alloca(calc_buffer_size);
1416 switch ((value_class_t)val->desc.clss) {
1418 if (buflen >= 8 + val->sign) sprintf(buf, "%sINFINITY", val->sign ? "-":"");
1419 else snprintf(buf, buflen, "%sINF", val->sign ? "-":NULL);
1422 snprintf(buf, buflen, "NAN");
1425 snprintf(buf, buflen, "0.0");
1428 /* XXX to be implemented */
1429 #ifdef HAVE_LONG_DOUBLE
1430 /* XXX 30 is arbitrary */
1431 snprintf(buf, buflen, "%.30LE", fc_val_to_ieee754(val));
1433 snprintf(buf, buflen, "%.18E", fc_val_to_ieee754(val));
1439 switch ((value_class_t)val->desc.clss) {
1441 if (buflen >= 8+val->sign) sprintf(buf, "%sINFINITY", val->sign?"-":"");
1442 else snprintf(buf, buflen, "%sINF", val->sign?"-":NULL);
1445 snprintf(buf, buflen, "NAN");
1448 snprintf(buf, buflen, "0.0");
1451 #ifdef HAVE_LONG_DOUBLE
1452 snprintf(buf, buflen, "%LA", fc_val_to_ieee754(val));
1454 snprintf(buf, buflen, "%A", fc_val_to_ieee754(val));
1461 snprintf(buf, buflen, "%s", sc_print(pack(val, mul_1), value_size*4, SC_HEX, 0));
1462 buf[buflen - 1] = '\0';
1468 unsigned char fc_sub_bits(const fp_value *value, unsigned num_bits, unsigned byte_ofs) {
1469 /* this is used to cache the packed version of the value */
1470 static char *packed_value = NULL;
1472 if (packed_value == NULL) packed_value = xmalloc(value_size);
1475 pack(value, packed_value);
1477 return sc_sub_bits(packed_value, num_bits, byte_ofs);
1480 /* Returns non-zero if the mantissa is zero, i.e. 1.0Exxx */
1481 int fc_zero_mantissa(const fp_value *value) {
1482 return sc_get_lowest_set_bit(_mant(value)) == ROUNDING_BITS + value->desc.mantissa_size;
1485 /* Returns the exponent of a value. */
1486 int fc_get_exponent(const fp_value *value) {
1487 int exp_bias = (1 << (value->desc.exponent_size - 1)) - 1;
1488 return sc_val_to_long(_exp(value)) - exp_bias;
1491 /* Return non-zero if a given value can be converted lossless into another precision */
1492 int fc_can_lossless_conv_to(const fp_value *value, char exp_size, char mant_size) {
1496 /* handle some special cases first */
1497 switch (value->desc.clss) {
1506 /* check if the exponent can be encoded: note, 0 and all ones are reserved for the exponent */
1507 exp_bias = (1 << (exp_size - 1)) - 1;
1508 v = fc_get_exponent(value) + exp_bias;
1509 if (0 < v && v < (1 << exp_size) - 1) {
1510 /* check the mantissa */
1511 v = value->desc.mantissa_size + ROUNDING_BITS - sc_get_lowest_set_bit(_mant(value));
1512 return v < mant_size;
1518 fc_rounding_mode_t fc_set_rounding_mode(fc_rounding_mode_t mode) {
1519 if (mode == FC_TONEAREST || mode == FC_TOPOSITIVE || mode == FC_TONEGATIVE || mode == FC_TOZERO)
1520 rounding_mode = mode;
1522 return rounding_mode;
1525 fc_rounding_mode_t fc_get_rounding_mode(void) {
1526 return rounding_mode;
1529 void init_fltcalc(int precision) {
1530 if (calc_buffer == NULL) {
1531 /* does nothing if already init */
1532 if (precision == 0) precision = FC_DEFAULT_PRECISION;
1534 init_strcalc(precision + 4);
1536 /* needs additionally two bits to round, a bit as explicit 1., and one for
1537 * addition overflow */
1538 max_precision = sc_get_precision() - 4;
1539 if (max_precision < precision)
1540 printf("WARNING: not enough precision available, using %d\n", max_precision);
1542 rounding_mode = FC_TONEAREST;
1543 value_size = sc_get_buffer_length();
1544 calc_buffer_size = sizeof(fp_value) + 2*value_size - 1;
1546 calc_buffer = xmalloc(calc_buffer_size);
1547 memset(calc_buffer, 0, calc_buffer_size);
1548 DEBUGPRINTF(("init fltcalc:\n\tVALUE_SIZE = %d\ntCALC_BUFFER_SIZE = %d\n\tcalc_buffer = %p\n\n", value_size, calc_buffer_size, calc_buffer));
1549 #ifdef HAVE_LONG_DOUBLE
1550 DEBUGPRINTF(("\tUsing long double (1-15-64) interface\n"));
1552 DEBUGPRINTF(("\tUsing double (1-11-52) interface\n"));
1554 #ifdef WORDS_BIGENDIAN
1555 DEBUGPRINTF(("\tWord order is big endian\n\n"));
1557 DEBUGPRINTF(("\tWord order is little endian\n\n"));
1562 void finish_fltcalc (void) {
1563 free(calc_buffer); calc_buffer = NULL;
1566 #ifdef FLTCALC_TRACE_CALC
1567 static char buffer[100];
1570 /* definition of interface functions */
1571 fp_value *fc_add(const fp_value *a, const fp_value *b, fp_value *result) {
1572 if (result == NULL) result = calc_buffer;
1574 TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1575 TRACEPRINTF(("+ %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1577 /* make the value with the bigger exponent the first one */
1578 if (sc_comp(_exp(a), _exp(b)) == -1)
1579 _fadd(b, a, result);
1581 _fadd(a, b, result);
1583 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1587 fp_value *fc_sub(const fp_value *a, const fp_value *b, fp_value *result) {
1590 if (result == NULL) result = calc_buffer;
1592 TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1593 TRACEPRINTF(("- %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1595 temp = alloca(calc_buffer_size);
1596 memcpy(temp, b, calc_buffer_size);
1597 temp->sign = !b->sign;
1598 if (sc_comp(_exp(a), _exp(temp)) == -1)
1599 _fadd(temp, a, result);
1601 _fadd(a, temp, result);
1603 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1607 fp_value *fc_mul(const fp_value *a, const fp_value *b, fp_value *result) {
1608 if (result == NULL) result = calc_buffer;
1610 TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1611 TRACEPRINTF(("* %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1613 _fmul(a, b, result);
1615 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1619 fp_value *fc_div(const fp_value *a, const fp_value *b, fp_value *result) {
1620 if (result == NULL) result = calc_buffer;
1622 TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1623 TRACEPRINTF(("/ %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1625 _fdiv(a, b, result);
1627 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1631 fp_value *fc_neg(const fp_value *a, fp_value *result) {
1632 if (result == NULL) result = calc_buffer;
1634 TRACEPRINTF(("- %s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1637 memcpy(result, a, calc_buffer_size);
1638 result->sign = !a->sign;
1640 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1644 fp_value *fc_int(const fp_value *a, fp_value *result) {
1645 if (result == NULL) result = calc_buffer;
1647 TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1648 TRACEPRINTF(("truncated to integer "));
1652 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1656 fp_value *fc_rnd(const fp_value *a, fp_value *result) {
1657 if (result == NULL) result = calc_buffer;
1660 TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1661 TRACEPRINTF(("rounded to integer "));
1663 assert(!"fc_rnd() not yet implemented");
1665 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1670 * convert a floating point value into an sc value ...
1672 int fc_flt2int(const fp_value *a, void *result, ir_mode *dst_mode) {
1673 if (a->desc.clss == NORMAL) {
1674 int exp_bias = (1 << (a->desc.exponent_size - 1)) - 1;
1675 int exp_val = sc_val_to_long(_exp(a)) - exp_bias;
1678 if (a->sign && !mode_is_signed(dst_mode)) {
1679 /* FIXME: for now we cannot convert this */
1683 assert(exp_val >= 0 && "floating point value not integral before fc_flt2int() call");
1684 shift = exp_val - (a->desc.mantissa_size + ROUNDING_BITS);
1687 sc_shlI(_mant(a), shift, 64, 0, result);
1689 sc_shrI(_mant(a), -shift, 64, 0, result);
1692 /* check for overflow */
1693 highest = sc_get_highest_set_bit(result);
1695 if (mode_is_signed(dst_mode)) {
1696 if (highest == sc_get_lowest_set_bit(result)) {
1697 /* need extra test for MIN_INT */
1698 if (highest >= (int) get_mode_size_bits(dst_mode)) {
1699 /* FIXME: handle overflow */
1703 if (highest >= (int) get_mode_size_bits(dst_mode) - 1) {
1704 /* FIXME: handle overflow */
1709 if (highest >= (int) get_mode_size_bits(dst_mode)) {
1710 /* FIXME: handle overflow */
1716 sc_neg(result, result);
1720 else if (a->desc.clss == ZERO) {
1728 unsigned fc_set_immediate_precision(unsigned bits) {
1729 unsigned old = immediate_prec;
1731 immediate_prec = bits;
1735 int fc_is_exact(void) {