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>
42 typedef uint32_t UINT32;
44 #ifdef HAVE_LONG_DOUBLE
45 #ifdef WORDS_BIGENDIAN
52 volatile long double d;
61 volatile long double d;
65 #ifdef WORDS_BIGENDIAN
85 * possible float states
88 NORMAL, /**< normal representation, implicit 1 */
90 SUBNORMAL, /**< denormals, implicit 0 */
92 NAN, /**< Not A Number */
95 /** A descriptor for an IEEE float value. */
97 unsigned char exponent_size; /**< size of exponent in bits */
98 unsigned char mantissa_size; /**< size of mantissa in bits */
99 value_class_t clss; /**< state of this float */
102 #define CLEAR_BUFFER(buffer) memset(buffer, 0, calc_buffer_size)
104 /* because variable sized structs are impossible, the internal
105 * value is represented as a pseudo-struct char array, addressed
108 * char sign; // 0 for positive, 1 for negative
109 * char exp[value_size];
110 * char mant[value_size];
114 #define _sign(a) (((char*)a)[SIGN_POS])
115 #define _exp(a) (&((char*)a)[EXPONENT_POS])
116 #define _mant(a) (&((char*)a)[MANTISSA_POS])
117 #define _desc(a) (*(descriptor_t *)&((char *)a)[DESCRIPTOR_POS])
119 #define _save_result(x) memcpy((x), sc_get_buffer(), value_size)
120 #define _shift_right(x, y, b) sc_shr((x), (y), value_size*4, 0, (b))
121 #define _shift_left(x, y, b) sc_shl((x), (y), value_size*4, 0, (b))
123 #define FC_DEFINE1(code) \
124 char *fc_##code(const void *a, void *result) { \
125 return _calc((const char*)a, NULL, FC_##code, (char*)result); \
128 #define FC_DEFINE2(code) \
129 char *fc_##code(const void *a, const void *b, void *result) { \
130 return _calc((const char*)a, (const char*)b, FC_##code, (char*)result); \
133 #define FUNC_PTR(code) fc_##code
136 # define DEBUGPRINTF(x) printf x
138 # define DEBUGPRINTF(x) ((void)0)
141 #if FLTCALC_TRACE_CALC
142 # define TRACEPRINTF(x) printf x
144 # define TRACEPRINTF(x) ((void)0)
147 static char *calc_buffer = NULL;
149 static fc_rounding_mode_t rounding_mode;
151 static int calc_buffer_size;
152 static int value_size;
154 static int EXPONENT_POS;
155 static int MANTISSA_POS;
156 static int DESCRIPTOR_POS;
158 static int max_precision;
163 static void _fail_char(const char *str, unsigned int len, int pos)
166 printf("ERROR: Unexpected character '%c'\n", *(str + pos));
168 printf("ERROR: Unexpected end of string\n");
169 while (len-- && *str) printf("%c", *str++); printf("\n");
170 while (pos--) printf(" "); printf("^\n");
171 /* the front end has to to check constant strings */
176 /** pack machine-like */
177 static char* _pack(const char *int_float, char *packed)
183 temp = alloca(value_size);
184 shift_val = alloca(value_size);
186 switch (_desc(int_float).clss) {
188 val_buffer = alloca(calc_buffer_size);
189 fc_get_qnan(_desc(int_float).exponent_size, _desc(int_float).mantissa_size, val_buffer);
190 int_float = val_buffer;
194 val_buffer = alloca(calc_buffer_size);
195 fc_get_plusinf(_desc(int_float).exponent_size, _desc(int_float).mantissa_size, val_buffer);
196 _sign(val_buffer) = _sign(int_float);
197 int_float = val_buffer;
204 sc_val_from_ulong(_sign(int_float), temp);
206 sc_val_from_ulong(_desc(int_float).exponent_size + _desc(int_float).mantissa_size, NULL);
207 _shift_left(temp, sc_get_buffer(), packed);
209 /* extract exponent */
210 sc_val_from_ulong(_desc(int_float).mantissa_size, shift_val);
212 _shift_left(_exp(int_float), shift_val, temp);
214 sc_or(temp, packed, packed);
216 /* extract mantissa */
217 /* remove 2 rounding bits */
218 sc_val_from_ulong(2, shift_val);
219 _shift_right(_mant(int_float), shift_val, temp);
221 /* remove leading 1 (or 0 if denormalized) */
222 sc_max_from_bits(_desc(int_float).mantissa_size, 0, shift_val); /* all mantissa bits are 1's */
223 sc_and(temp, shift_val, temp);
226 sc_or(temp, packed, packed);
231 char* _normalize(const char *in_val, char *out_val, int sticky)
234 char lsb, guard, round, round_dir = 0;
237 temp = alloca(value_size);
239 /* +2: save two rounding bits at the end */
240 hsb = 2 + _desc(in_val).mantissa_size - sc_get_highest_set_bit(_mant(in_val)) - 1;
242 if (in_val != out_val)
244 _sign(out_val) = _sign(in_val);
245 memcpy(&_desc(out_val), &_desc(in_val), sizeof(descriptor_t));
248 _desc(out_val).clss = NORMAL;
250 /* mantissa all zeros, so zero exponent (because of explicit one)*/
251 if (hsb == 2 + _desc(in_val).mantissa_size)
253 sc_val_from_ulong(0, _exp(out_val));
257 /* shift the first 1 into the left of the radix point (i.e. hsb == -1) */
261 sc_val_from_ulong(-hsb-1, temp);
263 _shift_right(_mant(in_val), temp, _mant(out_val));
265 /* remember if some bits were shifted away */
266 if (!sticky) sticky = sc_had_carry();
268 sc_add(_exp(in_val), temp, _exp(out_val));
273 sc_val_from_ulong(hsb+1, temp);
275 _shift_left(_mant(in_val), temp, _mant(out_val));
277 sc_sub(_exp(in_val), temp, _exp(out_val));
280 /* check for exponent underflow */
281 if (sc_is_negative(_exp(out_val)) || sc_is_zero(_exp(out_val))) {
282 DEBUGPRINTF(("Exponent underflow!\n"));
283 /* exponent underflow */
284 /* shift the mantissa right to have a zero exponent */
285 sc_val_from_ulong(1, temp);
286 sc_sub(temp, _exp(out_val), NULL);
288 _shift_right(_mant(out_val), sc_get_buffer(), _mant(out_val));
289 if (!sticky) sticky = sc_had_carry();
290 /* denormalized means exponent of zero */
291 sc_val_from_ulong(0, _exp(out_val));
293 _desc(out_val).clss = SUBNORMAL;
296 /* perform rounding by adding a value that clears the guard bit and the round bit
297 * and either causes a carry to round up or not */
298 /* get the last 3 bits of the value */
299 lsb = sc_sub_bits(_mant(out_val), _desc(out_val).mantissa_size + 2, 0) & 0x7;
300 guard = (lsb&0x2)>>1;
303 switch (rounding_mode)
306 /* round to nearest representable value, if in doubt choose the version
308 round_dir = guard && (sticky || round || lsb>>2);
311 /* if positive: round to one if the exact value is bigger, else to zero */
312 round_dir = (!_sign(out_val) && (guard || round || sticky));
315 /* if negative: round to one if the exact value is bigger, else to zero */
316 round_dir = (_sign(out_val) && (guard || round || sticky));
319 /* always round to 0 (chopping mode) */
323 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"));
327 guard = (round^guard)<<1;
328 lsb = !(round || guard)<<2 | guard | round;
332 lsb = -((guard<<1) | round);
335 /* add the rounded value */
337 sc_val_from_long(lsb, temp);
338 sc_add(_mant(out_val), temp, _mant(out_val));
341 /* could have rounded down to zero */
342 if (sc_is_zero(_mant(out_val)) && (_desc(out_val).clss == SUBNORMAL))
343 _desc(out_val).clss = ZERO;
345 /* check for rounding overflow */
346 hsb = 2 + _desc(out_val).mantissa_size - sc_get_highest_set_bit(_mant(out_val)) - 1;
347 if ((_desc(out_val).clss != SUBNORMAL) && (hsb < -1))
349 sc_val_from_ulong(1, temp);
350 _shift_right(_mant(out_val), temp, _mant(out_val));
352 sc_add(_exp(out_val), temp, _exp(out_val));
354 else if ((_desc(out_val).clss == SUBNORMAL) && (hsb == -1))
356 /* overflow caused the mantissa to be normal again,
357 * so adapt the exponent accordingly */
358 sc_val_from_ulong(1, temp);
359 sc_add(_exp(out_val), temp, _exp(out_val));
361 _desc(out_val).clss = NORMAL;
363 /* no further rounding is needed, because rounding overflow means
364 * the carry of the original rounding was propagated all the way
365 * up to the bit left of the radix point. This implies the bits
366 * to the right are all zeros (rounding is +1) */
368 /* check for exponent overflow */
369 sc_val_from_ulong((1 << _desc(out_val).exponent_size) - 1, temp);
370 if (sc_comp(_exp(out_val), temp) != -1) {
371 DEBUGPRINTF(("Exponent overflow!\n"));
372 /* exponent overflow, reaction depends on rounding method:
374 * mode | sign of value | result
375 *--------------------------------------------------------------
376 * TO_NEAREST | + | +inf
378 *--------------------------------------------------------------
379 * TO_POSITIVE | + | +inf
380 * | - | smallest representable value
381 *--------------------------------------------------------------
382 * TO_NEAGTIVE | + | largest representable value
384 *--------------------------------------------------------------
385 * TO_ZERO | + | largest representable value
386 * | - | smallest representable value
387 *--------------------------------------------------------------*/
388 if (_sign(out_val) == 0)
390 /* value is positive */
391 switch (rounding_mode) {
394 _desc(out_val).clss = INF;
399 fc_get_max(_desc(out_val).exponent_size, _desc(out_val).mantissa_size, out_val);
402 /* value is negative */
403 switch (rounding_mode) {
406 _desc(out_val).clss = INF;
411 fc_get_min(_desc(out_val).exponent_size, _desc(out_val).mantissa_size, out_val);
420 * Operations involving NaN's must return NaN
422 #define handle_NAN(a, b, result) \
424 if (_desc(a).clss == NAN) { \
425 if (a != result) memcpy(result, a, calc_buffer_size); \
428 if (_desc(b).clss == NAN) { \
429 if (b != result) memcpy(result, b, calc_buffer_size); \
436 * calculate a + b, where a is the value with the bigger exponent
438 static char* _fadd(const char* a, const char* b, char* result)
446 handle_NAN(a, b, result);
448 /* make sure result has a descriptor */
449 if (result != a && result != b)
450 memcpy(&_desc(result), &_desc(a), sizeof(descriptor_t));
452 /* determine if this is an addition or subtraction */
453 sign = _sign(a) ^ _sign(b);
455 /* produce NaN on inf - inf */
456 if (sign && (_desc(a).clss == INF) && (_desc(b).clss == INF))
457 return fc_get_qnan(_desc(a).exponent_size, _desc(b).mantissa_size, result);
459 temp = alloca(value_size);
460 exp_diff = alloca(value_size);
462 /* get exponent difference */
463 sc_sub(_exp(a), _exp(b), exp_diff);
465 /* initially set sign to be the sign of a, special treatment of subtraction
466 * when exponents are equal is required though.
467 * Also special care about the sign is needed when the mantissas are equal
469 if (sign && sc_val_to_long(exp_diff) == 0) {
470 switch (sc_comp(_mant(a), _mant(b))) {
472 _sign(result) = _sign(a); /* abs(a) is bigger and a is negative */
475 _sign(result) = (rounding_mode == FC_TONEGATIVE);
478 _sign(result) = _sign(b); /* abs(b) is bigger and b is negative */
481 /* can't be reached */
486 _sign(result) = _sign(a);
488 /* sign has been taken care of, check for special cases */
489 if (_desc(a).clss == ZERO) {
490 if (b != result) memcpy(result+SIGN_POS+1, b+SIGN_POS+1, calc_buffer_size-SIGN_POS-1);
493 if (_desc(b).clss == ZERO) {
494 if (a != result) memcpy(result+SIGN_POS+1, a+SIGN_POS+1, calc_buffer_size-SIGN_POS-1);
498 if (_desc(a).clss == INF) {
499 if (a != result) memcpy(result+SIGN_POS+1, a+SIGN_POS+1, calc_buffer_size-SIGN_POS-1);
502 if (_desc(b).clss == INF) {
503 if (b != result) memcpy(result+SIGN_POS+1, b+SIGN_POS+1, calc_buffer_size-SIGN_POS-1);
507 /* shift the smaller value to the right to align the radix point */
508 /* subnormals have their radix point shifted to the right,
509 * take care of this first */
510 if ((_desc(b).clss == SUBNORMAL) && (_desc(a).clss != SUBNORMAL))
512 sc_val_from_ulong(1, temp);
513 sc_sub(exp_diff, temp, exp_diff);
516 _shift_right(_mant(b), exp_diff, temp);
517 sticky = sc_had_carry();
521 /* if subtracting a little more than the represented value or adding a little
522 * more than the represented value to a negative value this, in addition to the
523 * still set sticky bit, takes account of the 'little more' */
524 char *temp1 = alloca(calc_buffer_size);
525 sc_val_from_ulong(1, temp1);
526 sc_add(temp, temp1, temp);
530 if (sc_comp(_mant(a), temp) == -1)
531 sc_sub(temp, _mant(a), _mant(result));
533 sc_sub(_mant(a), temp, _mant(result));
535 sc_add(_mant(a), temp, _mant(result));
538 /* _normalize expects a 'normal' radix point, adding two subnormals
539 * results in a subnormal radix point -> shifting before normalizing */
540 if ((_desc(a).clss == SUBNORMAL) && (_desc(b).clss == SUBNORMAL))
542 sc_val_from_ulong(1, NULL);
543 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
546 /* resulting exponent is the bigger one */
547 memmove(_exp(result), _exp(a), value_size);
549 return _normalize(result, result, sticky);
555 static char* _fmul(const char* a, const char* b, char* result)
559 handle_NAN(a, b, result);
561 temp = alloca(value_size);
563 if (result != a && result != b)
564 memcpy(&_desc(result), &_desc(a), sizeof(descriptor_t));
566 _sign(result) = _sign(a) ^ _sign(b);
568 /* produce NaN on 0 * inf */
569 if (_desc(a).clss == ZERO) {
570 if (_desc(b).clss == INF)
571 fc_get_qnan(_desc(a).exponent_size, _desc(a).mantissa_size, result);
573 if (a != result) memcpy(result+SIGN_POS+1, a+SIGN_POS+1, calc_buffer_size-1);
576 if (_desc(b).clss == ZERO) {
577 if (_desc(a).clss == INF)
578 fc_get_qnan(_desc(a).exponent_size, _desc(a).mantissa_size, result);
580 if (b != result) memcpy(result+SIGN_POS+1, b+SIGN_POS+1, calc_buffer_size-1);
584 if (_desc(a).clss == INF) {
585 if (a != result) memcpy(result+SIGN_POS+1, a+SIGN_POS+1, calc_buffer_size-1);
588 if (_desc(b).clss == INF) {
589 if (b != result) memcpy(result+SIGN_POS+1, b+SIGN_POS+1, calc_buffer_size-1);
593 /* exp = exp(a) + exp(b) - excess */
594 sc_add(_exp(a), _exp(b), _exp(result));
596 sc_val_from_ulong((1<<_desc(a).exponent_size)/2-1, temp);
597 sc_sub(_exp(result), temp, _exp(result));
599 /* mixed normal, subnormal values introduce an error of 1, correct it */
600 if ((_desc(a).clss == SUBNORMAL) ^ (_desc(b).clss == SUBNORMAL))
602 sc_val_from_ulong(1, temp);
603 sc_add(_exp(result), temp, _exp(result));
606 sc_mul(_mant(a), _mant(b), _mant(result));
608 /* realign result: after a multiplication the digits right of the radix
609 * point are the sum of the factors' digits after the radix point. As all
610 * values are normalized they both have the same amount of these digits,
611 * which has to be restored by proper shifting
612 * +2 because of the two rounding bits */
613 sc_val_from_ulong(2 + _desc(result).mantissa_size, temp);
615 _shift_right(_mant(result), temp, _mant(result));
617 return _normalize(result, result, sc_had_carry());
623 static char* _fdiv(const char* a, const char* b, char* result)
625 char *temp, *dividend;
627 handle_NAN(a, b, result);
629 temp = alloca(value_size);
630 dividend = alloca(value_size);
632 if (result != a && result != b)
633 memcpy(&_desc(result), &_desc(a), sizeof(descriptor_t));
635 _sign(result) = _sign(a) ^ _sign(b);
637 /* produce nan on 0/0 and inf/inf */
638 if (_desc(a).clss == ZERO) {
639 if (_desc(b).clss == ZERO)
641 fc_get_qnan(_desc(a).exponent_size, _desc(a).mantissa_size, result);
644 if (a != result) memcpy(result+SIGN_POS+1, a+SIGN_POS+1, calc_buffer_size-1);
648 if (_desc(b).clss == INF) {
649 if (_desc(a).clss == INF)
651 fc_get_qnan(_desc(a).exponent_size, _desc(a).mantissa_size, result);
654 sc_val_from_ulong(0, NULL);
655 _save_result(_exp(result));
656 _save_result(_mant(result));
657 _desc(result).clss = ZERO;
662 if (_desc(a).clss == INF) {
664 if (a != result) memcpy(result+SIGN_POS+1, a+SIGN_POS+1, calc_buffer_size-1);
667 if (_desc(b).clss == ZERO) {
668 /* division by zero */
670 fc_get_minusinf(_desc(a).exponent_size, _desc(a).mantissa_size, result);
672 fc_get_plusinf(_desc(a).exponent_size, _desc(a).mantissa_size, result);
676 /* exp = exp(a) - exp(b) + excess - 1*/
677 sc_sub(_exp(a), _exp(b), _exp(result));
678 sc_val_from_ulong((1 << _desc(a).exponent_size)/2-2, temp);
679 sc_add(_exp(result), temp, _exp(result));
681 /* mixed normal, subnormal values introduce an error of 1, correct it */
682 if ((_desc(a).clss == SUBNORMAL) ^ (_desc(b).clss == SUBNORMAL))
684 sc_val_from_ulong(1, temp);
685 sc_add(_exp(result), temp, _exp(result));
688 /* mant(res) = mant(a) / 1/2mant(b) */
689 /* to gain more bits of precision in the result the dividend could be
690 * shifted left, as this operation does not loose bits. This would not
691 * fit into the integer precision, but due to the rounding bits (which
692 * are always zero because the values are all normalized) the divisor
693 * can be shifted right instead to achieve the same result */
694 sc_val_from_ulong(2 + _desc(result).mantissa_size, temp);
696 _shift_left(_mant(a), temp, dividend);
699 char *divisor = alloca(calc_buffer_size);
700 sc_val_from_ulong(1, divisor);
701 _shift_right(_mant(b), divisor, divisor);
702 sc_div(dividend, divisor, _mant(result));
705 return _normalize(result, result, sc_had_carry());
709 static void _power_of_ten(int exp, descriptor_t *desc, char *result)
717 /* set new descriptor (else result is supposed to already have one) */
719 memcpy(&_desc(result), desc, sizeof(descriptor_t));
721 build = alloca(value_size);
722 temp = alloca(value_size);
724 sc_val_from_ulong((1 << _desc(result).exponent_size)/2-1, _exp(result));
728 /* temp is value of ten now */
729 sc_val_from_ulong(10, NULL);
732 for (exp--; exp > 0; exp--) {
734 sc_mul(build, temp, NULL);
738 /* temp is amount of left shift needed to put the value left of the radix point */
739 sc_val_from_ulong(_desc(result).mantissa_size + 2, temp);
741 _shift_left(build, temp, _mant(result));
743 _normalize(result, result, 0);
749 * Truncate the fractional part away.
751 * This does not clip to any integer rang.
753 static char* _trunc(const char *a, char *result)
756 * When exponent == 0 all bits left of the radix point
757 * are the integral part of the value. For 15bit exp_size
758 * this would require a left shift of max. 16383 bits which
760 * But it is enough to ensure that no bit right of the radix
761 * point remains set. This restricts the interesting
762 * exponents to the interval [0, mant_size-1].
763 * Outside this interval the truncated value is either 0 or
764 * it does not have fractional parts.
767 int exp_bias, exp_val;
770 temp = alloca(value_size);
773 memcpy(&_desc(result), &_desc(a), sizeof(descriptor_t));
775 exp_bias = (1<<_desc(a).exponent_size)/2-1;
776 exp_val = sc_val_to_long(_exp(a)) - exp_bias;
779 sc_val_from_ulong(0, NULL);
780 _save_result(_exp(result));
781 _save_result(_mant(result));
782 _desc(result).clss = ZERO;
787 if (exp_val > _desc(a).mantissa_size) {
789 memcpy(result, a, calc_buffer_size);
794 /* set up a proper mask to delete all bits right of the
795 * radix point if the mantissa had been shifted until exp == 0 */
796 sc_max_from_bits(1 + exp_val, 0, temp);
797 sc_val_from_long(_desc(a).mantissa_size - exp_val + 2, NULL);
798 _shift_left(temp, sc_get_buffer(), temp);
800 /* and the mask and return the result */
801 sc_and(_mant(a), temp, _mant(result));
803 if (a != result) memcpy(_exp(result), _exp(a), value_size);
809 * This does value sanity checking(or should do it), sets up any prerequisites,
810 * calls the proper internal functions, clears up and returns
813 char* _calc(const char *a, const char *b, int opcode, char *result)
816 #ifdef FLTCALC_TRACE_CALC
819 buffer = alloca(100);
822 if (result == NULL) result = calc_buffer;
824 TRACEPRINTF(("%s ", fc_print(a, buffer, 100, FC_PACKED)));
828 /* make the value with the bigger exponent the first one */
829 TRACEPRINTF(("+ %s ", fc_print(b, buffer, 100, FC_PACKED)));
830 if (sc_comp(_exp(a), _exp(b)) == -1)
836 TRACEPRINTF(("- %s ", fc_print(b, buffer, 100, FC_PACKED)));
837 temp = alloca(calc_buffer_size);
838 memcpy(temp, b, calc_buffer_size);
839 _sign(temp) = !_sign(b);
840 if (sc_comp(_exp(a), _exp(temp)) == -1)
841 _fadd(temp, a, result);
843 _fadd(a, temp, result);
846 TRACEPRINTF(("* %s ", fc_print(b, buffer, 100, FC_PACKED)));
850 TRACEPRINTF(("/ %s ", fc_print(b, buffer, 100, FC_PACKED)));
854 TRACEPRINTF(("negated "));
855 if (a != result) memcpy(result, a, calc_buffer_size);
856 _sign(result) = !_sign(a);
859 TRACEPRINTF(("truncated to integer "));
863 TRACEPRINTF(("rounded to integer "));
868 TRACEPRINTF(("= %s\n", fc_print(result, buffer, 100, FC_PACKED)));
873 * functions defined in fltcalc.h
875 const void *fc_get_buffer(void)
880 int fc_get_buffer_length(void)
882 return calc_buffer_size;
885 char* fc_val_from_str(const char *str, unsigned int len, char exp_size, char mant_size, char *result)
898 int exp_int, hsb, state;
903 char *mant_str, *exp_val, *power_val;
905 if (result == NULL) result = calc_buffer;
907 exp_val = alloca(value_size);
908 power_val = alloca(calc_buffer_size);
909 mant_str = alloca((len)?(len):(strlen(str)));
911 _desc(result).exponent_size = exp_size;
912 _desc(result).mantissa_size = mant_size;
913 _desc(result).clss = NORMAL;
920 while (len == 0 || str-old_str < len)
937 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
944 state = RIGHT_OF_DOT;
955 _fail_char(old_str, len, str - old_str);
961 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
962 mant_str[pos++] = *(str++);
966 state = RIGHT_OF_DOT;
977 mant_str[pos] = '\0';
981 _fail_char(old_str, len, str - old_str);
987 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
988 mant_str[pos++] = *(str++);
999 mant_str[pos] = '\0';
1003 _fail_char(old_str, len, str - old_str);
1013 if (*(str-1) != 'e' && *(str-1) != 'E') _fail_char(old_str, len, str - old_str);
1017 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
1018 mant_str[pos] = '\0';
1025 _fail_char(old_str, len, str - old_str);
1031 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
1036 case '\0': goto done;
1039 _fail_char(old_str, len, str - old_str);
1042 } /* switch(state) */
1045 sc_val_from_str(mant_str, strlen(mant_str), _mant(result));
1047 /* shift to put value left of radix point */
1048 sc_val_from_ulong(mant_size + 2, exp_val);
1050 _shift_left(_mant(result), exp_val, _mant(result));
1052 sc_val_from_ulong((1 << exp_size)/2-1, _exp(result));
1054 _normalize(result, result, 0);
1056 if (state == EXPONENT) {
1057 exp_int -= atoi(str-pos);
1060 _power_of_ten(exp_int, &_desc(result), power_val);
1062 _fdiv(result, power_val, result);
1067 /* XXX excuse of an implementation to make things work */
1069 #ifdef HAVE_LONG_DOUBLE
1070 val = strtold(str, NULL);
1072 val = strtod(str, NULL);
1075 DEBUGPRINTF(("val_from_str(%s)\n", str));
1076 return fc_val_from_float(val, exp_size, mant_size, result);
1080 char* fc_val_from_float(LLDBL l, char exp_size, char mant_size, char* result)
1083 int bias_res, bias_val, mant_val;
1085 UINT32 sign, exponent, mantissa0, mantissa1;
1088 bias_res = ((1<<exp_size)/2-1);
1090 #ifdef HAVE_LONG_DOUBLE
1093 sign = (srcval.val.high & 0x00008000) != 0;
1094 exponent = (srcval.val.high & 0x00007FFF) ;
1095 mantissa0 = srcval.val.mid;
1096 mantissa1 = srcval.val.low;
1097 #else /* no long double */
1100 sign = (srcval.val.high & 0x80000000) != 0;
1101 exponent = (srcval.val.high & 0x7FF00000) >> 20;
1102 mantissa0 = srcval.val.high & 0x000FFFFF;
1103 mantissa1 = srcval.val.low;
1106 #ifdef HAVE_LONG_DOUBLE
1107 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)); */
1108 DEBUGPRINTF(("(%d-%.4X-%.8X%.8X)\n", sign, exponent, mantissa0, mantissa1));
1110 TRACEPRINTF(("val_from_float(%.8X%.8X)\n", srcval.val.high, srcval.val.low));
1111 DEBUGPRINTF(("(%d-%.3X-%.5X%.8X)\n", sign, exponent, mantissa0, mantissa1));
1114 if (result == NULL) result = calc_buffer;
1115 temp = alloca(value_size);
1117 _desc(result).exponent_size = exp_size;
1118 _desc(result).mantissa_size = mant_size;
1121 _sign(result) = sign;
1123 /* sign and flag suffice to identify nan or inf, no exponent/mantissa
1124 * encoding is needed. the function can return immediately in these cases */
1126 _desc(result).clss = NAN;
1127 TRACEPRINTF(("val_from_float resulted in NAN\n"));
1130 else if (isinf(l)) {
1131 _desc(result).clss = INF;
1132 TRACEPRINTF(("val_from_float resulted in %sINF\n", (_sign(result)==1)?"-":""));
1136 /* build exponent, because input and output exponent and mantissa sizes may differ
1137 * this looks more complicated than it is: unbiased input exponent + output bias,
1138 * minus the mantissa difference which is added again later when the output float
1139 * becomes normalized */
1140 #ifdef HAVE_EXPLICIT_ONE
1141 sc_val_from_long((exponent-bias_val+bias_res)-(mant_val-mant_size-1), _exp(result));
1143 sc_val_from_long((exponent-bias_val+bias_res)-(mant_val-mant_size), _exp(result));
1146 /* build mantissa representation */
1147 #ifndef HAVE_EXPLICIT_ONE
1150 /* insert the hidden bit */
1151 sc_val_from_ulong(1, temp);
1152 sc_val_from_ulong(mant_val + 2, NULL);
1153 _shift_left(temp, sc_get_buffer(), NULL);
1158 sc_val_from_ulong(0, NULL);
1161 _save_result(_mant(result));
1163 /* bits from the upper word */
1164 sc_val_from_ulong(mantissa0, temp);
1165 sc_val_from_ulong(34, NULL);
1166 _shift_left(temp, sc_get_buffer(), temp);
1167 sc_or(_mant(result), temp, _mant(result));
1169 /* bits from the lower word */
1170 sc_val_from_ulong(mantissa1, temp);
1171 sc_val_from_ulong(2, NULL);
1172 _shift_left(temp, sc_get_buffer(), temp);
1173 sc_or(_mant(result), temp, _mant(result));
1175 /* _normalize expects the radix point to be normal, so shift mantissa of subnormal
1176 * origin one to the left */
1179 sc_val_from_ulong(1, NULL);
1180 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1183 _normalize(result, result, 0);
1185 TRACEPRINTF(("val_from_float results in %s\n", fc_print(result, temp, calc_buffer_size, FC_PACKED)));
1190 LLDBL fc_val_to_float(const void *val)
1204 #ifdef HAVE_LONG_DOUBLE
1205 char result_exponent = 15;
1206 char result_mantissa = 64;
1208 char result_exponent = 11;
1209 char result_mantissa = 52;
1212 temp = alloca(calc_buffer_size);
1213 #ifdef HAVE_EXPLICIT_ONE
1214 value = fc_cast(val, result_exponent, result_mantissa-1, temp);
1216 value = fc_cast(val, result_exponent, result_mantissa, temp);
1219 sign = _sign(value);
1221 /* @@@ long double exponent is 15bit, so the use of sc_val_to_long should not
1222 * lead to wrong results */
1223 exponent = sc_val_to_long(_exp(value)) ;
1225 sc_val_from_ulong(2, NULL);
1226 _shift_right(_mant(value), sc_get_buffer(), _mant(value));
1231 for (byte_offset = 0; byte_offset < 4; byte_offset++)
1232 mantissa1 |= sc_sub_bits(_mant(value), result_mantissa, byte_offset) << (byte_offset<<3);
1234 for (; (byte_offset<<3) < result_mantissa; byte_offset++)
1235 mantissa0 |= sc_sub_bits(_mant(value), result_mantissa, byte_offset) << ((byte_offset-4)<<3);
1237 #ifdef HAVE_LONG_DOUBLE
1238 buildval.val.high = sign << 15;
1239 buildval.val.high |= exponent;
1240 buildval.val.mid = mantissa0;
1241 buildval.val.low = mantissa1;
1242 #else /* no long double */
1243 mantissa0 &= 0x000FFFFF; /* get rid of garbage */
1244 buildval.val.high = sign << 31;
1245 buildval.val.high |= exponent << 20;
1246 buildval.val.high |= mantissa0;
1247 buildval.val.low = mantissa1;
1250 TRACEPRINTF(("val_to_float: %d-%x-%x%x\n", sign, exponent, mantissa0, mantissa1));
1254 char* fc_cast(const void *val, char exp_size, char mant_size, char *result)
1256 const char *value = (const char*) val;
1258 int exp_offset, val_bias, res_bias;
1260 if (result == NULL) result = calc_buffer;
1261 temp = alloca(value_size);
1263 if (_desc(value).exponent_size == exp_size && _desc(value).mantissa_size == mant_size)
1265 if (value != result) memcpy(result, value, calc_buffer_size);
1269 /* set the descriptor of the new value */
1270 _desc(result).exponent_size = exp_size;
1271 _desc(result).mantissa_size = mant_size;
1272 _desc(result).clss = _desc(value).clss;
1274 _sign(result) = _sign(value);
1276 /* when the mantissa sizes differ normalizing has to shift to align it.
1277 * this would change the exponent, which is unwanted. So calculate this
1278 * offset and add it */
1279 val_bias = (1<<_desc(value).exponent_size)/2-1;
1280 res_bias = (1<<exp_size)/2-1;
1282 exp_offset = (res_bias - val_bias) - (_desc(value).mantissa_size - mant_size);
1283 sc_val_from_long(exp_offset, temp);
1284 sc_add(_exp(value), temp, _exp(result));
1286 /* _normalize expects normalized radix point */
1287 if (_desc(val).clss == SUBNORMAL) {
1288 sc_val_from_ulong(1, NULL);
1289 _shift_left(_mant(val), sc_get_buffer(), _mant(result));
1290 } else if (value != result) {
1291 memcpy(_mant(result), _mant(value), value_size);
1293 memmove(_mant(result), _mant(value), value_size);
1296 _normalize(result, result, 0);
1297 TRACEPRINTF(("Cast results in %s\n", fc_print(result, temp, value_size, FC_PACKED)));
1301 char* fc_get_max(unsigned int exponent_size, unsigned int mantissa_size, char* result)
1303 if (result == NULL) result = calc_buffer;
1305 _desc(result).exponent_size = exponent_size;
1306 _desc(result).mantissa_size = mantissa_size;
1307 _desc(result).clss = NORMAL;
1311 sc_val_from_ulong((1<<exponent_size) - 2, _exp(result));
1313 sc_max_from_bits(mantissa_size + 1, 0, _mant(result));
1314 sc_val_from_ulong(2, NULL);
1315 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1320 char* fc_get_min(unsigned int exponent_size, unsigned int mantissa_size, char *result)
1322 if (result == NULL) result = calc_buffer;
1324 fc_get_max(exponent_size, mantissa_size, result);
1330 char* fc_get_snan(unsigned int exponent_size, unsigned int mantissa_size, char *result)
1332 if (result == NULL) result = calc_buffer;
1334 _desc(result).exponent_size = exponent_size;
1335 _desc(result).mantissa_size = mantissa_size;
1336 _desc(result).clss = NAN;
1340 sc_val_from_ulong((1<<exponent_size)-1, _exp(result));
1342 /* signaling NaN has non-zero mantissa with msb not set */
1343 sc_val_from_ulong(1, _mant(result));
1348 char* fc_get_qnan(unsigned int exponent_size, unsigned int mantissa_size, char *result)
1350 if (result == NULL) result = calc_buffer;
1352 _desc(result).exponent_size = exponent_size;
1353 _desc(result).mantissa_size = mantissa_size;
1354 _desc(result).clss = NAN;
1358 sc_val_from_ulong((1<<exponent_size)-1, _exp(result));
1360 /* quiet NaN has the msb of the mantissa set, so shift one there */
1361 sc_val_from_ulong(1, _mant(result));
1362 /* mantissa_size >+< 1 because of two extra rounding bits */
1363 sc_val_from_ulong(mantissa_size + 1, NULL);
1364 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1369 char* fc_get_plusinf(unsigned int exponent_size, unsigned int mantissa_size, char *result)
1371 if (result == NULL) result = calc_buffer;
1373 _desc(result).exponent_size = exponent_size;
1374 _desc(result).mantissa_size = mantissa_size;
1375 _desc(result).clss = NORMAL;
1379 sc_val_from_ulong((1<<exponent_size)-1, _exp(result));
1381 sc_val_from_ulong(0, _mant(result));
1386 char* fc_get_minusinf(unsigned int exponent_size, unsigned int mantissa_size, char *result)
1388 if (result == NULL) result = calc_buffer;
1390 fc_get_plusinf(exponent_size, mantissa_size, result);
1396 int fc_comp(const void *a, const void *b)
1398 const char *val_a = (const char*)a;
1399 const char *val_b = (const char*)b;
1403 * shortcut: if both values are identical, they are either
1404 * Unordered if NaN or equal
1407 return _desc(val_a).clss == NAN ? 2 : 0;
1409 /* unordered if one is a NaN */
1410 if (_desc(val_a).clss == NAN || _desc(val_b).clss == NAN)
1413 /* zero is equal independent of sign */
1414 if ((_desc(val_a).clss == ZERO) && (_desc(val_b).clss == ZERO))
1417 /* different signs make compare easy */
1418 if (_sign(val_a) != _sign(val_b))
1419 return (_sign(val_a)==0)?(1):(-1);
1421 mul = _sign(a) ? -1 : 1;
1423 /* both infinity means equality */
1424 if ((_desc(val_a).clss == INF) && (_desc(val_b).clss == INF))
1427 /* infinity is bigger than the rest */
1428 if (_desc(val_a).clss == INF)
1430 if (_desc(val_b).clss == INF)
1433 /* check first exponent, that mantissa if equal */
1434 switch (sc_comp(_exp(val_a), _exp(val_b))) {
1440 return sc_comp(_mant(val_a), _mant(val_b)) * mul;
1446 int fc_is_zero(const void *a)
1448 return _desc(a).clss == ZERO;
1451 int fc_is_negative(const void *a)
1456 int fc_is_inf(const void *a)
1458 return _desc(a).clss == INF;
1461 int fc_is_nan(const void *a)
1463 return _desc(a).clss == NAN;
1466 int fc_is_subnormal(const void *a)
1468 return _desc(a).clss == SUBNORMAL;
1471 char *fc_print(const void *a, char *buf, int buflen, unsigned base)
1476 val = (const char*)a;
1478 mul_1 = alloca(calc_buffer_size);
1482 switch (_desc(val).clss) {
1484 if (buflen >= 8+_sign(val)) sprintf(buf, "%sINFINITY", _sign(val)?"-":"");
1485 else snprintf(buf, buflen, "%sINF", _sign(val)?"-":NULL);
1488 snprintf(buf, buflen, "NAN");
1491 snprintf(buf, buflen, "0.0");
1494 /* XXX to be implemented */
1495 #ifdef HAVE_LONG_DOUBLE
1496 /* XXX 30 is arbitrary */
1497 snprintf(buf, buflen, "%.30LE", fc_val_to_float(val));
1499 snprintf(buf, buflen, "%.18E", fc_val_to_float(val));
1505 switch (_desc(val).clss) {
1507 if (buflen >= 8+_sign(val)) sprintf(buf, "%sINFINITY", _sign(val)?"-":"");
1508 else snprintf(buf, buflen, "%sINF", _sign(val)?"-":NULL);
1511 snprintf(buf, buflen, "NAN");
1514 snprintf(buf, buflen, "0.0");
1517 #ifdef HAVE_LONG_DOUBLE
1518 snprintf(buf, buflen, "%LA", fc_val_to_float(val));
1520 snprintf(buf, buflen, "%A", fc_val_to_float(val));
1527 snprintf(buf, buflen, "%s", sc_print(_pack(val, mul_1), value_size*4, SC_HEX, 0));
1528 buf[buflen - 1] = '\0';
1534 unsigned char fc_sub_bits(const void *value, unsigned num_bits, unsigned byte_ofs)
1536 /* this is used to cache the packed version of the value */
1537 static char *pack = NULL;
1539 if (pack == NULL) pack = xmalloc(value_size);
1542 _pack((const char*)value, pack);
1544 return sc_sub_bits(pack, num_bits, byte_ofs);
1547 fc_rounding_mode_t fc_set_rounding_mode(fc_rounding_mode_t mode)
1549 if (mode == FC_TONEAREST || mode == FC_TOPOSITIVE || mode == FC_TONEGATIVE || mode == FC_TOZERO)
1550 rounding_mode = mode;
1552 return rounding_mode;
1555 fc_rounding_mode_t fc_get_rounding_mode(void)
1557 return rounding_mode;
1560 void init_fltcalc(int precision)
1562 if (calc_buffer == NULL) {
1563 /* does nothing if already init */
1564 if (precision == 0) precision = FC_DEFAULT_PRECISION;
1566 init_strcalc(precision + 4);
1568 /* needs additionally two bits to round, a bit as explicit 1., and one for
1569 * addition overflow */
1570 max_precision = sc_get_precision() - 4;
1571 if (max_precision < precision)
1572 printf("WARING: not enough precision available, using %d\n", max_precision);
1574 rounding_mode = FC_TONEAREST;
1575 value_size = sc_get_buffer_length();
1577 EXPONENT_POS = SIGN_POS + sizeof(char);
1578 MANTISSA_POS = EXPONENT_POS + value_size;
1579 DESCRIPTOR_POS = MANTISSA_POS + value_size;
1580 calc_buffer_size = DESCRIPTOR_POS + sizeof(descriptor_t);
1582 calc_buffer = xmalloc(calc_buffer_size);
1583 memset(calc_buffer, 0, calc_buffer_size);
1584 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));
1585 #ifdef HAVE_LONG_DOUBLE
1586 DEBUGPRINTF(("\tUsing long double (1-15-64) interface\n"));
1588 DEBUGPRINTF(("\tUsing double (1-11-52) interface\n"));
1590 #ifdef WORDS_BIGENDIAN
1591 DEBUGPRINTF(("\tWord order is big endian\n\n"));
1593 DEBUGPRINTF(("\tWord order is little endian\n\n"));
1598 void finish_fltcalc (void) {
1599 free(calc_buffer); calc_buffer = NULL;
1602 /* definition of interface functions */