1// Copyright 2019 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 % 4 == 0
7$assert BATCH_TILE >= 4
8$ABC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
9#include <assert.h>
10
11#include <emmintrin.h>
12
13#include <xnnpack/common.h>
14#include <xnnpack/hswish.h>
15
16
17void xnn_f32_hswish_ukernel__sse_x${BATCH_TILE}(
18    size_t n,
19    const float* x,
20    float* y,
21    const union xnn_f32_hswish_params params[restrict XNN_MIN_ELEMENTS(1)]) XNN_DISABLE_TSAN
22{
23  assert(n != 0);
24  assert(n % sizeof(float) == 0);
25
26  const __m128 vsixth = _mm_load_ps(params->sse.sixth);
27  const __m128 vhalf = _mm_load_ps(params->sse.half);
28  const __m128 vone = _mm_load_ps(params->sse.one);
29  const __m128 vzero = _mm_setzero_ps();
30
31  for (; n >= ${BATCH_TILE} * sizeof(float); n -= ${BATCH_TILE} * sizeof(float)) {
32    const __m128 vx${ABC[0:4]} = _mm_loadu_ps(x);
33    $for N in range(4, BATCH_TILE, 4):
34      const __m128 vx${ABC[N:N+4]} = _mm_loadu_ps(x + ${N});
35    x += ${BATCH_TILE};
36
37    $for N in range(0, BATCH_TILE, 4):
38      __m128 vacc${ABC[N:N+4]} = _mm_mul_ps(vx${ABC[N:N+4]}, vsixth);
39
40    $for N in range(0, BATCH_TILE, 4):
41      vacc${ABC[N:N+4]} = _mm_add_ps(vacc${ABC[N:N+4]}, vhalf);
42
43    $for N in range(0, BATCH_TILE, 4):
44      vacc${ABC[N:N+4]} = _mm_max_ps(vacc${ABC[N:N+4]}, vzero);
45
46    $for N in range(0, BATCH_TILE, 4):
47      vacc${ABC[N:N+4]} = _mm_min_ps(vacc${ABC[N:N+4]}, vone);
48
49    $for N in range(0, BATCH_TILE, 4):
50      vacc${ABC[N:N+4]} = _mm_mul_ps(vacc${ABC[N:N+4]}, vx${ABC[N:N+4]});
51
52    _mm_storeu_ps(y, vacc${ABC[0:4]});
53    $for N in range(4, BATCH_TILE, 4):
54      _mm_storeu_ps(y + ${N}, vacc${ABC[N:N+4]});
55    y += ${BATCH_TILE};
56  }
57  $if BATCH_TILE > 4:
58    for (; n >= 4 * sizeof(float); n -= 4 * sizeof(float)) {
59      const __m128 vx0123 = _mm_loadu_ps(x);
60      x += 4;
61      __m128 vacc0123 = _mm_mul_ps(vx0123, vsixth);
62      vacc0123 = _mm_add_ps(vacc0123, vhalf);
63      vacc0123 = _mm_max_ps(vacc0123, vzero);
64      vacc0123 = _mm_min_ps(vacc0123, vone);
65      vacc0123 = _mm_mul_ps(vacc0123, vx0123);
66      _mm_storeu_ps(y, vacc0123);
67      y += 4;
68    }
69  if XNN_UNLIKELY(n != 0) {
70    const __m128 vx0123 = _mm_loadu_ps(x);
71    __m128 vacc0123 = _mm_mul_ps(vx0123, vsixth);
72    vacc0123 = _mm_add_ps(vacc0123, vhalf);
73    vacc0123 = _mm_max_ps(vacc0123, vzero);
74    vacc0123 = _mm_min_ps(vacc0123, vone);
75    vacc0123 = _mm_mul_ps(vacc0123, vx0123);
76
77    if (n & (2 * sizeof(float))) {
78      _mm_storel_pi((__m64*) y, vacc0123);
79      vacc0123 = _mm_movehl_ps(vacc0123, vacc0123);
80      y += 2;
81    }
82    if (n & (1 * sizeof(float))) {
83      _mm_store_ss(y, vacc0123);
84    }
85  }
86}
87