//===-- Half-precision tan(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/tanf16.h"
#include "hdr/errno_macros.h"
#include "hdr/fenv_macros.h"
#include "sincosf16_utils.h"
#include "src/__support/FPUtil/FEnvImpl.h"
#include "src/__support/FPUtil/FPBits.h"
#include "src/__support/FPUtil/cast.h"
#include "src/__support/FPUtil/except_value_utils.h"
#include "src/__support/FPUtil/multiply_add.h"
#include "src/__support/macros/optimization.h"

namespace LIBC_NAMESPACE_DECL {

#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
constexpr size_t N_EXCEPTS = 9;

constexpr fputil::ExceptValues<float16, N_EXCEPTS> TANF16_EXCEPTS{{
    // (input, RZ output, RU offset, RD offset, RN offset)
    {0x2894, 0x2894, 1, 0, 1},
    {0x3091, 0x3099, 1, 0, 0},
    {0x3098, 0x30a0, 1, 0, 0},
    {0x55ed, 0x3911, 1, 0, 0},
    {0x607b, 0xc638, 0, 1, 1},
    {0x674e, 0x3b7d, 1, 0, 0},
    {0x6807, 0x4014, 1, 0, 1},
    {0x6f4d, 0xbe19, 0, 1, 1},
    {0x7330, 0xcb62, 0, 1, 0},
}};
#endif // !LIBC_MATH_HAS_SKIP_ACCURATE_PASS

LLVM_LIBC_FUNCTION(float16, tanf16, (float16 x)) {
  using FPBits = fputil::FPBits<float16>;
  FPBits xbits(x);

  uint16_t x_u = xbits.uintval();
  uint16_t x_abs = x_u & 0x7fff;
  float xf = x;

#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
  bool x_sign = x_u >> 15;
  // Handle exceptional values
  if (auto r = TANF16_EXCEPTS.lookup_odd(x_abs, x_sign);
      LIBC_UNLIKELY(r.has_value()))
    return r.value();
#endif // !LIBC_MATH_HAS_SKIP_ACCURATE_PASS

  // |x| <= 0x1.d1p-5
  if (LIBC_UNLIKELY(x_abs <= 0x2b44)) {
    // |x| <= 0x1.398p-11
    if (LIBC_UNLIKELY(x_abs <= 0x10e6)) {
      // tan(+/-0) = +/-0
      if (LIBC_UNLIKELY(x_abs == 0))
        return x;

      int rounding = fputil::quick_get_round();

      // Exhaustive tests show that, when:
      // x > 0, and rounding upward or
      // x < 0, and rounding downward then,
      // tan(x) = x * 2^-11 + x
      if ((xbits.is_pos() && rounding == FE_UPWARD) ||
          (xbits.is_neg() && rounding == FE_DOWNWARD))
        return fputil::cast<float16>(fputil::multiply_add(xf, 0x1.0p-11f, xf));
      return x;
    }

    float xsq = xf * xf;

    // Degree-6 minimax odd polynomial of tan(x) generated by Sollya with:
    // > P = fpminimax(tan(x)/x, [|0, 2, 4, 6|], [|1, SG...|], [0, pi/32]);
    float result = fputil::polyeval(xsq, 0x1p0f, 0x1.555556p-2f, 0x1.110ee4p-3f,
                                    0x1.be80f6p-5f);

    return fputil::cast<float16>(xf * result);
  }

  // tan(+/-inf) = NaN, and tan(NaN) = NaN
  if (LIBC_UNLIKELY(x_abs >= 0x7c00)) {
    if (xbits.is_signaling_nan()) {
      fputil::raise_except_if_required(FE_INVALID);
      return FPBits::quiet_nan().get_val();
    }
    // x = +/-inf
    if (x_abs == 0x7c00) {
      fputil::set_errno_if_required(EDOM);
      fputil::raise_except_if_required(FE_INVALID);
    }

    return x + FPBits::quiet_nan().get_val();
  }

  // Range reduction:
  // For |x| > pi/32, we perform range reduction as follows:
  // Find k and y such that:
  //   x = (k + y) * pi/32;
  //   k is an integer, |y| < 0.5
  //
  // This is done by performing:
  //   k = round(x * 32/pi)
  //   y = x * 32/pi - k
  //
  // Once k and y are computed, we then deduce the answer by the formula:
  // tan(x) = sin(x) / cos(x)
  // 	    = (sin_y * cos_k + cos_y * sin_k) / (cos_y * cos_k - sin_y * sin_k)
  float sin_k, cos_k, sin_y, cosm1_y;
  sincosf16_eval(xf, sin_k, cos_k, sin_y, cosm1_y);

  // Note that, cosm1_y = cos_y - 1:
  using fputil::multiply_add;
  return fputil::cast<float16>(
      multiply_add(sin_y, cos_k, multiply_add(cosm1_y, sin_k, sin_k)) /
      multiply_add(sin_y, -sin_k, multiply_add(cosm1_y, cos_k, cos_k)));
}

} // namespace LIBC_NAMESPACE_DECL
