Path: blob/main/contrib/llvm-project/libc/src/__support/FPUtil/Hypot.h
213799 views
//===-- Implementation of hypotf function ---------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#ifndef LLVM_LIBC_SRC___SUPPORT_FPUTIL_HYPOT_H9#define LLVM_LIBC_SRC___SUPPORT_FPUTIL_HYPOT_H1011#include "BasicOperations.h"12#include "FEnvImpl.h"13#include "FPBits.h"14#include "rounding_mode.h"15#include "src/__support/CPP/bit.h"16#include "src/__support/CPP/type_traits.h"17#include "src/__support/common.h"18#include "src/__support/macros/config.h"19#include "src/__support/uint128.h"2021namespace LIBC_NAMESPACE_DECL {22namespace fputil {2324namespace internal {2526template <typename T>27LIBC_INLINE T find_leading_one(T mant, int &shift_length) {28shift_length = 0;29if (mant > 0) {30shift_length = (sizeof(mant) * 8) - 1 - cpp::countl_zero(mant);31}32return static_cast<T>((T(1) << shift_length));33}3435} // namespace internal3637template <typename T> struct DoubleLength;3839template <> struct DoubleLength<uint16_t> {40using Type = uint32_t;41};4243template <> struct DoubleLength<uint32_t> {44using Type = uint64_t;45};4647template <> struct DoubleLength<uint64_t> {48using Type = UInt128;49};5051// Correctly rounded IEEE 754 HYPOT(x, y) with round to nearest, ties to even.52//53// Algorithm:54// - Let a = max(|x|, |y|), b = min(|x|, |y|), then we have that:55// a <= sqrt(a^2 + b^2) <= min(a + b, a*sqrt(2))56// 1. So if b < eps(a)/2, then HYPOT(x, y) = a.57//58// - Moreover, the exponent part of HYPOT(x, y) is either the same or 1 more59// than the exponent part of a.60//61// 2. For the remaining cases, we will use the digit-by-digit (shift-and-add)62// algorithm to compute SQRT(Z):63//64// - For Y = y0.y1...yn... = SQRT(Z),65// let Y(n) = y0.y1...yn be the first n fractional digits of Y.66//67// - The nth scaled residual R(n) is defined to be:68// R(n) = 2^n * (Z - Y(n)^2)69//70// - Since Y(n) = Y(n - 1) + yn * 2^(-n), the scaled residual71// satisfies the following recurrence formula:72// R(n) = 2*R(n - 1) - yn*(2*Y(n - 1) + 2^(-n)),73// with the initial conditions:74// Y(0) = y0, and R(0) = Z - y0.75//76// - So the nth fractional digit of Y = SQRT(Z) can be decided by:77// yn = 1 if 2*R(n - 1) >= 2*Y(n - 1) + 2^(-n),78// 0 otherwise.79//80// 3. Precision analysis:81//82// - Notice that in the decision function:83// 2*R(n - 1) >= 2*Y(n - 1) + 2^(-n),84// the right hand side only uses up to the 2^(-n)-bit, and both sides are85// non-negative, so R(n - 1) can be truncated at the 2^(-(n + 1))-bit, so86// that 2*R(n - 1) is corrected up to the 2^(-n)-bit.87//88// - Thus, in order to round SQRT(a^2 + b^2) correctly up to n-fractional89// bits, we need to perform the summation (a^2 + b^2) correctly up to (2n +90// 2)-fractional bits, and the remaining bits are sticky bits (i.e. we only91// care if they are 0 or > 0), and the comparisons, additions/subtractions92// can be done in n-fractional bits precision.93//94// - For single precision (float), we can use uint64_t to store the sum a^2 +95// b^2 exact up to (2n + 2)-fractional bits.96//97// - Then we can feed this sum into the digit-by-digit algorithm for SQRT(Z)98// described above.99//100//101// Special cases:102// - HYPOT(x, y) is +Inf if x or y is +Inf or -Inf; else103// - HYPOT(x, y) is NaN if x or y is NaN.104//105template <typename T, cpp::enable_if_t<cpp::is_floating_point_v<T>, int> = 0>106LIBC_INLINE T hypot(T x, T y) {107using FPBits_t = FPBits<T>;108using StorageType = typename FPBits<T>::StorageType;109using DStorageType = typename DoubleLength<StorageType>::Type;110111FPBits_t x_abs = FPBits_t(x).abs();112FPBits_t y_abs = FPBits_t(y).abs();113114bool x_abs_larger = x_abs.uintval() >= y_abs.uintval();115116FPBits_t a_bits = x_abs_larger ? x_abs : y_abs;117FPBits_t b_bits = x_abs_larger ? y_abs : x_abs;118119if (LIBC_UNLIKELY(a_bits.is_inf_or_nan())) {120if (x_abs.is_signaling_nan() || y_abs.is_signaling_nan()) {121fputil::raise_except_if_required(FE_INVALID);122return FPBits_t::quiet_nan().get_val();123}124if (x_abs.is_inf() || y_abs.is_inf())125return FPBits_t::inf().get_val();126if (x_abs.is_nan())127return x;128// y is nan129return y;130}131132uint16_t a_exp = a_bits.get_biased_exponent();133uint16_t b_exp = b_bits.get_biased_exponent();134135if ((a_exp - b_exp >= FPBits_t::FRACTION_LEN + 2) || (x == 0) || (y == 0))136return x_abs.get_val() + y_abs.get_val();137138uint64_t out_exp = a_exp;139StorageType a_mant = a_bits.get_mantissa();140StorageType b_mant = b_bits.get_mantissa();141DStorageType a_mant_sq, b_mant_sq;142bool sticky_bits;143144// Add an extra bit to simplify the final rounding bit computation.145constexpr StorageType ONE = StorageType(1) << (FPBits_t::FRACTION_LEN + 1);146147a_mant <<= 1;148b_mant <<= 1;149150StorageType leading_one;151int y_mant_width;152if (a_exp != 0) {153leading_one = ONE;154a_mant |= ONE;155y_mant_width = FPBits_t::FRACTION_LEN + 1;156} else {157leading_one = internal::find_leading_one(a_mant, y_mant_width);158a_exp = 1;159}160161if (b_exp != 0)162b_mant |= ONE;163else164b_exp = 1;165166a_mant_sq = static_cast<DStorageType>(a_mant) * a_mant;167b_mant_sq = static_cast<DStorageType>(b_mant) * b_mant;168169// At this point, a_exp >= b_exp > a_exp - 25, so in order to line up aSqMant170// and bSqMant, we need to shift bSqMant to the right by (a_exp - b_exp) bits.171// But before that, remember to store the losing bits to sticky.172// The shift length is for a^2 and b^2, so it's double of the exponent173// difference between a and b.174uint16_t shift_length = static_cast<uint16_t>(2 * (a_exp - b_exp));175sticky_bits =176((b_mant_sq & ((DStorageType(1) << shift_length) - DStorageType(1))) !=177DStorageType(0));178b_mant_sq >>= shift_length;179180DStorageType sum = a_mant_sq + b_mant_sq;181if (sum >= (DStorageType(1) << (2 * y_mant_width + 2))) {182// a^2 + b^2 >= 4* leading_one^2, so we will need an extra bit to the left.183if (leading_one == ONE) {184// For normal result, we discard the last 2 bits of the sum and increase185// the exponent.186sticky_bits = sticky_bits || ((sum & 0x3U) != 0);187sum >>= 2;188++out_exp;189if (out_exp >= FPBits_t::MAX_BIASED_EXPONENT) {190if (int round_mode = quick_get_round();191round_mode == FE_TONEAREST || round_mode == FE_UPWARD)192return FPBits_t::inf().get_val();193return FPBits_t::max_normal().get_val();194}195} else {196// For denormal result, we simply move the leading bit of the result to197// the left by 1.198leading_one <<= 1;199++y_mant_width;200}201}202203StorageType y_new = leading_one;204StorageType r = static_cast<StorageType>(sum >> y_mant_width) - leading_one;205StorageType tail_bits = static_cast<StorageType>(sum) & (leading_one - 1);206207for (StorageType current_bit = leading_one >> 1; current_bit;208current_bit >>= 1) {209r = static_cast<StorageType>((r << 1)) +210((tail_bits & current_bit) ? 1 : 0);211StorageType tmp = static_cast<StorageType>((y_new << 1)) +212current_bit; // 2*y_new(n - 1) + 2^(-n)213if (r >= tmp) {214r -= tmp;215y_new += current_bit;216}217}218219bool round_bit = y_new & StorageType(1);220bool lsb = y_new & StorageType(2);221222if (y_new >= ONE) {223y_new -= ONE;224225if (out_exp == 0) {226out_exp = 1;227}228}229230y_new >>= 1;231232// Round to the nearest, tie to even.233int round_mode = quick_get_round();234switch (round_mode) {235case FE_TONEAREST:236// Round to nearest, ties to even237if (round_bit && (lsb || sticky_bits || (r != 0)))238++y_new;239break;240case FE_UPWARD:241if (round_bit || sticky_bits || (r != 0))242++y_new;243break;244}245246if (y_new >= (ONE >> 1)) {247y_new -= ONE >> 1;248++out_exp;249if (out_exp >= FPBits_t::MAX_BIASED_EXPONENT) {250if (round_mode == FE_TONEAREST || round_mode == FE_UPWARD)251return FPBits_t::inf().get_val();252return FPBits_t::max_normal().get_val();253}254}255256y_new |= static_cast<StorageType>(out_exp) << FPBits_t::FRACTION_LEN;257258if (!(round_bit || sticky_bits || (r != 0)))259fputil::clear_except_if_required(FE_INEXACT);260261return cpp::bit_cast<T>(y_new);262}263264} // namespace fputil265} // namespace LIBC_NAMESPACE_DECL266267#endif // LLVM_LIBC_SRC___SUPPORT_FPUTIL_HYPOT_H268269270