xref: /freebsd/contrib/llvm-project/compiler-rt/lib/builtins/floatsitf.c (revision 0b57cec536236d46e3dba9bd041533462f33dbb7)
1*0b57cec5SDimitry Andric //===-- lib/floatsitf.c - integer -> quad-precision conversion ----*- C -*-===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // This file implements integer to quad-precision conversion for the
10*0b57cec5SDimitry Andric // compiler-rt library in the IEEE-754 default round-to-nearest, ties-to-even
11*0b57cec5SDimitry Andric // mode.
12*0b57cec5SDimitry Andric //
13*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
14*0b57cec5SDimitry Andric 
15*0b57cec5SDimitry Andric #define QUAD_PRECISION
16*0b57cec5SDimitry Andric #include "fp_lib.h"
17*0b57cec5SDimitry Andric 
18*0b57cec5SDimitry Andric #if defined(CRT_HAS_128BIT) && defined(CRT_LDBL_128BIT)
19*0b57cec5SDimitry Andric COMPILER_RT_ABI fp_t __floatsitf(int a) {
20*0b57cec5SDimitry Andric 
21*0b57cec5SDimitry Andric   const int aWidth = sizeof a * CHAR_BIT;
22*0b57cec5SDimitry Andric 
23*0b57cec5SDimitry Andric   // Handle zero as a special case to protect clz
24*0b57cec5SDimitry Andric   if (a == 0)
25*0b57cec5SDimitry Andric     return fromRep(0);
26*0b57cec5SDimitry Andric 
27*0b57cec5SDimitry Andric   // All other cases begin by extracting the sign and absolute value of a
28*0b57cec5SDimitry Andric   rep_t sign = 0;
29*0b57cec5SDimitry Andric   unsigned aAbs = (unsigned)a;
30*0b57cec5SDimitry Andric   if (a < 0) {
31*0b57cec5SDimitry Andric     sign = signBit;
32*0b57cec5SDimitry Andric     aAbs = ~(unsigned)a + 1U;
33*0b57cec5SDimitry Andric   }
34*0b57cec5SDimitry Andric 
35*0b57cec5SDimitry Andric   // Exponent of (fp_t)a is the width of abs(a).
36*0b57cec5SDimitry Andric   const int exponent = (aWidth - 1) - __builtin_clz(aAbs);
37*0b57cec5SDimitry Andric   rep_t result;
38*0b57cec5SDimitry Andric 
39*0b57cec5SDimitry Andric   // Shift a into the significand field and clear the implicit bit.
40*0b57cec5SDimitry Andric   const int shift = significandBits - exponent;
41*0b57cec5SDimitry Andric   result = (rep_t)aAbs << shift ^ implicitBit;
42*0b57cec5SDimitry Andric 
43*0b57cec5SDimitry Andric   // Insert the exponent
44*0b57cec5SDimitry Andric   result += (rep_t)(exponent + exponentBias) << significandBits;
45*0b57cec5SDimitry Andric   // Insert the sign bit and return
46*0b57cec5SDimitry Andric   return fromRep(result | sign);
47*0b57cec5SDimitry Andric }
48*0b57cec5SDimitry Andric 
49*0b57cec5SDimitry Andric #endif
50