about summary refs log tree commit diff
path: root/src/math
diff options
context:
space:
mode:
authorSzabolcs Nagy <nsz@port70.net>2019-09-16 20:33:11 +0000
committerRich Felker <dalias@aerifal.cx>2019-09-27 11:18:59 -0400
commitca577951138127dcf4190a2eb3c7148b2ad6d779 (patch)
treec8f2686823505275503dd12f38ab0c96bdb41fbf /src/math
parent604f8d3d8b08ee4f548de193050ef93a7753c2e0 (diff)
downloadmusl-ca577951138127dcf4190a2eb3c7148b2ad6d779.tar.gz
musl-ca577951138127dcf4190a2eb3c7148b2ad6d779.tar.xz
musl-ca577951138127dcf4190a2eb3c7148b2ad6d779.zip
math: optimize lrint on 32bit targets
lrint in (LONG_MAX, 1/DBL_EPSILON) and in (-1/DBL_EPSILON, LONG_MIN)
is not trivial: rounding to int may be inexact, but the conversion to
int may overflow and then the inexact flag must not be raised. (the
overflow threshold is rounding mode dependent).

this matters on 32bit targets (without single instruction lrint or
rint), so the common case (when there is no overflow) is optimized by
inlining the lrint logic, otherwise the old code is kept as a fallback.

on my laptop an i486 lrint call is asm:10ns, old c:30ns, new c:21ns
on a smaller arm core: old c:71ns, new c:34ns
on a bigger arm core: old c:27ns, new c:19ns
Diffstat (limited to 'src/math')
-rw-r--r--src/math/lrint.c28
1 files changed, 27 insertions, 1 deletions
diff --git a/src/math/lrint.c b/src/math/lrint.c
index bdca8b7c..ddee7a0d 100644
--- a/src/math/lrint.c
+++ b/src/math/lrint.c
@@ -1,5 +1,6 @@
 #include <limits.h>
 #include <fenv.h>
+#include <math.h>
 #include "libm.h"
 
 /*
@@ -26,7 +27,18 @@ as a double.
 */
 
 #if LONG_MAX < 1U<<53 && defined(FE_INEXACT)
-long lrint(double x)
+#include <float.h>
+#include <stdint.h>
+#if FLT_EVAL_METHOD==0 || FLT_EVAL_METHOD==1
+#define EPS DBL_EPSILON
+#elif FLT_EVAL_METHOD==2
+#define EPS LDBL_EPSILON
+#endif
+#ifdef __GNUC__
+/* avoid stack frame in lrint */
+__attribute__((noinline))
+#endif
+static long lrint_slow(double x)
 {
 	#pragma STDC FENV_ACCESS ON
 	int e;
@@ -38,6 +50,20 @@ long lrint(double x)
 	/* conversion */
 	return x;
 }
+
+long lrint(double x)
+{
+	uint32_t abstop = asuint64(x)>>32 & 0x7fffffff;
+	uint64_t sign = asuint64(x) & (1ULL << 63);
+
+	if (abstop < 0x41dfffff) {
+		/* |x| < 0x7ffffc00, no overflow */
+		double_t toint = asdouble(asuint64(1/EPS) | sign);
+		double_t y = x + toint - toint;
+		return (long)y;
+	}
+	return lrint_slow(x);
+}
 #else
 long lrint(double x)
 {