3 * File name: ir/tv/fltcalc.c
9 * Copyright: (c) 2003 Universität Karlsruhe
10 * Licence: This file protected by GPL - GNU GENERAL PUBLIC LICENSE.
22 #include <math.h> /* need isnan() and isinf() (will be changed)*/
23 /* undef some reused constants defined by math.h */
28 #ifdef HAVE_INTTYPES_H
29 # include <inttypes.h>
48 typedef uint32_t UINT32;
50 #ifdef HAVE_LONG_DOUBLE
51 #ifdef WORDS_BIGENDIAN
58 volatile long double d;
67 volatile long double d;
71 #ifdef WORDS_BIGENDIAN
91 * possible float states
94 NORMAL, /**< normal representation, implicit 1 */
96 SUBNORMAL, /**< denormals, implicit 0 */
98 NAN, /**< Not A Number */
101 /** A descriptor for an IEEE float value. */
103 unsigned char exponent_size; /**< size of exponent in bits */
104 unsigned char mantissa_size; /**< size of mantissa in bits */
105 value_class_t clss; /**< state of this float */
108 #define CLEAR_BUFFER(buffer) memset(buffer, 0, calc_buffer_size)
110 /* because variable sized structs are impossible, the internal
111 * value is represented as a pseudo-struct char array, addressed
114 * char sign; // 0 for positive, 1 for negative
115 * char exp[value_size];
116 * char mant[value_size];
120 #define _sign(a) (((char*)a)[SIGN_POS])
121 #define _exp(a) (&((char*)a)[EXPONENT_POS])
122 #define _mant(a) (&((char*)a)[MANTISSA_POS])
123 #define _desc(a) (*(descriptor_t *)&((char *)a)[DESCRIPTOR_POS])
125 #define _save_result(x) memcpy((x), sc_get_buffer(), value_size)
126 #define _shift_right(x, y, b) sc_shr((x), (y), value_size*4, 0, (b))
127 #define _shift_left(x, y, b) sc_shl((x), (y), value_size*4, 0, (b))
129 #define FC_DEFINE1(code) \
130 char *fc_##code(const void *a, void *result) { \
131 return _calc((const char*)a, NULL, FC_##code, (char*)result); \
134 #define FC_DEFINE2(code) \
135 char *fc_##code(const void *a, const void *b, void *result) { \
136 return _calc((const char*)a, (const char*)b, FC_##code, (char*)result); \
139 #define FUNC_PTR(code) fc_##code
142 # define DEBUGPRINTF(x) printf x
144 # define DEBUGPRINTF(x) ((void)0)
147 #if FLTCALC_TRACE_CALC
148 # define TRACEPRINTF(x) printf x
150 # define TRACEPRINTF(x) ((void)0)
153 static char *calc_buffer = NULL;
155 static fc_rounding_mode_t rounding_mode;
157 static int calc_buffer_size;
158 static int value_size;
160 static int EXPONENT_POS;
161 static int MANTISSA_POS;
162 static int DESCRIPTOR_POS;
164 static int max_precision;
169 static void _fail_char(const char *str, unsigned int len, int pos)
172 printf("ERROR: Unexpected character '%c'\n", *(str + pos));
174 printf("ERROR: Unexpected end of string\n");
175 while (len-- && *str) printf("%c", *str++); printf("\n");
176 while (pos--) printf(" "); printf("^\n");
177 /* the front end has to to check constant strings */
182 /** pack machine-like */
183 static char* _pack(const char *int_float, char *packed)
189 temp = alloca(value_size);
190 shift_val = alloca(value_size);
192 switch (_desc(int_float).clss) {
194 val_buffer = alloca(calc_buffer_size);
195 fc_get_qnan(_desc(int_float).exponent_size, _desc(int_float).mantissa_size, val_buffer);
196 int_float = val_buffer;
200 val_buffer = alloca(calc_buffer_size);
201 fc_get_plusinf(_desc(int_float).exponent_size, _desc(int_float).mantissa_size, val_buffer);
202 _sign(val_buffer) = _sign(int_float);
203 int_float = val_buffer;
210 sc_val_from_ulong(_sign(int_float), temp);
212 sc_val_from_ulong(_desc(int_float).exponent_size + _desc(int_float).mantissa_size, NULL);
213 _shift_left(temp, sc_get_buffer(), packed);
215 /* extract exponent */
216 sc_val_from_ulong(_desc(int_float).mantissa_size, shift_val);
218 _shift_left(_exp(int_float), shift_val, temp);
220 sc_or(temp, packed, packed);
222 /* extract mantissa */
223 /* remove 2 rounding bits */
224 sc_val_from_ulong(2, shift_val);
225 _shift_right(_mant(int_float), shift_val, temp);
227 /* remove leading 1 (or 0 if denormalized) */
228 sc_max_from_bits(_desc(int_float).mantissa_size, 0, shift_val); /* all mantissa bits are 1's */
229 sc_and(temp, shift_val, temp);
232 sc_or(temp, packed, packed);
237 char* _normalize(const char *in_val, char *out_val, int sticky)
240 char lsb, guard, round, round_dir = 0;
243 temp = alloca(value_size);
245 /* +2: save two rounding bits at the end */
246 hsb = 2 + _desc(in_val).mantissa_size - sc_get_highest_set_bit(_mant(in_val)) - 1;
248 if (in_val != out_val)
250 _sign(out_val) = _sign(in_val);
251 memcpy(&_desc(out_val), &_desc(in_val), sizeof(descriptor_t));
254 _desc(out_val).clss = NORMAL;
256 /* mantissa all zeros, so zero exponent (because of explicit one)*/
257 if (hsb == 2 + _desc(in_val).mantissa_size)
259 sc_val_from_ulong(0, _exp(out_val));
263 /* shift the first 1 into the left of the radix point (i.e. hsb == -1) */
267 sc_val_from_ulong(-hsb-1, temp);
269 _shift_right(_mant(in_val), temp, _mant(out_val));
271 /* remember if some bits were shifted away */
272 if (!sticky) sticky = sc_had_carry();
274 sc_add(_exp(in_val), temp, _exp(out_val));
279 sc_val_from_ulong(hsb+1, temp);
281 _shift_left(_mant(in_val), temp, _mant(out_val));
283 sc_sub(_exp(in_val), temp, _exp(out_val));
286 /* check for exponent underflow */
287 if (sc_is_negative(_exp(out_val)) || sc_is_zero(_exp(out_val))) {
288 DEBUGPRINTF(("Exponent underflow!\n"));
289 /* exponent underflow */
290 /* shift the mantissa right to have a zero exponent */
291 sc_val_from_ulong(1, temp);
292 sc_sub(temp, _exp(out_val), NULL);
294 _shift_right(_mant(out_val), sc_get_buffer(), _mant(out_val));
295 if (!sticky) sticky = sc_had_carry();
296 /* denormalized means exponent of zero */
297 sc_val_from_ulong(0, _exp(out_val));
299 _desc(out_val).clss = SUBNORMAL;
302 /* perform rounding by adding a value that clears the guard bit and the round bit
303 * and either causes a carry to round up or not */
304 /* get the last 3 bits of the value */
305 lsb = sc_sub_bits(_mant(out_val), _desc(out_val).mantissa_size + 2, 0) & 0x7;
306 guard = (lsb&0x2)>>1;
309 switch (rounding_mode)
312 /* round to nearest representable value, if in doubt choose the version
314 round_dir = guard && (sticky || round || lsb>>2);
317 /* if positive: round to one if the exact value is bigger, else to zero */
318 round_dir = (!_sign(out_val) && (guard || round || sticky));
321 /* if negative: round to one if the exact value is bigger, else to zero */
322 round_dir = (_sign(out_val) && (guard || round || sticky));
325 /* always round to 0 (chopping mode) */
329 DEBUGPRINTF(("Rounding (s%d, l%d, g%d, r%d, s%d) %s\n", _sign(out_val), lsb>>2, guard, round, sticky, (round_dir)?"up":"down"));
333 guard = (round^guard)<<1;
334 lsb = !(round || guard)<<2 | guard | round;
338 lsb = -((guard<<1) | round);
341 /* add the rounded value */
343 sc_val_from_long(lsb, temp);
344 sc_add(_mant(out_val), temp, _mant(out_val));
347 /* could have rounded down to zero */
348 if (sc_is_zero(_mant(out_val)) && (_desc(out_val).clss == SUBNORMAL))
349 _desc(out_val).clss = ZERO;
351 /* check for rounding overflow */
352 hsb = 2 + _desc(out_val).mantissa_size - sc_get_highest_set_bit(_mant(out_val)) - 1;
353 if ((_desc(out_val).clss != SUBNORMAL) && (hsb < -1))
355 sc_val_from_ulong(1, temp);
356 _shift_right(_mant(out_val), temp, _mant(out_val));
358 sc_add(_exp(out_val), temp, _exp(out_val));
360 else if ((_desc(out_val).clss == SUBNORMAL) && (hsb == -1))
362 /* overflow caused the mantissa to be normal again,
363 * so adapt the exponent accordingly */
364 sc_val_from_ulong(1, temp);
365 sc_add(_exp(out_val), temp, _exp(out_val));
367 _desc(out_val).clss = NORMAL;
369 /* no further rounding is needed, because rounding overflow means
370 * the carry of the original rounding was propagated all the way
371 * up to the bit left of the radix point. This implies the bits
372 * to the right are all zeros (rounding is +1) */
374 /* check for exponent overflow */
375 sc_val_from_ulong((1 << _desc(out_val).exponent_size) - 1, temp);
376 if (sc_comp(_exp(out_val), temp) != -1) {
377 DEBUGPRINTF(("Exponent overflow!\n"));
378 /* exponent overflow, reaction depends on rounding method:
380 * mode | sign of value | result
381 *--------------------------------------------------------------
382 * TO_NEAREST | + | +inf
384 *--------------------------------------------------------------
385 * TO_POSITIVE | + | +inf
386 * | - | smallest representable value
387 *--------------------------------------------------------------
388 * TO_NEAGTIVE | + | largest representable value
390 *--------------------------------------------------------------
391 * TO_ZERO | + | largest representable value
392 * | - | smallest representable value
393 *--------------------------------------------------------------*/
394 if (_sign(out_val) == 0)
396 /* value is positive */
397 switch (rounding_mode) {
400 _desc(out_val).clss = INF;
405 fc_get_max(_desc(out_val).exponent_size, _desc(out_val).mantissa_size, out_val);
408 /* value is negative */
409 switch (rounding_mode) {
412 _desc(out_val).clss = INF;
417 fc_get_min(_desc(out_val).exponent_size, _desc(out_val).mantissa_size, out_val);
426 * Operations involving NaN's must return NaN
428 #define handle_NAN(a, b, result) \
430 if (_desc(a).clss == NAN) { \
431 if (a != result) memcpy(result, a, calc_buffer_size); \
434 if (_desc(b).clss == NAN) { \
435 if (b != result) memcpy(result, b, calc_buffer_size); \
442 * calculate a + b, where a is the value with the bigger exponent
444 static char* _fadd(const char* a, const char* b, char* result)
452 handle_NAN(a, b, result);
454 /* make sure result has a descriptor */
455 if (result != a && result != b)
456 memcpy(&_desc(result), &_desc(a), sizeof(descriptor_t));
458 /* determine if this is an addition or subtraction */
459 sign = _sign(a) ^ _sign(b);
461 /* produce NaN on inf - inf */
462 if (sign && (_desc(a).clss == INF) && (_desc(b).clss == INF))
463 return fc_get_qnan(_desc(a).exponent_size, _desc(b).mantissa_size, result);
465 temp = alloca(value_size);
466 exp_diff = alloca(value_size);
468 /* get exponent difference */
469 sc_sub(_exp(a), _exp(b), exp_diff);
471 /* initially set sign to be the sign of a, special treatment of subtraction
472 * when exponents are equal is required though.
473 * Also special care about the sign is needed when the mantissas are equal
475 if (sign && sc_val_to_long(exp_diff) == 0) {
476 switch (sc_comp(_mant(a), _mant(b))) {
478 _sign(result) = _sign(a); /* abs(a) is bigger and a is negative */
481 _sign(result) = (rounding_mode == FC_TONEGATIVE);
484 _sign(result) = _sign(b); /* abs(b) is bigger and b is negative */
487 /* can't be reached */
492 _sign(result) = _sign(a);
494 /* sign has been taken care of, check for special cases */
495 if (_desc(a).clss == ZERO) {
496 if (b != result) memcpy(result+SIGN_POS+1, b+SIGN_POS+1, calc_buffer_size-SIGN_POS-1);
499 if (_desc(b).clss == ZERO) {
500 if (a != result) memcpy(result+SIGN_POS+1, a+SIGN_POS+1, calc_buffer_size-SIGN_POS-1);
504 if (_desc(a).clss == INF) {
505 if (a != result) memcpy(result+SIGN_POS+1, a+SIGN_POS+1, calc_buffer_size-SIGN_POS-1);
508 if (_desc(b).clss == INF) {
509 if (b != result) memcpy(result+SIGN_POS+1, b+SIGN_POS+1, calc_buffer_size-SIGN_POS-1);
513 /* shift the smaller value to the right to align the radix point */
514 /* subnormals have their radix point shifted to the right,
515 * take care of this first */
516 if ((_desc(b).clss == SUBNORMAL) && (_desc(a).clss != SUBNORMAL))
518 sc_val_from_ulong(1, temp);
519 sc_sub(exp_diff, temp, exp_diff);
522 _shift_right(_mant(b), exp_diff, temp);
523 sticky = sc_had_carry();
527 /* if subtracting a little more than the represented value or adding a little
528 * more than the represented value to a negative value this, in addition to the
529 * still set sticky bit, takes account of the 'little more' */
530 char *temp1 = alloca(calc_buffer_size);
531 sc_val_from_ulong(1, temp1);
532 sc_add(temp, temp1, temp);
536 if (sc_comp(_mant(a), temp) == -1)
537 sc_sub(temp, _mant(a), _mant(result));
539 sc_sub(_mant(a), temp, _mant(result));
541 sc_add(_mant(a), temp, _mant(result));
544 /* _normalize expects a 'normal' radix point, adding two subnormals
545 * results in a subnormal radix point -> shifting before normalizing */
546 if ((_desc(a).clss == SUBNORMAL) && (_desc(b).clss == SUBNORMAL))
548 sc_val_from_ulong(1, NULL);
549 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
552 /* resulting exponent is the bigger one */
553 memmove(_exp(result), _exp(a), value_size);
555 return _normalize(result, result, sticky);
561 static char* _fmul(const char* a, const char* b, char* result)
565 handle_NAN(a, b, result);
567 temp = alloca(value_size);
569 if (result != a && result != b)
570 memcpy(&_desc(result), &_desc(a), sizeof(descriptor_t));
572 _sign(result) = _sign(a) ^ _sign(b);
574 /* produce NaN on 0 * inf */
575 if (_desc(a).clss == ZERO) {
576 if (_desc(b).clss == INF)
577 fc_get_qnan(_desc(a).exponent_size, _desc(a).mantissa_size, result);
579 if (a != result) memcpy(result+SIGN_POS+1, a+SIGN_POS+1, calc_buffer_size-1);
582 if (_desc(b).clss == ZERO) {
583 if (_desc(a).clss == INF)
584 fc_get_qnan(_desc(a).exponent_size, _desc(a).mantissa_size, result);
586 if (b != result) memcpy(result+SIGN_POS+1, b+SIGN_POS+1, calc_buffer_size-1);
590 if (_desc(a).clss == INF) {
591 if (a != result) memcpy(result+SIGN_POS+1, a+SIGN_POS+1, calc_buffer_size-1);
594 if (_desc(b).clss == INF) {
595 if (b != result) memcpy(result+SIGN_POS+1, b+SIGN_POS+1, calc_buffer_size-1);
599 /* exp = exp(a) + exp(b) - excess */
600 sc_add(_exp(a), _exp(b), _exp(result));
602 sc_val_from_ulong((1<<_desc(a).exponent_size)/2-1, temp);
603 sc_sub(_exp(result), temp, _exp(result));
605 /* mixed normal, subnormal values introduce an error of 1, correct it */
606 if ((_desc(a).clss == SUBNORMAL) ^ (_desc(b).clss == SUBNORMAL))
608 sc_val_from_ulong(1, temp);
609 sc_add(_exp(result), temp, _exp(result));
612 sc_mul(_mant(a), _mant(b), _mant(result));
614 /* realign result: after a multiplication the digits right of the radix
615 * point are the sum of the factors' digits after the radix point. As all
616 * values are normalized they both have the same amount of these digits,
617 * which has to be restored by proper shifting
618 * +2 because of the two rounding bits */
619 sc_val_from_ulong(2 + _desc(result).mantissa_size, temp);
621 _shift_right(_mant(result), temp, _mant(result));
623 return _normalize(result, result, sc_had_carry());
629 static char* _fdiv(const char* a, const char* b, char* result)
631 char *temp, *dividend;
633 handle_NAN(a, b, result);
635 temp = alloca(value_size);
636 dividend = alloca(value_size);
638 if (result != a && result != b)
639 memcpy(&_desc(result), &_desc(a), sizeof(descriptor_t));
641 _sign(result) = _sign(a) ^ _sign(b);
643 /* produce nan on 0/0 and inf/inf */
644 if (_desc(a).clss == ZERO) {
645 if (_desc(b).clss == ZERO)
647 fc_get_qnan(_desc(a).exponent_size, _desc(a).mantissa_size, result);
650 if (a != result) memcpy(result+SIGN_POS+1, a+SIGN_POS+1, calc_buffer_size-1);
654 if (_desc(b).clss == INF) {
655 if (_desc(a).clss == INF)
657 fc_get_qnan(_desc(a).exponent_size, _desc(a).mantissa_size, result);
660 sc_val_from_ulong(0, NULL);
661 _save_result(_exp(result));
662 _save_result(_mant(result));
663 _desc(result).clss = ZERO;
668 if (_desc(a).clss == INF) {
670 if (a != result) memcpy(result+SIGN_POS+1, a+SIGN_POS+1, calc_buffer_size-1);
673 if (_desc(b).clss == ZERO) {
674 /* division by zero */
676 fc_get_minusinf(_desc(a).exponent_size, _desc(a).mantissa_size, result);
678 fc_get_plusinf(_desc(a).exponent_size, _desc(a).mantissa_size, result);
682 /* exp = exp(a) - exp(b) + excess - 1*/
683 sc_sub(_exp(a), _exp(b), _exp(result));
684 sc_val_from_ulong((1 << _desc(a).exponent_size)/2-2, temp);
685 sc_add(_exp(result), temp, _exp(result));
687 /* mixed normal, subnormal values introduce an error of 1, correct it */
688 if ((_desc(a).clss == SUBNORMAL) ^ (_desc(b).clss == SUBNORMAL))
690 sc_val_from_ulong(1, temp);
691 sc_add(_exp(result), temp, _exp(result));
694 /* mant(res) = mant(a) / 1/2mant(b) */
695 /* to gain more bits of precision in the result the dividend could be
696 * shifted left, as this operation does not loose bits. This would not
697 * fit into the integer precision, but due to the rounding bits (which
698 * are always zero because the values are all normalized) the divisor
699 * can be shifted right instead to achieve the same result */
700 sc_val_from_ulong(2 + _desc(result).mantissa_size, temp);
702 _shift_left(_mant(a), temp, dividend);
705 char *divisor = alloca(calc_buffer_size);
706 sc_val_from_ulong(1, divisor);
707 _shift_right(_mant(b), divisor, divisor);
708 sc_div(dividend, divisor, _mant(result));
711 return _normalize(result, result, sc_had_carry());
714 static void _power_of_ten(int exp, descriptor_t *desc, char *result)
722 /* set new descriptor (else result is supposed to already have one) */
724 memcpy(&_desc(result), desc, sizeof(descriptor_t));
726 build = alloca(value_size);
727 temp = alloca(value_size);
729 sc_val_from_ulong((1 << _desc(result).exponent_size)/2-1, _exp(result));
733 /* temp is value of ten now */
734 sc_val_from_ulong(10, NULL);
737 for (exp--; exp > 0; exp--) {
739 sc_mul(build, temp, NULL);
743 /* temp is amount of left shift needed to put the value left of the radix point */
744 sc_val_from_ulong(_desc(result).mantissa_size + 2, temp);
746 _shift_left(build, temp, _mant(result));
748 _normalize(result, result, 0);
753 * Truncate the fractional part away.
755 * This does not clip to any integer rang.
757 static char* _trunc(const char *a, char *result)
760 * When exponent == 0 all bits left of the radix point
761 * are the integral part of the value. For 15bit exp_size
762 * this would require a left shift of max. 16383 bits which
764 * But it is enough to ensure that no bit right of the radix
765 * point remains set. This restricts the interesting
766 * exponents to the interval [0, mant_size-1].
767 * Outside this interval the truncated value is either 0 or
768 * it does not have fractional parts.
771 int exp_bias, exp_val;
774 temp = alloca(value_size);
777 memcpy(&_desc(result), &_desc(a), sizeof(descriptor_t));
779 exp_bias = (1<<_desc(a).exponent_size)/2-1;
780 exp_val = sc_val_to_long(_exp(a)) - exp_bias;
783 sc_val_from_ulong(0, NULL);
784 _save_result(_exp(result));
785 _save_result(_mant(result));
786 _desc(result).clss = ZERO;
791 if (exp_val > _desc(a).mantissa_size) {
793 memcpy(result, a, calc_buffer_size);
798 /* set up a proper mask to delete all bits right of the
799 * radix point if the mantissa had been shifted until exp == 0 */
800 sc_max_from_bits(1 + exp_val, 0, temp);
801 sc_val_from_long(_desc(a).mantissa_size - exp_val + 2, NULL);
802 _shift_left(temp, sc_get_buffer(), temp);
804 /* and the mask and return the result */
805 sc_and(_mant(a), temp, _mant(result));
807 if (a != result) memcpy(_exp(result), _exp(a), value_size);
813 * This does value sanity checking(or should do it), sets up any prerequisites,
814 * calls the proper internal functions, clears up and returns
817 char* _calc(const char *a, const char *b, int opcode, char *result)
820 #ifdef FLTCALC_TRACE_CALC
823 buffer = alloca(100);
826 if (result == NULL) result = calc_buffer;
828 TRACEPRINTF(("%s ", fc_print(a, buffer, 100, FC_PACKED)));
832 /* make the value with the bigger exponent the first one */
833 TRACEPRINTF(("+ %s ", fc_print(b, buffer, 100, FC_PACKED)));
834 if (sc_comp(_exp(a), _exp(b)) == -1)
840 TRACEPRINTF(("- %s ", fc_print(b, buffer, 100, FC_PACKED)));
841 temp = alloca(calc_buffer_size);
842 memcpy(temp, b, calc_buffer_size);
843 _sign(temp) = !_sign(b);
844 if (sc_comp(_exp(a), _exp(temp)) == -1)
845 _fadd(temp, a, result);
847 _fadd(a, temp, result);
850 TRACEPRINTF(("* %s ", fc_print(b, buffer, 100, FC_PACKED)));
854 TRACEPRINTF(("/ %s ", fc_print(b, buffer, 100, FC_PACKED)));
858 TRACEPRINTF(("negated "));
859 if (a != result) memcpy(result, a, calc_buffer_size);
860 _sign(result) = !_sign(a);
863 TRACEPRINTF(("truncated to integer "));
867 TRACEPRINTF(("rounded to integer "));
872 TRACEPRINTF(("= %s\n", fc_print(result, buffer, 100, FC_PACKED)));
877 * functions defined in fltcalc.h
879 const void *fc_get_buffer(void)
884 int fc_get_buffer_length(void)
886 return calc_buffer_size;
889 char* fc_val_from_str(const char *str, unsigned int len, char exp_size, char mant_size, char *result)
902 int exp_int, hsb, state;
907 char *mant_str, *exp_val, *power_val;
909 if (result == NULL) result = calc_buffer;
911 exp_val = alloca(value_size);
912 power_val = alloca(calc_buffer_size);
913 mant_str = alloca((len)?(len):(strlen(str)));
915 _desc(result).exponent_size = exp_size;
916 _desc(result).mantissa_size = mant_size;
917 _desc(result).clss = NORMAL;
924 while (len == 0 || str-old_str < len)
941 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
948 state = RIGHT_OF_DOT;
959 _fail_char(old_str, len, str - old_str);
965 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
966 mant_str[pos++] = *(str++);
970 state = RIGHT_OF_DOT;
981 mant_str[pos] = '\0';
985 _fail_char(old_str, len, str - old_str);
991 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
992 mant_str[pos++] = *(str++);
1003 mant_str[pos] = '\0';
1007 _fail_char(old_str, len, str - old_str);
1017 if (*(str-1) != 'e' && *(str-1) != 'E') _fail_char(old_str, len, str - old_str);
1021 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
1022 mant_str[pos] = '\0';
1029 _fail_char(old_str, len, str - old_str);
1035 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
1040 case '\0': goto done;
1043 _fail_char(old_str, len, str - old_str);
1046 } /* switch(state) */
1049 sc_val_from_str(mant_str, strlen(mant_str), _mant(result));
1051 /* shift to put value left of radix point */
1052 sc_val_from_ulong(mant_size + 2, exp_val);
1054 _shift_left(_mant(result), exp_val, _mant(result));
1056 sc_val_from_ulong((1 << exp_size)/2-1, _exp(result));
1058 _normalize(result, result, 0);
1060 if (state == EXPONENT) {
1061 exp_int -= atoi(str-pos);
1064 _power_of_ten(exp_int, &_desc(result), power_val);
1066 _fdiv(result, power_val, result);
1071 /* XXX excuse of an implementation to make things work */
1073 #ifdef HAVE_LONG_DOUBLE
1074 val = strtold(str, NULL);
1076 val = strtod(str, NULL);
1079 DEBUGPRINTF(("val_from_str(%s)\n", str));
1080 return fc_val_from_float(val, exp_size, mant_size, result);
1084 char* fc_val_from_float(LLDBL l, char exp_size, char mant_size, char* result)
1087 int bias_res, bias_val, mant_val;
1089 UINT32 sign, exponent, mantissa0, mantissa1;
1092 bias_res = ((1<<exp_size)/2-1);
1094 #ifdef HAVE_LONG_DOUBLE
1097 sign = (srcval.val.high & 0x00008000) != 0;
1098 exponent = (srcval.val.high & 0x00007FFF) ;
1099 mantissa0 = srcval.val.mid;
1100 mantissa1 = srcval.val.low;
1101 #else /* no long double */
1104 sign = (srcval.val.high & 0x80000000) != 0;
1105 exponent = (srcval.val.high & 0x7FF00000) >> 20;
1106 mantissa0 = srcval.val.high & 0x000FFFFF;
1107 mantissa1 = srcval.val.low;
1110 #ifdef HAVE_LONG_DOUBLE
1111 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)); */
1112 DEBUGPRINTF(("(%d-%.4X-%.8X%.8X)\n", sign, exponent, mantissa0, mantissa1));
1114 TRACEPRINTF(("val_from_float(%.8X%.8X)\n", srcval.val.high, srcval.val.low));
1115 DEBUGPRINTF(("(%d-%.3X-%.5X%.8X)\n", sign, exponent, mantissa0, mantissa1));
1118 if (result == NULL) result = calc_buffer;
1119 temp = alloca(value_size);
1121 _desc(result).exponent_size = exp_size;
1122 _desc(result).mantissa_size = mant_size;
1125 _sign(result) = sign;
1127 /* sign and flag suffice to identify nan or inf, no exponent/mantissa
1128 * encoding is needed. the function can return immediately in these cases */
1130 _desc(result).clss = NAN;
1131 TRACEPRINTF(("val_from_float resulted in NAN\n"));
1134 else if (isinf(l)) {
1135 _desc(result).clss = INF;
1136 TRACEPRINTF(("val_from_float resulted in %sINF\n", (_sign(result)==1)?"-":""));
1140 /* build exponent, because input and output exponent and mantissa sizes may differ
1141 * this looks more complicated than it is: unbiased input exponent + output bias,
1142 * minus the mantissa difference which is added again later when the output float
1143 * becomes normalized */
1144 #ifdef HAVE_EXPLICIT_ONE
1145 sc_val_from_long((exponent-bias_val+bias_res)-(mant_val-mant_size-1), _exp(result));
1147 sc_val_from_long((exponent-bias_val+bias_res)-(mant_val-mant_size), _exp(result));
1150 /* build mantissa representation */
1151 #ifndef HAVE_EXPLICIT_ONE
1154 /* insert the hidden bit */
1155 sc_val_from_ulong(1, temp);
1156 sc_val_from_ulong(mant_val + 2, NULL);
1157 _shift_left(temp, sc_get_buffer(), NULL);
1162 sc_val_from_ulong(0, NULL);
1165 _save_result(_mant(result));
1167 /* bits from the upper word */
1168 sc_val_from_ulong(mantissa0, temp);
1169 sc_val_from_ulong(34, NULL);
1170 _shift_left(temp, sc_get_buffer(), temp);
1171 sc_or(_mant(result), temp, _mant(result));
1173 /* bits from the lower word */
1174 sc_val_from_ulong(mantissa1, temp);
1175 sc_val_from_ulong(2, NULL);
1176 _shift_left(temp, sc_get_buffer(), temp);
1177 sc_or(_mant(result), temp, _mant(result));
1179 /* _normalize expects the radix point to be normal, so shift mantissa of subnormal
1180 * origin one to the left */
1183 sc_val_from_ulong(1, NULL);
1184 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1187 _normalize(result, result, 0);
1189 TRACEPRINTF(("val_from_float results in %s\n", fc_print(result, temp, calc_buffer_size, FC_PACKED)));
1194 LLDBL fc_val_to_float(const void *val)
1208 #ifdef HAVE_LONG_DOUBLE
1209 char result_exponent = 15;
1210 char result_mantissa = 64;
1212 char result_exponent = 11;
1213 char result_mantissa = 52;
1216 temp = alloca(calc_buffer_size);
1217 #ifdef HAVE_EXPLICIT_ONE
1218 value = fc_cast(val, result_exponent, result_mantissa-1, temp);
1220 value = fc_cast(val, result_exponent, result_mantissa, temp);
1223 sign = _sign(value);
1225 /* @@@ long double exponent is 15bit, so the use of sc_val_to_long should not
1226 * lead to wrong results */
1227 exponent = sc_val_to_long(_exp(value)) ;
1229 sc_val_from_ulong(2, NULL);
1230 _shift_right(_mant(value), sc_get_buffer(), _mant(value));
1235 for (byte_offset = 0; byte_offset < 4; byte_offset++)
1236 mantissa1 |= sc_sub_bits(_mant(value), result_mantissa, byte_offset) << (byte_offset<<3);
1238 for (; (byte_offset<<3) < result_mantissa; byte_offset++)
1239 mantissa0 |= sc_sub_bits(_mant(value), result_mantissa, byte_offset) << ((byte_offset-4)<<3);
1241 #ifdef HAVE_LONG_DOUBLE
1242 buildval.val.high = sign << 15;
1243 buildval.val.high |= exponent;
1244 buildval.val.mid = mantissa0;
1245 buildval.val.low = mantissa1;
1246 #else /* no long double */
1247 mantissa0 &= 0x000FFFFF; /* get rid of garbage */
1248 buildval.val.high = sign << 31;
1249 buildval.val.high |= exponent << 20;
1250 buildval.val.high |= mantissa0;
1251 buildval.val.low = mantissa1;
1254 TRACEPRINTF(("val_to_float: %d-%x-%x%x\n", sign, exponent, mantissa0, mantissa1));
1258 char* fc_cast(const void *val, char exp_size, char mant_size, char *result)
1260 const char *value = (const char*) val;
1262 int exp_offset, val_bias, res_bias;
1264 if (result == NULL) result = calc_buffer;
1265 temp = alloca(value_size);
1267 if (_desc(value).exponent_size == exp_size && _desc(value).mantissa_size == mant_size)
1269 if (value != result) memcpy(result, value, calc_buffer_size);
1273 /* set the descriptor of the new value */
1274 _desc(result).exponent_size = exp_size;
1275 _desc(result).mantissa_size = mant_size;
1276 _desc(result).clss = _desc(value).clss;
1278 _sign(result) = _sign(value);
1280 /* when the mantissa sizes differ normalizing has to shift to align it.
1281 * this would change the exponent, which is unwanted. So calculate this
1282 * offset and add it */
1283 val_bias = (1<<_desc(value).exponent_size)/2-1;
1284 res_bias = (1<<exp_size)/2-1;
1286 exp_offset = (res_bias - val_bias) - (_desc(value).mantissa_size - mant_size);
1287 sc_val_from_long(exp_offset, temp);
1288 sc_add(_exp(value), temp, _exp(result));
1290 /* _normalize expects normalized radix point */
1291 if (_desc(val).clss == SUBNORMAL) {
1292 sc_val_from_ulong(1, NULL);
1293 _shift_left(_mant(val), sc_get_buffer(), _mant(result));
1294 } else if (value != result) {
1295 memcpy(_mant(result), _mant(value), value_size);
1297 memmove(_mant(result), _mant(value), value_size);
1300 _normalize(result, result, 0);
1301 TRACEPRINTF(("Cast results in %s\n", fc_print(result, temp, value_size, FC_PACKED)));
1305 char* fc_get_max(unsigned int exponent_size, unsigned int mantissa_size, char* result)
1307 if (result == NULL) result = calc_buffer;
1309 _desc(result).exponent_size = exponent_size;
1310 _desc(result).mantissa_size = mantissa_size;
1311 _desc(result).clss = NORMAL;
1315 sc_val_from_ulong((1<<exponent_size) - 2, _exp(result));
1317 sc_max_from_bits(mantissa_size + 1, 0, _mant(result));
1318 sc_val_from_ulong(2, NULL);
1319 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1324 char* fc_get_min(unsigned int exponent_size, unsigned int mantissa_size, char *result)
1326 if (result == NULL) result = calc_buffer;
1328 fc_get_max(exponent_size, mantissa_size, result);
1334 char* fc_get_snan(unsigned int exponent_size, unsigned int mantissa_size, char *result)
1336 if (result == NULL) result = calc_buffer;
1338 _desc(result).exponent_size = exponent_size;
1339 _desc(result).mantissa_size = mantissa_size;
1340 _desc(result).clss = NAN;
1344 sc_val_from_ulong((1<<exponent_size)-1, _exp(result));
1346 /* signaling NaN has non-zero mantissa with msb not set */
1347 sc_val_from_ulong(1, _mant(result));
1352 char* fc_get_qnan(unsigned int exponent_size, unsigned int mantissa_size, char *result)
1354 if (result == NULL) result = calc_buffer;
1356 _desc(result).exponent_size = exponent_size;
1357 _desc(result).mantissa_size = mantissa_size;
1358 _desc(result).clss = NAN;
1362 sc_val_from_ulong((1<<exponent_size)-1, _exp(result));
1364 /* quiet NaN has the msb of the mantissa set, so shift one there */
1365 sc_val_from_ulong(1, _mant(result));
1366 /* mantissa_size >+< 1 because of two extra rounding bits */
1367 sc_val_from_ulong(mantissa_size + 1, NULL);
1368 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1373 char* fc_get_plusinf(unsigned int exponent_size, unsigned int mantissa_size, char *result)
1375 if (result == NULL) result = calc_buffer;
1377 _desc(result).exponent_size = exponent_size;
1378 _desc(result).mantissa_size = mantissa_size;
1379 _desc(result).clss = NORMAL;
1383 sc_val_from_ulong((1<<exponent_size)-1, _exp(result));
1385 sc_val_from_ulong(0, _mant(result));
1390 char* fc_get_minusinf(unsigned int exponent_size, unsigned int mantissa_size, char *result)
1392 if (result == NULL) result = calc_buffer;
1394 fc_get_plusinf(exponent_size, mantissa_size, result);
1400 int fc_comp(const void *a, const void *b)
1402 const char *val_a = (const char*)a;
1403 const char *val_b = (const char*)b;
1407 * shortcut: if both values are identical, they are either
1408 * Unordered if NaN or equal
1411 return _desc(val_a).clss == NAN ? 2 : 0;
1413 /* unordered if one is a NaN */
1414 if (_desc(val_a).clss == NAN || _desc(val_b).clss == NAN)
1417 /* zero is equal independent of sign */
1418 if ((_desc(val_a).clss == ZERO) && (_desc(val_b).clss == ZERO))
1421 /* different signs make compare easy */
1422 if (_sign(val_a) != _sign(val_b))
1423 return (_sign(val_a)==0)?(1):(-1);
1425 mul = _sign(a) ? -1 : 1;
1427 /* both infinity means equality */
1428 if ((_desc(val_a).clss == INF) && (_desc(val_b).clss == INF))
1431 /* infinity is bigger than the rest */
1432 if (_desc(val_a).clss == INF)
1434 if (_desc(val_b).clss == INF)
1437 /* check first exponent, that mantissa if equal */
1438 switch (sc_comp(_exp(val_a), _exp(val_b))) {
1444 return sc_comp(_mant(val_a), _mant(val_b)) * mul;
1450 int fc_is_zero(const void *a)
1452 return _desc(a).clss == ZERO;
1455 int fc_is_negative(const void *a)
1460 int fc_is_inf(const void *a)
1462 return _desc(a).clss == INF;
1465 int fc_is_nan(const void *a)
1467 return _desc(a).clss == NAN;
1470 int fc_is_subnormal(const void *a)
1472 return _desc(a).clss == SUBNORMAL;
1475 char *fc_print(const void *a, char *buf, int buflen, unsigned base)
1480 val = (const char*)a;
1482 mul_1 = alloca(calc_buffer_size);
1486 switch (_desc(val).clss) {
1488 if (buflen >= 8+_sign(val)) sprintf(buf, "%sINFINITY", _sign(val)?"-":"");
1489 else snprintf(buf, buflen, "%sINF", _sign(val)?"-":NULL);
1492 snprintf(buf, buflen, "NAN");
1495 snprintf(buf, buflen, "0.0");
1498 /* XXX to be implemented */
1499 #ifdef HAVE_LONG_DOUBLE
1500 /* XXX 30 is arbitrary */
1501 snprintf(buf, buflen, "%.30LE", fc_val_to_float(val));
1503 snprintf(buf, buflen, "%.18E", fc_val_to_float(val));
1509 switch (_desc(val).clss) {
1511 if (buflen >= 8+_sign(val)) sprintf(buf, "%sINFINITY", _sign(val)?"-":"");
1512 else snprintf(buf, buflen, "%sINF", _sign(val)?"-":NULL);
1515 snprintf(buf, buflen, "NAN");
1518 snprintf(buf, buflen, "0.0");
1521 #ifdef HAVE_LONG_DOUBLE
1522 snprintf(buf, buflen, "%LA", fc_val_to_float(val));
1524 snprintf(buf, buflen, "%A", fc_val_to_float(val));
1531 snprintf(buf, buflen, "%s", sc_print(_pack(val, mul_1), value_size*4, SC_HEX));
1537 unsigned char fc_sub_bits(const void *value, unsigned num_bits, unsigned byte_ofs)
1539 /* this is used to cache the packed version of the value */
1540 static char *pack = NULL;
1542 if (pack == NULL) pack = xmalloc(value_size);
1545 _pack((const char*)value, pack);
1547 return sc_sub_bits(pack, num_bits, byte_ofs);
1550 fc_rounding_mode_t fc_set_rounding_mode(fc_rounding_mode_t mode)
1552 if (mode == FC_TONEAREST || mode == FC_TOPOSITIVE || mode == FC_TONEGATIVE || mode == FC_TOZERO)
1553 rounding_mode = mode;
1555 return rounding_mode;
1558 fc_rounding_mode_t fc_get_rounding_mode(void)
1560 return rounding_mode;
1563 void init_fltcalc(int precision)
1565 if (calc_buffer == NULL) {
1566 /* does nothing if already init */
1567 if (precision == 0) precision = FC_DEFAULT_PRECISION;
1569 init_strcalc(precision + 4);
1571 /* needs additionally two bits to round, a bit as explicit 1., and one for
1572 * addition overflow */
1573 max_precision = sc_get_precision() - 4;
1574 if (max_precision < precision)
1575 printf("WARING: not enough precision available, using %d\n", max_precision);
1577 rounding_mode = FC_TONEAREST;
1578 value_size = sc_get_buffer_length();
1580 EXPONENT_POS = SIGN_POS + sizeof(char);
1581 MANTISSA_POS = EXPONENT_POS + value_size;
1582 DESCRIPTOR_POS = MANTISSA_POS + value_size;
1583 calc_buffer_size = DESCRIPTOR_POS + sizeof(descriptor_t);
1585 calc_buffer = xmalloc(calc_buffer_size);
1586 DEBUGPRINTF(("init fltcalc:\n\tVALUE_SIZE = %d\n\tSIGN_POS = %d\n\tEXPONENT_POS = %d\n\tMANTISSA_POS = %d\n\tDESCRIPTOR_POS = %d\n\tCALC_BUFFER_SIZE = %d\n\tcalc_buffer = %p\n\n", value_size, SIGN_POS, EXPONENT_POS, MANTISSA_POS, DESCRIPTOR_POS, calc_buffer_size, calc_buffer));
1587 #ifdef HAVE_LONG_DOUBLE
1588 DEBUGPRINTF(("\tUsing long double (1-15-64) interface\n"));
1590 DEBUGPRINTF(("\tUsing double (1-11-52) interface\n"));
1592 #ifdef WORDS_BIGENDIAN
1593 DEBUGPRINTF(("\tWord order is big endian\n\n"));
1595 DEBUGPRINTF(("\tWord order is little endian\n\n"));
1600 void finish_fltcalc (void) {
1601 free(calc_buffer); calc_buffer = NULL;
1604 /* definition of interface functions */