• 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 
xnn_math_f32_f16_cvt__scalar_bitcast(size_t n,const float * input,void * output)15 void xnn_math_f32_f16_cvt__scalar_bitcast(
16     size_t n,
17     const float* input,
18     void* output)
19 {
20   assert(n % (sizeof(uint16_t)) == 0);
21 
22   const uint32_t vnonsign_mask = UINT32_C(0x7FFFFFFF);
23   const uint32_t vexp_bias = UINT32_C(0x07800000);
24   const float vscale_to_inf = 0x1.0p+112f;
25   const uint32_t vexpw_max = UINT32_C(0x7F800000);
26   const float vscale_to_zero = 0x1.0p-110f;
27   const uint32_t vbias_min = UINT32_C(0x40000000);
28   const uint16_t vexph_mask = UINT16_C(0x7C00);
29   const uint16_t vmanth_mask = UINT16_C(0x0FFF);
30   const uint16_t vnanh = UINT16_C(0x7E00);
31 
32   uint16_t* o = (uint16_t*) output;
33   for (; n != 0; n -= sizeof(uint16_t)) {
34     const float vx = *input++;
35 
36     const uint32_t vw = float_as_uint32(vx);
37     const uint32_t vnonsignw = vw & vnonsign_mask;
38 
39     float vf = uint32_as_float(vnonsignw);
40     const uint32_t vsignw = vw ^ vnonsignw;
41     uint32_t vbias = vnonsignw + vexp_bias;
42 
43     vf *= vscale_to_inf;
44     vbias &= vexpw_max;
45 
46     vf *= vscale_to_zero;
47     vbias = math_max_u32(vbias, vbias_min);
48 
49     vf += uint32_as_float(vbias);
50 
51     const uint32_t vbits = float_as_uint32(vf);
52 
53     const uint16_t vexph = (uint16_t) (vbits >> 13) & vexph_mask;
54     const uint16_t vmanth = (uint16_t) vbits & vmanth_mask;
55     const uint16_t vsignh = (uint16_t) (vsignw >> 16);
56 
57     uint16_t vh = vexph + vmanth;
58     if XNN_UNPREDICTABLE(vnonsignw > vexpw_max) {
59       vh = vnanh;
60     }
61     vh |= vsignh;
62 
63     *o++ = vh;
64   }
65 }
66