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