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$assert BATCH_TILE % 8 == 0
7$assert BATCH_TILE >= 8
8$ABC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
9#include <assert.h>
10
11#include <immintrin.h>
12
13#include <xnnpack/common.h>
14#include <xnnpack/vunary.h>
15
16
17static const int32_t mask_table[14] = {-1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0};
18
19void xnn_f32_vsqrt_ukernel__avx_sqrt_x${BATCH_TILE}(
20    size_t n,
21    const float* x,
22    float* y,
23    const union xnn_f32_sqrt_params params[restrict XNN_MIN_ELEMENTS(1)])
24{
25  assert(n != 0);
26  assert(n % sizeof(float) == 0);
27
28  $if BATCH_TILE > 8:
29    for (; n >= ${BATCH_TILE} * sizeof(float); n -= ${BATCH_TILE} * sizeof(float)) {
30      const __m256 vx${ABC[0:8]} = _mm256_loadu_ps(x);
31      $for N in range(8, BATCH_TILE, 8):
32        const __m256 vx${ABC[N:N+8]} = _mm256_loadu_ps(x + ${N});
33      x += ${BATCH_TILE};
34
35      $for N in range(0, BATCH_TILE, 8):
36        const __m256 vy${ABC[N:N+8]} = _mm256_sqrt_ps(vx${ABC[N:N+8]});
37
38      _mm256_storeu_ps(y, vy${ABC[0:8]});
39      $for N in range(8, BATCH_TILE, 8):
40        _mm256_storeu_ps(y + ${N}, vy${ABC[N:N+8]});
41      y += ${BATCH_TILE};
42    }
43  for (; n >= 8 * sizeof(float); n -= 8 * sizeof(float)) {
44    const __m256 vx = _mm256_loadu_ps(x);
45    x += 8;
46    const __m256 vy = _mm256_sqrt_ps(vx);
47    _mm256_storeu_ps(y, vy);
48    y += 8;
49  }
50  if XNN_UNLIKELY(n != 0) {
51    assert(n >= 1 * sizeof(float));
52    assert(n <= 7 * sizeof(float));
53    __m256i vmask = _mm256_loadu_si256((const __m256i*) ((uintptr_t) &mask_table[7] - n));
54
55    const __m256 vx = _mm256_maskload_ps(x, vmask);
56    const __m256 vy = _mm256_sqrt_ps(vx);
57
58    // _mm256_maskstore_ps(y, vmask, vy) could be used here, but triggers msan failures (probably an msan bug).
59    __m128 vy_lo = _mm256_castps256_ps128(vy);
60    if (n & (4 * sizeof(float))) {
61      _mm_storeu_ps(y, vy_lo);
62      vy_lo = _mm256_extractf128_ps(vy, 1);
63      y += 4;
64    }
65    if (n & (2 * sizeof(float))) {
66      _mm_storel_pi((__m64*) y, vy_lo);
67      vy_lo = _mm_movehl_ps(vy_lo, vy_lo);
68      y += 2;
69    }
70    if (n & (1 * sizeof(float))) {
71      _mm_store_ss(y, vy_lo);
72    }
73  }
74}
75