1 // Copyright 2020 Google LLC
2 //
3 // This source code is licensed under the BSD-style license found in the
4 // LICENSE file in the root directory of this source tree.
5
6 #include <assert.h>
7 #include <math.h>
8 #include <stddef.h>
9
10 #include <xnnpack/common.h>
11 #include <xnnpack/math-stubs.h>
12
13
xnn_math_f32_roundu__scalar_addsub(size_t n,const float * input,float * output)14 void xnn_math_f32_roundu__scalar_addsub(
15 size_t n,
16 const float* input,
17 float* output)
18 {
19 assert(n % sizeof(float) == 0);
20
21 // Addition of this number to a floating-point number x cause rounding of the result to an integer. Then this magic
22 // number is subtracted back from the result to get original x rounded to integer. This trick works only for
23 // 0 <= x < 2**24, but all numbers in 2**23 <= x < 2**24 range are integers, so we can further restrict it to
24 // 0 <= x < 2**23. Then the upper bound of the validity interval is conveniently the same as the magic number.
25 const float vmagic_number = 0x1.000000p+23f;
26 // Unit constant to increment results rounded "wrong way" (i.e. down) in the round-to-nearest-even operation.
27 const float vone = 1.0f;
28
29 for (; n != 0; n -= sizeof(float)) {
30 const float vx = *input++;
31
32 // The rounding trick works only for x >= 0, so we compute absolute value of x, round it, and restore the sign in
33 // the end. This method works for round-to-nearest-even because it is an odd function.
34 const float vabsx = fabsf(vx);
35 // Addition-subtraction trick with the magic number to cause rounding to integer for abs(x).
36 // Note: the result is valid only for 0 <= abs(x) < 2**23.
37 // Note: addition-subtraction implicitly converts SNaN inputs to QNaNs.
38 const float vprerndabsx = (vabsx + vmagic_number) - vmagic_number;
39
40 // Select between the abs(x) rounded using addition-subtraction trick and the abs(x) value.
41 // For abs(x) < 2**23, the result is abs(x) rounded via addition-subtraction trick.
42 // For abs(x) >= 2**23, the result is abs(x) itself (already an integer).
43 // For NaN inputs, the result is abs(x) converted to QNaN as a side-effect of addition-subtraction.
44 const float vrndabsx = XNN_UNPREDICTABLE(vabsx >= vmagic_number) ? vabsx : vprerndabsx;
45 // Restore the sign of the rounded value.
46 const float vrndx = copysignf(vrndabsx, vx);
47
48 // Adjust x rounded to nearest-even to get x rounded up.
49 const float vprey = XNN_UNPREDICTABLE(vrndx < vx) ? vrndx + vone : vrndx;
50 // Restore the sign of the adjusted value.
51 // This second restoration of the sign is important to produce negative zero for -1.0 < x < -0.5 inputs, where
52 // otherwise we would get -1.0 (rounded x) + 1.0 (adjustment) = +0.0.
53 const float vy = copysignf(vprey, vrndx);
54
55 *output++ = vy;
56 }
57 }
58