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_fabsf(size_t n,const float * input,void * output)15void xnn_math_f32_f16_cvt__scalar_fabsf( 16 size_t n, 17 const float* input, 18 void* output) 19 { 20 assert(n % (sizeof(uint16_t)) == 0); 21 22 const float vscale_to_inf = 0x1.0p+112f; 23 const uint32_t vexp_bias = UINT32_C(0x07800000); 24 const float vscale_to_zero = 0x1.0p-110f; 25 const uint32_t vexpw_max = UINT32_C(0x7F800000); 26 const uint32_t vbias_min = UINT32_C(0x40000000); 27 const uint16_t vexph_mask = UINT16_C(0x7C00); 28 const uint16_t vmanth_mask = UINT16_C(0x0FFF); 29 const uint16_t vnanh = UINT16_C(0x7E00); 30 31 uint16_t* o = (uint16_t*) output; 32 for (; n != 0; n -= sizeof(uint16_t)) { 33 const float vx = *input++; 34 35 const float vabsx = fabsf(vx); 36 uint32_t vsignw = float_as_uint32(vx); 37 38 const uint32_t vnonsignw = float_as_uint32(vabsx); 39 float vf = vabsx * vscale_to_inf; 40 41 uint32_t vbias = vnonsignw + vexp_bias; 42 vsignw ^= vnonsignw; 43 44 vf *= vscale_to_zero; 45 vbias &= vexpw_max; 46 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