• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 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 <stddef.h>
8 #include <stdint.h>
9 #include <math.h>
10 
11 #include <xnnpack/math.h>
12 #include <xnnpack/math-stubs.h>
13 
14 #include <fp16/bitcasts.h>
15 
16 
xnn_math_f32_f16_cvt__scalar_fabsf(size_t n,const float * input,void * output)17 void xnn_math_f32_f16_cvt__scalar_fabsf(
18     size_t n,
19     const float* input,
20     void* output)
21 {
22   assert(n % (sizeof(uint16_t)) == 0);
23 
24   const float vscale_to_inf = 0x1.0p+112f;
25   const uint32_t vexp_bias = UINT32_C(0x07800000);
26   const float vscale_to_zero = 0x1.0p-110f;
27   const uint32_t vexpw_max = UINT32_C(0x7F800000);
28   const uint32_t vbias_min = UINT32_C(0x40000000);
29   const uint16_t vexph_mask = UINT16_C(0x7C00);
30   const uint16_t vmanth_mask = UINT16_C(0x0FFF);
31   const uint16_t vnanh = UINT16_C(0x7E00);
32 
33   uint16_t* o = (uint16_t*) output;
34   for (; n != 0; n -= sizeof(uint16_t)) {
35     const float vx = *input++;
36 
37     const float vabsx = fabsf(vx);
38     uint32_t vsignw = fp32_to_bits(vx);
39 
40     const uint32_t vnonsignw = fp32_to_bits(vabsx);
41     float vf = vabsx * vscale_to_inf;
42 
43     uint32_t vbias = vnonsignw + vexp_bias;
44     vsignw ^= vnonsignw;
45 
46     vf *= vscale_to_zero;
47     vbias &= vexpw_max;
48 
49     vbias = math_max_u32(vbias, vbias_min);
50 
51     vf += fp32_from_bits(vbias);
52 
53     const uint32_t vbits = fp32_to_bits(vf);
54 
55     const uint16_t vexph = (uint16_t) (vbits >> 13) & vexph_mask;
56     const uint16_t vmanth = (uint16_t) vbits & vmanth_mask;
57     const uint16_t vsignh = (uint16_t) (vsignw >> 16);
58 
59     uint16_t vh = vexph + vmanth;
60     if XNN_UNPREDICTABLE(vnonsignw > vexpw_max) {
61       vh = vnanh;
62     }
63     vh |= vsignh;
64 
65     *o++ = vh;
66   }
67 }
68