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 <stddef.h>
8
9 #include <immintrin.h>
10
11 #include <xnnpack/math.h>
12 #include <xnnpack/math-stubs.h>
13
14
xnn_math_f32_sqrt__fma3_nr1fma1adj(size_t n,const float * input,float * output)15 void xnn_math_f32_sqrt__fma3_nr1fma1adj(
16 size_t n,
17 const float* input,
18 float* output)
19 {
20 assert(n % (8 * sizeof(float)) == 0);
21
22 const __m256 vhalf = _mm256_set1_ps(0.5f);
23 for (; n != 0; n -= 8 * sizeof(float)) {
24 const __m256 vx = _mm256_load_ps(input);
25 input += 8;
26
27 // Initial approximation
28 const __m256 vrsqrtx = _mm256_rsqrt_ps(vx);
29 __m256 vsqrtx = _mm256_mul_ps(vrsqrtx, vx);
30 __m256 vhalfrsqrtx = _mm256_mul_ps(vrsqrtx, vhalf);
31
32 // Netwon-Raphson iteration:
33 // residual <- 0.5 - sqrtx * halfrsqrtx
34 // halfrsqrtx <- halfrsqrtx + halfrsqrtx * residual
35 // sqrtx <- sqrtx + sqrtx * residual
36 const __m256 vresidual = _mm256_fnmadd_ps(vsqrtx, vhalfrsqrtx, vhalf);
37 vhalfrsqrtx = _mm256_fmadd_ps(vhalfrsqrtx, vresidual, vhalfrsqrtx);
38 vsqrtx = _mm256_fmadd_ps(vsqrtx, vresidual, vsqrtx);
39
40 // Final adjustment:
41 // adjustment <- x - sqrtx * sqrtx
42 // sqrtx <- sqrtx + halfrsqrtx * adjustment
43 const __m256 vadjustment = _mm256_fnmadd_ps(vsqrtx, vsqrtx, vx);
44 vsqrtx = _mm256_fmadd_ps(vhalfrsqrtx, vadjustment, vsqrtx);
45
46 const __m256 vy = vsqrtx;
47
48 _mm256_store_ps(output, vy);
49 output += 8;
50 }
51 }
52