1 //===-- Single-precision 2^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 "src/math/exp2f.h"
10 #include "exp_utils.h"
11 #include "math_utils.h"
12 
13 #include "src/__support/common.h"
14 #include <math.h>
15 
16 #include <stdint.h>
17 
18 #define T exp2f_data.tab
19 #define C exp2f_data.poly
20 #define SHIFT exp2f_data.shift_scaled
21 
22 namespace __llvm_libc {
23 
24 LLVM_LIBC_FUNCTION(float, exp2f, (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(128.0f))) {
33     // |x| >= 128 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 > 0.0f)
39       return overflow<float>(0);
40     if (x <= -150.0f)
41       return underflow<float>(0);
42     if (x < -149.0f)
43       return may_underflow<float>(0);
44   }
45 
46   // x = k/N + r with r in [-1/(2N), 1/(2N)] and int k.
47   kd = static_cast<double>(xd + SHIFT);
48   ki = as_uint64_bits(kd);
49   kd -= SHIFT; // k/N for int k.
50   r = xd - kd;
51 
52   // exp2(x) = 2^(k/N) * 2^r ~= s * (C0*r^3 + C1*r^2 + C2*r + 1)
53   t = T[ki % N];
54   t += ki << (52 - EXP2F_TABLE_BITS);
55   s = as_double(t);
56   z = C[0] * r + C[1];
57   r2 = r * r;
58   y = C[2] * r + 1;
59   y = z * r2 + y;
60   y = y * s;
61   return static_cast<float>(y);
62 }
63 
64 } // namespace __llvm_libc
65