• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- Single-precision atan2f 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 #include "src/math/atan2f.h"
10 #include "inv_trigf_utils.h"
11 #include "src/__support/FPUtil/FPBits.h"
12 #include "src/__support/FPUtil/PolyEval.h"
13 #include "src/__support/FPUtil/double_double.h"
14 #include "src/__support/FPUtil/multiply_add.h"
15 #include "src/__support/FPUtil/nearest_integer.h"
16 #include "src/__support/FPUtil/rounding_mode.h"
17 #include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
18 
19 namespace LIBC_NAMESPACE {
20 
21 namespace {
22 
23 // Look up tables for accurate pass:
24 
25 // atan(i/16) with i = 0..16, generated by Sollya with:
26 // > for i from 0 to 16 do {
27 //     a = round(atan(i/16), D, RN);
28 //     b = round(atan(i/16) - a, D, RN);
29 //     print("{", b, ",", a, "},");
30 //   };
31 constexpr fputil::DoubleDouble ATAN_I[17] = {
32     {0.0, 0.0},
33     {-0x1.c934d86d23f1dp-60, 0x1.ff55bb72cfdeap-5},
34     {-0x1.cd37686760c17p-59, 0x1.fd5ba9aac2f6ep-4},
35     {0x1.347b0b4f881cap-58, 0x1.7b97b4bce5b02p-3},
36     {0x1.8ab6e3cf7afbdp-57, 0x1.f5b75f92c80ddp-3},
37     {-0x1.963a544b672d8p-57, 0x1.362773707ebccp-2},
38     {-0x1.c63aae6f6e918p-56, 0x1.6f61941e4def1p-2},
39     {-0x1.24dec1b50b7ffp-56, 0x1.a64eec3cc23fdp-2},
40     {0x1.a2b7f222f65e2p-56, 0x1.dac670561bb4fp-2},
41     {-0x1.d5b495f6349e6p-56, 0x1.0657e94db30dp-1},
42     {-0x1.928df287a668fp-58, 0x1.1e00babdefeb4p-1},
43     {0x1.1021137c71102p-55, 0x1.345f01cce37bbp-1},
44     {0x1.2419a87f2a458p-56, 0x1.4978fa3269ee1p-1},
45     {0x1.0028e4bc5e7cap-57, 0x1.5d58987169b18p-1},
46     {-0x1.8c34d25aadef6p-56, 0x1.700a7c5784634p-1},
47     {-0x1.bf76229d3b917p-56, 0x1.819d0b7158a4dp-1},
48     {0x1.1a62633145c07p-55, 0x1.921fb54442d18p-1},
49 };
50 
51 // Taylor polynomial, generated by Sollya with:
52 // > for i from 0 to 8 do {
53 //     j = (-1)^(i + 1)/(2*i + 1);
54 //     a = round(j, D, RN);
55 //     b = round(j - a, D, RN);
56 //     print("{", b, ",", a, "},");
57 //   };
58 constexpr fputil::DoubleDouble COEFFS[9] = {
59     {0.0, 1.0},                                      // 1
60     {-0x1.5555555555555p-56, -0x1.5555555555555p-2}, // -1/3
61     {-0x1.999999999999ap-57, 0x1.999999999999ap-3},  // 1/5
62     {-0x1.2492492492492p-57, -0x1.2492492492492p-3}, // -1/7
63     {0x1.c71c71c71c71cp-58, 0x1.c71c71c71c71cp-4},   // 1/9
64     {0x1.745d1745d1746p-59, -0x1.745d1745d1746p-4},  // -1/11
65     {-0x1.3b13b13b13b14p-58, 0x1.3b13b13b13b14p-4},  // 1/13
66     {-0x1.1111111111111p-60, -0x1.1111111111111p-4}, // -1/15
67     {0x1.e1e1e1e1e1e1ep-61, 0x1.e1e1e1e1e1e1ep-5},   // 1/17
68 };
69 
70 // Veltkamp's splitting of a double precision into hi + lo, where the hi part is
71 // slightly smaller than an even split, so that the product of
72 //   hi * (s1 * k + s2) is exact,
73 // where:
74 //   s1, s2 are single precsion,
75 //   1/16 <= s1/s2 <= 1
76 //   1/16 <= k <= 1 is an integer.
77 // So the maximal precision of (s1 * k + s2) is:
78 //   prec(s1 * k + s2) = 2 + log2(msb(s2)) - log2(lsb(k_d * s1))
79 //                     = 2 + log2(msb(s1)) + 4 - log2(lsb(k_d)) - log2(lsb(s1))
80 //                     = 2 + log2(lsb(s1)) + 23 + 4 - (-4) - log2(lsb(s1))
81 //                     = 33.
82 // Thus, the Veltkamp splitting constant is C = 2^33 + 1.
83 // This is used when FMA instruction is not available.
split_d(double a)84 [[maybe_unused]] constexpr fputil::DoubleDouble split_d(double a) {
85   fputil::DoubleDouble r{0.0, 0.0};
86   constexpr double C = 0x1.0p33 + 1.0;
87   double t1 = C * a;
88   double t2 = a - t1;
89   r.hi = t1 + t2;
90   r.lo = a - r.hi;
91   return r;
92 }
93 
94 // Compute atan( num_d / den_d ) in double-double precision.
95 //   num_d      = min(|x|, |y|)
96 //   den_d      = max(|x|, |y|)
97 //   q_d        = num_d / den_d
98 //   idx, k_d   = round( 2^4 * num_d / den_d )
99 //   final_sign = sign of the final result
100 //   const_term = the constant term in the final expression.
atan2f_double_double(double num_d,double den_d,double q_d,int idx,double k_d,double final_sign,const fputil::DoubleDouble & const_term)101 float atan2f_double_double(double num_d, double den_d, double q_d, int idx,
102                            double k_d, double final_sign,
103                            const fputil::DoubleDouble &const_term) {
104   fputil::DoubleDouble q;
105   double num_r, den_r;
106 
107   if (idx != 0) {
108     // The following range reduction is accurate even without fma for
109     //   1/16 <= n/d <= 1.
110     // atan(n/d) - atan(idx/16) = atan((n/d - idx/16) / (1 + (n/d) * (idx/16)))
111     //                          = atan((n - d*(idx/16)) / (d + n*idx/16))
112     k_d *= 0x1.0p-4;
113     num_r = fputil::multiply_add(k_d, -den_d, num_d); // Exact
114     den_r = fputil::multiply_add(k_d, num_d, den_d);  // Exact
115     q.hi = num_r / den_r;
116   } else {
117     // For 0 < n/d < 1/16, we just need to calculate the lower part of their
118     // quotient.
119     q.hi = q_d;
120     num_r = num_d;
121     den_r = den_d;
122   }
123 #ifdef LIBC_TARGET_CPU_HAS_FMA
124   q.lo = fputil::multiply_add(q.hi, -den_r, num_r) / den_r;
125 #else
126   // Compute `(num_r - q.hi * den_r) / den_r` accurately without FMA
127   // instructions.
128   fputil::DoubleDouble q_hi_dd = split_d(q.hi);
129   double t1 = fputil::multiply_add(q_hi_dd.hi, -den_r, num_r); // Exact
130   double t2 = fputil::multiply_add(q_hi_dd.lo, -den_r, t1);
131   q.lo = t2 / den_r;
132 #endif // LIBC_TARGET_CPU_HAS_FMA
133 
134   // Taylor polynomial, evaluating using Horner's scheme:
135   //   P = x - x^3/3 + x^5/5 -x^7/7 + x^9/9 - x^11/11 + x^13/13 - x^15/15
136   //       + x^17/17
137   //     = x*(1 + x^2*(-1/3 + x^2*(1/5 + x^2*(-1/7 + x^2*(1/9 + x^2*
138   //          *(-1/11 + x^2*(1/13 + x^2*(-1/15 + x^2 * 1/17))))))))
139   fputil::DoubleDouble q2 = fputil::quick_mult(q, q);
140   fputil::DoubleDouble p_dd =
141       fputil::polyeval(q2, COEFFS[0], COEFFS[1], COEFFS[2], COEFFS[3],
142                        COEFFS[4], COEFFS[5], COEFFS[6], COEFFS[7], COEFFS[8]);
143   fputil::DoubleDouble r_dd =
144       fputil::add(const_term, fputil::multiply_add(q, p_dd, ATAN_I[idx]));
145   r_dd.hi *= final_sign;
146   r_dd.lo *= final_sign;
147 
148   // Make sure the sum is normalized:
149   fputil::DoubleDouble rr = fputil::exact_add(r_dd.hi, r_dd.lo);
150   // Round to odd.
151   uint64_t rr_bits = cpp::bit_cast<uint64_t>(rr.hi);
152   if (LIBC_UNLIKELY(((rr_bits & 0xfff'ffff) == 0) && (rr.lo != 0.0))) {
153     Sign hi_sign = fputil::FPBits<double>(rr.hi).sign();
154     Sign lo_sign = fputil::FPBits<double>(rr.lo).sign();
155     if (hi_sign == lo_sign) {
156       ++rr_bits;
157     } else if ((rr_bits & fputil::FPBits<double>::FRACTION_MASK) > 0) {
158       --rr_bits;
159     }
160   }
161 
162   return static_cast<float>(cpp::bit_cast<double>(rr_bits));
163 }
164 
165 } // anonymous namespace
166 
167 // There are several range reduction steps we can take for atan2(y, x) as
168 // follow:
169 
170 // * Range reduction 1: signness
171 // atan2(y, x) will return a number between -PI and PI representing the angle
172 // forming by the 0x axis and the vector (x, y) on the 0xy-plane.
173 // In particular, we have that:
174 //   atan2(y, x) = atan( y/x )         if x >= 0 and y >= 0 (I-quadrant)
175 //               = pi + atan( y/x )    if x < 0 and y >= 0  (II-quadrant)
176 //               = -pi + atan( y/x )   if x < 0 and y < 0   (III-quadrant)
177 //               = atan( y/x )         if x >= 0 and y < 0  (IV-quadrant)
178 // Since atan function is odd, we can use the formula:
179 //   atan(-u) = -atan(u)
180 // to adjust the above conditions a bit further:
181 //   atan2(y, x) = atan( |y|/|x| )         if x >= 0 and y >= 0 (I-quadrant)
182 //               = pi - atan( |y|/|x| )    if x < 0 and y >= 0  (II-quadrant)
183 //               = -pi + atan( |y|/|x| )   if x < 0 and y < 0   (III-quadrant)
184 //               = -atan( |y|/|x| )        if x >= 0 and y < 0  (IV-quadrant)
185 // Which can be simplified to:
186 //   atan2(y, x) = sign(y) * atan( |y|/|x| )             if x >= 0
187 //               = sign(y) * (pi - atan( |y|/|x| ))      if x < 0
188 
189 // * Range reduction 2: reciprocal
190 // Now that the argument inside atan is positive, we can use the formula:
191 //   atan(1/x) = pi/2 - atan(x)
192 // to make the argument inside atan <= 1 as follow:
193 //   atan2(y, x) = sign(y) * atan( |y|/|x|)            if 0 <= |y| <= x
194 //               = sign(y) * (pi/2 - atan( |x|/|y| )   if 0 <= x < |y|
195 //               = sign(y) * (pi - atan( |y|/|x| ))    if 0 <= |y| <= -x
196 //               = sign(y) * (pi/2 + atan( |x|/|y| ))  if 0 <= -x < |y|
197 
198 // * Range reduction 3: look up table.
199 // After the previous two range reduction steps, we reduce the problem to
200 // compute atan(u) with 0 <= u <= 1, or to be precise:
201 //   atan( n / d ) where n = min(|x|, |y|) and d = max(|x|, |y|).
202 // An accurate polynomial approximation for the whole [0, 1] input range will
203 // require a very large degree.  To make it more efficient, we reduce the input
204 // range further by finding an integer idx such that:
205 //   | n/d - idx/16 | <= 1/32.
206 // In particular,
207 //   idx := 2^-4 * round(2^4 * n/d)
208 // Then for the fast pass, we find a polynomial approximation for:
209 //   atan( n/d ) ~ atan( idx/16 ) + (n/d - idx/16) * Q(n/d - idx/16)
210 // For the accurate pass, we use the addition formula:
211 //   atan( n/d ) - atan( idx/16 ) = atan( (n/d - idx/16)/(1 + (n*idx)/(16*d)) )
212 //                                = atan( (n - d * idx/16)/(d + n * idx/16) )
213 // And finally we use Taylor polynomial to compute the RHS in the accurate pass:
214 //   atan(u) ~ P(u) = u - u^3/3 + u^5/5 - u^7/7 + u^9/9 - u^11/11 + u^13/13 -
215 //                      - u^15/15 + u^17/17
216 // It's error in double-double precision is estimated in Sollya to be:
217 // > P = x - x^3/3 + x^5/5 -x^7/7 + x^9/9 - x^11/11 + x^13/13 - x^15/15
218 //       + x^17/17;
219 // > dirtyinfnorm(atan(x) - P, [-2^-5, 2^-5]);
220 // 0x1.aec6f...p-100
221 // which is about rounding errors of double-double (2^-104).
222 
223 LLVM_LIBC_FUNCTION(float, atan2f, (float y, float x)) {
224   using FPBits = typename fputil::FPBits<float>;
225   constexpr double IS_NEG[2] = {1.0, -1.0};
226   constexpr double PI = 0x1.921fb54442d18p1;
227   constexpr double PI_LO = 0x1.1a62633145c07p-53;
228   constexpr double PI_OVER_4 = 0x1.921fb54442d18p-1;
229   constexpr double PI_OVER_2 = 0x1.921fb54442d18p0;
230   constexpr double THREE_PI_OVER_4 = 0x1.2d97c7f3321d2p+1;
231   // Adjustment for constant term:
232   //   CONST_ADJ[x_sign][y_sign][recip]
233   constexpr fputil::DoubleDouble CONST_ADJ[2][2][2] = {
234       {{{0.0, 0.0}, {-PI_LO / 2, -PI_OVER_2}},
235        {{-0.0, -0.0}, {-PI_LO / 2, -PI_OVER_2}}},
236       {{{-PI_LO, -PI}, {PI_LO / 2, PI_OVER_2}},
237        {{-PI_LO, -PI}, {PI_LO / 2, PI_OVER_2}}}};
238 
239   FPBits x_bits(x), y_bits(y);
240   bool x_sign = x_bits.sign().is_neg();
241   bool y_sign = y_bits.sign().is_neg();
242   x_bits.set_sign(Sign::POS);
243   y_bits.set_sign(Sign::POS);
244   uint32_t x_abs = x_bits.uintval();
245   uint32_t y_abs = y_bits.uintval();
246   uint32_t max_abs = x_abs > y_abs ? x_abs : y_abs;
247   uint32_t min_abs = x_abs <= y_abs ? x_abs : y_abs;
248 
249   if (LIBC_UNLIKELY(max_abs >= 0x7f80'0000U || min_abs == 0U)) {
250     if (x_bits.is_nan() || y_bits.is_nan())
251       return FPBits::quiet_nan().get_val();
252     size_t x_except = x_abs == 0 ? 0 : (x_abs == 0x7f80'0000 ? 2 : 1);
253     size_t y_except = y_abs == 0 ? 0 : (y_abs == 0x7f80'0000 ? 2 : 1);
254 
255     // Exceptional cases:
256     //   EXCEPT[y_except][x_except][x_is_neg]
257     // with x_except & y_except:
258     //   0: zero
259     //   1: finite, non-zero
260     //   2: infinity
261     constexpr double EXCEPTS[3][3][2] = {
262         {{0.0, PI}, {0.0, PI}, {0.0, PI}},
263         {{PI_OVER_2, PI_OVER_2}, {0.0, 0.0}, {0.0, PI}},
264         {{PI_OVER_2, PI_OVER_2},
265          {PI_OVER_2, PI_OVER_2},
266          {PI_OVER_4, THREE_PI_OVER_4}},
267     };
268 
269     double r = IS_NEG[y_sign] * EXCEPTS[y_except][x_except][x_sign];
270 
271     return static_cast<float>(r);
272   }
273 
274   bool recip = x_abs < y_abs;
275   double final_sign = IS_NEG[(x_sign != y_sign) != recip];
276   fputil::DoubleDouble const_term = CONST_ADJ[x_sign][y_sign][recip];
277   double num_d = static_cast<double>(FPBits(min_abs).get_val());
278   double den_d = static_cast<double>(FPBits(max_abs).get_val());
279   double q_d = num_d / den_d;
280 
281   double k_d = fputil::nearest_integer(q_d * 0x1.0p4f);
282   int idx = static_cast<int>(k_d);
283   q_d = fputil::multiply_add(k_d, -0x1.0p-4, q_d);
284 
285   double p = atan_eval(q_d, idx);
286   double r = final_sign *
287              fputil::multiply_add(q_d, p, const_term.hi + ATAN_COEFFS[idx][0]);
288 
289   constexpr uint32_t LOWER_ERR = 4;
290   // Mask sticky bits in double precision before rounding to single precision.
291   constexpr uint32_t MASK =
292       mask_trailing_ones<uint32_t, fputil::FPBits<double>::SIG_LEN -
293                                        FPBits::SIG_LEN - 1>();
294   constexpr uint32_t UPPER_ERR = MASK - LOWER_ERR;
295 
296   uint32_t r_bits = static_cast<uint32_t>(cpp::bit_cast<uint64_t>(r)) & MASK;
297 
298   // Ziv's rounding test.
299   if (LIBC_LIKELY(r_bits > LOWER_ERR && r_bits < UPPER_ERR))
300     return static_cast<float>(r);
301 
302   return atan2f_double_double(num_d, den_d, q_d, idx, k_d, final_sign,
303                               const_term);
304 }
305 
306 } // namespace LIBC_NAMESPACE
307