|
| 1 | +//===-- Half-precision rsqrt function -------------------------------------===// |
| 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 | +#include "src/math/rsqrtf16.h" |
| 10 | +#include "hdr/errno_macros.h" |
| 11 | +#include "hdr/fenv_macros.h" |
| 12 | +#include "src/__support/FPUtil/FEnvImpl.h" |
| 13 | +#include "src/__support/FPUtil/FPBits.h" |
| 14 | +#include "src/__support/FPUtil/PolyEval.h" |
| 15 | +#include "src/__support/FPUtil/cast.h" |
| 16 | +#include "src/__support/FPUtil/multiply_add.h" |
| 17 | +#include "src/__support/FPUtil/sqrt.h" |
| 18 | +#include "src/__support/macros/optimization.h" |
| 19 | + |
| 20 | +namespace LIBC_NAMESPACE_DECL { |
| 21 | + |
| 22 | +LLVM_LIBC_FUNCTION(float16, rsqrtf16, (float16 x)) { |
| 23 | + using FPBits = fputil::FPBits<float16>; |
| 24 | + FPBits xbits(x); |
| 25 | + |
| 26 | + uint16_t x_u = xbits.uintval(); |
| 27 | + uint16_t x_abs = x_u & 0x7fff; |
| 28 | + uint16_t x_sign = x_u >> 15; |
| 29 | + |
| 30 | + // x is NaN |
| 31 | + if (LIBC_UNLIKELY(xbits.is_nan())) { |
| 32 | + if (xbits.is_signaling_nan()) { |
| 33 | + fputil::raise_except_if_required(FE_INVALID); |
| 34 | + return FPBits::quiet_nan().get_val(); |
| 35 | + } |
| 36 | + return x; |
| 37 | + } |
| 38 | + |
| 39 | + // |x| = 0 |
| 40 | + if (LIBC_UNLIKELY(x_abs == 0x0)) { |
| 41 | + fputil::raise_except_if_required(FE_DIVBYZERO); |
| 42 | + fputil::set_errno_if_required(ERANGE); |
| 43 | + return FPBits::quiet_nan().get_val(); |
| 44 | + } |
| 45 | + |
| 46 | + // -inf <= x < 0 |
| 47 | + if (LIBC_UNLIKELY(x_sign == 1)) { |
| 48 | + fputil::raise_except_if_required(FE_INVALID); |
| 49 | + fputil::set_errno_if_required(EDOM); |
| 50 | + return FPBits::quiet_nan().get_val(); |
| 51 | + } |
| 52 | + |
| 53 | + // x = +inf => rsqrt(x) = 0 |
| 54 | + if (LIBC_UNLIKELY(xbits.is_inf())) { |
| 55 | + return fputil::cast<float16>(0.0f); |
| 56 | + } |
| 57 | + |
| 58 | + // x = 1 => rsqrt(x) = 1 |
| 59 | + if (LIBC_UNLIKELY(x_u == 0x1)) { |
| 60 | + return fputil::cast<float16>(1.0f); |
| 61 | + } |
| 62 | + |
| 63 | + // x is valid, estimate the result - below is temporary solution for just testing |
| 64 | + float xf = x; |
| 65 | + return fputil::cast<float16>(1.0f / xf); |
| 66 | +} |
| 67 | +} // namespace LIBC_NAMESPACE_DECL |
0 commit comments