float.c: mark read_exponent() static
[nasm.git] / float.c
blobf19454df6117968d37bc47ab8957a88a52957ba3
1 /* float.c floating-point constant support for the Netwide Assembler
3 * The Netwide Assembler is copyright (C) 1996 Simon Tatham and
4 * Julian Hall. All rights reserved. The software is
5 * redistributable under the licence given in the file "Licence"
6 * distributed in the NASM archive.
8 * initial version 13/ix/96 by Simon Tatham
9 */
11 #include "compiler.h"
13 #include <ctype.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <inttypes.h>
19 #include "nasm.h"
20 #include "float.h"
23 * -----------------
24 * local variables
25 * -----------------
27 static efunc error;
28 static bool daz = false; /* denormals as zero */
29 static enum float_round rc = FLOAT_RC_NEAR; /* rounding control */
32 * -----------
33 * constants
34 * -----------
37 /* 112 bits + 64 bits for accuracy + 16 bits for rounding */
38 #define MANT_WORDS 12
40 /* 52 digits fit in 176 bits because 10^53 > 2^176 > 10^52 */
41 #define MANT_DIGITS 52
43 /* the format and the argument list depend on MANT_WORDS */
44 #define MANT_FMT "%04x%04x_%04x%04x_%04x%04x_%04x%04x_%04x%04x_%04x%04x"
45 #define MANT_ARG SOME_ARG(mant, 0)
47 #define SOME_ARG(a,i) (a)[(i)+0], (a)[(i)+1], (a)[(i)+2], (a)[(i)+3], \
48 (a)[(i)+4], (a)[(i)+5], (a)[(i)+6], (a)[(i)+7], (a)[(i)+8], \
49 (a)[(i)+9], (a)[(i)+10], (a)[(i)+11]
52 * ---------------------------------------------------------------------------
53 * emit a printf()-like debug message... but only if DEBUG_FLOAT was defined
54 * ---------------------------------------------------------------------------
57 #ifdef DEBUG_FLOAT
58 #define dprintf(x) printf x
59 #else /* */
60 #define dprintf(x) do { } while (0)
61 #endif /* */
64 * ---------------------------------------------------------------------------
65 * multiply
66 * ---------------------------------------------------------------------------
68 static int float_multiply(uint16_t * to, uint16_t * from)
70 uint32_t temp[MANT_WORDS * 2];
71 int32_t i, j;
73 /*
74 * guaranteed that top bit of 'from' is set -- so we only have
75 * to worry about _one_ bit shift to the left
77 dprintf(("%s=" MANT_FMT "\n", "mul1", SOME_ARG(to, 0)));
78 dprintf(("%s=" MANT_FMT "\n", "mul2", SOME_ARG(from, 0)));
80 memset(temp, 0, sizeof temp);
82 for (i = 0; i < MANT_WORDS; i++) {
83 for (j = 0; j < MANT_WORDS; j++) {
84 uint32_t n;
85 n = (uint32_t) to[i] * (uint32_t) from[j];
86 temp[i + j] += n >> 16;
87 temp[i + j + 1] += n & 0xFFFF;
91 for (i = MANT_WORDS * 2; --i;) {
92 temp[i - 1] += temp[i] >> 16;
93 temp[i] &= 0xFFFF;
96 dprintf(("%s=" MANT_FMT "_" MANT_FMT "\n", "temp", SOME_ARG(temp, 0),
97 SOME_ARG(temp, MANT_WORDS)));
99 if (temp[0] & 0x8000) {
100 for (i = 0; i < MANT_WORDS; i++) {
101 to[i] = temp[i] & 0xFFFF;
103 dprintf(("%s=" MANT_FMT " (%i)\n", "prod", SOME_ARG(to, 0), 0));
104 return 0;
105 } else {
106 for (i = 0; i < MANT_WORDS; i++) {
107 to[i] = (temp[i] << 1) + !!(temp[i + 1] & 0x8000);
109 dprintf(("%s=" MANT_FMT " (%i)\n", "prod", SOME_ARG(to, 0), -1));
110 return -1;
115 * ---------------------------------------------------------------------------
116 * read an exponent; returns INT32_MAX on error
117 * ---------------------------------------------------------------------------
119 static int32_t read_exponent(const char *string, int32_t max)
121 int32_t i = 0;
122 bool neg = false;
124 if (*string == '+') {
125 string++;
126 } else if (*string == '-') {
127 neg = true;
128 string++;
130 while (*string) {
131 if (*string >= '0' && *string <= '9') {
132 i = (i * 10) + (*string - '0');
135 * To ensure that underflows and overflows are
136 * handled properly we must avoid wraparounds of
137 * the signed integer value that is used to hold
138 * the exponent. Therefore we cap the exponent at
139 * +/-5000, which is slightly more/less than
140 * what's required for normal and denormal numbers
141 * in single, double, and extended precision, but
142 * sufficient to avoid signed integer wraparound.
144 if (i > max) {
145 break;
147 } else if (*string == '_') {
148 /* do nothing */
149 } else {
150 error(ERR_NONFATAL,
151 "invalid character in floating-point constant %s: '%c'",
152 "exponent", *string);
153 return INT32_MAX;
155 string++;
158 return neg ? -i : i;
162 * ---------------------------------------------------------------------------
163 * convert
164 * ---------------------------------------------------------------------------
166 static bool ieee_flconvert(const char *string, uint16_t * mant,
167 int32_t * exponent)
169 char digits[MANT_DIGITS];
170 char *p, *q, *r;
171 uint16_t mult[MANT_WORDS], bit;
172 uint16_t *m;
173 int32_t tenpwr, twopwr;
174 int32_t extratwos;
175 bool started, seendot, warned;
176 p = digits;
177 tenpwr = 0;
178 started = seendot = false;
179 warned = (pass0 != 1);
180 while (*string && *string != 'E' && *string != 'e') {
181 if (*string == '.') {
182 if (!seendot) {
183 seendot = true;
184 } else {
185 error(ERR_NONFATAL,
186 "too many periods in floating-point constant");
187 return false;
189 } else if (*string >= '0' && *string <= '9') {
190 if (*string == '0' && !started) {
191 if (seendot) {
192 tenpwr--;
194 } else {
195 started = true;
196 if (p < digits + sizeof(digits)) {
197 *p++ = *string - '0';
198 } else {
199 if (!warned) {
200 error(ERR_WARNING|ERR_WARN_FL_TOOLONG,
201 "floating-point constant significand contains "
202 "more than %i digits", MANT_DIGITS);
203 warned = true;
206 if (!seendot) {
207 tenpwr++;
210 } else if (*string == '_') {
211 /* do nothing */
212 } else {
213 error(ERR_NONFATAL,
214 "invalid character in floating-point constant %s: '%c'",
215 "significand", *string);
216 return false;
218 string++;
221 if (*string) {
222 int32_t e;
224 string++; /* eat the E */
225 e = read_exponent(string, 5000);
226 if (e == INT32_MAX)
227 return false;
228 tenpwr += e;
232 * At this point, the memory interval [digits,p) contains a
233 * series of decimal digits zzzzzzz, such that our number X
234 * satisfies X = 0.zzzzzzz * 10^tenpwr.
236 q = digits;
237 dprintf(("X = 0."));
238 while (q < p) {
239 dprintf(("%c", *q + '0'));
240 q++;
242 dprintf((" * 10^%i\n", tenpwr));
245 * Now convert [digits,p) to our internal representation.
247 bit = 0x8000;
248 for (m = mant; m < mant + MANT_WORDS; m++) {
249 *m = 0;
251 m = mant;
252 q = digits;
253 started = false;
254 twopwr = 0;
255 while (m < mant + MANT_WORDS) {
256 uint16_t carry = 0;
257 while (p > q && !p[-1]) {
258 p--;
260 if (p <= q) {
261 break;
263 for (r = p; r-- > q;) {
264 int32_t i;
265 i = 2 * *r + carry;
266 if (i >= 10) {
267 carry = 1;
268 i -= 10;
269 } else {
270 carry = 0;
272 *r = i;
274 if (carry) {
275 *m |= bit;
276 started = true;
278 if (started) {
279 if (bit == 1) {
280 bit = 0x8000;
281 m++;
282 } else {
283 bit >>= 1;
285 } else {
286 twopwr--;
289 twopwr += tenpwr;
292 * At this point, the 'mant' array contains the first frac-
293 * tional places of a base-2^16 real number which when mul-
294 * tiplied by 2^twopwr and 5^tenpwr gives X.
296 dprintf(("X = " MANT_FMT " * 2^%i * 5^%i\n", MANT_ARG, twopwr,
297 tenpwr));
300 * Now multiply 'mant' by 5^tenpwr.
302 if (tenpwr < 0) { /* mult = 5^-1 = 0.2 */
303 for (m = mult; m < mult + MANT_WORDS - 1; m++) {
304 *m = 0xCCCC;
306 mult[MANT_WORDS - 1] = 0xCCCD;
307 extratwos = -2;
308 tenpwr = -tenpwr;
311 * If tenpwr was 1000...000b, then it becomes 1000...000b. See
312 * the "ANSI C" comment below for more details on that case.
314 * Because we already truncated tenpwr to +5000...-5000 inside
315 * the exponent parsing code, this shouldn't happen though.
317 } else if (tenpwr > 0) { /* mult = 5^+1 = 5.0 */
318 mult[0] = 0xA000;
319 for (m = mult + 1; m < mult + MANT_WORDS; m++) {
320 *m = 0;
322 extratwos = 3;
323 } else {
324 extratwos = 0;
326 while (tenpwr) {
327 dprintf(("loop=" MANT_FMT " * 2^%i * 5^%i (%i)\n", MANT_ARG,
328 twopwr, tenpwr, extratwos));
329 if (tenpwr & 1) {
330 dprintf(("mant*mult\n"));
331 twopwr += extratwos + float_multiply(mant, mult);
333 dprintf(("mult*mult\n"));
334 extratwos = extratwos * 2 + float_multiply(mult, mult);
335 tenpwr >>= 1;
338 * In ANSI C, the result of right-shifting a signed integer is
339 * considered implementation-specific. To ensure that the loop
340 * terminates even if tenpwr was 1000...000b to begin with, we
341 * manually clear the MSB, in case a 1 was shifted in.
343 * Because we already truncated tenpwr to +5000...-5000 inside
344 * the exponent parsing code, this shouldn't matter; neverthe-
345 * less it is the right thing to do here.
347 tenpwr &= (uint32_t) - 1 >> 1;
351 * At this point, the 'mant' array contains the first frac-
352 * tional places of a base-2^16 real number in [0.5,1) that
353 * when multiplied by 2^twopwr gives X. Or it contains zero
354 * of course. We are done.
356 *exponent = twopwr;
357 return true;
361 * ---------------------------------------------------------------------------
362 * round a mantissa off after i words
363 * ---------------------------------------------------------------------------
366 #define ROUND_COLLECT_BITS \
367 for (j = i; j < MANT_WORDS; j++) { \
368 m = m | mant[j]; \
371 #define ROUND_ABS_DOWN \
372 for (j = i; j < MANT_WORDS; j++) { \
373 mant[j] = 0x0000; \
376 #define ROUND_ABS_UP \
377 do { \
378 ++mant[--i]; \
379 mant[i] &= 0xFFFF; \
380 } while (i > 0 && !mant[i]); \
381 return (!i && !mant[i]);
383 static bool ieee_round(int sign, uint16_t * mant, int32_t i)
385 uint16_t m = 0;
386 int32_t j;
387 if ((sign == 0x0000) || (sign == 0x8000)) {
388 if (rc == FLOAT_RC_NEAR) {
389 if (mant[i] & 0x8000) {
390 mant[i] &= 0x7FFF;
391 ROUND_COLLECT_BITS;
392 mant[i] |= 0x8000;
393 if (m) {
394 ROUND_ABS_UP;
395 } else {
396 if (mant[i - 1] & 1) {
397 ROUND_ABS_UP;
398 } else {
399 ROUND_ABS_DOWN;
402 } else {
403 ROUND_ABS_DOWN;
405 } else if (((sign == 0x0000) && (rc == FLOAT_RC_DOWN))
406 || ((sign == 0x8000) && (rc == FLOAT_RC_UP))) {
407 ROUND_COLLECT_BITS;
408 if (m) {
409 ROUND_ABS_DOWN;
411 } else if (((sign == 0x0000) && (rc == FLOAT_RC_UP))
412 || ((sign == 0x8000) && (rc == FLOAT_RC_DOWN))) {
413 ROUND_COLLECT_BITS;
414 if (m) {
415 ROUND_ABS_UP;
417 } else if (rc == FLOAT_RC_ZERO) {
418 ROUND_ABS_DOWN;
419 } else {
420 error(ERR_PANIC, "float_round() can't handle rc=%i", rc);
422 } else {
423 error(ERR_PANIC, "float_round() can't handle sign=%i", sign);
425 return false;
428 static int hexval(char c)
430 if (c >= '0' && c <= '9')
431 return c - '0';
432 else if (c >= 'a' && c <= 'f')
433 return c - 'a' + 10;
434 else
435 return c - 'A' + 10;
438 static bool ieee_flconvert_hex(const char *string, uint16_t * mant,
439 int32_t * exponent)
441 static const int log2tbl[16] =
442 { -1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3 };
443 uint16_t mult[MANT_WORDS + 1], *mp;
444 int ms;
445 int32_t twopwr;
446 int seendot, seendigit;
447 unsigned char c;
449 twopwr = 0;
450 seendot = seendigit = 0;
451 ms = 0;
452 mp = NULL;
454 memset(mult, 0, sizeof mult);
456 while ((c = *string++) != '\0') {
457 if (c == '.') {
458 if (!seendot)
459 seendot = true;
460 else {
461 error(ERR_NONFATAL,
462 "too many periods in floating-point constant");
463 return false;
465 } else if (isxdigit(c)) {
466 int v = hexval(c);
468 if (!seendigit && v) {
469 int l = log2tbl[v];
471 seendigit = 1;
472 mp = mult;
473 ms = 15 - l;
475 twopwr = seendot ? twopwr - 4 + l : l - 3;
478 if (seendigit) {
479 if (ms <= 0) {
480 *mp |= v >> -ms;
481 mp++;
482 if (mp > &mult[MANT_WORDS])
483 mp = &mult[MANT_WORDS]; /* Guard slot */
484 ms += 16;
486 *mp |= v << ms;
487 ms -= 4;
489 if (!seendot)
490 twopwr += 4;
491 } else {
492 if (seendot)
493 twopwr -= 4;
495 } else if (c == 'p' || c == 'P') {
496 int32_t e;
497 e = read_exponent(string, 16384);
498 if (e == INT32_MAX)
499 return false;
500 twopwr += e;
501 break;
502 } else if (c == '_') {
503 /* ignore */
504 } else {
505 error(ERR_NONFATAL,
506 "floating-point constant: `%c' is invalid character", c);
507 return false;
511 if (!seendigit) {
512 memset(mant, 0, 2 * MANT_WORDS); /* Zero */
513 *exponent = 0;
514 } else {
515 memcpy(mant, mult, 2 * MANT_WORDS);
516 *exponent = twopwr;
519 return true;
523 * Shift a mantissa to the right by i bits.
525 static void ieee_shr(uint16_t * mant, int i)
527 uint16_t n, m;
528 int j = 0;
529 int sr, sl, offs;
531 sr = i%16; sl = 16-sr;
532 offs = i/16;
534 if (sr == 0) {
535 if (offs)
536 for (j = MANT_WORDS-1; j >= offs; j--)
537 mant[j] = mant[j-offs];
538 } else {
539 n = mant[MANT_WORDS-1-offs] >> sr;
540 for (j = MANT_WORDS-1; j > offs; j--) {
541 m = mant[j-offs-1];
542 mant[j] = (m << sl) | n;
543 n = m >> sr;
545 mant[j--] = n;
547 while (j >= 0)
548 mant[j--] = 0;
551 #if defined(__i386__) || defined(__x86_64__)
552 #define put(a,b) (*(uint16_t *)(a) = (b))
553 #else
554 #define put(a,b) (((a)[0] = (b)), ((a)[1] = (b) >> 8))
555 #endif
557 /* Set a bit, using *bigendian* bit numbering (0 = MSB) */
558 static void set_bit(uint16_t *mant, int bit)
560 mant[bit >> 4] |= 1 << (~bit & 15);
563 /* Test a single bit */
564 static int test_bit(const uint16_t *mant, int bit)
566 return (mant[bit >> 4] >> (~bit & 15)) & 1;
569 /* Report if the mantissa value is all zero */
570 static bool is_zero(const uint16_t *mant)
572 int i;
574 for (i = 0; i < MANT_WORDS; i++)
575 if (mant[i])
576 return false;
578 return true;
581 /* Produce standard IEEE formats, with implicit or explicit integer
582 bit; this makes the following assumptions:
584 - the sign bit is the MSB, followed by the exponent,
585 followed by the integer bit if present.
586 - the sign bit plus exponent fit in 16 bits.
587 - the exponent bias is 2^(n-1)-1 for an n-bit exponent */
589 struct ieee_format {
590 int words;
591 int mantissa; /* Fractional bits in the mantissa */
592 int explicit; /* Explicit integer */
593 int exponent; /* Bits in the exponent */
597 * The 16- and 128-bit formats are expected to be in IEEE 754r.
598 * AMD SSE5 uses the 16-bit format.
600 * The 32- and 64-bit formats are the original IEEE 754 formats.
602 * The 80-bit format is x87-specific, but widely used.
604 static const struct ieee_format ieee_16 = { 1, 10, 0, 5 };
605 static const struct ieee_format ieee_32 = { 2, 23, 0, 8 };
606 static const struct ieee_format ieee_64 = { 4, 52, 0, 11 };
607 static const struct ieee_format ieee_80 = { 5, 63, 1, 15 };
608 static const struct ieee_format ieee_128 = { 8, 112, 0, 15 };
610 /* Types of values we can generate */
611 enum floats {
612 FL_ZERO,
613 FL_DENORMAL,
614 FL_NORMAL,
615 FL_INFINITY,
616 FL_QNAN,
617 FL_SNAN
620 static int to_float(const char *str, int sign, uint8_t * result,
621 const struct ieee_format *fmt)
623 uint16_t mant[MANT_WORDS], *mp;
624 int32_t exponent = 0;
625 int32_t expmax = 1 << (fmt->exponent - 1);
626 uint16_t one_mask = 0x8000 >> ((fmt->exponent+fmt->explicit) % 16);
627 int one_pos = (fmt->exponent+fmt->explicit)/16;
628 int i;
629 int shift;
630 enum floats type;
631 bool ok;
633 sign = (sign < 0 ? 0x8000 : 0);
635 if (str[0] == '_') {
636 /* Special tokens */
638 switch (str[2]) {
639 case 'n': /* __nan__ */
640 case 'N':
641 case 'q': /* __qnan__ */
642 case 'Q':
643 type = FL_QNAN;
644 break;
645 case 's': /* __snan__ */
646 case 'S':
647 type = FL_SNAN;
648 break;
649 case 'i': /* __infinity__ */
650 case 'I':
651 type = FL_INFINITY;
652 break;
653 default:
654 error(ERR_NONFATAL,
655 "internal error: unknown FP constant token `%s'\n", str);
656 type = FL_QNAN;
657 break;
659 } else {
660 if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
661 ok = ieee_flconvert_hex(str + 2, mant, &exponent);
662 else
663 ok = ieee_flconvert(str, mant, &exponent);
665 if (!ok) {
666 type = FL_QNAN;
667 } else if (mant[0] & 0x8000) {
669 * Non-zero.
671 exponent--;
672 if (exponent >= 2 - expmax && exponent <= expmax) {
673 type = FL_NORMAL;
674 } else if (exponent < 2 - expmax &&
675 exponent >= 2 - expmax - fmt->mantissa) {
676 type = FL_DENORMAL;
677 } else if (exponent > 0) {
678 if (pass0 == 1)
679 error(ERR_WARNING|ERR_WARN_FL_OVERFLOW,
680 "overflow in floating-point constant");
681 type = FL_INFINITY;
682 } else {
683 /* underflow */
684 if (pass0 == 1)
685 error(ERR_WARNING|ERR_WARN_FL_UNDERFLOW,
686 "underflow in floating-point constant");
687 type = FL_ZERO;
689 } else {
690 /* Zero */
691 type = FL_ZERO;
695 switch (type) {
696 case FL_ZERO:
697 zero:
698 memset(mant, 0, sizeof mant);
699 break;
701 case FL_DENORMAL:
703 shift = -(exponent + expmax - 2 - fmt->exponent)
704 + fmt->explicit;
705 ieee_shr(mant, shift);
706 ieee_round(sign, mant, fmt->words);
707 if (mant[one_pos] & one_mask) {
708 /* One's position is set, we rounded up into normal range */
709 exponent = 1;
710 if (!fmt->explicit)
711 mant[one_pos] &= ~one_mask; /* remove explicit one */
712 mant[0] |= exponent << (15 - fmt->exponent);
713 } else {
714 if (daz || is_zero(mant)) {
715 /* Flush denormals to zero */
716 if (pass0 == 1)
717 error(ERR_WARNING|ERR_WARN_FL_UNDERFLOW,
718 "underflow in floating-point constant");
719 goto zero;
720 } else {
721 if (pass0 == 1)
722 error(ERR_WARNING|ERR_WARN_FL_DENORM,
723 "denormal floating-point constant");
726 break;
729 case FL_NORMAL:
730 exponent += expmax - 1;
731 ieee_shr(mant, fmt->exponent+fmt->explicit);
732 ieee_round(sign, mant, fmt->words);
733 /* did we scale up by one? */
734 if (test_bit(mant, fmt->exponent+fmt->explicit-1)) {
735 ieee_shr(mant, 1);
736 exponent++;
737 if (exponent >= (expmax << 1)-1) {
738 if (pass0 == 1)
739 error(ERR_WARNING|ERR_WARN_FL_OVERFLOW,
740 "overflow in floating-point constant");
741 type = FL_INFINITY;
742 goto overflow;
746 if (!fmt->explicit)
747 mant[one_pos] &= ~one_mask; /* remove explicit one */
748 mant[0] |= exponent << (15 - fmt->exponent);
749 break;
751 case FL_INFINITY:
752 case FL_QNAN:
753 case FL_SNAN:
754 overflow:
755 memset(mant, 0, sizeof mant);
756 mant[0] = ((1 << fmt->exponent)-1) << (15 - fmt->exponent);
757 if (fmt->explicit)
758 mant[one_pos] |= one_mask;
759 if (type == FL_QNAN)
760 set_bit(mant, fmt->exponent+fmt->explicit+1);
761 else if (type == FL_SNAN)
762 set_bit(mant, fmt->exponent+fmt->explicit+fmt->mantissa);
763 break;
766 mant[0] |= sign;
768 for (mp = &mant[fmt->words], i = 0; i < fmt->words; i++) {
769 uint16_t m = *--mp;
770 put(result, m);
771 result += 2;
774 return 1; /* success */
777 int float_const(const char *number, int32_t sign, uint8_t * result,
778 int bytes, efunc err)
780 error = err;
782 switch (bytes) {
783 case 2:
784 return to_float(number, sign, result, &ieee_16);
785 case 4:
786 return to_float(number, sign, result, &ieee_32);
787 case 8:
788 return to_float(number, sign, result, &ieee_64);
789 case 10:
790 return to_float(number, sign, result, &ieee_80);
791 case 16:
792 return to_float(number, sign, result, &ieee_128);
793 default:
794 error(ERR_PANIC, "strange value %d passed to float_const", bytes);
795 return 0;
799 /* Set floating-point options */
800 int float_option(const char *option)
802 if (!nasm_stricmp(option, "daz")) {
803 daz = true;
804 return 0;
805 } else if (!nasm_stricmp(option, "nodaz")) {
806 daz = false;
807 return 0;
808 } else if (!nasm_stricmp(option, "near")) {
809 rc = FLOAT_RC_NEAR;
810 return 0;
811 } else if (!nasm_stricmp(option, "down")) {
812 rc = FLOAT_RC_DOWN;
813 return 0;
814 } else if (!nasm_stricmp(option, "up")) {
815 rc = FLOAT_RC_UP;
816 return 0;
817 } else if (!nasm_stricmp(option, "zero")) {
818 rc = FLOAT_RC_ZERO;
819 return 0;
820 } else if (!nasm_stricmp(option, "default")) {
821 rc = FLOAT_RC_NEAR;
822 daz = false;
823 return 0;
824 } else {
825 return -1; /* Unknown option */