1//===-- Implementation header for exp ---------------------------*- C++ -*-===//
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#ifndef LLVM_LIBC_SRC___SUPPORT_MATH_EXP_H
10#define LLVM_LIBC_SRC___SUPPORT_MATH_EXP_H
11
12#include "exp_constants.h"
13#include "exp_utils.h"
14#include "src/__support/CPP/bit.h"
15#include "src/__support/CPP/optional.h"
16#include "src/__support/FPUtil/FEnvImpl.h"
17#include "src/__support/FPUtil/FPBits.h"
18#include "src/__support/FPUtil/PolyEval.h"
19#include "src/__support/FPUtil/double_double.h"
20#include "src/__support/FPUtil/dyadic_float.h"
21#include "src/__support/FPUtil/multiply_add.h"
22#include "src/__support/FPUtil/nearest_integer.h"
23#include "src/__support/FPUtil/rounding_mode.h"
24#include "src/__support/FPUtil/triple_double.h"
25#include "src/__support/common.h"
26#include "src/__support/integer_literals.h"
27#include "src/__support/macros/config.h"
28#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
29
30namespace LIBC_NAMESPACE_DECL {
31
32namespace math {
33
34namespace exp_internal {
35
36using fputil::DoubleDouble;
37using fputil::TripleDouble;
38using DFloat128 = typename fputil::DyadicFloat<128>;
39
40using LIBC_NAMESPACE::operator""_u128;
41
42// log2(e)
43LIBC_INLINE_VAR constexpr double LOG2_E = 0x1.71547652b82fep+0;
44
45// Error bounds:
46// Errors when using double precision.
47LIBC_INLINE_VAR constexpr double EXP_ERR_D = 0x1.8p-63;
48
49#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
50// Errors when using double-double precision.
51LIBC_INLINE_VAR constexpr double EXP_ERR_DD = 0x1.0p-99;
52#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
53
54// -2^-12 * log(2)
55// > a = -2^-12 * log(2);
56// > b = round(a, 30, RN);
57// > c = round(a - b, 30, RN);
58// > d = round(a - b - c, D, RN);
59// Errors < 1.5 * 2^-133
60LIBC_INLINE_VAR constexpr double MLOG_2_EXP2_M12_HI = -0x1.62e42ffp-13;
61LIBC_INLINE_VAR constexpr double MLOG_2_EXP2_M12_MID = 0x1.718432a1b0e26p-47;
62
63#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
64LIBC_INLINE_VAR constexpr double MLOG_2_EXP2_M12_MID_30 = 0x1.718432ap-47;
65LIBC_INLINE_VAR constexpr double MLOG_2_EXP2_M12_LO = 0x1.b0e2633fe0685p-79;
66#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
67
68// Polynomial approximations with double precision:
69// Return expm1(dx) / x ~ 1 + dx / 2 + dx^2 / 6 + dx^3 / 24.
70// For |dx| < 2^-13 + 2^-30:
71// | output - expm1(dx) / dx | < 2^-51.
72LIBC_INLINE double poly_approx_d(double dx) {
73 // dx^2
74 double dx2 = dx * dx;
75 // c0 = 1 + dx / 2
76 double c0 = fputil::multiply_add(x: dx, y: 0.5, z: 1.0);
77 // c1 = 1/6 + dx / 24
78 double c1 =
79 fputil::multiply_add(x: dx, y: 0x1.5555555555555p-5, z: 0x1.5555555555555p-3);
80 // p = dx^2 * c1 + c0 = 1 + dx / 2 + dx^2 / 6 + dx^3 / 24
81 double p = fputil::multiply_add(x: dx2, y: c1, z: c0);
82 return p;
83}
84
85#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
86// Polynomial approximation with double-double precision:
87// Return exp(dx) ~ 1 + dx + dx^2 / 2 + ... + dx^6 / 720
88// For |dx| < 2^-13 + 2^-30:
89// | output - exp(dx) | < 2^-101
90LIBC_INLINE DoubleDouble poly_approx_dd(const DoubleDouble &dx) {
91 // Taylor polynomial.
92 constexpr DoubleDouble COEFFS[] = {
93 {.lo: 0, .hi: 0x1p0}, // 1
94 {.lo: 0, .hi: 0x1p0}, // 1
95 {.lo: 0, .hi: 0x1p-1}, // 1/2
96 {.lo: 0x1.5555555555555p-57, .hi: 0x1.5555555555555p-3}, // 1/6
97 {.lo: 0x1.5555555555555p-59, .hi: 0x1.5555555555555p-5}, // 1/24
98 {.lo: 0x1.1111111111111p-63, .hi: 0x1.1111111111111p-7}, // 1/120
99 {.lo: -0x1.f49f49f49f49fp-65, .hi: 0x1.6c16c16c16c17p-10}, // 1/720
100 };
101
102 DoubleDouble p = fputil::polyeval(x: dx, a0: COEFFS[0], a: COEFFS[1], a: COEFFS[2],
103 a: COEFFS[3], a: COEFFS[4], a: COEFFS[5], a: COEFFS[6]);
104 return p;
105}
106
107// Polynomial approximation with 128-bit precision:
108// Return exp(dx) ~ 1 + dx + dx^2 / 2 + ... + dx^7 / 5040
109// For |dx| < 2^-13 + 2^-30:
110// | output - exp(dx) | < 2^-126.
111LIBC_INLINE DFloat128 poly_approx_f128(const DFloat128 &dx) {
112 constexpr DFloat128 COEFFS_128[]{
113 {Sign::POS, -127, 0x80000000'00000000'00000000'00000000_u128}, // 1.0
114 {Sign::POS, -127, 0x80000000'00000000'00000000'00000000_u128}, // 1.0
115 {Sign::POS, -128, 0x80000000'00000000'00000000'00000000_u128}, // 0.5
116 {Sign::POS, -130, 0xaaaaaaaa'aaaaaaaa'aaaaaaaa'aaaaaaab_u128}, // 1/6
117 {Sign::POS, -132, 0xaaaaaaaa'aaaaaaaa'aaaaaaaa'aaaaaaab_u128}, // 1/24
118 {Sign::POS, -134, 0x88888888'88888888'88888888'88888889_u128}, // 1/120
119 {Sign::POS, -137, 0xb60b60b6'0b60b60b'60b60b60'b60b60b6_u128}, // 1/720
120 {Sign::POS, -140, 0xd00d00d0'0d00d00d'00d00d00'd00d00d0_u128}, // 1/5040
121 };
122
123 DFloat128 p = fputil::polyeval(x: dx, a0: COEFFS_128[0], a: COEFFS_128[1],
124 a: COEFFS_128[2], a: COEFFS_128[3], a: COEFFS_128[4],
125 a: COEFFS_128[5], a: COEFFS_128[6], a: COEFFS_128[7]);
126 return p;
127}
128
129// Compute exp(x) using 128-bit precision.
130// TODO(lntue): investigate triple-double precision implementation for this
131// step.
132LIBC_INLINE DFloat128 exp_f128(double x, double kd, int idx1, int idx2) {
133 // Recalculate dx:
134
135 double t1 = fputil::multiply_add(x: kd, y: MLOG_2_EXP2_M12_HI, z: x); // exact
136 double t2 = kd * MLOG_2_EXP2_M12_MID_30; // exact
137 double t3 = kd * MLOG_2_EXP2_M12_LO; // Error < 2^-133
138
139 DFloat128 dx = fputil::quick_add(
140 a: DFloat128(t1), b: fputil::quick_add(a: DFloat128(t2), b: DFloat128(t3)));
141
142 // TODO: Skip recalculating exp_mid1 and exp_mid2.
143 DFloat128 exp_mid1 =
144 fputil::quick_add(a: DFloat128(EXP2_MID1[idx1].hi),
145 b: fputil::quick_add(a: DFloat128(EXP2_MID1[idx1].mid),
146 b: DFloat128(EXP2_MID1[idx1].lo)));
147
148 DFloat128 exp_mid2 =
149 fputil::quick_add(a: DFloat128(EXP2_MID2[idx2].hi),
150 b: fputil::quick_add(a: DFloat128(EXP2_MID2[idx2].mid),
151 b: DFloat128(EXP2_MID2[idx2].lo)));
152
153 DFloat128 exp_mid = fputil::quick_mul(a: exp_mid1, b: exp_mid2);
154
155 DFloat128 p = poly_approx_f128(dx);
156
157 DFloat128 r = fputil::quick_mul(a: exp_mid, b: p);
158
159 r.exponent += static_cast<int>(kd) >> 12;
160
161 return r;
162}
163
164// Compute exp(x) with double-double precision.
165LIBC_INLINE DoubleDouble exp_double_double(double x, double kd,
166 const DoubleDouble &exp_mid) {
167 // Recalculate dx:
168 // dx = x - k * 2^-12 * log(2)
169 double t1 = fputil::multiply_add(x: kd, y: MLOG_2_EXP2_M12_HI, z: x); // exact
170 double t2 = kd * MLOG_2_EXP2_M12_MID_30; // exact
171 double t3 = kd * MLOG_2_EXP2_M12_LO; // Error < 2^-130
172
173 DoubleDouble dx = fputil::exact_add(a: t1, b: t2);
174 dx.lo += t3;
175
176 // Degree-6 Taylor polynomial approximation in double-double precision.
177 // | p - exp(x) | < 2^-100.
178 DoubleDouble p = poly_approx_dd(dx);
179
180 // Error bounds: 2^-99.
181 DoubleDouble r = fputil::quick_mult(a: exp_mid, b: p);
182
183 return r;
184}
185#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
186
187// Check for exceptional cases when
188// |x| <= 2^-53 or x < log(2^-1075) or x >= 0x1.6232bdd7abcd3p+9
189LIBC_INLINE double set_exceptional(double x) {
190 using FPBits = typename fputil::FPBits<double>;
191 FPBits xbits(x);
192
193 uint64_t x_u = xbits.uintval();
194 uint64_t x_abs = xbits.abs().uintval();
195
196 // |x| <= 2^-53
197 if (x_abs <= 0x3ca0'0000'0000'0000ULL) {
198 // exp(x) ~ 1 + x
199 return 1 + x;
200 }
201
202 // x <= log(2^-1075) || x >= 0x1.6232bdd7abcd3p+9 or inf/nan.
203
204 // x <= log(2^-1075) or -inf/nan
205 if (x_u >= 0xc087'4910'd52d'3052ULL) {
206 // exp(-Inf) = 0
207 if (xbits.is_inf())
208 return 0.0;
209
210 // exp(nan) = nan
211 if (xbits.is_nan())
212 return x;
213
214#ifndef LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY
215 if (fputil::quick_get_round() == FE_UPWARD)
216 return FPBits::min_subnormal().get_val();
217#endif
218 fputil::set_errno_if_required(ERANGE);
219 fputil::raise_except_if_required(FE_UNDERFLOW);
220 return 0.0;
221 }
222
223 // x >= round(log(MAX_NORMAL), D, RU) = 0x1.62e42fefa39fp+9 or +inf/nan
224 // x is finite
225 if (x_u < 0x7ff0'0000'0000'0000ULL) {
226#ifndef LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY
227 int rounding = fputil::quick_get_round();
228 if (rounding == FE_DOWNWARD || rounding == FE_TOWARDZERO)
229 return FPBits::max_normal().get_val();
230#endif
231
232 fputil::set_errno_if_required(ERANGE);
233 fputil::raise_except_if_required(FE_OVERFLOW);
234 }
235 // x is +inf or nan
236 return x + FPBits::inf().get_val();
237}
238
239} // namespace exp_internal
240
241LIBC_INLINE double exp(double x) {
242 using namespace exp_internal;
243 using FPBits = typename fputil::FPBits<double>;
244 FPBits xbits(x);
245
246 uint64_t x_u = xbits.uintval();
247
248 // Upper bound: max normal number = 2^1023 * (2 - 2^-52)
249 // > round(log (2^1023 ( 2 - 2^-52 )), D, RU) = 0x1.62e42fefa39fp+9
250 // > round(log (2^1023 ( 2 - 2^-52 )), D, RD) = 0x1.62e42fefa39efp+9
251 // > round(log (2^1023 ( 2 - 2^-52 )), D, RN) = 0x1.62e42fefa39efp+9
252 // > round(exp(0x1.62e42fefa39fp+9), D, RN) = infty
253
254 // Lower bound: min denormal number / 2 = 2^-1075
255 // > round(log(2^-1075), D, RN) = -0x1.74910d52d3052p9
256
257 // Another lower bound: min normal number = 2^-1022
258 // > round(log(2^-1022), D, RN) = -0x1.6232bdd7abcd2p9
259
260 // x < log(2^-1075) or x >= 0x1.6232bdd7abcd3p+9 or |x| < 2^-53.
261 if (LIBC_UNLIKELY(x_u >= 0xc0874910d52d3052 ||
262 (x_u < 0xbca0000000000000 && x_u >= 0x40862e42fefa39f0) ||
263 x_u < 0x3ca0000000000000)) {
264 return set_exceptional(x);
265 }
266
267 // Now log(2^-1075) <= x <= -2^-53 or 2^-53 <= x < log(2^1023 * (2 - 2^-52))
268
269 // Range reduction:
270 // Let x = log(2) * (hi + mid1 + mid2) + lo
271 // in which:
272 // hi is an integer
273 // mid1 * 2^6 is an integer
274 // mid2 * 2^12 is an integer
275 // then:
276 // exp(x) = 2^hi * 2^(mid1) * 2^(mid2) * exp(lo).
277 // With this formula:
278 // - multiplying by 2^hi is exact and cheap, simply by adding the exponent
279 // field.
280 // - 2^(mid1) and 2^(mid2) are stored in 2 x 64-element tables.
281 // - exp(lo) ~ 1 + lo + a0 * lo^2 + ...
282 //
283 // They can be defined by:
284 // hi + mid1 + mid2 = 2^(-12) * round(2^12 * log_2(e) * x)
285 // If we store L2E = round(log2(e), D, RN), then:
286 // log2(e) - L2E ~ 1.5 * 2^(-56)
287 // So the errors when computing in double precision is:
288 // | x * 2^12 * log_2(e) - D(x * 2^12 * L2E) | <=
289 // <= | x * 2^12 * log_2(e) - x * 2^12 * L2E | +
290 // + | x * 2^12 * L2E - D(x * 2^12 * L2E) |
291 // <= 2^12 * ( |x| * 1.5 * 2^-56 + eps(x)) for RN
292 // 2^12 * ( |x| * 1.5 * 2^-56 + 2*eps(x)) for other rounding modes.
293 // So if:
294 // hi + mid1 + mid2 = 2^(-12) * round(x * 2^12 * L2E) is computed entirely
295 // in double precision, the reduced argument:
296 // lo = x - log(2) * (hi + mid1 + mid2) is bounded by:
297 // |lo| <= 2^-13 + (|x| * 1.5 * 2^-56 + 2*eps(x))
298 // < 2^-13 + (1.5 * 2^9 * 1.5 * 2^-56 + 2*2^(9 - 52))
299 // < 2^-13 + 2^-41
300 //
301
302 // The following trick computes the round(x * L2E) more efficiently
303 // than using the rounding instructions, with the tradeoff for less accuracy,
304 // and hence a slightly larger range for the reduced argument `lo`.
305 //
306 // To be precise, since |x| < |log(2^-1075)| < 1.5 * 2^9,
307 // |x * 2^12 * L2E| < 1.5 * 2^9 * 1.5 < 2^23,
308 // So we can fit the rounded result round(x * 2^12 * L2E) in int32_t.
309 // Thus, the goal is to be able to use an additional addition and fixed width
310 // shift to get an int32_t representing round(x * 2^12 * L2E).
311 //
312 // Assuming int32_t using 2-complement representation, since the mantissa part
313 // of a double precision is unsigned with the leading bit hidden, if we add an
314 // extra constant C = 2^e1 + 2^e2 with e1 > e2 >= 2^25 to the product, the
315 // part that are < 2^e2 in resulted mantissa of (x*2^12*L2E + C) can be
316 // considered as a proper 2-complement representations of x*2^12*L2E.
317 //
318 // One small problem with this approach is that the sum (x*2^12*L2E + C) in
319 // double precision is rounded to the least significant bit of the dorminant
320 // factor C. In order to minimize the rounding errors from this addition, we
321 // want to minimize e1. Another constraint that we want is that after
322 // shifting the mantissa so that the least significant bit of int32_t
323 // corresponds to the unit bit of (x*2^12*L2E), the sign is correct without
324 // any adjustment. So combining these 2 requirements, we can choose
325 // C = 2^33 + 2^32, so that the sign bit corresponds to 2^31 bit, and hence
326 // after right shifting the mantissa, the resulting int32_t has correct sign.
327 // With this choice of C, the number of mantissa bits we need to shift to the
328 // right is: 52 - 33 = 19.
329 //
330 // Moreover, since the integer right shifts are equivalent to rounding down,
331 // we can add an extra 0.5 so that it will become round-to-nearest, tie-to-
332 // +infinity. So in particular, we can compute:
333 // hmm = x * 2^12 * L2E + C,
334 // where C = 2^33 + 2^32 + 2^-1, then if
335 // k = int32_t(lower 51 bits of double(x * 2^12 * L2E + C) >> 19),
336 // the reduced argument:
337 // lo = x - log(2) * 2^-12 * k is bounded by:
338 // |lo| <= 2^-13 + 2^-41 + 2^-12*2^-19
339 // = 2^-13 + 2^-31 + 2^-41.
340 //
341 // Finally, notice that k only uses the mantissa of x * 2^12 * L2E, so the
342 // exponent 2^12 is not needed. So we can simply define
343 // C = 2^(33 - 12) + 2^(32 - 12) + 2^(-13 - 12), and
344 // k = int32_t(lower 51 bits of double(x * L2E + C) >> 19).
345
346 // Rounding errors <= 2^-31 + 2^-41.
347 double tmp = fputil::multiply_add(x, y: LOG2_E, z: 0x1.8000'0000'4p21);
348 int k = static_cast<int>(cpp::bit_cast<uint64_t>(from: tmp) >> 19);
349 double kd = static_cast<double>(k);
350
351 uint32_t idx1 = (k >> 6) & 0x3f;
352 uint32_t idx2 = k & 0x3f;
353 int hi = k >> 12;
354
355 bool denorm = (hi <= -1022);
356
357 DoubleDouble exp_mid1{.lo: EXP2_MID1[idx1].mid, .hi: EXP2_MID1[idx1].hi};
358 DoubleDouble exp_mid2{.lo: EXP2_MID2[idx2].mid, .hi: EXP2_MID2[idx2].hi};
359
360 DoubleDouble exp_mid = fputil::quick_mult(a: exp_mid1, b: exp_mid2);
361
362 // |x - (hi + mid1 + mid2) * log(2) - dx| < 2^11 * eps(M_LOG_2_EXP2_M12.lo)
363 // = 2^11 * 2^-13 * 2^-52
364 // = 2^-54.
365 // |dx| < 2^-13 + 2^-30.
366 double lo_h = fputil::multiply_add(x: kd, y: MLOG_2_EXP2_M12_HI, z: x); // exact
367 double dx = fputil::multiply_add(x: kd, y: MLOG_2_EXP2_M12_MID, z: lo_h);
368
369 // We use the degree-4 Taylor polynomial to approximate exp(lo):
370 // exp(lo) ~ 1 + lo + lo^2 / 2 + lo^3 / 6 + lo^4 / 24 = 1 + lo * P(lo)
371 // So that the errors are bounded by:
372 // |P(lo) - expm1(lo)/lo| < |lo|^4 / 64 < 2^(-13 * 4) / 64 = 2^-58
373 // Let P_ be an evaluation of P where all intermediate computations are in
374 // double precision. Using either Horner's or Estrin's schemes, the evaluated
375 // errors can be bounded by:
376 // |P_(dx) - P(dx)| < 2^-51
377 // => |dx * P_(dx) - expm1(lo) | < 1.5 * 2^-64
378 // => 2^(mid1 + mid2) * |dx * P_(dx) - expm1(lo)| < 1.5 * 2^-63.
379 // Since we approximate
380 // 2^(mid1 + mid2) ~ exp_mid.hi + exp_mid.lo,
381 // We use the expression:
382 // (exp_mid.hi + exp_mid.lo) * (1 + dx * P_(dx)) ~
383 // ~ exp_mid.hi + (exp_mid.hi * dx * P_(dx) + exp_mid.lo)
384 // with errors bounded by 1.5 * 2^-63.
385
386 double mid_lo = dx * exp_mid.hi;
387
388 // Approximate expm1(dx)/dx ~ 1 + dx / 2 + dx^2 / 6 + dx^3 / 24.
389 double p = poly_approx_d(dx);
390
391 double lo = fputil::multiply_add(x: p, y: mid_lo, z: exp_mid.lo);
392
393#ifdef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
394 if (LIBC_UNLIKELY(denorm)) {
395 return ziv_test_denorm</*SKIP_ZIV_TEST=*/true>(hi, exp_mid.hi, lo,
396 EXP_ERR_D)
397 .value();
398 } else {
399 // to multiply by 2^hi, a fast way is to simply add hi to the exponent
400 // field.
401 int64_t exp_hi = static_cast<int64_t>(hi) * (1LL << FPBits::FRACTION_LEN);
402 double r =
403 cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(exp_mid.hi + lo));
404 return r;
405 }
406#else
407 if (LIBC_UNLIKELY(denorm)) {
408 if (auto r = ziv_test_denorm(hi, mid: exp_mid.hi, lo, err: EXP_ERR_D);
409 LIBC_LIKELY(r.has_value()))
410 return r.value();
411 } else {
412 double upper = exp_mid.hi + (lo + EXP_ERR_D);
413 double lower = exp_mid.hi + (lo - EXP_ERR_D);
414
415 if (LIBC_LIKELY(upper == lower)) {
416 // to multiply by 2^hi, a fast way is to simply add hi to the exponent
417 // field.
418 int64_t exp_hi = static_cast<int64_t>(hi) * (1LL << FPBits::FRACTION_LEN);
419 double r = cpp::bit_cast<double>(from: exp_hi + cpp::bit_cast<int64_t>(from: upper));
420 return r;
421 }
422 }
423
424 // Use double-double
425 DoubleDouble r_dd = exp_double_double(x, kd, exp_mid);
426
427 if (LIBC_UNLIKELY(denorm)) {
428 if (auto r = ziv_test_denorm(hi, mid: r_dd.hi, lo: r_dd.lo, err: EXP_ERR_DD);
429 LIBC_LIKELY(r.has_value()))
430 return r.value();
431 } else {
432 double upper_dd = r_dd.hi + (r_dd.lo + EXP_ERR_DD);
433 double lower_dd = r_dd.hi + (r_dd.lo - EXP_ERR_DD);
434
435 if (LIBC_LIKELY(upper_dd == lower_dd)) {
436 int64_t exp_hi = static_cast<int64_t>(hi) * (1LL << FPBits::FRACTION_LEN);
437 double r =
438 cpp::bit_cast<double>(from: exp_hi + cpp::bit_cast<int64_t>(from: upper_dd));
439 return r;
440 }
441 }
442
443 // Use 128-bit precision
444 DFloat128 r_f128 = exp_f128(x, kd, idx1, idx2);
445
446 return static_cast<double>(r_f128);
447#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
448}
449
450} // namespace math
451
452} // namespace LIBC_NAMESPACE_DECL
453
454#endif // LLVM_LIBC_SRC___SUPPORT_MATH_EXP_H
455