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