Daniel Dunbar | fd08999 | 2009-06-26 16:47:03 +0000 | [diff] [blame] | 1 | //===-- floatundisf.c - Implement __floatundisf ---------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file implements __floatundisf for the compiler_rt library. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #include "int_lib.h" |
| 15 | #include <float.h> |
| 16 | |
| 17 | // Returns: convert a to a float, rounding toward even. |
| 18 | |
| 19 | // Assumption: float is a IEEE 32 bit floating point type |
| 20 | // du_int is a 64 bit integral type |
| 21 | |
| 22 | // seee eeee emmm mmmm mmmm mmmm mmmm mmmm |
| 23 | |
| 24 | float |
| 25 | __floatundisf(du_int a) |
| 26 | { |
| 27 | if (a == 0) |
| 28 | return 0.0F; |
| 29 | const unsigned N = sizeof(du_int) * CHAR_BIT; |
| 30 | int sd = N - __builtin_clzll(a); // number of significant digits |
| 31 | int e = sd - 1; // exponent |
| 32 | if (sd > FLT_MANT_DIG) |
| 33 | { |
| 34 | // start: 0000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQxxxxxxxxxxxxxxxxxx |
| 35 | // finish: 000000000000000000000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQR |
| 36 | // 12345678901234567890123456 |
| 37 | // 1 = msb 1 bit |
| 38 | // P = bit FLT_MANT_DIG-1 bits to the right of 1 |
| 39 | // Q = bit FLT_MANT_DIG bits to the right of 1 |
| 40 | // R = "or" of all bits to the right of Q |
| 41 | switch (sd) |
| 42 | { |
| 43 | case FLT_MANT_DIG + 1: |
| 44 | a <<= 1; |
| 45 | break; |
| 46 | case FLT_MANT_DIG + 2: |
| 47 | break; |
| 48 | default: |
| 49 | a = (a >> (sd - (FLT_MANT_DIG+2))) | |
| 50 | ((a & ((du_int)(-1) >> ((N + FLT_MANT_DIG+2) - sd))) != 0); |
| 51 | }; |
| 52 | // finish: |
| 53 | a |= (a & 4) != 0; // Or P into R |
| 54 | ++a; // round - this step may add a significant bit |
| 55 | a >>= 2; // dump Q and R |
| 56 | // a is now rounded to FLT_MANT_DIG or FLT_MANT_DIG+1 bits |
| 57 | if (a & ((du_int)1 << FLT_MANT_DIG)) |
| 58 | { |
| 59 | a >>= 1; |
| 60 | ++e; |
| 61 | } |
| 62 | // a is now rounded to FLT_MANT_DIG bits |
| 63 | } |
| 64 | else |
| 65 | { |
| 66 | a <<= (FLT_MANT_DIG - sd); |
| 67 | // a is now rounded to FLT_MANT_DIG bits |
| 68 | } |
| 69 | float_bits fb; |
| 70 | fb.u = ((e + 127) << 23) | // exponent |
| 71 | ((su_int)a & 0x007FFFFF); // mantissa |
| 72 | return fb.f; |
| 73 | } |