1//===-- floattidf.c - Implement __floattidf -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements __floattidf for the compiler_rt library.
10//
11//===----------------------------------------------------------------------===//
12
13#include "int_lib.h"
14
15#ifdef CRT_HAS_128BIT
16
17// Returns: convert a to a double, rounding toward even.
18
19// Assumption: double is a IEEE 64 bit floating point type
20//            ti_int is a 128 bit integral type
21
22// seee eeee eeee mmmm mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm mmmm mmmm
23// mmmm
24
25COMPILER_RT_ABI double __floattidf(ti_int a) {
26  if (a == 0)
27    return 0.0;
28  const unsigned N = sizeof(ti_int) * CHAR_BIT;
29  const ti_int s = a >> (N - 1);
30  a = (a ^ s) - s;
31  int sd = N - __clzti2(a); // number of significant digits
32  int e = sd - 1;           // exponent
33  if (sd > DBL_MANT_DIG) {
34    // start:  0000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQxxxxxxxxxxxxxxxxxx
35    //  finish: 000000000000000000000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQR
36    //                                               12345678901234567890123456
37    // 1 = msb 1 bit
38    // P = bit DBL_MANT_DIG-1 bits to the right of 1
39    // Q = bit DBL_MANT_DIG bits to the right of 1
40    // R = "or" of all bits to the right of Q
41    switch (sd) {
42    case DBL_MANT_DIG + 1:
43      a <<= 1;
44      break;
45    case DBL_MANT_DIG + 2:
46      break;
47    default:
48      a = ((tu_int)a >> (sd - (DBL_MANT_DIG + 2))) |
49          ((a & ((tu_int)(-1) >> ((N + DBL_MANT_DIG + 2) - sd))) != 0);
50    };
51    // finish:
52    a |= (a & 4) != 0; // Or P into R
53    ++a;               // round - this step may add a significant bit
54    a >>= 2;           // dump Q and R
55    // a is now rounded to DBL_MANT_DIG or DBL_MANT_DIG+1 bits
56    if (a & ((tu_int)1 << DBL_MANT_DIG)) {
57      a >>= 1;
58      ++e;
59    }
60    // a is now rounded to DBL_MANT_DIG bits
61  } else {
62    a <<= (DBL_MANT_DIG - sd);
63    // a is now rounded to DBL_MANT_DIG bits
64  }
65  double_bits fb;
66  fb.u.s.high = ((su_int)s & 0x80000000) |        // sign
67                ((e + 1023) << 20) |              // exponent
68                ((su_int)(a >> 32) & 0x000FFFFF); // mantissa-high
69  fb.u.s.low = (su_int)a;                         // mantissa-low
70  return fb.f;
71}
72
73#endif // CRT_HAS_128BIT
74