Skip to content

Commit f698dee

Browse files
lntuesibidanov
andcommitted
[libc][math] Improve the performance of sqrtf128.
Use a combination of polynomial approximation and Newton-Raphson iterations in 64-bit and 128-bit integers to improve the performance of sqrtf128. The correct rounding is provided by squaring the result and comparing it with the argument. Co-authored-by: Alexei Sibidanov <[email protected]>
1 parent 2d5f07c commit f698dee

17 files changed

+568
-39
lines changed

libc/src/__support/big_int.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,7 @@ LIBC_INLINE constexpr void quick_mul_hi(cpp::array<word, N> &dst,
241241
}
242242

243243
template <typename word, size_t N>
244-
LIBC_INLINE constexpr bool is_negative(cpp::array<word, N> &array) {
244+
LIBC_INLINE constexpr bool is_negative(const cpp::array<word, N> &array) {
245245
using signed_word = cpp::make_signed_t<word>;
246246
return cpp::bit_cast<signed_word>(array.back()) < 0;
247247
}

libc/src/math/generic/CMakeLists.txt

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3379,8 +3379,12 @@ add_entrypoint_object(
33793379
HDRS
33803380
../sqrtf128.h
33813381
DEPENDS
3382+
libc.src.__support.CPP.bit
3383+
libc.src.__support.FPUtil.fenv_impl
3384+
libc.src.__support.FPUtil.fp_bits
3385+
libc.src.__support.FPUtil.rounding_mode
3386+
libc.src.__support.macros.optimization
33823387
libc.src.__support.macros.properties.types
3383-
libc.src.__support.FPUtil.sqrt
33843388
COMPILE_OPTIONS
33853389
${libc_opt_high_flag}
33863390
)

libc/src/math/generic/sqrtf128.cpp

Lines changed: 338 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,355 @@
11
//===-- Implementation of sqrtf128 function -------------------------------===//
22
//
3+
// Copyright (c) 2024 Alexei Sibidanov <[email protected]>
4+
//
35
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
46
// See https://llvm.org/LICENSE.txt for license information.
57
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
68
//
79
//===----------------------------------------------------------------------===//
810

911
#include "src/math/sqrtf128.h"
10-
#include "src/__support/FPUtil/sqrt.h"
12+
#include "src/__support/CPP/bit.h"
13+
#include "src/__support/FPUtil/FEnvImpl.h"
14+
#include "src/__support/FPUtil/FPBits.h"
15+
#include "src/__support/FPUtil/rounding_mode.h"
1116
#include "src/__support/common.h"
12-
#include "src/__support/macros/config.h"
17+
#include "src/__support/macros/optimization.h"
18+
#include "src/__support/uint128.h"
1319

1420
namespace LIBC_NAMESPACE_DECL {
1521

22+
using FPBits = fputil::FPBits<float128>;
23+
24+
namespace {
25+
26+
template <typename T, typename U = T> static inline constexpr T prod_hi(T, U);
27+
28+
// Get high part of integer multiplications.
29+
// Use template to prevent implicit conversion.
30+
template <>
31+
inline constexpr uint64_t prod_hi<uint64_t>(uint64_t x, uint64_t y) {
32+
return static_cast<uint64_t>(
33+
(static_cast<UInt128>(x) * static_cast<UInt128>(y)) >> 64);
34+
}
35+
36+
// Get high part of unsigned 128x64 bit multiplication.
37+
template <>
38+
inline constexpr UInt128 prod_hi<UInt128, uint64_t>(UInt128 y, uint64_t x) {
39+
uint64_t y_lo = static_cast<uint64_t>(y);
40+
uint64_t y_hi = static_cast<uint64_t>(y >> 64);
41+
UInt128 xyl = static_cast<UInt128>(x) * static_cast<UInt128>(y_lo);
42+
UInt128 xyh = static_cast<UInt128>(x) * static_cast<UInt128>(y_hi);
43+
return xyh + (xyl >> 64);
44+
}
45+
46+
// Get high part of signed 64x64 bit multiplication.
47+
template <> inline constexpr int64_t prod_hi<int64_t>(int64_t x, int64_t y) {
48+
return static_cast<int64_t>(
49+
(static_cast<Int128>(x) * static_cast<Int128>(y)) >> 64);
50+
}
51+
52+
// Get high 128-bit part of unsigned 128x128 bit multiplication.
53+
template <> inline constexpr UInt128 prod_hi<UInt128>(UInt128 x, UInt128 y) {
54+
uint64_t x_lo = static_cast<uint64_t>(x);
55+
uint64_t x_hi = static_cast<uint64_t>(x >> 64);
56+
uint64_t y_lo = static_cast<uint64_t>(y);
57+
uint64_t y_hi = static_cast<uint64_t>(y >> 64);
58+
59+
UInt128 xh_yh = static_cast<UInt128>(x_hi) * static_cast<UInt128>(y_hi);
60+
UInt128 xh_yl = static_cast<UInt128>(x_hi) * static_cast<UInt128>(y_lo);
61+
UInt128 xl_yh = static_cast<UInt128>(x_lo) * static_cast<UInt128>(y_hi);
62+
63+
xh_yh += xh_yl >> 64;
64+
65+
return xh_yh + (xl_yh >> 64);
66+
}
67+
68+
// Get high 128-bit part of mixed sign 128x128 bit multiplication.
69+
template <>
70+
inline constexpr Int128 prod_hi<Int128, UInt128>(Int128 x, UInt128 y) {
71+
UInt128 mask = static_cast<UInt128>(x >> 127);
72+
UInt128 negative_part = y & mask;
73+
UInt128 prod = prod_hi(static_cast<UInt128>(x), y);
74+
return static_cast<Int128>(prod - negative_part);
75+
}
76+
77+
constexpr uint32_t RSQRT_COEFFS[64][4] = {
78+
{0xffffffff, 0xfffff780, 0xbff55815, 0x9bb5b6e7},
79+
{0xfc0bd889, 0xfa1d6e7d, 0xb8a95a89, 0x938bf8f0},
80+
{0xf82ec882, 0xf473bea9, 0xb1bf4705, 0x8bed0079},
81+
{0xf467f280, 0xeefff2a1, 0xab309d4a, 0x84cdb431},
82+
{0xf0b6848c, 0xe9bf46f4, 0xa4f76232, 0x7e24037b},
83+
{0xed19b75e, 0xe4af2628, 0x9f0e1340, 0x77e6ca62},
84+
{0xe990cdad, 0xdfcd2521, 0x996f9b96, 0x720db8df},
85+
{0xe61b138e, 0xdb16ffde, 0x94174a00, 0x6c913cff},
86+
{0xe2b7dddf, 0xd68a967b, 0x8f00c812, 0x676a6f92},
87+
{0xdf6689b7, 0xd225ea80, 0x8a281226, 0x62930308},
88+
{0xdc267bea, 0xcde71c63, 0x8589702c, 0x5e05343e},
89+
{0xd8f7208e, 0xc9cc6948, 0x81216f2e, 0x59bbbcf8},
90+
{0xd5d7ea91, 0xc5d428ee, 0x7cecdb76, 0x55b1c7d6},
91+
{0xd2c8534e, 0xc1fccbc9, 0x78e8bb45, 0x51e2e592},
92+
{0xcfc7da32, 0xbe44d94a, 0x75124a0a, 0x4e4b0369},
93+
{0xccd6045f, 0xbaaaee41, 0x7166f40f, 0x4ae66284},
94+
{0xc9f25c5c, 0xb72dbb69, 0x6de45288, 0x47b19045},
95+
{0xc71c71c7, 0xb3cc040f, 0x6a882804, 0x44a95f5f},
96+
{0xc453d90f, 0xb0849cd4, 0x67505d2a, 0x41cae1a0},
97+
{0xc1982b2e, 0xad566a85, 0x643afdc8, 0x3f13625c},
98+
{0xbee9056f, 0xaa406113, 0x6146361f, 0x3c806169},
99+
{0xbc46092e, 0xa7418293, 0x5e70506d, 0x3a0f8e8e},
100+
{0xb9aedba5, 0xa458de58, 0x5bb7b2b1, 0x37bec572},
101+
{0xb72325b7, 0xa1859022, 0x591adc9a, 0x358c09e2},
102+
{0xb4a293c2, 0x9ec6bf52, 0x569865a7, 0x33758476},
103+
{0xb22cd56d, 0x9c1b9e36, 0x542efb6a, 0x31797f8a},
104+
{0xafc19d86, 0x9983695c, 0x51dd5ffb, 0x2f96647a},
105+
{0xad60a1d1, 0x96fd66f7, 0x4fa2687c, 0x2dcab91f},
106+
{0xab099ae9, 0x9488e64b, 0x4d7cfbc9, 0x2c151d8a},
107+
{0xa8bc441a, 0x92253f20, 0x4b6c1139, 0x2a7449ef},
108+
{0xa6785b42, 0x8fd1d14a, 0x496eaf82, 0x28e70cc3},
109+
{0xa43da0ae, 0x8d8e042a, 0x4783eba7, 0x276c4900},
110+
{0xa20bd701, 0x8b594648, 0x45aae80a, 0x2602f493},
111+
{0x9fe2c315, 0x89330ce4, 0x43e2d382, 0x24aa16ec},
112+
{0x9dc22be4, 0x871ad399, 0x422ae88c, 0x2360c7af},
113+
{0x9ba9da6c, 0x85101c05, 0x40826c88, 0x22262d7b},
114+
{0x99999999, 0x83126d70, 0x3ee8af07, 0x20f97cd2},
115+
{0x97913630, 0x81215480, 0x3d5d0922, 0x1fd9f714},
116+
{0x95907eb8, 0x7f3c62ef, 0x3bdedce0, 0x1ec6e994},
117+
{0x93974369, 0x7d632f45, 0x3a6d94a9, 0x1dbfacbb},
118+
{0x91a55615, 0x7b955498, 0x3908a2be, 0x1cc3a33b},
119+
{0x8fba8a1c, 0x79d2724e, 0x37af80bf, 0x1bd23960},
120+
{0x8dd6b456, 0x781a2be4, 0x3661af39, 0x1aeae458},
121+
{0x8bf9ab07, 0x766c28ba, 0x351eb539, 0x1a0d21a2},
122+
{0x8a2345cc, 0x74c813dd, 0x33e61feb, 0x19387676},
123+
{0x88535d90, 0x732d9bdc, 0x32b7823a, 0x186c6f3e},
124+
{0x8689cc7e, 0x719c7297, 0x3192747d, 0x17a89f21},
125+
{0x84c66df1, 0x70144d19, 0x30769424, 0x16ec9f89},
126+
{0x83091e6a, 0x6e94e36c, 0x2f63836f, 0x16380fbf},
127+
{0x8151bb87, 0x6d1df079, 0x2e58e925, 0x158a9484},
128+
{0x7fa023f1, 0x6baf31de, 0x2d567053, 0x14e3d7ba},
129+
{0x7df43758, 0x6a4867d3, 0x2c5bc811, 0x1443880e},
130+
{0x7c4dd664, 0x68e95508, 0x2b68a346, 0x13a958ab},
131+
{0x7aace2b0, 0x6791be86, 0x2a7cb871, 0x131500ee},
132+
{0x79113ebc, 0x66416b95, 0x2997c17a, 0x12863c29},
133+
{0x777acde8, 0x64f825a1, 0x28b97b82, 0x11fcc95c},
134+
{0x75e9746a, 0x63b5b822, 0x27e1a6b4, 0x11786b03},
135+
{0x745d1746, 0x6279f081, 0x2710061d, 0x10f8e6da},
136+
{0x72d59c46, 0x61449e06, 0x26445f86, 0x107e05ac},
137+
{0x7152e9f4, 0x601591be, 0x257e7b4d, 0x10079327},
138+
{0x6fd4e793, 0x5eec9e6b, 0x24be2445, 0x0f955da9},
139+
{0x6e5b7d16, 0x5dc9986e, 0x24032795, 0x0f273620},
140+
{0x6ce6931d, 0x5cac55b7, 0x234d5496, 0x0ebcefdb},
141+
{0x6b7612ec, 0x5b94adb2, 0x229c7cbc, 0x0e56606e},
142+
};
143+
144+
// Approximate rsqrt with cubic polynomials.
145+
// The range [1,2] is splitted into 64 equal sub-ranges and the reciprocal
146+
// square root is approximated by a cubic polynomial by the minimax method in
147+
// each subrange. The approximation accuracy fits into 32-33 bits and thus it is
148+
// natural to round coefficients into 32 bit. The constant coefficient can be
149+
// rounded to 33 bits since the most significant bit is always 1 and implicitly
150+
// assumed in the table.
151+
LIBC_INLINE uint64_t rsqrt_approx(uint64_t m) {
152+
// ULP(m) = 2^-64.
153+
// Use the top 6 bits as index for looking up polynomial coeffs.
154+
uint64_t indx = m >> 58;
155+
156+
uint64_t c0 = static_cast<uint64_t>(RSQRT_COEFFS[indx][0]);
157+
c0 <<= 31; // to 64 bit with the space for the implicit bit
158+
c0 |= 1ull << 63; // add implicit bit
159+
160+
uint64_t c1 = static_cast<uint64_t>(RSQRT_COEFFS[indx][1]);
161+
c1 <<= 25; // to 64 bit format
162+
163+
uint64_t c2 = static_cast<uint64_t>(RSQRT_COEFFS[indx][2]);
164+
uint64_t c3 = static_cast<uint64_t>(RSQRT_COEFFS[indx][3]);
165+
166+
uint64_t d = (m << 6) >> 32; // local coordinate in the subrange [0, 2^32]
167+
uint64_t d2 = (d * d) >> 32; // square of the local coordinate
168+
uint64_t re = c0 + (d2 * c2 >> 13); // even part of the polynomial (positive)
169+
uint64_t ro = d * ((c1 + ((d2 * c3) >> 19)) >> 26) >>
170+
6; // odd part of the polynomial (negative)
171+
uint64_t r = re - ro; // maximal error < 1.55e-10 and it is less than 2^-32
172+
173+
// Newton-Raphson first order step to improve accuracy of the result to almost
174+
// 64 bits:
175+
// For the initial approximation r0 ~ 1/sqrt(x), let
176+
// h = r0^2 * x - 1
177+
// be its scaled error. Then the first-order Newton-Raphson iteration is:
178+
// r1 = r0 - r0 * h / 2
179+
// which has error bounded by:
180+
// |r1 - 1/sqrt(x)| < h^2 / 2.
181+
uint64_t r2 = prod_hi<uint64_t>(r, r);
182+
// h = r0^2*x - 1.
183+
int64_t h = static_cast<int64_t>(prod_hi<uint64_t>(m, r2) + r2);
184+
// hr = r * h / 2
185+
int64_t hr = prod_hi<int64_t>(h, static_cast<int64_t>(r >> 1));
186+
r -= hr;
187+
// Adjust in the unlucky case x~1;
188+
if (LIBC_UNLIKELY(!r))
189+
--r;
190+
return r;
191+
}
192+
193+
} // anonymous namespace
194+
16195
LLVM_LIBC_FUNCTION(float128, sqrtf128, (float128 x)) {
17-
return fputil::sqrt<float128>(x);
196+
using FPBits = fputil::FPBits<float128>;
197+
// Get rounding mode.
198+
uint32_t rm = fputil::get_round();
199+
200+
FPBits xbits(x);
201+
UInt128 x_u = xbits.uintval();
202+
// Bring leading bit of the mantissa to the highest bit.
203+
// ulp(x_frac) = 2^-128.
204+
UInt128 x_frac = xbits.get_mantissa() << (FPBits::EXP_LEN + 1);
205+
206+
int sign_exp = static_cast<int>(x_u >> FPBits::FRACTION_LEN);
207+
208+
if (LIBC_UNLIKELY(sign_exp == 0 || sign_exp >= 0x7fff)) {
209+
// Special cases: NAN, inf, negative numbers
210+
if (sign_exp >= 0x7fff) {
211+
// x = -0 or x = inf
212+
if (xbits.is_zero() || xbits == xbits.inf())
213+
return x;
214+
// x is nan
215+
if (xbits.is_nan()) {
216+
// pass through quiet nan
217+
if (xbits.is_quiet_nan())
218+
return x;
219+
// transform signaling nan to quiet and return
220+
return xbits.quiet_nan().get_val();
221+
}
222+
// x < 0 or x = -inf
223+
fputil::set_errno_if_required(EDOM);
224+
fputil::raise_except_if_required(FE_INVALID);
225+
return xbits.quiet_nan().get_val();
226+
}
227+
// x is subnormal or x=+0
228+
if (x == 0)
229+
return x;
230+
231+
// Normalize subnormal inputs.
232+
sign_exp = -cpp::countl_zero(x_frac);
233+
int normal_shifts = 1 - sign_exp;
234+
x_frac <<= normal_shifts;
235+
}
236+
237+
// For sign_exp = biased exponent of x = real_exponent + 16383,
238+
// let f be the real exponent of the output:
239+
// f = floor(real_exponent / 2)
240+
// Then:
241+
// floor((sign_exp + 1) / 2) = f + 8192
242+
// Hence, the biased exponent of the final result is:
243+
// f + 16383 = floor((sign_exp + 1) / 2) + 8191.
244+
// Since the output mantissa will include the hidden bit, we can define the
245+
// output exponent part:
246+
// e2 = floor((sign_exp + 1) / 2) + 8190
247+
unsigned i = static_cast<unsigned>(1 - (sign_exp & 1));
248+
uint32_t q2 = (sign_exp + 1) >> 1;
249+
// Exponent of the final result
250+
uint32_t e2 = q2 + 8190;
251+
252+
constexpr uint64_t RSQRT_2[2] = {~0ull,
253+
0xb504f333f9de6484 /* 2^64/sqrt(2) */};
254+
255+
// Approximate 1/sqrt(1 + x_frac)
256+
// Error: |r_1 - 1/sqrt(x)| < 2^-63.
257+
uint64_t r1 = rsqrt_approx(static_cast<uint64_t>(x_frac >> 64));
258+
// Adjust for the even/odd exponent.
259+
uint64_t r2 = prod_hi(r1, RSQRT_2[i]);
260+
unsigned shift = 2 - i;
261+
262+
// Normalized input:
263+
// 1 <= x_reduced < 4
264+
UInt128 x_reduced = (x_frac >> shift) | (UInt128(1) << (126 + i));
265+
// With r2 ~ 1/sqrt(x) up to 2^-63, we perform another round of Newton-Raphson
266+
// iteration:
267+
// r3 = r2 - r2 * h / 2,
268+
// for h = r2^2 * x - 1.
269+
// Then:
270+
// sqrt(x) = x * (1 / sqrt(x))
271+
// ~ x * r3
272+
// = x * (r2 - r2 * h / 2)
273+
// = (x * r2) - (x * r2) * h / 2
274+
UInt128 sx = prod_hi(x_reduced, r2);
275+
UInt128 h = prod_hi(sx, r2) << 2;
276+
UInt128 ds = static_cast<UInt128>(prod_hi(static_cast<Int128>(h), sx));
277+
UInt128 v = (sx << 1) - ds;
278+
279+
uint32_t nrst = rm == FE_TONEAREST;
280+
// The result lies within (-2,5) of true square root so we now
281+
// test that we can correctly round the result taking into account
282+
// the rounding mode
283+
// check the lowest 14 bits.
284+
int dd = (static_cast<int>(v) << 18) >> 18;
285+
286+
if (LIBC_UNLIKELY(dd < 4 && dd >= -8)) { // can round correctly?
287+
// m is almost the final result it can be only 1 ulp off so we
288+
// just need to test both possibilities. We square it and
289+
// compare with the initial argument.
290+
UInt128 m = v >> 15;
291+
UInt128 m2 = m * m;
292+
Int128 t0, t1;
293+
// The difference of the squared result and the argument
294+
t0 = static_cast<Int128>(m2 - (x_reduced << 98));
295+
if (t0 == 0) {
296+
// the square root is exact
297+
v = m << 15;
298+
} else {
299+
// Add +-1 ulp to m depend on the sign of the difference. Here
300+
// we do not need to square again since (m+1)^2 = m^2 + 2*m +
301+
// 1 so just need to add shifted m and 1.
302+
t1 = t0;
303+
Int128 sgn = t0 >> 127; // sign of the difference
304+
t1 -= (m << 1) ^ sgn;
305+
t1 += 1 + sgn;
306+
307+
Int128 sgn1 = t1 >> 127;
308+
if (LIBC_UNLIKELY(sgn == sgn1)) {
309+
t0 = t1;
310+
v -= sgn << 15;
311+
t1 -= (m << 1) ^ sgn;
312+
t1 += 1 + sgn;
313+
}
314+
315+
if (t1 == 0) {
316+
// 1 ulp offset brings again an exact root
317+
v = (m - (2 * sgn + 1)) << 15;
318+
} else {
319+
t1 += t0;
320+
Int128 side = t1 >> 127; // select what is closer m or m+-1
321+
v &= ~UInt128(0) << 15; // wipe the fractional bits
322+
v -= ((sgn & side) | (~sgn & 1)) << (15 + side);
323+
v |= 1; // add sticky bit since we cannot have an exact mid-point
324+
// situation
325+
}
326+
}
327+
}
328+
329+
unsigned frac = static_cast<unsigned>(v) & 0x7fff; // fractional part
330+
unsigned rnd; // round bit
331+
if (LIBC_LIKELY(nrst != 0)) {
332+
rnd = frac >> 14; // round to nearest tie to even
333+
} else if (rm == FE_UPWARD) {
334+
rnd = !!frac; // round up
335+
} else if (rm == FE_DOWNWARD) {
336+
rnd = 0; // round down
337+
} else {
338+
rnd = 0; // round to zero
339+
}
340+
341+
v >>= 15; // position mantissa
342+
v += rnd; // round
343+
344+
// // Set inexact flag only if square root is inexact
345+
// // TODO: We will have to raise FE_INEXACT most of the time, but this
346+
// // operation is very costly, especially in x86-64, since technically, it
347+
// // needs to synchronize both SSE and x87 flags. Need to investigate
348+
// // further to see how we can make this performant.
349+
// if(frac) fputil::raise_except_if_required(FE_INEXACT);
350+
351+
v += static_cast<UInt128>(e2) << FPBits::FRACTION_LEN; // place exponent
352+
return cpp::bit_cast<float128>(v);
18353
}
19354

20355
} // namespace LIBC_NAMESPACE_DECL

0 commit comments

Comments
 (0)