1 //===-- Single-precision cos 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/cosf.h"
10 #include "math_utils.h"
11 #include "sincosf_utils.h"
12 
13 #include "src/__support/common.h"
14 #include <math.h>
15 
16 #include <stdint.h>
17 
18 namespace __llvm_libc {
19 
20 // Fast cosf implementation. Worst-case ULP is 0.5607, maximum relative
21 // error is 0.5303 * 2^-23. A single-step range reduction is used for
22 // small values. Large inputs have their range reduced using fast integer
23 // arithmetic.
24 LLVM_LIBC_FUNCTION(float, cosf, (float y)) {
25   double x = y;
26   double s;
27   int n;
28   const sincos_t *p = &SINCOSF_TABLE[0];
29 
30   if (abstop12(y) < abstop12(PIO4)) {
31     double x2 = x * x;
32 
33     if (unlikely(abstop12(y) < abstop12(as_float(0x39800000))))
34       return 1.0f;
35 
36     return sinf_poly(x, x2, p, 1);
37   } else if (likely(abstop12(y) < abstop12(120.0f))) {
38     x = reduce_fast(x, p, &n);
39 
40     // Setup the signs for sin and cos.
41     s = p->sign[n & 3];
42 
43     if (n & 2)
44       p = &SINCOSF_TABLE[1];
45 
46     return sinf_poly(x * s, x * x, p, n ^ 1);
47   } else if (abstop12(y) < abstop12(INFINITY)) {
48     uint32_t xi = as_uint32_bits(y);
49     int sign = xi >> 31;
50 
51     x = reduce_large(xi, &n);
52 
53     // Setup signs for sin and cos - include original sign.
54     s = p->sign[(n + sign) & 3];
55 
56     if ((n + sign) & 2)
57       p = &SINCOSF_TABLE[1];
58 
59     return sinf_poly(x * s, x * x, p, n ^ 1);
60   }
61 
62   return invalid(y);
63 }
64 
65 } // namespace __llvm_libc
66