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