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