//===-- Single-precision tan 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/tanf.h"
#include "sincosf_utils.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/common.h"

#include <errno.h>

namespace __llvm_libc {

// Exceptional cases for tanf.
constexpr size_t N_EXCEPTS = 6;

constexpr fputil::ExceptValues<float, N_EXCEPTS> TANF_EXCEPTS{{
    // (inputs, RZ output, RU offset, RD offset, RN offset)
    // x = 0x1.ada6aap27, tan(x) = 0x1.e80304p-3 (RZ)
    {0x4d56d355, 0x3e740182, 1, 0, 0},
    // x = 0x1.862064p33, tan(x) = -0x1.8dee56p-3 (RZ)
    {0x50431032, 0xbe46f72b, 0, 1, 1},
    // x = 0x1.af61dap48, tan(x) = 0x1.60d1c6p-2 (RZ)
    {0x57d7b0ed, 0x3eb068e3, 1, 0, 1},
    // x = 0x1.0088bcp52, tan(x) = 0x1.ca1edp0 (RZ)
    {0x5980445e, 0x3fe50f68, 1, 0, 0},
    // x = 0x1.f90dfcp72, tan(x) = 0x1.597f9cp-1 (RZ)
    {0x63fc86fe, 0x3f2cbfce, 1, 0, 0},
    // x = 0x1.a6ce12p86, tan(x) = -0x1.c5612ep-1 (RZ)
    {0x6ad36709, 0xbf62b097, 0, 1, 0},
}};

LLVM_LIBC_FUNCTION(float, tanf, (float x)) {
  using FPBits = typename fputil::FPBits<float>;
  FPBits xbits(x);
  bool x_sign = xbits.uintval() >> 31;
  uint32_t x_abs = xbits.uintval() & 0x7fff'ffffU;

  // |x| < pi/32
  if (unlikely(x_abs <= 0x3dc9'0fdbU)) {
    double xd = static_cast<double>(x);

    // |x| < 0x1.0p-12f
    if (unlikely(x_abs < 0x3980'0000U)) {
      if (unlikely(x_abs == 0U)) {
        // For signed zeros.
        return x;
      }
      // When |x| < 2^-12, the relative error of the approximation tan(x) ~ x
      // is:
      //   |tan(x) - x| / |tan(x)| < |x^3| / (3|x|)
      //                           = x^2 / 3
      //                           < 2^-25
      //                           < epsilon(1)/2.
      // So the correctly rounded values of tan(x) are:
      //   = x + sign(x)*eps(x) if rounding mode = FE_UPWARD and x is positive,
      //                        or (rounding mode = FE_DOWNWARD and x is
      //                        negative),
      //   = x otherwise.
      // To simplify the rounding decision and make it more efficient, we use
      //   fma(x, 2^-25, x) instead.
      // Note: to use the formula x + 2^-25*x to decide the correct rounding, we
      // do need fma(x, 2^-25, x) to prevent underflow caused by 2^-25*x when
      // |x| < 2^-125. For targets without FMA instructions, we simply use
      // double for intermediate results as it is more efficient than using an
      // emulated version of FMA.
#if defined(LIBC_TARGET_HAS_FMA)
      return fputil::multiply_add(x, 0x1.0p-25f, x);
#else
      return static_cast<float>(fputil::multiply_add(xd, 0x1.0p-25, xd));
#endif // LIBC_TARGET_HAS_FMA
    }

    // |x| < pi/32
    double xsq = xd * xd;

    // Degree-9 minimax odd polynomial of tan(x) generated by Sollya with:
    // > P = fpminimax(tan(x)/x, [|0, 2, 4, 6, 8|], [|1, D...|], [0, pi/32]);
    double result =
        fputil::polyeval(xsq, 1.0, 0x1.555555553d022p-2, 0x1.111111ce442c1p-3,
                         0x1.ba180a6bbdecdp-5, 0x1.69c0a88a0b71fp-6);
    return xd * result;
  }

  // Check for exceptional values
  if (unlikely(x_abs == 0x3f8a1f62U)) {
    // |x| = 0x1.143ec4p0
    float sign = x_sign ? -1.0f : 1.0f;

    return fputil::multiply_add(sign, 0x1.ddf9f4p0f, sign * 0x1.1p-24f);
  }

  // |x| > 0x1.ada6a8p+27f
  if (unlikely(x_abs > 0x4d56'd354U)) {
    // Inf or NaN
    if (unlikely(x_abs >= 0x7f80'0000U)) {
      if (x_abs == 0x7f80'0000U) {
        errno = EDOM;
        fputil::set_except(FE_INVALID);
      }
      return x +
             FPBits::build_nan(1 << (fputil::MantissaWidth<float>::VALUE - 1));
    }
    // Other large exceptional values
    if (auto r = TANF_EXCEPTS.lookup_odd(x_abs, x_sign);
        unlikely(r.has_value()))
      return r.value();
  }

  // For |x| >= pi/32, we use the definition of tan(x) function:
  //   tan(x) = sin(x) / cos(x)
  // The we follow the same computations of sin(x) and cos(x) as sinf, cosf,
  // and sincosf.

  double xd = static_cast<double>(x);
  double sin_k, cos_k, sin_y, cosm1_y;

  sincosf_eval(xd, x_abs, sin_k, cos_k, sin_y, cosm1_y);
  // tan(x) = sin(x) / cos(x)
  //        = (sin_y * cos_k + cos_y * sin_k) / (cos_y * cos_k - sin_y * sin_k)
  using fputil::multiply_add;
  return 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 __llvm_libc
