• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* This file is distributed under the University of Illinois Open Source
2  * License. See LICENSE.TXT for details.
3  */
4 
5 /* uint64_t __fixunstfdi(long double x); */
6 /* This file implements the PowerPC 128-bit double-double -> uint64_t conversion */
7 
8 #include "DD.h"
9 #include <stdint.h>
10 
__fixunstfdi(long double input)11 uint64_t __fixunstfdi(long double input)
12 {
13 	const DD x = { .ld = input };
14 	const doublebits hibits = { .d = x.s.hi };
15 
16 	const uint32_t highWordMinusOne = (uint32_t)(hibits.x >> 32) - UINT32_C(0x3ff00000);
17 
18 	/* If (1.0 - tiny) <= input < 0x1.0p64: */
19 	if (UINT32_C(0x04000000) > highWordMinusOne)
20 	{
21 		const int unbiasedHeadExponent = highWordMinusOne >> 20;
22 
23 		uint64_t result = hibits.x & UINT64_C(0x000fffffffffffff); /* mantissa(hi) */
24 		result |= UINT64_C(0x0010000000000000); /* matissa(hi) with implicit bit */
25 		result <<= 11; /* mantissa(hi) left aligned in the int64 field. */
26 
27 		/* If the tail is non-zero, we need to patch in the tail bits. */
28 		if (0.0 != x.s.lo)
29 		{
30 			const doublebits lobits = { .d = x.s.lo };
31 			int64_t tailMantissa = lobits.x & INT64_C(0x000fffffffffffff);
32 			tailMantissa |= INT64_C(0x0010000000000000);
33 
34 			/* At this point we have the mantissa of |tail| */
35 
36 			const int64_t negationMask = ((int64_t)(lobits.x)) >> 63;
37 			tailMantissa = (tailMantissa ^ negationMask) - negationMask;
38 
39 			/* Now we have the mantissa of tail as a signed 2s-complement integer */
40 
41 			const int biasedTailExponent = (int)(lobits.x >> 52) & 0x7ff;
42 
43 			/* Shift the tail mantissa into the right position, accounting for the
44 			 * bias of 11 that we shifted the head mantissa by.
45 			 */
46 			tailMantissa >>= (unbiasedHeadExponent - (biasedTailExponent - (1023 - 11)));
47 
48 			result += tailMantissa;
49 		}
50 
51 		result >>= (63 - unbiasedHeadExponent);
52 		return result;
53 	}
54 
55 	/* Edge cases are handled here, with saturation. */
56 	if (1.0 > x.s.hi)
57 		return UINT64_C(0);
58 	else
59 		return UINT64_MAX;
60 }
61