// Copyright 2020 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.

$ABC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
$assert REQUANTIZATION == "FP32" or not REQUANTIZATION
$assert DATATYPE in ["QC8", "QS8", "QU8", "QD8_F16", "QD8_F32", "QC4_F16", "QC4_F32"]
$assert DATATYPE != "QC8" or REQUANTIZATION == "FP32"
#include <assert.h>

#include <immintrin.h>

#include "xnnpack/igemm.h"
#include "xnnpack/intrinsics-polyfill.h"
#include "xnnpack/math.h"
#include "xnnpack/unaligned.h"
$if PREFETCH:
  #include "xnnpack/prefetch.h"


$DATATYPE_SPEC = {"QC8": "qs8_qc8w", "QS8": "qs8", "QU8": "qu8", "QD8_F16" : "qd8_f16_qc8w", "QD8_F32": "qd8_f32_qc8w", "QC4_F16": "qd8_f16_qc4w", "QC4_F32": "qd8_f32_qc4w"}[DATATYPE]
$REQUANTIZATION_SPEC = "_" + REQUANTIZATION.lower() if REQUANTIZATION else ""
$PARAMS_STRUCT = REQUANTIZATION.lower() + "_scalar"
$PARAMS_TYPE = {"QC8": "union xnn_qs8_qc8w_conv_minmax_params", "QS8": "union xnn_qs8_conv_minmax_params", "QU8": "union xnn_qu8_conv_minmax_params", "QD8_F16": "union xnn_f16_minmax_params", "QD8_F32": "union xnn_f32_minmax_params", "QC4_F16": "struct xnn_f16_qc4w_minmax_params", "QC4_F32": "struct xnn_f32_qc4w_minmax_params"}[DATATYPE]
$XINT8_T = "uint8_t" if DATATYPE == "QU8" else "int8_t"
$OUT_T = {"QC8": "int8_t", "QD8_F16": "xnn_float16", "QD8_F32": "float", "QC4_F16": "xnn_float16", "QC4_F32": "float", "QS8": "int8_t", "QU8": "uint8_t"}[DATATYPE]
$ISA = "avx2" if AVX == 2 else "avx256skx"
void xnn_${DATATYPE_SPEC}_igemm_minmax${REQUANTIZATION_SPEC}_ukernel_${MR}x8c8__${ISA}${"_prfm" if PREFETCH else ""}(
    size_t mr,
    size_t nc,
    size_t kc,
    size_t ks,
    const ${XINT8_T}** restrict a,
    const void* restrict w,
    ${OUT_T}* restrict c,
    size_t cm_stride,
    size_t cn_stride,
    size_t a_offset,
    const ${XINT8_T}* zero,
    $if DATATYPE in ["QD8_F16", "QD8_F32", "QC4_F16", "QC4_F32"]:
      const int8_t* zero_data,
      const ${PARAMS_TYPE} params[restrict XNN_MIN_ELEMENTS(1)],
      const struct xnn_qd8_quantization_params quantization_params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS
    $else:
      const ${PARAMS_TYPE} params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS
{
  assert(mr != 0);
  assert(mr <= ${MR});
  assert(nc != 0);
  assert(kc != 0);
  assert(ks != 0);
  assert(ks % (${MR} * sizeof(void*)) == 0);
  assert(a_offset % sizeof(${XINT8_T}) == 0);
  assert(a != NULL);
  assert(w != NULL);
  assert(c != NULL);

  kc = round_up_po2(kc, 8 * sizeof(${XINT8_T}));
  $if DATATYPE in ["QD8_F16", "QC4_F16"]:
    uint16_t* c0 = (uint16_t*) c;
  $else:
    ${OUT_T}* c0 = c;
  $for M in range(1, MR):
    $if DATATYPE in ["QD8_F16", "QC4_F16"]:
      uint16_t* c${M} = (uint16_t*) ((uintptr_t) c${M-1} + cm_stride);
    $else:
      ${OUT_T}* c${M} = (${OUT_T}*) ((uintptr_t) c${M-1} + cm_stride);
    $if M % 2 == 0:
      if XNN_UNPREDICTABLE(mr <= ${M}) {
        c${M} = c${M-1};
      }
    $elif M + 1 == MR:
      if XNN_UNPREDICTABLE(mr != ${M+1}) {
        c${M} = c${M-1};
      }
    $else:
      if XNN_UNPREDICTABLE(mr < ${M+1}) {
        c${M} = c${M-1};
      }

  $if DATATYPE in ["QD8_F16", "QD8_F32", "QC4_F16", "QC4_F32"]:
    const __m256i vinput_zero_point = _mm256_set1_epi32((int) quantization_params->zero_point);
    const __m256 vinput_scale = _mm256_broadcast_ss(&quantization_params->inv_scale);
    $if "F16" in DATATYPE:
      const __m256 vmin = _mm256_cvtph_ps(_mm_set1_epi16(*(const uint16_t*) &params->scalar.min));
      const __m256 vmax = _mm256_cvtph_ps(_mm_set1_epi16(*(const uint16_t*) &params->scalar.max));
    $else:
      const __m256 vmin = _mm256_set1_ps(params->scalar.min);
      const __m256 vmax = _mm256_set1_ps(params->scalar.max);
    // XNN_FORCE_REALIZATION(vinput_zero_point);
    // XNN_FORCE_REALIZATION(vinput_scale);
    // XNN_FORCE_REALIZATION(vmin);
    // XNN_FORCE_REALIZATION(vmax);
  $else:
    $if DATATYPE != "QC8":
      const __m256 vscale = _mm256_set1_ps(params->${PARAMS_STRUCT}.scale);
      // XNN_FORCE_REALIZATION(vscale);
    const __m256 voutput_max_less_zero_point = _mm256_set1_ps((int32_t) params->${PARAMS_STRUCT}.output_max - (int32_t) params->${PARAMS_STRUCT}.output_zero_point);
    const __m256i voutput_zero_point = _mm256_set1_epi16(params->${PARAMS_STRUCT}.output_zero_point);
    const __m256i voutput_min = _mm256_set1_epi8(params->${PARAMS_STRUCT}.output_min);
    // XNN_FORCE_REALIZATION(voutput_max_less_zero_point);
    // XNN_FORCE_REALIZATION(voutput_zero_point);
    // XNN_FORCE_REALIZATION(voutput_min);

  $if DATATYPE == "QU8":
    const __m256i vb_zero_point = _mm256_set1_epi16(params->${PARAMS_STRUCT}.kernel_zero_point);
    XNN_FORCE_REALIZATION(vb_zero_point);
  do {
    $if DATATYPE in ["QD8_F16", "QD8_F32", "QC4_F16", "QC4_F32"]:
      $for N in range(0, 8, 2):
        const __m128i vinit${ABC[N:N+1]} = _mm_cvtsi32_si128(((const int*) w)[${ABC[N:N+1]}]);
        const __m128i vinit${ABC[N+1:N+2]} = _mm_cvtsi32_si128(((const int*) w)[${ABC[N+1:N+2]}]);
        const __m256i vinit${ABC[N:N+2]} = _mm256_inserti128_si256(_mm256_castsi128_si256(vinit${ABC[N:N+1]}), vinit${ABC[N+1:N+2]}, 1);
      $for N in range(0, 8, 2):
        __m256i vacc0x${ABC[N:N+2]} = _mm256_mullo_epi32(vinit${ABC[N:N+2]}, vinput_zero_point);
      $for M in range(1, MR):
        $for N in range(0, 8, 2):
          __m256i vacc${M}x${ABC[N:N+2]} = vacc0x${ABC[N:N+2]};
    $else:
      $for N in range(0, 8, 2):
        const __m128i vbias0x${N} = _mm_cvtsi32_si128(((const int*) w)[${N}]);
        const __m128i vbias0x${N+1} = _mm_cvtsi32_si128(((const int*) w)[${N+1}]);
        __m256i vacc0x${N}${N+1} = _mm256_inserti128_si256(_mm256_castsi128_si256(vbias0x${N}), vbias0x${N+1}, 1);
      $for M in range(1, MR):
        $for N in range(0, 8, 2):
          __m256i vacc${M}x${N}${N+1} = vacc0x${N}${N+1};
    w = (const int32_t*) w + 8;

    size_t p = ks;
    do {
      $for M in range(MR):
        const ${XINT8_T}* restrict a${M} = a[${M}];
        if XNN_UNPREDICTABLE(a${M} != zero) {
          a${M} = (const ${XINT8_T}*) ((uintptr_t) a${M} + a_offset);
        $if DATATYPE in ["QD8_F16", "QD8_F32", "QC4_F16", "QC4_F32"]:
          } else {
            a${M} = zero_data;
        }
      a += ${MR};

      size_t k = 0;
      while (k < kc) {
        $for M in range(MR):
          const __m128i va${M} = _mm_broadcastq_epi64(_mm_loadl_epi64((const __m128i*) a${M}));
          $if DATATYPE == "QU8":
            const __m256i vxa${M} = _mm256_cvtepu8_epi16(va${M});
          $else:
            const __m256i vxa${M} = _mm256_cvtepi8_epi16(va${M});
          a${M} += 8;

        $for N in range(0, 8, 2):
          $if N == 0:
            const __m128i vb${N}${N+1} = _mm_load_si128((const __m128i*) w);
          $else:
            const __m128i vb${N}${N+1} = _mm_load_si128((const __m128i*) ((const ${XINT8_T}*) w + ${N * 8}));
          $if DATATYPE == "QU8":
            const __m256i vxb${N}${N+1} = _mm256_sub_epi16(_mm256_cvtepu8_epi16(vb${N}${N+1}), vb_zero_point);
          $else:
            const __m256i vxb${N}${N+1} = _mm256_cvtepi8_epi16(vb${N}${N+1});

          $for M in range(MR):
            vacc${M}x${N}${N+1} = _mm256_add_epi32(vacc${M}x${N}${N+1}, _mm256_madd_epi16(vxa${M}, vxb${N}${N+1}));

        w = (const void*) ((const ${XINT8_T}*) w + 64);
        k += 8 * sizeof(${XINT8_T});
      }
      p -= ${MR} * sizeof(void*);
    } while (p != 0);

    $for M in range(MR):
      const __m256i vacc${M}x0213 = _mm256_hadd_epi32(vacc${M}x01, vacc${M}x23);
      const __m256i vacc${M}x4657 = _mm256_hadd_epi32(vacc${M}x45, vacc${M}x67);

    $for M in range(MR):
      const __m256i vacc${M}x02461357 = _mm256_hadd_epi32(vacc${M}x0213, vacc${M}x4657);

    const __m256i vpermute_mask = _mm256_set_epi32(7, 3, 6, 2, 5, 1, 4, 0);
    $for M in range(MR):
      __m256i vacc${M}x01234567 = _mm256_permutevar8x32_epi32(vacc${M}x02461357, vpermute_mask);

    $if DATATYPE in ["QD8_F16", "QD8_F32", "QC4_F16", "QC4_F32"]:
      $for M in range(MR):
        __m256 vout${M}x01234567 = _mm256_cvtepi32_ps(vacc${M}x01234567);

      $for M in range(MR):
        vout${M}x01234567 = _mm256_mul_ps(vout${M}x01234567, vinput_scale);

      const __m256 vfilter_output_scale01234567 = _mm256_load_ps((const float*) w);
      const __m256 vbias01234567 = _mm256_load_ps((const float*) w + 8);
      w = (const float*) w + 16;
      $for M in range(MR):
        vout${M}x01234567 = _mm256_fmadd_ps(vout${M}x01234567, vfilter_output_scale01234567, vbias01234567);

      $if DATATYPE in ["QC4_F16", "QD8_F16"]:
        $for M in reversed(range(MR)):
          vout${M}x01234567 = _mm256_max_ps(vout${M}x01234567, vmin);

        $for M in reversed(range(MR)):
          vout${M}x01234567 = _mm256_min_ps(vout${M}x01234567, vmax);
        $for M in reversed(range(MR)):
          __m128i vfp16out${M}x01234567 = _mm256_cvtps_ph(vout${M}x01234567, _MM_FROUND_TO_NEAREST_INT);
        if XNN_LIKELY(nc >= 8) {
          $for M in reversed(range(MR)):
            _mm_storeu_si128((__m128i*) c${M}, vfp16out${M}x01234567);
            c${M} = (uint16_t*) ((uintptr_t) c${M} + cn_stride);

          a = (const ${XINT8_T}**restrict) ((uintptr_t) a - ks);
          nc -= 8;
        } else {
          $if AVX == 2:
            if (nc & 4) {
              $for M in reversed(range(MR)):
                _mm_storel_epi64((__m128i*) c${M}, vfp16out${M}x01234567);

              $for M in reversed(range(MR)):
                vfp16out${M}x01234567 = _mm_unpackhi_epi64(vfp16out${M}x01234567, vfp16out${M}x01234567);

              $for M in reversed(range(MR)):
                c${M} += 4;
            }
            if (nc & 2) {
              $for M in reversed(range(MR)):
                _mm_storeu_si32(c${M}, vfp16out${M}x01234567);

              $for M in reversed(range(MR)):
                vfp16out${M}x01234567 = _mm_srli_epi64(vfp16out${M}x01234567, 32);

              $for M in reversed(range(MR)):
                c${M} += 2;
            }
            if (nc & 1) {
              $for M in reversed(range(MR)):
                *c${M} = (uint16_t) _mm_extract_epi16(vfp16out${M}x01234567, 0);
            }
          $else:
            // Prepare mask for valid 16-bit elements (depends on nc).
            const __mmask8 vmask = _cvtu32_mask8((UINT32_C(1) << nc) - 1);
            $for M in reversed(range(MR)):
              _mm_mask_storeu_epi16(c${M}, vmask, vfp16out${M}x01234567);
          nc = 0;
        }
      $else:
        $for M in range(MR):
          vout${M}x01234567 = _mm256_max_ps(vout${M}x01234567, vmin);

        $for M in range(MR):
          vout${M}x01234567 = _mm256_min_ps(vout${M}x01234567, vmax);

        if XNN_LIKELY(nc >= 8) {
          $for M in reversed(range(MR)):
            _mm256_storeu_ps(c${M}, vout${M}x01234567);
            c${M} = (float*) ((uintptr_t) c${M} + cn_stride);

          a = (const ${XINT8_T}**restrict) ((uintptr_t) a - ks);
          nc -= 8;
        } else {
          $if AVX == 2:
            $for M in reversed(range(MR)):
              __m128 vout${M}x0123 = _mm256_castps256_ps128(vout${M}x01234567);
            if (nc & 4) {
              $for M in reversed(range(MR)):
                _mm_storeu_ps(c${M}, vout${M}x0123);

              $for M in reversed(range(MR)):
                vout${M}x0123 = _mm256_extractf128_ps(vout${M}x01234567, 1);

              $for M in reversed(range(MR)):
                c${M} += 4;
            }
            if (nc & 2) {
              $for M in reversed(range(MR)):
                _mm_storel_pi((__m64*) c${M}, vout${M}x0123);

              $for M in reversed(range(MR)):
                vout${M}x0123 = _mm_movehl_ps(vout${M}x0123, vout${M}x0123);

              $for M in reversed(range(MR)):
                c${M} += 2;
            }
            if (nc & 1) {
              $for M in reversed(range(MR)):
                _mm_store_ss(c${M}, vout${M}x0123);
            }
          $else:
            // Prepare mask for valid 32-bit elements (depends on nc).
            const __mmask8 vmask = _cvtu32_mask8((UINT32_C(1) << nc) - 1);
            $for M in reversed(range(MR)):
              _mm256_mask_storeu_ps(c${M}, vmask, vout${M}x01234567);
          nc = 0;
        }
    $else:
      $for M in range(MR):
        __m256 vscaled${M}x01234567 = _mm256_cvtepi32_ps(vacc${M}x01234567);

      $if DATATYPE == "QC8":
        const __m256 vscale01234567 = _mm256_load_ps(w);
        w = (const void*) ((const float*) w + 8);
        $for M in range(MR):
          vscaled${M}x01234567 = _mm256_mul_ps(vscaled${M}x01234567, vscale01234567);
      $else:
        $for M in range(MR):
          vscaled${M}x01234567 = _mm256_mul_ps(vscaled${M}x01234567, vscale);

      $for M in range(MR):
        vscaled${M}x01234567 = _mm256_min_ps(vscaled${M}x01234567, voutput_max_less_zero_point);

      $for M in range(MR):
        vacc${M}x01234567 = _mm256_cvtps_epi32(vscaled${M}x01234567);

      $for M in range(0, MR, 2):
        __m256i vacc${M}${min(M+1, MR-1)}x01234567 = _mm256_adds_epi16(_mm256_packs_epi32(vacc${M}x01234567, vacc${min(M+1, MR-1)}x01234567), voutput_zero_point);

      $for M in range(0, MR, 2):
        vacc${M}${min(M+1, MR-1)}x01234567 = _mm256_permute4x64_epi64(vacc${M}${min(M+1, MR-1)}x01234567, _MM_SHUFFLE(3, 1, 2, 0));

      $if DATATYPE == "QU8":
        $if MR > 2:
          __m256i vout = _mm256_packus_epi16(vacc0${min(1, MR-1)}x01234567, vacc${min(2, MR-1)}${min(3, MR-1)}x01234567);
        $else:
          __m256i vout = _mm256_packus_epi16(vacc0${min(1, MR-1)}x01234567, vacc0${min(1, MR-1)}x01234567);

        vout = _mm256_max_epu8(vout, voutput_min);
      $else:
        $if MR > 2:
          __m256i vout = _mm256_packs_epi16(vacc0${min(1, MR-1)}x01234567, vacc${min(2, MR-1)}${min(3, MR-1)}x01234567);
        $else:
          __m256i vout = _mm256_packs_epi16(vacc0${min(1, MR-1)}x01234567, vacc0${min(1, MR-1)}x01234567);

        vout = _mm256_max_epi8(vout, voutput_min);

      __m128i vout_lo = _mm256_castsi256_si128(vout);
      __m128i vout_hi = _mm256_extracti128_si256(vout, 1);

      if (nc >= 8) {
        $if MR > 3:
          _mm_storeh_pi((__m64*) c3, _mm_castsi128_ps(vout_hi));
        $if MR > 2:
          _mm_storeh_pi((__m64*) c2, _mm_castsi128_ps(vout_lo));
        $if MR > 1:
          _mm_storel_epi64((__m128i*) c1, vout_hi);
        _mm_storel_epi64((__m128i*) c0, vout_lo);

        $for M in reversed(range(MR)):
          c${M} = (${XINT8_T}*) ((uintptr_t) c${M} + cn_stride);

        a = (const ${XINT8_T}**restrict) ((uintptr_t) a - ks);

        nc -= 8;
      } else {
        if (nc & 4) {
          $if MR > 3:
            unaligned_store_u32(c3, (uint32_t) _mm_extract_epi32(vout_hi, 2));
          $if MR > 2:
            unaligned_store_u32(c2, (uint32_t) _mm_extract_epi32(vout_lo, 2));
          $if MR > 1:
            _mm_storeu_si32(c1, vout_hi);
          _mm_storeu_si32(c0, vout_lo);

          $for M in reversed(range(MR)):
            c${M} += 4;

          vout_lo = _mm_srli_epi64(vout_lo, 32);
          vout_hi = _mm_srli_epi64(vout_hi, 32);
        }
        if (nc & 2) {
          $if MR > 3:
            unaligned_store_u16(c3, (uint16_t) _mm_extract_epi16(vout_hi, 4));
          $if MR > 2:
            unaligned_store_u16(c2, (uint16_t) _mm_extract_epi16(vout_lo, 4));
          $if MR > 1:
            unaligned_store_u16(c1, (uint16_t) _mm_extract_epi16(vout_hi, 0));
          unaligned_store_u16(c0, (uint16_t) _mm_extract_epi16(vout_lo, 0));

          $for M in reversed(range(MR)):
            c${M} += 2;

          vout_lo = _mm_srli_epi32(vout_lo, 16);
          vout_hi = _mm_srli_epi32(vout_hi, 16);
        }
        if (nc & 1) {
          $if MR > 3:
            *c3 = (${XINT8_T}) _mm_extract_epi8(vout_hi, 8);
          $if MR > 2:
            *c2 = (${XINT8_T}) _mm_extract_epi8(vout_lo, 8);
          $if MR > 1:
            *c1 = (${XINT8_T}) _mm_extract_epi8(vout_hi, 0);
          *c0 = (${XINT8_T}) _mm_extract_epi8(vout_lo, 0);
        }

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