xref: /freebsd/contrib/llvm-project/compiler-rt/lib/builtins/fp_fixuint_impl.inc (revision 0b57cec536236d46e3dba9bd041533462f33dbb7)
1*0b57cec5SDimitry Andric//===-- lib/fixdfsi.c - Double-precision -> integer 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 float to unsigned integer conversion for the
10*0b57cec5SDimitry Andric// compiler-rt library.
11*0b57cec5SDimitry Andric//
12*0b57cec5SDimitry Andric//===----------------------------------------------------------------------===//
13*0b57cec5SDimitry Andric
14*0b57cec5SDimitry Andric#include "fp_lib.h"
15*0b57cec5SDimitry Andric
16*0b57cec5SDimitry Andricstatic __inline fixuint_t __fixuint(fp_t a) {
17*0b57cec5SDimitry Andric  // Break a into sign, exponent, significand parts.
18*0b57cec5SDimitry Andric  const rep_t aRep = toRep(a);
19*0b57cec5SDimitry Andric  const rep_t aAbs = aRep & absMask;
20*0b57cec5SDimitry Andric  const int sign = aRep & signBit ? -1 : 1;
21*0b57cec5SDimitry Andric  const int exponent = (aAbs >> significandBits) - exponentBias;
22*0b57cec5SDimitry Andric  const rep_t significand = (aAbs & significandMask) | implicitBit;
23*0b57cec5SDimitry Andric
24*0b57cec5SDimitry Andric  // If either the value or the exponent is negative, the result is zero.
25*0b57cec5SDimitry Andric  if (sign == -1 || exponent < 0)
26*0b57cec5SDimitry Andric    return 0;
27*0b57cec5SDimitry Andric
28*0b57cec5SDimitry Andric  // If the value is too large for the integer type, saturate.
29*0b57cec5SDimitry Andric  if ((unsigned)exponent >= sizeof(fixuint_t) * CHAR_BIT)
30*0b57cec5SDimitry Andric    return ~(fixuint_t)0;
31*0b57cec5SDimitry Andric
32*0b57cec5SDimitry Andric  // If 0 <= exponent < significandBits, right shift to get the result.
33*0b57cec5SDimitry Andric  // Otherwise, shift left.
34*0b57cec5SDimitry Andric  if (exponent < significandBits)
35*0b57cec5SDimitry Andric    return significand >> (significandBits - exponent);
36*0b57cec5SDimitry Andric  else
37*0b57cec5SDimitry Andric    return (fixuint_t)significand << (exponent - significandBits);
38*0b57cec5SDimitry Andric}
39