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 % 16 == 0
7$assert BATCH_TILE >= 16
8$ABC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
9#include <assert.h>
10
11#include <immintrin.h>
12
13#include <xnnpack/clamp.h>
14#include <xnnpack/common.h>
15#include <xnnpack/intrinsics-polyfill.h>
16
17
18void xnn_f32_clamp_ukernel__avx512f_x${BATCH_TILE}(
19    size_t n,
20    const float* x,
21    float* y,
22    const union xnn_f32_minmax_params params[restrict XNN_MIN_ELEMENTS(1)])
23{
24  assert(n != 0);
25  assert(n % sizeof(float) == 0);
26  assert(x != NULL);
27  assert(y != NULL);
28
29  const __m512 vy_min = _mm512_broadcast_f32x4(_mm_load_ps(params->sse.min));
30  const __m512 vy_max = _mm512_broadcast_f32x4(_mm_load_ps(params->sse.max));
31
32  for (; n >= ${BATCH_TILE} * sizeof(float); n -= ${BATCH_TILE} * sizeof(float)) {
33    __m512 vacc${ABC[0:16]} = _mm512_loadu_ps(x);
34    $for N in range(16, BATCH_TILE, 16):
35      __m512 vacc${ABC[N:N+16]} = _mm512_loadu_ps(x + ${N});
36    x += ${BATCH_TILE};
37
38    $for N in range(0, BATCH_TILE, 16):
39      vacc${ABC[N:N+16]} = _mm512_max_ps(vacc${ABC[N:N+16]}, vy_min);
40
41    $for N in range(0, BATCH_TILE, 16):
42      vacc${ABC[N:N+16]} = _mm512_min_ps(vacc${ABC[N:N+16]}, vy_max);
43
44    _mm512_storeu_ps(y, vacc${ABC[0:16]});
45    $for N in range(16, BATCH_TILE, 16):
46      _mm512_storeu_ps(y + ${N}, vacc${ABC[N:N+16]});
47    y += ${BATCH_TILE};
48  }
49  $if BATCH_TILE > 16:
50    for (; n >= 16 * sizeof(float); n -= 16 * sizeof(float)) {
51      __m512 vacc = _mm512_loadu_ps(x);
52      x += 16;
53
54      vacc = _mm512_max_ps(vacc, vy_min);
55      vacc = _mm512_min_ps(vacc, vy_max);
56
57      _mm512_storeu_ps(y, vacc);
58      y += 16;
59    }
60  if XNN_UNLIKELY(n != 0) {
61    assert(n >= 1 * sizeof(float));
62    assert(n <= 15 * sizeof(float));
63    // Prepare mask for valid 32-bit elements (depends on n).
64    n >>= 2 /* log2(sizeof(float)) */;
65    const __mmask16 vmask = _cvtu32_mask16((uint16_t) ((uint32_t) (UINT32_C(1) << n) - UINT32_C(1)));
66
67    __m512 vacc = _mm512_maskz_loadu_ps(vmask, x);
68    vacc = _mm512_max_ps(vacc, vy_min);
69    vacc = _mm512_min_ps(vacc, vy_max);
70    _mm512_mask_storeu_ps(y, vmask, vacc);
71  }
72}
73