1//===-- Single-precision cosh 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/coshf.h"
10#include "src/__support/FPUtil/FPBits.h"
11#include "src/__support/FPUtil/multiply_add.h"
12#include "src/__support/FPUtil/rounding_mode.h"
13#include "src/__support/macros/config.h"
14#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
15#include "src/math/generic/explogxf.h"
16
17namespace LIBC_NAMESPACE_DECL {
18
19LLVM_LIBC_FUNCTION(float, coshf, (float x)) {
20 using FPBits = typename fputil::FPBits<float>;
21
22 FPBits xbits(x);
23 xbits.set_sign(Sign::POS);
24 x = xbits.get_val();
25
26 uint32_t x_u = xbits.uintval();
27
28 // When |x| >= 90, or x is inf or nan
29 if (LIBC_UNLIKELY(x_u >= 0x42b4'0000U || x_u <= 0x3280'0000U)) {
30 // |x| <= 2^-26
31 if (x_u <= 0x3280'0000U) {
32 return 1.0f + x;
33 }
34
35 if (xbits.is_inf_or_nan())
36 return x + FPBits::inf().get_val();
37
38 int rounding = fputil::quick_get_round();
39 if (LIBC_UNLIKELY(rounding == FE_DOWNWARD || rounding == FE_TOWARDZERO))
40 return FPBits::max_normal().get_val();
41
42 fputil::set_errno_if_required(ERANGE);
43 fputil::raise_except_if_required(FE_OVERFLOW);
44
45 return x + FPBits::inf().get_val();
46 }
47
48 // TODO: We should be able to reduce the latency and reciprocal throughput
49 // further by using a low degree (maybe 3-7 ?) minimax polynomial for small
50 // but not too small inputs, such as |x| < 2^-2, or |x| < 2^-3.
51
52 // cosh(x) = (e^x + e^(-x)) / 2.
53 return static_cast<float>(exp_pm_eval</*is_sinh*/ false>(x));
54}
55
56} // namespace LIBC_NAMESPACE_DECL
57

source code of libc/src/math/generic/coshf.cpp