1//===-- Double-precision tan 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#ifndef LLVM_LIBC_SRC___SUPPORT_MATH_TAN_H
10#define LLVM_LIBC_SRC___SUPPORT_MATH_TAN_H
11
12#include "hdr/errno_macros.h"
13#include "src/__support/FPUtil/FEnvImpl.h"
14#include "src/__support/FPUtil/FPBits.h"
15#include "src/__support/FPUtil/double_double.h"
16#include "src/__support/FPUtil/dyadic_float.h"
17#include "src/__support/FPUtil/except_value_utils.h"
18#include "src/__support/FPUtil/multiply_add.h"
19#include "src/__support/FPUtil/polyeval.h"
20#include "src/__support/FPUtil/rounding_mode.h"
21#include "src/__support/macros/attributes.h"
22#include "src/__support/macros/config.h"
23#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
24#include "src/__support/macros/properties/cpu_features.h" // LIBC_TARGET_CPU_HAS_FMA
25#include "src/__support/math/range_reduction_double_common.h"
26
27#ifdef LIBC_TARGET_CPU_HAS_FMA_DOUBLE
28#include "src/__support/math/range_reduction_double_fma.h"
29#else
30#include "src/__support/math/range_reduction_double_nofma.h"
31#endif // LIBC_TARGET_CPU_HAS_FMA_DOUBLE
32
33namespace LIBC_NAMESPACE_DECL {
34
35namespace math {
36
37namespace tan_internal {
38
39using DoubleDouble = fputil::DoubleDouble;
40using DFloat128 = typename fputil::DyadicFloat<128>;
41
42LIBC_INLINE double tan_eval(const DoubleDouble &u, DoubleDouble &result) {
43 // Evaluate tan(y) = tan(x - k * (pi/128))
44 // We use the degree-9 Taylor approximation:
45 // tan(y) ~ P(y) = y + y^3/3 + 2*y^5/15 + 17*y^7/315 + 62*y^9/2835
46 // Then the error is bounded by:
47 // |tan(y) - P(y)| < 2^-6 * |y|^11 < 2^-6 * 2^-66 = 2^-72.
48 // For y ~ u_hi + u_lo, fully expanding the polynomial and drop any terms
49 // < ulp(u_hi^3) gives us:
50 // P(y) = y + y^3/3 + 2*y^5/15 + 17*y^7/315 + 62*y^9/2835 = ...
51 // ~ u_hi + u_hi^3 * (1/3 + u_hi^2 * (2/15 + u_hi^2 * (17/315 +
52 // + u_hi^2 * 62/2835))) +
53 // + u_lo (1 + u_hi^2 * (1 + u_hi^2 * 2/3))
54 double u_hi_sq = u.hi * u.hi; // Error < ulp(u_hi^2) < 2^(-6 - 52) = 2^-58.
55 // p1 ~ 17/315 + u_hi^2 62 / 2835.
56 double p1 =
57 fputil::multiply_add(x: u_hi_sq, y: 0x1.664f4882c10fap-6, z: 0x1.ba1ba1ba1ba1cp-5);
58 // p2 ~ 1/3 + u_hi^2 2 / 15.
59 double p2 =
60 fputil::multiply_add(x: u_hi_sq, y: 0x1.1111111111111p-3, z: 0x1.5555555555555p-2);
61 // q1 ~ 1 + u_hi^2 * 2/3.
62 double q1 = fputil::multiply_add(x: u_hi_sq, y: 0x1.5555555555555p-1, z: 1.0);
63 double u_hi_3 = u_hi_sq * u.hi;
64 double u_hi_4 = u_hi_sq * u_hi_sq;
65 // p3 ~ 1/3 + u_hi^2 * (2/15 + u_hi^2 * (17/315 + u_hi^2 * 62/2835))
66 double p3 = fputil::multiply_add(x: u_hi_4, y: p1, z: p2);
67 // q2 ~ 1 + u_hi^2 * (1 + u_hi^2 * 2/3)
68 double q2 = fputil::multiply_add(x: u_hi_sq, y: q1, z: 1.0);
69 double tan_lo = fputil::multiply_add(x: u_hi_3, y: p3, z: u.lo * q2);
70 // Overall, |tan(y) - (u_hi + tan_lo)| < ulp(u_hi^3) <= 2^-71.
71 // And the relative errors is:
72 // |(tan(y) - (u_hi + tan_lo)) / tan(y) | <= 2*ulp(u_hi^2) < 2^-64
73 result = fputil::exact_add(a: u.hi, b: tan_lo);
74 return fputil::multiply_add(x: fputil::FPBits<double>(u_hi_3).abs().get_val(),
75 y: 0x1.0p-51, z: 0x1.0p-102);
76}
77
78#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
79// tan(x) ~ x + x^3/3 + x^5 * 2/15 + x^7 * 17/315 + x^9 * 62/2835 +
80// + x^11 * 1382/155925 + x^13 * 21844/6081075 +
81// + x^15 * 929569/638512875 + x^17 * 6404582/10854718875
82// Relative errors < 2^-127 for |u| < pi/256.
83LIBC_INLINE_VAR constexpr DFloat128 TAN_COEFFS[9] = {
84 {Sign::POS, -127, 0x80000000'00000000'00000000'00000000_u128}, // 1
85 {Sign::POS, -129, 0xaaaaaaaa'aaaaaaaa'aaaaaaaa'aaaaaaab_u128}, // 1
86 {Sign::POS, -130, 0x88888888'88888888'88888888'88888889_u128}, // 2/15
87 {Sign::POS, -132, 0xdd0dd0dd'0dd0dd0d'd0dd0dd0'dd0dd0dd_u128}, // 17/315
88 {Sign::POS, -133, 0xb327a441'6087cf99'6b5dd24e'ec0b327a_u128}, // 62/2835
89 {Sign::POS, -134,
90 0x91371aaf'3611e47a'da8e1cba'7d900eca_u128}, // 1382/155925
91 {Sign::POS, -136,
92 0xeb69e870'abeefdaf'e606d2e4'd1e65fbc_u128}, // 21844/6081075
93 {Sign::POS, -137,
94 0xbed1b229'5baf15b5'0ec9af45'a2619971_u128}, // 929569/638512875
95 {Sign::POS, -138,
96 0x9aac1240'1b3a2291'1b2ac7e3'e4627d0a_u128}, // 6404582/10854718875
97};
98
99// Accurate evaluation of tan for small u.
100[[maybe_unused]] LIBC_INLINE DFloat128 tan_eval(const DFloat128 &u) {
101 DFloat128 u_sq = fputil::quick_mul(a: u, b: u);
102 return fputil::quick_mul(a: u, b: fputil::loop_polyeval(x: u_sq, a: TAN_COEFFS));
103}
104
105// Calculation a / b = a * (1/b) for DFloat128.
106// Using the initial approximation of q ~ (1/b), then apply 2 Newton-Raphson
107// iterations, before multiplying by a.
108[[maybe_unused]] LIBC_INLINE DFloat128 newton_raphson_div(const DFloat128 &a,
109 DFloat128 b,
110 double q) {
111 DFloat128 q0(q);
112 LIBC_BIT_CAST_CONSTEXPR_VAR DFloat128 TWO(2.0);
113 b.sign = (b.sign == Sign::POS) ? Sign::NEG : Sign::POS;
114 DFloat128 q1 =
115 fputil::quick_mul(a: q0, b: fputil::quick_add(a: TWO, b: fputil::quick_mul(a: b, b: q0)));
116 DFloat128 q2 =
117 fputil::quick_mul(a: q1, b: fputil::quick_add(a: TWO, b: fputil::quick_mul(a: b, b: q1)));
118 return fputil::quick_mul(a, b: q2);
119}
120#endif // !LIBC_MATH_HAS_SKIP_ACCURATE_PASS
121
122} // namespace tan_internal
123
124LIBC_INLINE double tan(double x) {
125 using namespace tan_internal;
126 using namespace math::range_reduction_double_internal;
127 using FPBits = typename fputil::FPBits<double>;
128 FPBits xbits(x);
129
130 uint16_t x_e = xbits.get_biased_exponent();
131
132 DoubleDouble y;
133 unsigned k;
134 LargeRangeReduction range_reduction_large{};
135
136 // |x| < 2^16
137 if (LIBC_LIKELY(x_e < FPBits::EXP_BIAS + FAST_PASS_EXPONENT)) {
138 // |x| < 2^-7
139 if (LIBC_UNLIKELY(x_e < FPBits::EXP_BIAS - 7)) {
140 // |x| < 2^-27, |tan(x) - x| < ulp(x)/2.
141 if (LIBC_UNLIKELY(x_e < FPBits::EXP_BIAS - 27)) {
142 // Signed zeros.
143 if (LIBC_UNLIKELY(x == 0.0))
144 return x + x; // Make sure it works with FTZ/DAZ.
145
146#ifdef LIBC_TARGET_CPU_HAS_FMA_DOUBLE
147 return fputil::multiply_add(x, 0x1.0p-54, x);
148#else
149 if (LIBC_UNLIKELY(x_e < 4)) {
150 // TODO: UB for rounding nearest
151#ifndef LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY
152 int rounding_mode = fputil::quick_get_round();
153 if ((xbits.sign() == Sign::POS && rounding_mode == FE_UPWARD) ||
154 (xbits.sign() == Sign::NEG && rounding_mode == FE_DOWNWARD))
155 return FPBits(xbits.uintval() + 1).get_val();
156#endif // !LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY
157 }
158 return fputil::multiply_add(x, y: 0x1.0p-54, z: x);
159#endif // LIBC_TARGET_CPU_HAS_FMA_DOUBLE
160 }
161 // No range reduction needed.
162 k = 0;
163 y.lo = 0.0;
164 y.hi = x;
165 } else {
166 // Small range reduction.
167 k = range_reduction_small(x, u&: y);
168 }
169 } else {
170 // Inf or NaN
171 if (LIBC_UNLIKELY(x_e > 2 * FPBits::EXP_BIAS)) {
172 if (xbits.is_signaling_nan()) {
173 fputil::raise_except_if_required(FE_INVALID);
174 return FPBits::quiet_nan().get_val();
175 }
176 // tan(+-Inf) = NaN
177 if (xbits.get_mantissa() == 0) {
178 fputil::set_errno_if_required(EDOM);
179 fputil::raise_except_if_required(FE_INVALID);
180 }
181 return x + FPBits::quiet_nan().get_val();
182 }
183
184 // Large range reduction.
185 k = range_reduction_large.fast(x, u&: y);
186 }
187
188 DoubleDouble tan_y;
189 [[maybe_unused]] double err = tan_eval(u: y, result&: tan_y);
190
191 // Look up sin(k * pi/128) and cos(k * pi/128)
192#ifdef LIBC_MATH_HAS_SMALL_TABLES
193 // Memory saving versions. Use 65-entry table:
194 auto get_idx_dd = [](unsigned kk) -> DoubleDouble {
195 unsigned idx = (kk & 64) ? 64 - (kk & 63) : (kk & 63);
196 DoubleDouble ans = SIN_K_PI_OVER_128[idx];
197 if (kk & 128) {
198 ans.hi = -ans.hi;
199 ans.lo = -ans.lo;
200 }
201 return ans;
202 };
203 DoubleDouble msin_k = get_idx_dd(k + 128);
204 DoubleDouble cos_k = get_idx_dd(k + 64);
205#else
206 // Fast look up version, but needs 256-entry table.
207 // cos(k * pi/128) = sin(k * pi/128 + pi/2) = sin((k + 64) * pi/128).
208 DoubleDouble msin_k = SIN_K_PI_OVER_128[(k + 128) & 255];
209 DoubleDouble cos_k = SIN_K_PI_OVER_128[(k + 64) & 255];
210#endif // LIBC_MATH_HAS_SMALL_TABLES
211
212 // After range reduction, k = round(x * 128 / pi) and y = x - k * (pi / 128).
213 // So k is an integer and -pi / 256 <= y <= pi / 256.
214 // Then tan(x) = sin(x) / cos(x)
215 // = sin((k * pi/128 + y) / cos((k * pi/128 + y)
216 // = (cos(y) * sin(k*pi/128) + sin(y) * cos(k*pi/128)) /
217 // / (cos(y) * cos(k*pi/128) - sin(y) * sin(k*pi/128))
218 // = (sin(k*pi/128) + tan(y) * cos(k*pi/128)) /
219 // / (cos(k*pi/128) - tan(y) * sin(k*pi/128))
220 DoubleDouble cos_k_tan_y = fputil::quick_mult(a: tan_y, b: cos_k);
221 DoubleDouble msin_k_tan_y = fputil::quick_mult(a: tan_y, b: msin_k);
222
223 // num_dd = sin(k*pi/128) + tan(y) * cos(k*pi/128)
224 DoubleDouble num_dd = fputil::exact_add<false>(a: cos_k_tan_y.hi, b: -msin_k.hi);
225 // den_dd = cos(k*pi/128) - tan(y) * sin(k*pi/128)
226 DoubleDouble den_dd = fputil::exact_add<false>(a: msin_k_tan_y.hi, b: cos_k.hi);
227 num_dd.lo += cos_k_tan_y.lo - msin_k.lo;
228 den_dd.lo += msin_k_tan_y.lo + cos_k.lo;
229
230#ifdef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
231 double tan_x = (num_dd.hi + num_dd.lo) / (den_dd.hi + den_dd.lo);
232 return tan_x;
233#else
234 // Accurate test and pass for correctly rounded implementation.
235
236 // Accurate double-double division
237 DoubleDouble tan_x = fputil::div(a: num_dd, b: den_dd);
238
239 // Simple error bound: |1 / den_dd| < 2^(1 + floor(-log2(den_dd)))).
240 uint64_t den_inv = (static_cast<uint64_t>(FPBits::EXP_BIAS + 1)
241 << (FPBits::FRACTION_LEN + 1)) -
242 (FPBits(den_dd.hi).uintval() & FPBits::EXP_MASK);
243
244 // For tan_x = (num_dd + err) / (den_dd + err), the error is bounded by:
245 // | tan_x - num_dd / den_dd | <= err * ( 1 + | tan_x * den_dd | ).
246 double tan_err =
247 err * fputil::multiply_add(x: FPBits(den_inv).get_val(),
248 y: FPBits(tan_x.hi).abs().get_val(), z: 1.0);
249
250 double err_higher = tan_x.lo + tan_err;
251 double err_lower = tan_x.lo - tan_err;
252
253 double tan_upper = tan_x.hi + err_higher;
254 double tan_lower = tan_x.hi + err_lower;
255
256 // Ziv's rounding test.
257 if (LIBC_LIKELY(tan_upper == tan_lower))
258 return tan_upper;
259
260 DFloat128 u_f128;
261 if (LIBC_LIKELY(x_e < FPBits::EXP_BIAS + FAST_PASS_EXPONENT))
262 u_f128 = range_reduction_small_f128(x);
263 else
264 u_f128 = range_reduction_large.accurate();
265
266 DFloat128 tan_u = tan_eval(u: u_f128);
267
268 auto get_sin_k = [](unsigned kk) -> DFloat128 {
269 unsigned idx = (kk & 64) ? 64 - (kk & 63) : (kk & 63);
270 DFloat128 ans = SIN_K_PI_OVER_128_F128[idx];
271 if (kk & 128)
272 ans.sign = Sign::NEG;
273 return ans;
274 };
275
276 // cos(k * pi/128) = sin(k * pi/128 + pi/2) = sin((k + 64) * pi/128).
277 DFloat128 sin_k_f128 = get_sin_k(k);
278 DFloat128 cos_k_f128 = get_sin_k(k + 64);
279 DFloat128 msin_k_f128 = get_sin_k(k + 128);
280
281 // num_f128 = sin(k*pi/128) + tan(y) * cos(k*pi/128)
282 DFloat128 num_f128 =
283 fputil::quick_add(a: sin_k_f128, b: fputil::quick_mul(a: cos_k_f128, b: tan_u));
284 // den_f128 = cos(k*pi/128) - tan(y) * sin(k*pi/128)
285 DFloat128 den_f128 =
286 fputil::quick_add(a: cos_k_f128, b: fputil::quick_mul(a: msin_k_f128, b: tan_u));
287
288 // tan(x) = (sin(k*pi/128) + tan(y) * cos(k*pi/128)) /
289 // / (cos(k*pi/128) - tan(y) * sin(k*pi/128))
290 // TODO: The initial seed 1.0/den_dd.hi for Newton-Raphson reciprocal can be
291 // reused from DoubleDouble fputil::div in the fast pass.
292 DFloat128 result = newton_raphson_div(a: num_f128, b: den_f128, q: 1.0 / den_dd.hi);
293
294 // TODO: Add assertion if Ziv's accuracy tests fail in debug mode.
295 // https://github.com/llvm/llvm-project/issues/96452.
296 return static_cast<double>(result);
297
298#endif // !LIBC_MATH_HAS_SKIP_ACCURATE_PASS
299}
300
301} // namespace math
302
303} // namespace LIBC_NAMESPACE_DECL
304
305#endif // LLVM_LIBC_SRC___SUPPORT_MATH_TAN_H
306