|
| 1 | +// Unless explicitly stated otherwise all files in this repository are |
| 2 | +// dual-licensed under the Apache-2.0 License or BSD-3-Clause License. |
| 3 | +// |
| 4 | +// This product includes software developed at Datadog |
| 5 | +// (https://www.datadoghq.com/). Copyright 2023 Datadog, Inc. |
| 6 | + |
| 7 | +#if defined(__linux__) |
| 8 | + |
| 9 | +#ifndef _GNU_SOURCE |
| 10 | +#define _GNU_SOURCE |
| 11 | +#endif |
| 12 | +#include <dlfcn.h> |
| 13 | +#include <stdint.h> |
| 14 | +#include <stdlib.h> |
| 15 | + |
| 16 | +#if defined(__aarch64__) |
| 17 | +// Extracted from https://git.musl-libc.org/cgit/musl/tree/src/math/aarch64/ceilf.c |
| 18 | +static float ceilf_local(float x) |
| 19 | +{ |
| 20 | + __asm__ ("frintp %s0, %s1" : "=w"(x) : "w"(x)); |
| 21 | + return x; |
| 22 | +} |
| 23 | +#else |
| 24 | +/* fp_force_eval ensures that the input value is computed when that's |
| 25 | + otherwise unused. To prevent the constant folding of the input |
| 26 | + expression, an additional fp_barrier may be needed or a compilation |
| 27 | + mode that does so (e.g. -frounding-math in gcc). Then it can be |
| 28 | + used to evaluate an expression for its fenv side-effects only. */ |
| 29 | + |
| 30 | +static inline void fp_force_evalf(float x) |
| 31 | +{ |
| 32 | + volatile float y; |
| 33 | + y = x; |
| 34 | + (void)y; |
| 35 | +} |
| 36 | + |
| 37 | +static float ceilf_local(float x) |
| 38 | +{ |
| 39 | + // Extracted from https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c |
| 40 | + union {float f; uint32_t i;} u = {x}; |
| 41 | + int e = (int)(u.i >> 23 & 0xff) - 0x7f; |
| 42 | + uint32_t m; |
| 43 | + |
| 44 | + if (e >= 23) { |
| 45 | + return x; |
| 46 | + } |
| 47 | + if (e >= 0) { |
| 48 | + m = 0x007fffff >> e; |
| 49 | + if ((u.i & m) == 0) { |
| 50 | + return x; |
| 51 | + } |
| 52 | + fp_force_evalf(x + 0x1p120f); |
| 53 | + if (u.i >> 31 == 0){ |
| 54 | + u.i += m; |
| 55 | + } |
| 56 | + u.i &= ~m; |
| 57 | + } else { |
| 58 | + fp_force_evalf(x + 0x1p120f); |
| 59 | + if (u.i >> 31) { |
| 60 | + u.f = -0.0; |
| 61 | + } else if (u.i << 1) { |
| 62 | + u.f = 1.0; |
| 63 | + } |
| 64 | + } |
| 65 | + return u.f; |
| 66 | +} |
| 67 | +#endif |
| 68 | + |
| 69 | +#define unlikely(x) __builtin_expect(!!(x), 0) |
| 70 | + |
| 71 | +typedef float (*ceilf_t)(float); |
| 72 | + |
| 73 | +__attribute__((weak)) |
| 74 | +float ceilf(float x) |
| 75 | +{ |
| 76 | + static ceilf_t ceilf_global_; |
| 77 | + |
| 78 | + // benign race |
| 79 | + if (unlikely(ceilf_global_ == NULL)) { |
| 80 | + void *ceilf_sym = dlsym(RTLD_DEFAULT, "ceilf"); |
| 81 | + if (ceilf_sym == NULL || ceilf_sym == &ceilf) { |
| 82 | + ceilf_global_ = &ceilf_local; |
| 83 | + } else { |
| 84 | + ceilf_global_ = (ceilf_t)ceilf_sym; |
| 85 | + } |
| 86 | + } |
| 87 | + return ceilf_global_(x); |
| 88 | +} |
| 89 | +#endif |
| 90 | + |
0 commit comments