xref: /freebsd/contrib/llvm-project/compiler-rt/lib/builtins/floatuntitf.c (revision c8e7f78a3d28ff6e6223ed136ada8e1e2f34965e)
1 //===-- lib/floatuntitf.c - uint128 -> quad-precision conversion --*- C -*-===//
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 tu_int to quad-precision conversion for the
10 // compiler-rt library in the IEEE-754 default round-to-nearest, ties-to-even
11 // mode.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #define QUAD_PRECISION
16 #include "fp_lib.h"
17 #include "int_lib.h"
18 
19 // Returns: convert a tu_int to a fp_t, rounding toward even.
20 
21 // Assumption: fp_t is a IEEE 128 bit floating point type
22 //             tu_int is a 128 bit integral type
23 
24 // seee eeee eeee eeee mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm mmmm mmmm
25 // mmmm | mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm
26 // mmmm mmmm mmmm
27 
28 #if defined(CRT_HAS_TF_MODE)
29 COMPILER_RT_ABI fp_t __floatuntitf(tu_int a) {
30   if (a == 0)
31     return 0.0;
32   const unsigned N = sizeof(tu_int) * CHAR_BIT;
33   int sd = N - __clzti2(a); // number of significant digits
34   int e = sd - 1;           // exponent
35   if (sd > TF_MANT_DIG) {
36     //  start:  0000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQxxxxxxxxxxxxxxxxxx
37     //  finish: 000000000000000000000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQR
38     //                                                12345678901234567890123456
39     //  1 = msb 1 bit
40     //  P = bit TF_MANT_DIG-1 bits to the right of 1
41     //  Q = bit TF_MANT_DIG bits to the right of 1
42     //  R = "or" of all bits to the right of Q
43     switch (sd) {
44     case TF_MANT_DIG + 1:
45       a <<= 1;
46       break;
47     case TF_MANT_DIG + 2:
48       break;
49     default:
50       a = (a >> (sd - (TF_MANT_DIG + 2))) |
51           ((a & ((tu_int)(-1) >> ((N + TF_MANT_DIG + 2) - sd))) != 0);
52     };
53     // finish:
54     a |= (a & 4) != 0; // Or P into R
55     ++a;               // round - this step may add a significant bit
56     a >>= 2;           // dump Q and R
57     // a is now rounded to TF_MANT_DIG or TF_MANT_DIG+1 bits
58     if (a & ((tu_int)1 << TF_MANT_DIG)) {
59       a >>= 1;
60       ++e;
61     }
62     // a is now rounded to TF_MANT_DIG bits
63   } else {
64     a <<= (TF_MANT_DIG - sd);
65     // a is now rounded to TF_MANT_DIG bits
66   }
67 
68   long_double_bits fb;
69   fb.u.high.all = (du_int)(e + 16383) << 48             // exponent
70                   | ((a >> 64) & 0x0000ffffffffffffLL); // significand
71   fb.u.low.all = (du_int)(a);
72   return fb.f;
73 }
74 
75 #endif
76