//===-- Half-precision 2^x function ---------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "src/math/exp2f16.h"
#include "expxf16.h"
#include "hdr/errno_macros.h"
#include "hdr/fenv_macros.h"
#include "src/__support/CPP/array.h"
#include "src/__support/FPUtil/FEnvImpl.h"
#include "src/__support/FPUtil/FPBits.h"
#include "src/__support/FPUtil/PolyEval.h"
#include "src/__support/FPUtil/except_value_utils.h"
#include "src/__support/FPUtil/multiply_add.h"
#include "src/__support/FPUtil/nearest_integer.h"
#include "src/__support/FPUtil/rounding_mode.h"
#include "src/__support/common.h"
#include "src/__support/macros/config.h"
#include "src/__support/macros/optimization.h"

namespace LIBC_NAMESPACE_DECL {

static constexpr fputil::ExceptValues<float16, 3> EXP2F16_EXCEPTS = {{
    // (input, RZ output, RU offset, RD offset, RN offset)
    // x = 0x1.714p-11, exp2f16(x) = 0x1p+0 (RZ)
    {0x11c5U, 0x3c00U, 1U, 0U, 1U},
    // x = -0x1.558p-4, exp2f16(x) = 0x1.e34p-1 (RZ)
    {0xad56U, 0x3b8dU, 1U, 0U, 0U},
    // x = -0x1.d5cp-4, exp2f16(x) = 0x1.d8cp-1 (RZ)
    {0xaf57U, 0x3b63U, 1U, 0U, 0U},
}};

LLVM_LIBC_FUNCTION(float16, exp2f16, (float16 x)) {
  using FPBits = fputil::FPBits<float16>;
  FPBits x_bits(x);

  uint16_t x_u = x_bits.uintval();
  uint16_t x_abs = x_u & 0x7fffU;

  // When |x| >= 16, or x is NaN.
  if (LIBC_UNLIKELY(x_abs >= 0x4c00U)) {
    // exp2(NaN) = NaN
    if (x_bits.is_nan()) {
      if (x_bits.is_signaling_nan()) {
        fputil::raise_except_if_required(FE_INVALID);
        return FPBits::quiet_nan().get_val();
      }

      return x;
    }

    // When x >= 16.
    if (x_bits.is_pos()) {
      // exp2(+inf) = +inf
      if (x_bits.is_inf())
        return FPBits::inf().get_val();

      switch (fputil::quick_get_round()) {
      case FE_TONEAREST:
      case FE_UPWARD:
        fputil::set_errno_if_required(ERANGE);
        fputil::raise_except_if_required(FE_OVERFLOW);
        return FPBits::inf().get_val();
      default:
        return FPBits::max_normal().get_val();
      }
    }

    // When x <= -25.
    if (x_u >= 0xce40U) {
      // exp2(-inf) = +0
      if (x_bits.is_inf())
        return FPBits::zero().get_val();

      fputil::set_errno_if_required(ERANGE);
      fputil::raise_except_if_required(FE_UNDERFLOW | FE_INEXACT);

      if (fputil::fenv_is_round_up())
        return FPBits::min_subnormal().get_val();
      return FPBits::zero().get_val();
    }
  }

  if (auto r = EXP2F16_EXCEPTS.lookup(x_u); LIBC_UNLIKELY(r.has_value()))
    return r.value();

  // For -25 < x < 16, to compute 2^x, we perform the following range reduction:
  // find hi, mid, lo, such that:
  //   x = hi + mid + lo, in which
  //     hi is an integer,
  //     mid * 2^3 is an integer,
  //     -2^(-4) <= lo < 2^(-4).
  // In particular,
  //   hi + mid = round(x * 2^3) * 2^(-3).
  // Then,
  //   2^x = 2^(hi + mid + lo) = 2^hi * 2^mid * 2^lo.
  // We store 2^mid in the lookup table EXP2_MID_BITS, and compute 2^hi * 2^mid
  // by adding hi to the exponent field of 2^mid.  2^lo is computed using a
  // degree-3 minimax polynomial generated by Sollya.

  float xf = x;
  float kf = fputil::nearest_integer(xf * 0x1.0p+3f);
  int x_hi_mid = static_cast<int>(kf);
  int x_hi = x_hi_mid >> 3;
  int x_mid = x_hi_mid & 0x7;
  // lo = x - (hi + mid) = round(x * 2^3) * (-2^(-3)) + x
  float lo = fputil::multiply_add(kf, -0x1.0p-3f, xf);

  uint32_t exp2_hi_mid_bits =
      EXP2_MID_BITS[x_mid] +
      static_cast<uint32_t>(x_hi << fputil::FPBits<float>::FRACTION_LEN);
  float exp2_hi_mid = fputil::FPBits<float>(exp2_hi_mid_bits).get_val();
  // Degree-3 minimax polynomial generated by Sollya with the following
  // commands:
  //   > display = hexadecimal;
  //   > P = fpminimax((2^x - 1)/x, 2, [|SG...|], [-2^-4, 2^-4]);
  //   > 1 + x * P;
  float exp2_lo = fputil::polyeval(lo, 0x1p+0f, 0x1.62e43p-1f, 0x1.ec0aa6p-3f,
                                   0x1.c6b4a6p-5f);
  return static_cast<float16>(exp2_hi_mid * exp2_lo);
}

} // namespace LIBC_NAMESPACE_DECL
