blob: 5a9284819f054223712b13b7066e110d739f3d06 [file] [log] [blame]
Daniel Dunbarb3a69012009-06-26 16:47:03 +00001//===-- floatdisf.c - Implement __floatdisf -------------------------------===//
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 __floatdisf 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// di_int is a 64 bit integral type
21
22// seee eeee emmm mmmm mmmm mmmm mmmm mmmm
23
24float
25__floatdisf(di_int a)
26{
27 if (a == 0)
28 return 0.0F;
29 const unsigned N = sizeof(di_int) * CHAR_BIT;
30 const di_int s = a >> (N-1);
31 a = (a ^ s) - s;
32 int sd = N - __builtin_clzll(a); // number of significant digits
33 int e = sd - 1; // exponent
34 if (sd > FLT_MANT_DIG)
35 {
36 // start: 0000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQxxxxxxxxxxxxxxxxxx
37 // finish: 000000000000000000000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQR
38 // 12345678901234567890123456
39 // 1 = msb 1 bit
40 // P = bit FLT_MANT_DIG-1 bits to the right of 1
41 // Q = bit FLT_MANT_DIG bits to the right of 1
42 // R = "or" of all bits to the right of Q
43 switch (sd)
44 {
45 case FLT_MANT_DIG + 1:
46 a <<= 1;
47 break;
48 case FLT_MANT_DIG + 2:
49 break;
50 default:
51 a = ((du_int)a >> (sd - (FLT_MANT_DIG+2))) |
52 ((a & ((du_int)(-1) >> ((N + FLT_MANT_DIG+2) - sd))) != 0);
53 };
54 // finish:
55 a |= (a & 4) != 0; // Or P into R
56 ++a; // round - this step may add a significant bit
57 a >>= 2; // dump Q and R
58 // a is now rounded to FLT_MANT_DIG or FLT_MANT_DIG+1 bits
59 if (a & ((du_int)1 << FLT_MANT_DIG))
60 {
61 a >>= 1;
62 ++e;
63 }
64 // a is now rounded to FLT_MANT_DIG bits
65 }
66 else
67 {
68 a <<= (FLT_MANT_DIG - sd);
69 // a is now rounded to FLT_MANT_DIG bits
70 }
71 float_bits fb;
72 fb.u = ((su_int)s & 0x80000000) | // sign
73 ((e + 127) << 23) | // exponent
74 ((su_int)a & 0x007FFFFF); // mantissa
75 return fb.f;
76}