1 //===-- Single-precision e^x 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 "exp_utils.h"
10 #include "math_utils.h"
11 
12 #include "src/__support/common.h"
13 #include <math.h>
14 
15 #include <stdint.h>
16 
17 #define InvLn2N exp2f_data.invln2_scaled
18 #define T exp2f_data.tab
19 #define C exp2f_data.poly_scaled
20 #define SHIFT exp2f_data.shift
21 
22 namespace __llvm_libc {
23 
LLVM_LIBC_ENTRYPOINT(expf)24 float LLVM_LIBC_ENTRYPOINT(expf)(float x) {
25   uint32_t abstop;
26   uint64_t ki, t;
27   // double_t for better performance on targets with FLT_EVAL_METHOD == 2.
28   double_t kd, xd, z, r, r2, y, s;
29 
30   xd = static_cast<double_t>(x);
31   abstop = top12_bits(x) & 0x7ff;
32   if (unlikely(abstop >= top12_bits(88.0f))) {
33     // |x| >= 88 or x is nan.
34     if (as_uint32_bits(x) == as_uint32_bits(-INFINITY))
35       return 0.0f;
36     if (abstop >= top12_bits(INFINITY))
37       return x + x;
38     if (x > as_float(0x42b17217)) // x > log(0x1p128) ~= 88.72
39       return overflow<float>(0);
40     if (x < as_float(0xc2cff1b4)) // x < log(0x1p-150) ~= -103.97
41       return underflow<float>(0);
42     if (x < as_float(0xc2ce8ecf)) // x < log(0x1p-149) ~= -103.28
43       return may_underflow<float>(0);
44   }
45 
46   // x*N/Ln2 = k + r with r in [-1/2, 1/2] and int k.
47   z = InvLn2N * xd;
48 
49   // Round and convert z to int, the result is in [-150*N, 128*N] and
50   // ideally nearest int is used, otherwise the magnitude of r can be
51   // bigger which gives larger approximation error.
52   kd = static_cast<double>(z + SHIFT);
53   ki = as_uint64_bits(kd);
54   kd -= SHIFT;
55   r = z - kd;
56 
57   // exp(x) = 2^(k/N) * 2^(r/N) ~= s *(C0*r^3 + C1*r^2 + C2*r + 1)
58   t = T[ki % N];
59   t += ki << (52 - EXP2F_TABLE_BITS);
60   s = as_double(t);
61   z = C[0] * r + C[1];
62   r2 = r * r;
63   y = C[2] * r + 1;
64   y = z * r2 + y;
65   y = y * s;
66   return static_cast<float>(y);
67 }
68 
69 } // namespace __llvm_libc
70