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