2 * Copyright (C) 1995-2007 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 typedef uint32_t UINT32;
57 #ifdef HAVE_LONG_DOUBLE
58 #ifdef WORDS_BIGENDIAN
65 volatile long double d;
74 volatile long double d;
78 #ifdef WORDS_BIGENDIAN
98 * possible float states
101 NORMAL, /**< normal representation, implicit 1 */
103 SUBNORMAL, /**< denormals, implicit 0 */
105 NAN, /**< Not A Number */
108 /** A descriptor for an IEEE float value. */
110 unsigned char exponent_size; /**< size of exponent in bits */
111 unsigned char mantissa_size; /**< size of mantissa in bits */
112 value_class_t clss; /**< state of this float */
115 #define CLEAR_BUFFER(buffer) memset(buffer, 0, calc_buffer_size)
117 /* our floating point value */
121 char value[1]; /* exp[value_size] + mant[value_size] */
124 #define _exp(a) &((a)->value[0])
125 #define _mant(a) &((a)->value[value_size])
127 #define _save_result(x) memcpy((x), sc_get_buffer(), value_size)
128 #define _shift_right(x, y, b) sc_shr((x), (y), value_size*4, 0, (b))
129 #define _shift_left(x, y, b) sc_shl((x), (y), value_size*4, 0, (b))
133 # define DEBUGPRINTF(x) printf x
135 # define DEBUGPRINTF(x) ((void)0)
138 #ifdef FLTCALC_TRACE_CALC
139 # define TRACEPRINTF(x) printf x
141 # define TRACEPRINTF(x) ((void)0)
144 /** The immediate precision. */
145 static unsigned immediate_prec = 0;
147 /** A temporal buffer. */
148 static fp_value *calc_buffer = NULL;
150 /** Current rounding mode.*/
151 static fc_rounding_mode_t rounding_mode;
153 static int calc_buffer_size;
154 static int value_size;
155 static int max_precision;
158 static void fail_char(const char *str, unsigned int len, int pos) {
160 printf("ERROR: Unexpected character '%c'\n", *(str + pos));
162 printf("ERROR: Unexpected end of string\n");
163 while (len-- && *str) printf("%c", *str++); printf("\n");
164 while (pos--) printf(" "); printf("^\n");
165 /* the front end has to to check constant strings */
170 /** pack machine-like */
171 static void *pack(const fp_value *int_float, void *packed) {
174 fp_value *val_buffer;
176 temp = alloca(value_size);
177 shift_val = alloca(value_size);
179 switch (int_float->desc.clss) {
181 val_buffer = alloca(calc_buffer_size);
182 fc_get_qnan(int_float->desc.exponent_size, int_float->desc.mantissa_size, val_buffer);
183 int_float = val_buffer;
187 val_buffer = alloca(calc_buffer_size);
188 fc_get_plusinf(int_float->desc.exponent_size, int_float->desc.mantissa_size, val_buffer);
189 val_buffer->sign = int_float->sign;
190 int_float = val_buffer;
197 sc_val_from_ulong(int_float->sign, temp);
199 sc_val_from_ulong(int_float->desc.exponent_size + int_float->desc.mantissa_size, NULL);
200 _shift_left(temp, sc_get_buffer(), packed);
202 /* extract exponent */
203 sc_val_from_ulong(int_float->desc.mantissa_size, shift_val);
205 _shift_left(_exp(int_float), shift_val, temp);
207 sc_or(temp, packed, packed);
209 /* extract mantissa */
210 /* remove 2 rounding bits */
211 sc_val_from_ulong(2, shift_val);
212 _shift_right(_mant(int_float), shift_val, temp);
214 /* remove leading 1 (or 0 if denormalized) */
215 sc_max_from_bits(int_float->desc.mantissa_size, 0, shift_val); /* all mantissa bits are 1's */
216 sc_and(temp, shift_val, temp);
219 sc_or(temp, packed, packed);
224 static void normalize(const fp_value *in_val, fp_value *out_val, int sticky) {
226 char lsb, guard, round, round_dir = 0;
227 char *temp = alloca(value_size);
229 /* +2: save two rounding bits at the end */
230 hsb = 2 + in_val->desc.mantissa_size - sc_get_highest_set_bit(_mant(in_val)) - 1;
232 if (in_val != out_val) {
233 out_val->sign = in_val->sign;
234 memcpy(&out_val->desc, &in_val->desc, sizeof(out_val->desc));
237 out_val->desc.clss = NORMAL;
239 /* mantissa all zeros, so zero exponent (because of explicit one)*/
240 if (hsb == 2 + in_val->desc.mantissa_size) {
241 sc_val_from_ulong(0, _exp(out_val));
245 /* shift the first 1 into the left of the radix point (i.e. hsb == -1) */
248 sc_val_from_ulong(-hsb-1, temp);
250 _shift_right(_mant(in_val), temp, _mant(out_val));
252 /* remember if some bits were shifted away */
253 if (!sticky) sticky = sc_had_carry();
255 sc_add(_exp(in_val), temp, _exp(out_val));
256 } else if (hsb > -1) {
258 sc_val_from_ulong(hsb+1, temp);
260 _shift_left(_mant(in_val), temp, _mant(out_val));
262 sc_sub(_exp(in_val), temp, _exp(out_val));
265 /* check for exponent underflow */
266 if (sc_is_negative(_exp(out_val)) || sc_is_zero(_exp(out_val))) {
267 DEBUGPRINTF(("Exponent underflow!\n"));
268 /* exponent underflow */
269 /* shift the mantissa right to have a zero exponent */
270 sc_val_from_ulong(1, temp);
271 sc_sub(temp, _exp(out_val), NULL);
273 _shift_right(_mant(out_val), sc_get_buffer(), _mant(out_val));
274 if (!sticky) sticky = sc_had_carry();
275 /* denormalized means exponent of zero */
276 sc_val_from_ulong(0, _exp(out_val));
278 out_val->desc.clss = SUBNORMAL;
281 /* perform rounding by adding a value that clears the guard bit and the round bit
282 * and either causes a carry to round up or not */
283 /* get the last 3 bits of the value */
284 lsb = sc_sub_bits(_mant(out_val), out_val->desc.mantissa_size + 2, 0) & 0x7;
285 guard = (lsb&0x2)>>1;
288 switch (rounding_mode) {
290 /* round to nearest representable value, if in doubt choose the version
292 round_dir = guard && (sticky || round || lsb>>2);
295 /* if positive: round to one if the exact value is bigger, else to zero */
296 round_dir = (!out_val->sign && (guard || round || sticky));
299 /* if negative: round to one if the exact value is bigger, else to zero */
300 round_dir = (out_val->sign && (guard || round || sticky));
303 /* always round to 0 (chopping mode) */
307 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"));
309 if (round_dir == 1) {
310 guard = (round^guard)<<1;
311 lsb = !(round || guard)<<2 | guard | round;
313 lsb = -((guard<<1) | round);
316 /* add the rounded value */
318 sc_val_from_long(lsb, temp);
319 sc_add(_mant(out_val), temp, _mant(out_val));
322 /* could have rounded down to zero */
323 if (sc_is_zero(_mant(out_val)) && (out_val->desc.clss == SUBNORMAL))
324 out_val->desc.clss = ZERO;
326 /* check for rounding overflow */
327 hsb = 2 + out_val->desc.mantissa_size - sc_get_highest_set_bit(_mant(out_val)) - 1;
328 if ((out_val->desc.clss != SUBNORMAL) && (hsb < -1)) {
329 sc_val_from_ulong(1, temp);
330 _shift_right(_mant(out_val), temp, _mant(out_val));
332 sc_add(_exp(out_val), temp, _exp(out_val));
333 } else if ((out_val->desc.clss == SUBNORMAL) && (hsb == -1)) {
334 /* overflow caused the mantissa to be normal again,
335 * so adapt the exponent accordingly */
336 sc_val_from_ulong(1, temp);
337 sc_add(_exp(out_val), temp, _exp(out_val));
339 out_val->desc.clss = NORMAL;
341 /* no further rounding is needed, because rounding overflow means
342 * the carry of the original rounding was propagated all the way
343 * up to the bit left of the radix point. This implies the bits
344 * to the right are all zeros (rounding is +1) */
346 /* check for exponent overflow */
347 sc_val_from_ulong((1 << out_val->desc.exponent_size) - 1, temp);
348 if (sc_comp(_exp(out_val), temp) != -1) {
349 DEBUGPRINTF(("Exponent overflow!\n"));
350 /* exponent overflow, reaction depends on rounding method:
352 * mode | sign of value | result
353 *--------------------------------------------------------------
354 * TO_NEAREST | + | +inf
356 *--------------------------------------------------------------
357 * TO_POSITIVE | + | +inf
358 * | - | smallest representable value
359 *--------------------------------------------------------------
360 * TO_NEAGTIVE | + | largest representable value
362 *--------------------------------------------------------------
363 * TO_ZERO | + | largest representable value
364 * | - | smallest representable value
365 *--------------------------------------------------------------*/
366 if (out_val->sign == 0) {
367 /* value is positive */
368 switch (rounding_mode) {
371 out_val->desc.clss = INF;
376 fc_get_max(out_val->desc.exponent_size, out_val->desc.mantissa_size, out_val);
379 /* value is negative */
380 switch (rounding_mode) {
383 out_val->desc.clss = INF;
388 fc_get_min(out_val->desc.exponent_size, out_val->desc.mantissa_size, out_val);
395 * Operations involving NaN's must return NaN
397 #define handle_NAN(a, b, result) \
399 if (a->desc.clss == NAN) { \
400 if (a != result) memcpy(result, a, calc_buffer_size); \
403 if (b->desc.clss == NAN) { \
404 if (b != result) memcpy(result, b, calc_buffer_size); \
411 * calculate a + b, where a is the value with the bigger exponent
413 static void _fadd(const fp_value *a, const fp_value *b, fp_value *result) {
420 handle_NAN(a, b, result);
422 /* make sure result has a descriptor */
423 if (result != a && result != b)
424 memcpy(&result->desc, &a->desc, sizeof(descriptor_t));
426 /* determine if this is an addition or subtraction */
427 sign = a->sign ^ b->sign;
429 /* produce NaN on inf - inf */
430 if (sign && (a->desc.clss == INF) && (b->desc.clss == INF)) {
431 fc_get_qnan(a->desc.exponent_size, b->desc.mantissa_size, result);
435 temp = alloca(value_size);
436 exp_diff = alloca(value_size);
438 /* get exponent difference */
439 sc_sub(_exp(a), _exp(b), exp_diff);
441 /* initially set sign to be the sign of a, special treatment of subtraction
442 * when exponents are equal is required though.
443 * Also special care about the sign is needed when the mantissas are equal
445 if (sign && sc_val_to_long(exp_diff) == 0) {
446 switch (sc_comp(_mant(a), _mant(b))) {
448 res_sign = a->sign; /* abs(a) is bigger and a is negative */
451 res_sign = (rounding_mode == FC_TONEGATIVE);
454 res_sign = b->sign; /* abs(b) is bigger and b is negative */
457 /* can't be reached */
464 result->sign = res_sign;
466 /* sign has been taken care of, check for special cases */
467 if (a->desc.clss == ZERO || b->desc.clss == INF) {
469 memcpy(result, b, calc_buffer_size);
470 result->sign = res_sign;
473 if (b->desc.clss == ZERO || a->desc.clss == INF) {
475 memcpy(result, a, calc_buffer_size);
476 result->sign = res_sign;
480 /* shift the smaller value to the right to align the radix point */
481 /* subnormals have their radix point shifted to the right,
482 * take care of this first */
483 if ((b->desc.clss == SUBNORMAL) && (a->desc.clss != SUBNORMAL)) {
484 sc_val_from_ulong(1, temp);
485 sc_sub(exp_diff, temp, exp_diff);
488 _shift_right(_mant(b), exp_diff, temp);
489 sticky = sc_had_carry();
491 if (sticky && sign) {
492 /* if subtracting a little more than the represented value or adding a little
493 * more than the represented value to a negative value this, in addition to the
494 * still set sticky bit, takes account of the 'little more' */
495 char *temp1 = alloca(calc_buffer_size);
496 sc_val_from_ulong(1, temp1);
497 sc_add(temp, temp1, temp);
501 if (sc_comp(_mant(a), temp) == -1)
502 sc_sub(temp, _mant(a), _mant(result));
504 sc_sub(_mant(a), temp, _mant(result));
506 sc_add(_mant(a), temp, _mant(result));
509 /* _normalize expects a 'normal' radix point, adding two subnormals
510 * results in a subnormal radix point -> shifting before normalizing */
511 if ((a->desc.clss == SUBNORMAL) && (b->desc.clss == SUBNORMAL)) {
512 sc_val_from_ulong(1, NULL);
513 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
516 /* resulting exponent is the bigger one */
517 memmove(_exp(result), _exp(a), value_size);
519 normalize(result, result, sticky);
525 static void _fmul(const fp_value *a, const fp_value *b, fp_value *result) {
529 handle_NAN(a, b, result);
531 temp = alloca(value_size);
533 if (result != a && result != b)
534 memcpy(&result->desc, &a->desc, sizeof(descriptor_t));
536 result->sign = res_sign = a->sign ^ b->sign;
538 /* produce NaN on 0 * inf */
539 if (a->desc.clss == ZERO) {
540 if (b->desc.clss == INF)
541 fc_get_qnan(a->desc.exponent_size, a->desc.mantissa_size, result);
544 memcpy(result, a, calc_buffer_size);
545 result->sign = res_sign;
549 if (b->desc.clss == ZERO) {
550 if (a->desc.clss == INF)
551 fc_get_qnan(a->desc.exponent_size, a->desc.mantissa_size, result);
554 memcpy(result, b, calc_buffer_size);
555 result->sign = res_sign;
560 if (a->desc.clss == INF) {
562 memcpy(result, a, calc_buffer_size);
563 result->sign = res_sign;
566 if (b->desc.clss == INF) {
568 memcpy(result, b, calc_buffer_size);
569 result->sign = res_sign;
573 /* exp = exp(a) + exp(b) - excess */
574 sc_add(_exp(a), _exp(b), _exp(result));
576 sc_val_from_ulong((1 << (a->desc.exponent_size - 1)) - 1, temp);
577 sc_sub(_exp(result), temp, _exp(result));
579 /* mixed normal, subnormal values introduce an error of 1, correct it */
580 if ((a->desc.clss == SUBNORMAL) ^ (b->desc.clss == SUBNORMAL)) {
581 sc_val_from_ulong(1, temp);
582 sc_add(_exp(result), temp, _exp(result));
585 sc_mul(_mant(a), _mant(b), _mant(result));
587 /* realign result: after a multiplication the digits right of the radix
588 * point are the sum of the factors' digits after the radix point. As all
589 * values are normalized they both have the same amount of these digits,
590 * which has to be restored by proper shifting
591 * +2 because of the two rounding bits */
592 sc_val_from_ulong(2 + result->desc.mantissa_size, temp);
594 _shift_right(_mant(result), temp, _mant(result));
596 normalize(result, result, sc_had_carry());
602 static void _fdiv(const fp_value *a, const fp_value *b, fp_value *result) {
603 char *temp, *dividend;
606 handle_NAN(a, b, result);
608 temp = alloca(value_size);
609 dividend = alloca(value_size);
611 if (result != a && result != b)
612 memcpy(&result->desc, &a->desc, sizeof(descriptor_t));
614 result->sign = res_sign = a->sign ^ b->sign;
616 /* produce NAN on 0/0 and inf/inf */
617 if (a->desc.clss == ZERO) {
618 if (b->desc.clss == ZERO)
620 fc_get_qnan(a->desc.exponent_size, a->desc.mantissa_size, result);
624 memcpy(result, a, calc_buffer_size);
625 result->sign = res_sign;
630 if (b->desc.clss == INF) {
631 if (a->desc.clss == INF)
633 fc_get_qnan(a->desc.exponent_size, a->desc.mantissa_size, result);
636 sc_val_from_ulong(0, NULL);
637 _save_result(_exp(result));
638 _save_result(_mant(result));
639 result->desc.clss = ZERO;
644 if (a->desc.clss == INF) {
647 memcpy(result, a, calc_buffer_size);
648 result->sign = res_sign;
651 if (b->desc.clss == ZERO) {
652 /* division by zero */
654 fc_get_minusinf(a->desc.exponent_size, a->desc.mantissa_size, result);
656 fc_get_plusinf(a->desc.exponent_size, a->desc.mantissa_size, result);
660 /* exp = exp(a) - exp(b) + excess - 1*/
661 sc_sub(_exp(a), _exp(b), _exp(result));
662 sc_val_from_ulong((1 << (a->desc.exponent_size - 1)) - 2, temp);
663 sc_add(_exp(result), temp, _exp(result));
665 /* mixed normal, subnormal values introduce an error of 1, correct it */
666 if ((a->desc.clss == SUBNORMAL) ^ (b->desc.clss == SUBNORMAL)) {
667 sc_val_from_ulong(1, temp);
668 sc_add(_exp(result), temp, _exp(result));
671 /* mant(res) = mant(a) / 1/2mant(b) */
672 /* to gain more bits of precision in the result the dividend could be
673 * shifted left, as this operation does not loose bits. This would not
674 * fit into the integer precision, but due to the rounding bits (which
675 * are always zero because the values are all normalized) the divisor
676 * can be shifted right instead to achieve the same result */
677 sc_val_from_ulong(2 + result->desc.mantissa_size, temp);
679 _shift_left(_mant(a), temp, dividend);
682 char *divisor = alloca(calc_buffer_size);
683 sc_val_from_ulong(1, divisor);
684 _shift_right(_mant(b), divisor, divisor);
685 sc_div(dividend, divisor, _mant(result));
688 normalize(result, result, sc_had_carry());
692 static void _power_of_ten(int exp, descriptor_t *desc, char *result) {
699 /* set new descriptor (else result is supposed to already have one) */
701 memcpy(&result->desc, desc, sizeof(descriptor_t));
703 build = alloca(value_size);
704 temp = alloca(value_size);
706 sc_val_from_ulong((1 << result->desc.exponent_size)/2-1, _exp(result));
709 /* temp is value of ten now */
710 sc_val_from_ulong(10, NULL);
713 for (exp--; exp > 0; exp--) {
715 sc_mul(build, temp, NULL);
719 /* temp is amount of left shift needed to put the value left of the radix point */
720 sc_val_from_ulong(result->desc.mantissa_size + 2, temp);
722 _shift_left(build, temp, _mant(result));
724 _normalize(result, result, 0);
730 * Truncate the fractional part away.
732 * This does not clip to any integer range.
734 static void _trunc(const fp_value *a, fp_value *result) {
736 * When exponent == 0 all bits left of the radix point
737 * are the integral part of the value. For 15bit exp_size
738 * this would require a left shift of max. 16383 bits which
740 * But it is enough to ensure that no bit right of the radix
741 * point remains set. This restricts the interesting
742 * exponents to the interval [0, mant_size-1].
743 * Outside this interval the truncated value is either 0 or
744 * it does not have fractional parts.
747 int exp_bias, exp_val;
750 temp = alloca(value_size);
753 memcpy(&result->desc, &a->desc, sizeof(descriptor_t));
755 exp_bias = (1 << (a->desc.exponent_size - 1)) - 1;
756 exp_val = sc_val_to_long(_exp(a)) - exp_bias;
759 sc_val_from_ulong(0, NULL);
760 _save_result(_exp(result));
761 _save_result(_mant(result));
762 result->desc.clss = ZERO;
767 if (exp_val > a->desc.mantissa_size) {
769 memcpy(result, a, calc_buffer_size);
774 /* set up a proper mask to delete all bits right of the
775 * radix point if the mantissa had been shifted until exp == 0 */
776 sc_max_from_bits(1 + exp_val, 0, temp);
777 sc_val_from_long(a->desc.mantissa_size - exp_val + 2, NULL);
778 _shift_left(temp, sc_get_buffer(), temp);
780 /* and the mask and return the result */
781 sc_and(_mant(a), temp, _mant(result));
783 if (a != result) memcpy(_exp(result), _exp(a), value_size);
789 * functions defined in fltcalc.h
791 const void *fc_get_buffer(void) {
795 int fc_get_buffer_length(void) {
796 return calc_buffer_size;
799 void *fc_val_from_str(const char *str, unsigned int len, char exp_size, char mant_size, void *result) {
811 int exp_int, hsb, state;
816 char *mant_str, *exp_val, *power_val;
819 if (result == NULL) result = calc_buffer;
821 exp_val = alloca(value_size);
822 power_val = alloca(calc_buffer_size);
823 mant_str = alloca((len)?(len):(strlen(str)));
825 result->desc.exponent_size = exp_size;
826 result->desc.mantissa_size = mant_size;
827 result->desc.clss = NORMAL;
834 while (len == 0 || str-old_str < len) {
850 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
857 state = RIGHT_OF_DOT;
868 fail_char(old_str, len, str - old_str);
874 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
875 mant_str[pos++] = *(str++);
879 state = RIGHT_OF_DOT;
890 mant_str[pos] = '\0';
894 fail_char(old_str, len, str - old_str);
900 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
901 mant_str[pos++] = *(str++);
912 mant_str[pos] = '\0';
916 fail_char(old_str, len, str - old_str);
926 if (*(str-1) != 'e' && *(str-1) != 'E') fail_char(old_str, len, str - old_str);
930 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
931 mant_str[pos] = '\0';
938 fail_char(old_str, len, str - old_str);
944 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
949 case '\0': goto done;
952 fail_char(old_str, len, str - old_str);
955 } /* switch(state) */
958 sc_val_from_str(mant_str, strlen(mant_str), _mant(result));
960 /* shift to put value left of radix point */
961 sc_val_from_ulong(mant_size + 2, exp_val);
963 _shift_left(_mant(result), exp_val, _mant(result));
965 sc_val_from_ulong((1 << exp_size)/2-1, _exp(result));
967 _normalize(result, result, 0);
969 if (state == EXPONENT) {
970 exp_int -= atoi(str-pos);
973 _power_of_ten(exp_int, &result->desc, power_val);
975 _fdiv(result, power_val, result);
979 /* XXX excuse of an implementation to make things work */
981 fp_value *tmp = alloca(calc_buffer_size);
984 #ifdef HAVE_LONG_DOUBLE
985 val = strtold(str, NULL);
986 DEBUGPRINTF(("val_from_str(%s)\n", str));
987 fc_val_from_ieee754(val, 15, 64, tmp);
989 val = strtod(str, NULL);
990 DEBUGPRINTF(("val_from_str(%s)\n", str));
991 fc_val_from_ieee754(val, 11, 52, tmp);
992 #endif /* HAVE_LONG_DOUBLE */
993 return fc_cast(tmp, exp_size, mant_size, result);
997 fp_value *fc_val_from_ieee754(LLDBL l, char exp_size, char mant_size, fp_value *result) {
999 int bias_res, bias_val, mant_val;
1001 UINT32 sign, exponent, mantissa0, mantissa1;
1004 bias_res = ((1<<exp_size)/2-1);
1006 #ifdef HAVE_LONG_DOUBLE
1009 sign = (srcval.val.high & 0x00008000) != 0;
1010 exponent = (srcval.val.high & 0x00007FFF) ;
1011 mantissa0 = srcval.val.mid;
1012 mantissa1 = srcval.val.low;
1013 #else /* no long double */
1016 sign = (srcval.val.high & 0x80000000) != 0;
1017 exponent = (srcval.val.high & 0x7FF00000) >> 20;
1018 mantissa0 = srcval.val.high & 0x000FFFFF;
1019 mantissa1 = srcval.val.low;
1022 #ifdef HAVE_LONG_DOUBLE
1023 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)); */
1024 DEBUGPRINTF(("(%d-%.4X-%.8X%.8X)\n", sign, exponent, mantissa0, mantissa1));
1026 TRACEPRINTF(("val_from_float(%.8X%.8X)\n", srcval.val.high, srcval.val.low));
1027 DEBUGPRINTF(("(%d-%.3X-%.5X%.8X)\n", sign, exponent, mantissa0, mantissa1));
1030 if (result == NULL) result = calc_buffer;
1031 temp = alloca(value_size);
1033 result->desc.exponent_size = exp_size;
1034 result->desc.mantissa_size = mant_size;
1037 result->sign = sign;
1039 /* sign and flag suffice to identify nan or inf, no exponent/mantissa
1040 * encoding is needed. the function can return immediately in these cases */
1042 result->desc.clss = NAN;
1043 TRACEPRINTF(("val_from_float resulted in NAN\n"));
1046 else if (isinf(l)) {
1047 result->desc.clss = INF;
1048 TRACEPRINTF(("val_from_float resulted in %sINF\n", (result->sign == 1) ? "-" : ""));
1052 /* build exponent, because input and output exponent and mantissa sizes may differ
1053 * this looks more complicated than it is: unbiased input exponent + output bias,
1054 * minus the mantissa difference which is added again later when the output float
1055 * becomes normalized */
1056 #ifdef HAVE_EXPLICIT_ONE
1057 sc_val_from_long((exponent-bias_val+bias_res)-(mant_val-mant_size-1), _exp(result));
1059 sc_val_from_long((exponent-bias_val+bias_res)-(mant_val-mant_size), _exp(result));
1062 /* build mantissa representation */
1063 #ifndef HAVE_EXPLICIT_ONE
1064 if (exponent != 0) {
1065 /* insert the hidden bit */
1066 sc_val_from_ulong(1, temp);
1067 sc_val_from_ulong(mant_val + 2, NULL);
1068 _shift_left(temp, sc_get_buffer(), NULL);
1073 sc_val_from_ulong(0, NULL);
1076 _save_result(_mant(result));
1078 /* bits from the upper word */
1079 sc_val_from_ulong(mantissa0, temp);
1080 sc_val_from_ulong(34, NULL);
1081 _shift_left(temp, sc_get_buffer(), temp);
1082 sc_or(_mant(result), temp, _mant(result));
1084 /* bits from the lower word */
1085 sc_val_from_ulong(mantissa1, temp);
1086 sc_val_from_ulong(2, NULL);
1087 _shift_left(temp, sc_get_buffer(), temp);
1088 sc_or(_mant(result), temp, _mant(result));
1090 /* _normalize expects the radix point to be normal, so shift mantissa of subnormal
1091 * origin one to the left */
1092 if (exponent == 0) {
1093 sc_val_from_ulong(1, NULL);
1094 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1097 normalize(result, result, 0);
1099 TRACEPRINTF(("val_from_float results in %s\n", fc_print(result, temp, calc_buffer_size, FC_PACKED)));
1104 LLDBL fc_val_to_ieee754(const fp_value *val) {
1106 fp_value *temp = NULL;
1117 #ifdef HAVE_LONG_DOUBLE
1118 char result_exponent = 15;
1119 char result_mantissa = 64;
1121 char result_exponent = 11;
1122 char result_mantissa = 52;
1125 temp = alloca(calc_buffer_size);
1126 #ifdef HAVE_EXPLICIT_ONE
1127 value = fc_cast(val, result_exponent, result_mantissa-1, temp);
1129 value = fc_cast(val, result_exponent, result_mantissa, temp);
1134 /* @@@ long double exponent is 15bit, so the use of sc_val_to_long should not
1135 * lead to wrong results */
1136 exponent = sc_val_to_long(_exp(value)) ;
1138 sc_val_from_ulong(2, NULL);
1139 _shift_right(_mant(value), sc_get_buffer(), _mant(value));
1144 for (byte_offset = 0; byte_offset < 4; byte_offset++)
1145 mantissa1 |= sc_sub_bits(_mant(value), result_mantissa, byte_offset) << (byte_offset<<3);
1147 for (; (byte_offset<<3) < result_mantissa; byte_offset++)
1148 mantissa0 |= sc_sub_bits(_mant(value), result_mantissa, byte_offset) << ((byte_offset-4)<<3);
1150 #ifdef HAVE_LONG_DOUBLE
1151 buildval.val.high = sign << 15;
1152 buildval.val.high |= exponent;
1153 buildval.val.mid = mantissa0;
1154 buildval.val.low = mantissa1;
1155 #else /* no long double */
1156 mantissa0 &= 0x000FFFFF; /* get rid of garbage */
1157 buildval.val.high = sign << 31;
1158 buildval.val.high |= exponent << 20;
1159 buildval.val.high |= mantissa0;
1160 buildval.val.low = mantissa1;
1163 TRACEPRINTF(("val_to_float: %d-%x-%x%x\n", sign, exponent, mantissa0, mantissa1));
1167 fp_value *fc_cast(const fp_value *value, char exp_size, char mant_size, fp_value *result) {
1169 int exp_offset, val_bias, res_bias;
1171 if (result == NULL) result = calc_buffer;
1172 temp = alloca(value_size);
1174 if (value->desc.exponent_size == exp_size && value->desc.mantissa_size == mant_size) {
1175 if (value != result)
1176 memcpy(result, value, calc_buffer_size);
1180 /* set the descriptor of the new value */
1181 result->desc.exponent_size = exp_size;
1182 result->desc.mantissa_size = mant_size;
1183 result->desc.clss = value->desc.clss;
1185 result->sign = value->sign;
1187 /* when the mantissa sizes differ normalizing has to shift to align it.
1188 * this would change the exponent, which is unwanted. So calculate this
1189 * offset and add it */
1190 val_bias = (1 << (value->desc.exponent_size - 1)) - 1;
1191 res_bias = (1 << (exp_size - 1)) - 1;
1193 exp_offset = (res_bias - val_bias) - (value->desc.mantissa_size - mant_size);
1194 sc_val_from_long(exp_offset, temp);
1195 sc_add(_exp(value), temp, _exp(result));
1197 /* _normalize expects normalized radix point */
1198 if (value->desc.clss == SUBNORMAL) {
1199 sc_val_from_ulong(1, NULL);
1200 _shift_left(_mant(value), sc_get_buffer(), _mant(result));
1201 } else if (value != result) {
1202 memcpy(_mant(result), _mant(value), value_size);
1204 memmove(_mant(result), _mant(value), value_size);
1207 normalize(result, result, 0);
1208 TRACEPRINTF(("Cast results in %s\n", fc_print(result, temp, value_size, FC_PACKED)));
1212 fp_value *fc_get_max(unsigned int exponent_size, unsigned int mantissa_size, fp_value *result) {
1213 if (result == NULL) result = calc_buffer;
1215 result->desc.exponent_size = exponent_size;
1216 result->desc.mantissa_size = mantissa_size;
1217 result->desc.clss = NORMAL;
1221 sc_val_from_ulong((1<<exponent_size) - 2, _exp(result));
1223 sc_max_from_bits(mantissa_size + 1, 0, _mant(result));
1224 sc_val_from_ulong(2, NULL);
1225 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1230 fp_value *fc_get_min(unsigned int exponent_size, unsigned int mantissa_size, fp_value *result) {
1231 if (result == NULL) result = calc_buffer;
1233 fc_get_max(exponent_size, mantissa_size, result);
1239 fp_value *fc_get_snan(unsigned int exponent_size, unsigned int mantissa_size, fp_value *result) {
1240 if (result == NULL) result = calc_buffer;
1242 result->desc.exponent_size = exponent_size;
1243 result->desc.mantissa_size = mantissa_size;
1244 result->desc.clss = NAN;
1248 sc_val_from_ulong((1<<exponent_size)-1, _exp(result));
1250 /* signaling NaN has non-zero mantissa with msb not set */
1251 sc_val_from_ulong(1, _mant(result));
1256 fp_value *fc_get_qnan(unsigned int exponent_size, unsigned int mantissa_size, fp_value *result) {
1257 if (result == NULL) result = calc_buffer;
1259 result->desc.exponent_size = exponent_size;
1260 result->desc.mantissa_size = mantissa_size;
1261 result->desc.clss = NAN;
1265 sc_val_from_ulong((1<<exponent_size)-1, _exp(result));
1267 /* quiet NaN has the msb of the mantissa set, so shift one there */
1268 sc_val_from_ulong(1, _mant(result));
1269 /* mantissa_size >+< 1 because of two extra rounding bits */
1270 sc_val_from_ulong(mantissa_size + 1, NULL);
1271 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1276 fp_value *fc_get_plusinf(unsigned int exponent_size, unsigned int mantissa_size, fp_value *result) {
1277 if (result == NULL) result = calc_buffer;
1279 result->desc.exponent_size = exponent_size;
1280 result->desc.mantissa_size = mantissa_size;
1281 result->desc.clss = NORMAL;
1285 sc_val_from_ulong((1<<exponent_size)-1, _exp(result));
1287 sc_val_from_ulong(0, _mant(result));
1292 fp_value *fc_get_minusinf(unsigned int exponent_size, unsigned int mantissa_size, fp_value *result) {
1293 if (result == NULL) result = calc_buffer;
1295 fc_get_plusinf(exponent_size, mantissa_size, result);
1301 int fc_comp(const fp_value *val_a, const fp_value *val_b) {
1305 * shortcut: if both values are identical, they are either
1306 * Unordered if NaN or equal
1309 return val_a->desc.clss == NAN ? 2 : 0;
1311 /* unordered if one is a NaN */
1312 if (val_a->desc.clss == NAN || val_b->desc.clss == NAN)
1315 /* zero is equal independent of sign */
1316 if ((val_a->desc.clss == ZERO) && (val_b->desc.clss == ZERO))
1319 /* different signs make compare easy */
1320 if (val_a->sign != val_b->sign)
1321 return (val_a->sign == 0) ? (1) : (-1);
1323 mul = val_a->sign ? -1 : 1;
1325 /* both infinity means equality */
1326 if ((val_a->desc.clss == INF) && (val_b->desc.clss == INF))
1329 /* infinity is bigger than the rest */
1330 if (val_a->desc.clss == INF)
1332 if (val_b->desc.clss == INF)
1335 /* check first exponent, that mantissa if equal */
1336 switch (sc_comp(_exp(val_a), _exp(val_b))) {
1342 return sc_comp(_mant(val_a), _mant(val_b)) * mul;
1348 int fc_is_zero(const fp_value *a) {
1349 return a->desc.clss == ZERO;
1352 int fc_is_negative(const fp_value *a) {
1356 int fc_is_inf(const fp_value *a) {
1357 return a->desc.clss == INF;
1360 int fc_is_nan(const fp_value *a) {
1361 return a->desc.clss == NAN;
1364 int fc_is_subnormal(const fp_value *a) {
1365 return a->desc.clss == SUBNORMAL;
1368 char *fc_print(const fp_value *val, char *buf, int buflen, unsigned base) {
1371 mul_1 = alloca(calc_buffer_size);
1375 switch (val->desc.clss) {
1377 if (buflen >= 8 + val->sign) sprintf(buf, "%sINFINITY", val->sign ? "-":"");
1378 else snprintf(buf, buflen, "%sINF", val->sign ? "-":NULL);
1381 snprintf(buf, buflen, "NAN");
1384 snprintf(buf, buflen, "0.0");
1387 /* XXX to be implemented */
1388 #ifdef HAVE_LONG_DOUBLE
1389 /* XXX 30 is arbitrary */
1390 snprintf(buf, buflen, "%.30LE", fc_val_to_ieee754(val));
1392 snprintf(buf, buflen, "%.18E", fc_val_to_ieee754(val));
1398 switch (val->desc.clss) {
1400 if (buflen >= 8+val->sign) sprintf(buf, "%sINFINITY", val->sign?"-":"");
1401 else snprintf(buf, buflen, "%sINF", val->sign?"-":NULL);
1404 snprintf(buf, buflen, "NAN");
1407 snprintf(buf, buflen, "0.0");
1410 #ifdef HAVE_LONG_DOUBLE
1411 snprintf(buf, buflen, "%LA", fc_val_to_ieee754(val));
1413 snprintf(buf, buflen, "%A", fc_val_to_ieee754(val));
1420 snprintf(buf, buflen, "%s", sc_print(pack(val, mul_1), value_size*4, SC_HEX, 0));
1421 buf[buflen - 1] = '\0';
1427 unsigned char fc_sub_bits(const fp_value *value, unsigned num_bits, unsigned byte_ofs) {
1428 /* this is used to cache the packed version of the value */
1429 static char *packed_value = NULL;
1431 if (packed_value == NULL) packed_value = xmalloc(value_size);
1434 pack(value, packed_value);
1436 return sc_sub_bits(packed_value, num_bits, byte_ofs);
1439 int fc_zero_mantissa(const fp_value *value) {
1440 return sc_get_lowest_set_bit(_mant(value)) == 2 + value->desc.mantissa_size;
1443 int fc_get_exponent(const fp_value *value) {
1444 int exp_bias = (1 << (value->desc.exponent_size - 1)) - 1;
1445 return sc_val_to_long(_exp(value)) - exp_bias;
1449 fc_rounding_mode_t fc_set_rounding_mode(fc_rounding_mode_t mode) {
1450 if (mode == FC_TONEAREST || mode == FC_TOPOSITIVE || mode == FC_TONEGATIVE || mode == FC_TOZERO)
1451 rounding_mode = mode;
1453 return rounding_mode;
1456 fc_rounding_mode_t fc_get_rounding_mode(void) {
1457 return rounding_mode;
1460 void init_fltcalc(int precision) {
1461 if (calc_buffer == NULL) {
1462 /* does nothing if already init */
1463 if (precision == 0) precision = FC_DEFAULT_PRECISION;
1465 init_strcalc(precision + 4);
1467 /* needs additionally two bits to round, a bit as explicit 1., and one for
1468 * addition overflow */
1469 max_precision = sc_get_precision() - 4;
1470 if (max_precision < precision)
1471 printf("WARNING: not enough precision available, using %d\n", max_precision);
1473 rounding_mode = FC_TONEAREST;
1474 value_size = sc_get_buffer_length();
1475 calc_buffer_size = sizeof(fp_value) + 2*value_size - 1;
1477 calc_buffer = xmalloc(calc_buffer_size);
1478 memset(calc_buffer, 0, calc_buffer_size);
1479 DEBUGPRINTF(("init fltcalc:\n\tVALUE_SIZE = %d\ntCALC_BUFFER_SIZE = %d\n\tcalc_buffer = %p\n\n", value_size, calc_buffer_size, calc_buffer));
1480 #ifdef HAVE_LONG_DOUBLE
1481 DEBUGPRINTF(("\tUsing long double (1-15-64) interface\n"));
1483 DEBUGPRINTF(("\tUsing double (1-11-52) interface\n"));
1485 #ifdef WORDS_BIGENDIAN
1486 DEBUGPRINTF(("\tWord order is big endian\n\n"));
1488 DEBUGPRINTF(("\tWord order is little endian\n\n"));
1493 void finish_fltcalc (void) {
1494 free(calc_buffer); calc_buffer = NULL;
1497 static char buffer[100];
1499 /* definition of interface functions */
1500 fp_value *fc_add(const fp_value *a, const fp_value *b, fp_value *result) {
1501 if (result == NULL) result = calc_buffer;
1503 TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1504 TRACEPRINTF(("+ %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1506 /* make the value with the bigger exponent the first one */
1507 if (sc_comp(_exp(a), _exp(b)) == -1)
1508 _fadd(b, a, result);
1510 _fadd(a, b, result);
1512 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1516 fp_value *fc_sub(const fp_value *a, const fp_value *b, fp_value *result) {
1519 if (result == NULL) result = calc_buffer;
1521 TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1522 TRACEPRINTF(("- %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1524 temp = alloca(calc_buffer_size);
1525 memcpy(temp, b, calc_buffer_size);
1526 temp->sign = !b->sign;
1527 if (sc_comp(_exp(a), _exp(temp)) == -1)
1528 _fadd(temp, a, result);
1530 _fadd(a, temp, result);
1532 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1536 fp_value *fc_mul(const fp_value *a, const fp_value *b, fp_value *result) {
1537 if (result == NULL) result = calc_buffer;
1539 TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1540 TRACEPRINTF(("* %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1542 _fmul(a, b, result);
1544 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1548 fp_value *fc_div(const fp_value *a, const fp_value *b, fp_value *result) {
1549 if (result == NULL) result = calc_buffer;
1551 TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1552 TRACEPRINTF(("/ %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1554 _fdiv(a, b, result);
1556 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1560 fp_value *fc_neg(const fp_value *a, fp_value *result) {
1561 if (result == NULL) result = calc_buffer;
1563 TRACEPRINTF(("- %s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1566 memcpy(result, a, calc_buffer_size);
1567 result->sign = !a->sign;
1569 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1573 fp_value *fc_int(const fp_value *a, fp_value *result) {
1574 if (result == NULL) result = calc_buffer;
1576 TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1577 TRACEPRINTF(("truncated to integer "));
1581 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1585 fp_value *fc_rnd(const fp_value *a, fp_value *result) {
1586 if (result == NULL) result = calc_buffer;
1588 TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1589 TRACEPRINTF(("rounded to integer "));
1591 assert(!"fc_rnd() not yet implemented");
1593 TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1597 unsigned fc_set_immediate_precision(unsigned bits) {
1598 unsigned old = immediate_prec;
1600 immediate_prec = bits;