// Copyright 2019 Google LLC
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.

$assert DATATYPE in ["F32", "QC4", "QC8"]
$if DATATYPE == "QC8" and SSE == 2:
  $assert NR % 8 == 0
$elif DATATYPE == "QC4":
  $assert NR == 8
$else:
  $assert NR % 4 == 0
$ABC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
$SSE_HEADER = {1: "xmmintrin.h", 2: "emmintrin.h", 4: "smmintrin.h"}[SSE]
#include <assert.h>

#include <${SSE_HEADER}>

#include "xnnpack/gemm.h"
$if DATATYPE == "QC8" and SSE == 4:
  #include "xnnpack/unaligned.h"


$RANGE_MR = list(reversed(range(MR))) if INC else list(range(MR))
$ISA = {1: "sse", 2: "sse2", 4: "sse41"}[SSE]
$DATATYPE_SPEC = {"F32": "f32", "QC8": "f32_qc8w", "QC4": "f32_qc4w"}[DATATYPE]
void xnn_${DATATYPE_SPEC}_gemm${"inc" if INC else ""}_minmax_ukernel_${MR}x${NR}s4__${ISA}(
    size_t mr,
    size_t nc,
    size_t kc,
    const float* restrict a,
    size_t a_stride,
    $if DATATYPE == "F32":
      const float* restrict w,
    $else:
      const void* restrict w,
    float* restrict c,
    size_t cm_stride,
    size_t cn_stride,
    $if INC:
      const float* restrict acc,
    $if DATATYPE == "QC4":
      const struct xnn_f32_qc4w_minmax_params params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS
    $else:
      const union xnn_f32_minmax_params params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS
{
  assert(mr != 0);
  assert(mr <= ${MR});
  assert(nc != 0);
  assert(kc != 0);
  assert(kc % sizeof(float) == 0);
  assert(a != NULL);
  assert(w != NULL);
  assert(c != NULL);
  $if INC:
    assert(acc != NULL);

  const float* a0 = a;
  float* c0 = c;
  $for M in range(1, MR):
    const float* a${M} = (const float*) ((uintptr_t) a${M-1} + a_stride);
    float* c${M} = (float*) ((uintptr_t) c${M-1} + cm_stride);
    $if M % 2 == 0:
      if XNN_UNPREDICTABLE(mr <= ${M}) {
        a${M} = a${M-1};
        c${M} = c${M-1};
      }
    $elif M + 1 == MR:
      if XNN_UNPREDICTABLE(mr != ${M+1}) {
        a${M} = a${M-1};
        c${M} = c${M-1};
      }
    $else:
      if XNN_UNPREDICTABLE(mr < ${M+1}) {
        a${M} = a${M-1};
        c${M} = c${M-1};
      }
  $if DATATYPE == "QC4":
    const __m128i vminus_kernel_zero_point = _mm_set1_epi32(-params->scalar.kernel_zero_point);
    const __m128i vmask = _mm_set1_epi8(params->scalar.mask);

  const __m128 vmin = _mm_set1_ps(params->scalar.min);
  const __m128 vmax = _mm_set1_ps(params->scalar.max);
  XNN_FORCE_REALIZATION(vmin);
  XNN_FORCE_REALIZATION(vmax);

  do {
    $if INC:
      $for M in range(MR):
        $for N in range(0, NR, 4):
          __m128 vacc${M}x${ABC[N:N+4]} = _mm_load_ps(acc + ${M*NR+N});
      acc += ${MR*NR};
    $else:
      $for N in range(0, NR, 4):
        $if DATATYPE == "F32":
          __m128 vacc0x${ABC[N:N+4]} = _mm_load_ps(w + ${N});
        $else:
          __m128 vacc0x${ABC[N:N+4]} = _mm_loadu_ps((const float*) w + ${N});
      $for M in range(1, MR):
        $for N in range(0, NR, 4):
          __m128 vacc${M}x${ABC[N:N+4]} = vacc0x${ABC[N:N+4]};
      $if DATATYPE == "F32":
        w += ${NR};
      $else:
        w = (const float*) w + ${NR};

    size_t k = kc;
    for (; k >= 4 * sizeof(float); k -= 4 * sizeof(float)) {
      $for M in range(MR):
        __m128 va${M} = _mm_loadu_ps(a${M});
        a${M} += 4;

      $for L in range(4):
        $if DATATYPE == "F32":
          $for N in range(0, NR, 4):
            const __m128 vb${ABC[N:N+4]}c${L} = _mm_load_ps(w + ${L * NR + N});
        $elif DATATYPE == "QC4":
          $if L % 4 == 0:
            $if SSE >= 4:
              $for N in range(0, NR, 8):
                const __m128i vbwi${ABC[N:N+8]}c01 = _mm_cvtepu8_epi16(_mm_loadl_epi64((const __m128i *) ((const int8_t*) w + ${N * 2})));
                const __m128i vbwi${ABC[N:N+8]}c23 = _mm_cvtepu8_epi16(_mm_loadl_epi64((const __m128i *) ((const int8_t*) w + ${N * 2 + 8})));
              $for N in range(0, NR, 8):
                __m128i vbw${ABC[N:N+8]}c0 = _mm_and_si128(vbwi${ABC[N:N+8]}c01, vmask);
                __m128i vbw${ABC[N:N+8]}c1 = _mm_srli_epi16(vbwi${ABC[N:N+8]}c01, 4);
                __m128i vbw${ABC[N:N+8]}c2 = _mm_and_si128(vbwi${ABC[N:N+8]}c23, vmask);
                __m128i vbw${ABC[N:N+8]}c3 = _mm_srli_epi16(vbwi${ABC[N:N+8]}c23, 4);
            $else:
              $for N in range(0, NR, 8):
                __m128i vbi${ABC[N:N+8]}c0123 = _mm_loadu_si128((const __m128i *) ((const int8_t*) w + ${N * 2}));
              $for N in range(0, NR, 8):
                __m128i vbwi${ABC[N:N+8]}c01 = _mm_unpacklo_epi8(vbi${ABC[N:N+8]}c0123, vbi${ABC[N:N+8]}c0123);
                __m128i vbwi${ABC[N:N+8]}c23 = _mm_unpackhi_epi8(vbi${ABC[N:N+8]}c0123, vbi${ABC[N:N+8]}c0123);
                __m128i vbw${ABC[N:N+8]}c0 = _mm_and_si128(vbwi${ABC[N:N+8]}c01, vmask);
                __m128i vbw${ABC[N:N+8]}c1 = _mm_srli_epi16(vbwi${ABC[N:N+8]}c01, 12);
                __m128i vbw${ABC[N:N+8]}c2 = _mm_and_si128(vbwi${ABC[N:N+8]}c23, vmask);
                __m128i vbw${ABC[N:N+8]}c3 = _mm_srli_epi16(vbwi${ABC[N:N+8]}c23, 12);
          $for N in range(0, NR, 8):
            __m128i vbi${ABC[N:N+4]}c${L} = _mm_unpacklo_epi16(vbw${ABC[N:N+8]}c${L}, _mm_setzero_si128());
            __m128i vbi${ABC[N+4:N+8]}c${L} = _mm_unpackhi_epi16(vbw${ABC[N:N+8]}c${L}, _mm_setzero_si128());
            vbi${ABC[N:N+4]}c${L} = _mm_add_epi32(vbi${ABC[N:N+4]}c${L}, vminus_kernel_zero_point);
            vbi${ABC[N+4:N+8]}c${L} = _mm_add_epi32(vbi${ABC[N+4:N+8]}c${L}, vminus_kernel_zero_point);
            const __m128 vb${ABC[N:N+4]}c${L} = _mm_cvtepi32_ps(vbi${ABC[N:N+4]}c${L});
            const __m128 vb${ABC[N+4:N+8]}c${L} = _mm_cvtepi32_ps(vbi${ABC[N+4:N+8]}c${L});
        $elif DATATYPE == "QC8":
          $if SSE >= 4:
            $for N in range(0, NR, 4):
              const __m128i vbi${ABC[N:N+4]}c${L} = _mm_cvtepi8_epi32(_mm_cvtsi32_si128((int) unaligned_load_s32((const int8_t*) w + ${L * NR + N})));
            $for N in range(0, NR, 4):
              const __m128 vb${ABC[N:N+4]}c${L} = _mm_cvtepi32_ps(vbi${ABC[N:N+4]}c${L});
          $else:
            $for N in range(0, NR, 8):
              const __m128i vb${ABC[N:N+8]}c${L} = _mm_loadl_epi64((const __m128i *) ((const int8_t*) w + ${L * NR + N}));
            $for N in range(0, NR, 8):
              const __m128i vbw${ABC[N:N+8]}c${L} = _mm_unpacklo_epi8(vb${ABC[N:N+8]}c${L}, vb${ABC[N:N+8]}c${L});
              const __m128 vb${ABC[N:N+4]}c${L} = _mm_cvtepi32_ps(_mm_srai_epi32(_mm_unpacklo_epi16(vbw${ABC[N:N+8]}c${L}, vbw${ABC[N:N+8]}c${L}), 24));
              const __m128 vb${ABC[N+4:N+8]}c${L} = _mm_cvtepi32_ps(_mm_srai_epi32(_mm_unpackhi_epi16(vbw${ABC[N:N+8]}c${L}, vbw${ABC[N:N+8]}c${L}), 24));

        $for N in range(0, NR, 4):
          $for M in range(MR):
            vacc${M}x${ABC[N:N+4]} = _mm_add_ps(vacc${M}x${ABC[N:N+4]}, _mm_mul_ps(va${M}, vb${ABC[N:N+4]}c${L}));

        $if L + 1 != 4:
          $for M in range(MR):
            va${M} = _mm_shuffle_ps(va${M}, va${M}, _MM_SHUFFLE(0, 3, 2, 1));

      $if DATATYPE == "F32":
        w += ${NR * 4};
      $elif DATATYPE == "QC4":
        w = (const int8_t*) w + ${NR * 4 // 2};
      $else:
        w = (const int8_t*) w + ${NR * 4};
    }
    if XNN_UNLIKELY(k != 0) {
      $for M in range(MR):
        __m128 va${M} = _mm_loadu_ps(a${M});
        a${M} = (const float*) ((uintptr_t) a${M} + k);

      $for L in range(4):
        $if DATATYPE == "F32":
          $for N in range(0, NR, 4):
            const __m128 vb${ABC[N:N+4]}c${L} = _mm_load_ps(w + ${L * NR + N});
        $elif DATATYPE == "QC4":
          $if L % 4 == 0:
            $if SSE >= 4:
              $for N in range(0, NR, 8):
                const __m128i vbwi${ABC[N:N+8]}c01 = _mm_cvtepu8_epi16(_mm_loadl_epi64((const __m128i *) ((const int8_t*) w + ${N * 2})));
                const __m128i vbwi${ABC[N:N+8]}c23 = _mm_cvtepu8_epi16(_mm_loadl_epi64((const __m128i *) ((const int8_t*) w + ${N * 2 + 8})));
              $for N in range(0, NR, 8):
                __m128i vbw${ABC[N:N+8]}c0 = _mm_and_si128(vbwi${ABC[N:N+8]}c01, vmask);
                __m128i vbw${ABC[N:N+8]}c1 = _mm_srli_epi16(vbwi${ABC[N:N+8]}c01, 4);
                __m128i vbw${ABC[N:N+8]}c2 = _mm_and_si128(vbwi${ABC[N:N+8]}c23, vmask);
                __m128i vbw${ABC[N:N+8]}c3 = _mm_srli_epi16(vbwi${ABC[N:N+8]}c23, 4);
            $else:
              $for N in range(0, NR, 8):
                __m128i vbi${ABC[N:N+8]}c0123 = _mm_loadu_si128((const __m128i *) ((const int8_t*) w + ${N * 2}));
              $for N in range(0, NR, 8):
                __m128i vbwi${ABC[N:N+8]}c01 = _mm_unpacklo_epi8(vbi${ABC[N:N+8]}c0123, vbi${ABC[N:N+8]}c0123);
                __m128i vbwi${ABC[N:N+8]}c23 = _mm_unpackhi_epi8(vbi${ABC[N:N+8]}c0123, vbi${ABC[N:N+8]}c0123);
                __m128i vbw${ABC[N:N+8]}c0 = _mm_and_si128(vbwi${ABC[N:N+8]}c01, vmask);
                __m128i vbw${ABC[N:N+8]}c1 = _mm_srli_epi16(vbwi${ABC[N:N+8]}c01, 12);
                __m128i vbw${ABC[N:N+8]}c2 = _mm_and_si128(vbwi${ABC[N:N+8]}c23, vmask);
                __m128i vbw${ABC[N:N+8]}c3 = _mm_srli_epi16(vbwi${ABC[N:N+8]}c23, 12);
          $for N in range(0, NR, 8):
            __m128i vbi${ABC[N:N+4]}c${L} = _mm_unpacklo_epi16(vbw${ABC[N:N+8]}c${L}, _mm_setzero_si128());
            __m128i vbi${ABC[N+4:N+8]}c${L} = _mm_unpackhi_epi16(vbw${ABC[N:N+8]}c${L}, _mm_setzero_si128());
            vbi${ABC[N:N+4]}c${L} = _mm_add_epi32(vbi${ABC[N:N+4]}c${L}, vminus_kernel_zero_point);
            vbi${ABC[N+4:N+8]}c${L} = _mm_add_epi32(vbi${ABC[N+4:N+8]}c${L}, vminus_kernel_zero_point);
            const __m128 vb${ABC[N:N+4]}c${L} = _mm_cvtepi32_ps(vbi${ABC[N:N+4]}c${L});
            const __m128 vb${ABC[N+4:N+8]}c${L} = _mm_cvtepi32_ps(vbi${ABC[N+4:N+8]}c${L});
        $elif DATATYPE == "QC8":
          $if SSE >= 4:
            $for N in range(0, NR, 4):
              const __m128i vbi${ABC[N:N+4]}c${L} = _mm_cvtepi8_epi32(_mm_cvtsi32_si128((int) unaligned_load_s32((const int8_t*) w + ${L * NR + N})));
            $for N in range(0, NR, 4):
              const __m128 vb${ABC[N:N+4]}c${L} = _mm_cvtepi32_ps(vbi${ABC[N:N+4]}c${L});
          $else:
            $for N in range(0, NR, 8):
              const __m128i vb${ABC[N:N+8]}c${L} = _mm_loadl_epi64((const __m128i *) ((const int8_t*) w + ${L * NR + N}));
            $for N in range(0, NR, 8):
              const __m128i vbw${ABC[N:N+8]}c${L} = _mm_unpacklo_epi8(vb${ABC[N:N+8]}c${L}, vb${ABC[N:N+8]}c${L});
              const __m128 vb${ABC[N:N+4]}c${L} = _mm_cvtepi32_ps(_mm_srai_epi32(_mm_unpacklo_epi16(vbw${ABC[N:N+8]}c${L}, vbw${ABC[N:N+8]}c${L}), 24));
              const __m128 vb${ABC[N+4:N+8]}c${L} = _mm_cvtepi32_ps(_mm_srai_epi32(_mm_unpackhi_epi16(vbw${ABC[N:N+8]}c${L}, vbw${ABC[N:N+8]}c${L}), 24));

        $for N in range(0, NR, 4):
          $for M in range(MR):
            vacc${M}x${ABC[N:N+4]} = _mm_add_ps(vacc${M}x${ABC[N:N+4]}, _mm_mul_ps(_mm_andnot_ps(_mm_cmpeq_ps(_mm_setzero_ps(), vb${ABC[N:N+4]}c${L}), va${M}), vb${ABC[N:N+4]}c${L}));

        $if L + 1 != 4:
          $for M in range(MR):
            va${M} = _mm_shuffle_ps(va${M}, va${M}, _MM_SHUFFLE(0, 3, 2, 1));

      $if DATATYPE == "F32":
        w += ${NR * 4};
      $elif DATATYPE == "QC4":
        w = (const int8_t*) w + ${NR * 4 // 2};
      $else:
        w = (const int8_t*) w + ${NR * 4};
    }

    $if DATATYPE in ["QC8", "QC4"]:
      $for N in range(0, NR, 4):
        const __m128 vscale${ABC[N:N+4]} = _mm_loadu_ps((const float*) w + ${N});
        $for M in range(MR):
          vacc${M}x${ABC[N:N+4]} = _mm_mul_ps(vacc${M}x${ABC[N:N+4]}, vscale${ABC[N:N+4]});
      w = (const float*) w + ${NR};
    $for N in range(0, NR, 4):
      $for M in range(MR):
        vacc${M}x${ABC[N:N+4]} = _mm_min_ps(vacc${M}x${ABC[N:N+4]}, vmax);

    $for N in range(0, NR, 4):
      $for M in range(MR):
        vacc${M}x${ABC[N:N+4]} = _mm_max_ps(vacc${M}x${ABC[N:N+4]}, vmin);

    if XNN_LIKELY(nc >= ${NR}) {
      $for M in RANGE_MR:
        _mm_storeu_ps(c${M}, vacc${M}x${ABC[0:4]});
        $for N in range(4, NR, 4):
          _mm_storeu_ps(c${M} + ${N}, vacc${M}x${ABC[N:N+4]});
        c${M} = (float*) ((uintptr_t) c${M} + cn_stride);

      $for M in RANGE_MR:
        a${M} = (const float*) ((uintptr_t) a${M} - kc);

      nc -= ${NR};
    } else {
      $for LOG2N in reversed(range(NR.bit_length())):
        $if NR != 1 << LOG2N:
          if (nc & ${1 << LOG2N}) {
            $if LOG2N >= 2:
              $for M in RANGE_MR:
                _mm_storeu_ps(c${M}, vacc${M}x${ABC[0:4]});
                $for N in range(4, 1 << LOG2N, 4):
                  _mm_storeu_ps(c${M} + ${N}, vacc${M}x${ABC[N:N+4]});

              $for M in RANGE_MR:
                $for N in range(0, NR - (1 << LOG2N), 4):
                  vacc${M}x${ABC[N:N+4]} = vacc${M}x${ABC[N + (1 << LOG2N):N + (1 << LOG2N)+4]};

              $for M in RANGE_MR:
                c${M} += ${1 << LOG2N};
            $elif LOG2N == 1:
              $for M in RANGE_MR:
                _mm_storel_pi((__m64*) c${M}, vacc${M}x${ABC[0:4]});

              $for M in RANGE_MR:
                vacc${M}x${ABC[0:4]} = _mm_movehl_ps(vacc${M}x${ABC[0:4]}, vacc${M}x${ABC[0:4]});

              $for M in RANGE_MR:
                c${M} += 2;
            $elif LOG2N == 0:
              $for M in RANGE_MR:
                _mm_store_ss(c${M}, vacc${M}x${ABC[0:4]});
          }

      nc = 0;
    }
  } while (nc != 0);
}
