truncdfsf2.c revision 215125
1//===-- lib/truncdfsf2.c - double -> single conversion ------------*- C -*-===//
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 a fairly generic conversion from a wider to a narrower
11// IEEE-754 floating-point type in the default (round to nearest, ties to even)
12// rounding mode.  The constants and types defined following the includes below
13// parameterize the conversion.
14//
15// This routine can be trivially adapted to support conversions to
16// half-precision or from quad-precision. It does not support types that don't
17// use the usual IEEE-754 interchange formats; specifically, some work would be
18// needed to adapt it to (for example) the Intel 80-bit format or PowerPC
19// double-double format.
20//
21// Note please, however, that this implementation is only intended to support
22// *narrowing* operations; if you need to convert to a *wider* floating-point
23// type (e.g. float -> double), then this routine will not do what you want it
24// to.
25//
26// It also requires that integer types at least as large as both formats
27// are available on the target platform; this may pose a problem when trying
28// to add support for quad on some 32-bit systems, for example.
29//
30// Finally, the following assumptions are made:
31//
32// 1. floating-point types and integer types have the same endianness on the
33//    target platform
34//
35// 2. quiet NaNs, if supported, are indicated by the leading bit of the
36//    significand field being set
37//
38//===----------------------------------------------------------------------===//
39
40#include <stdint.h>
41#include <limits.h>
42#include <stdbool.h>
43
44typedef double src_t;
45typedef uint64_t src_rep_t;
46#define SRC_REP_C UINT64_C
47static const int srcSigBits = 52;
48
49typedef float dst_t;
50typedef uint32_t dst_rep_t;
51#define DST_REP_C UINT32_C
52static const int dstSigBits = 23;
53
54// End of specialization parameters.  Two helper routines for conversion to and
55// from the representation of floating-point data as integer values follow.
56
57static inline src_rep_t srcToRep(src_t x) {
58    const union { src_t f; src_rep_t i; } rep = {.f = x};
59    return rep.i;
60}
61
62static inline dst_t dstFromRep(dst_rep_t x) {
63    const union { dst_t f; dst_rep_t i; } rep = {.i = x};
64    return rep.f;
65}
66
67// End helper routines.  Conversion implementation follows.
68
69dst_t __truncdfsf2(src_t a) {
70
71    // Various constants whose values follow from the type parameters.
72    // Any reasonable optimizer will fold and propagate all of these.
73    const int srcBits = sizeof(src_t)*CHAR_BIT;
74    const int srcExpBits = srcBits - srcSigBits - 1;
75    const int srcInfExp = (1 << srcExpBits) - 1;
76    const int srcExpBias = srcInfExp >> 1;
77
78    const src_rep_t srcMinNormal = SRC_REP_C(1) << srcSigBits;
79    const src_rep_t significandMask = srcMinNormal - 1;
80    const src_rep_t srcInfinity = (src_rep_t)srcInfExp << srcSigBits;
81    const src_rep_t srcSignMask = SRC_REP_C(1) << (srcSigBits + srcExpBits);
82    const src_rep_t srcAbsMask = srcSignMask - 1;
83    const src_rep_t roundMask = (SRC_REP_C(1) << (srcSigBits - dstSigBits)) - 1;
84    const src_rep_t halfway = SRC_REP_C(1) << (srcSigBits - dstSigBits - 1);
85
86    const int dstBits = sizeof(dst_t)*CHAR_BIT;
87    const int dstExpBits = dstBits - dstSigBits - 1;
88    const int dstInfExp = (1 << dstExpBits) - 1;
89    const int dstExpBias = dstInfExp >> 1;
90
91    const int underflowExponent = srcExpBias + 1 - dstExpBias;
92    const int overflowExponent = srcExpBias + dstInfExp - dstExpBias;
93    const src_rep_t underflow = (src_rep_t)underflowExponent << srcSigBits;
94    const src_rep_t overflow = (src_rep_t)overflowExponent << srcSigBits;
95
96    const dst_rep_t dstQNaN = DST_REP_C(1) << (dstSigBits - 1);
97    const dst_rep_t dstNaNCode = dstQNaN - 1;
98
99    // Break a into a sign and representation of the absolute value
100    const src_rep_t aRep = srcToRep(a);
101    const src_rep_t aAbs = aRep & srcAbsMask;
102    const src_rep_t sign = aRep & srcSignMask;
103    dst_rep_t absResult;
104
105    if (aAbs - underflow < aAbs - overflow) {
106        // The exponent of a is within the range of normal numbers in the
107        // destination format.  We can convert by simply right-shifting with
108        // rounding and adjusting the exponent.
109        absResult = aAbs >> (srcSigBits - dstSigBits);
110        absResult -= (dst_rep_t)(srcExpBias - dstExpBias) << dstSigBits;
111
112        const src_rep_t roundBits = aAbs & roundMask;
113
114        // Round to nearest
115        if (roundBits > halfway)
116            absResult++;
117
118        // Ties to even
119        else if (roundBits == halfway)
120            absResult += absResult & 1;
121    }
122
123    else if (aAbs > srcInfinity) {
124        // a is NaN.
125        // Conjure the result by beginning with infinity, setting the qNaN
126        // bit and inserting the (truncated) trailing NaN field.
127        absResult = (dst_rep_t)dstInfExp << dstSigBits;
128        absResult |= dstQNaN;
129        absResult |= aAbs & dstNaNCode;
130    }
131
132    else if (aAbs > overflow) {
133        // a overflows to infinity.
134        absResult = (dst_rep_t)dstInfExp << dstSigBits;
135    }
136
137    else {
138        // a underflows on conversion to the destination type or is an exact
139        // zero.  The result may be a denormal or zero.  Extract the exponent
140        // to get the shift amount for the denormalization.
141        const int aExp = aAbs >> srcSigBits;
142        const int shift = srcExpBias - dstExpBias - aExp + 1;
143
144        const src_rep_t significand = (aRep & significandMask) | srcMinNormal;
145
146        // Right shift by the denormalization amount with sticky.
147        if (shift > srcSigBits) {
148            absResult = 0;
149        } else {
150            const bool sticky = significand << (srcBits - shift);
151            src_rep_t denormalizedSignificand = significand >> shift | sticky;
152            absResult = denormalizedSignificand >> (srcSigBits - dstSigBits);
153            const src_rep_t roundBits = denormalizedSignificand & roundMask;
154            // Round to nearest
155            if (roundBits > halfway)
156                absResult++;
157            // Ties to even
158            else if (roundBits == halfway)
159                absResult += absResult & 1;
160        }
161    }
162
163    // Apply the signbit to (dst_t)abs(a).
164    const dst_rep_t result = absResult | sign >> (srcBits - dstBits);
165    return dstFromRep(result);
166
167}
168