// Copyright 2024 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", "QD8_F16", "QD8_F32"]
#include <assert.h>

#include <immintrin.h>

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


$GFNI = 0
$DATATYPE_SPEC = {"QC8": "qs8_qc8w", "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" if REQUANTIZATION else "scalar"
$PARAMS_TYPE = {"QC8": "union xnn_qs8_qc8w_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", "QU8": "uint8_t"}[DATATYPE]
$_MM_MAX_EPX8 = "_mm_max_epu8" if DATATYPE == "QU8" else "_mm_max_epi8"
$_MM256_CVTXEPI32_EPI8 = "_mm256_cvtusepi32_epi8" if DATATYPE == "QU8" else "_mm256_cvtsepi32_epi8"
$_MM256_DPBUSD_EPI32 = "_mm256_dpbssd_epi32" if VARIANT == "AVXVNNIINT8" else "_mm256_dpbusd_avx_epi32" if AVX == 2 else "_mm256_dpbusd_epi32"
$ISA = "avxvnniint8" if VARIANT == "AVXVNNIINT8" else "avxvnni" if AVX == 2 else "avx256vnnigfni" if GFNI else "avx256vnni"
void xnn_${DATATYPE_SPEC}_igemm_minmax${REQUANTIZATION_SPEC}_ukernel_${MR}x8c8__${ISA}${"_gfni" if GFNI else ""}${"_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(kc % 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"]:
    $if VARIANT == "AVXVNNIINT8":
      const __m256i vinput_zero_point = _mm256_set1_epi32((int) quantization_params->zero_point);
    $else:
      const __m256i vinput_zero_point = _mm256_set1_epi32((int) quantization_params->zero_point);
    const __m256 vinput_inv_scale = _mm256_set1_ps(quantization_params->inv_scale);
    $if "F16" in DATATYPE:
      const __m256 voutput_min = _mm256_cvtph_ps(_mm_set1_epi16(*(const uint16_t*) &params->scalar.min));
      const __m256 voutput_max = _mm256_cvtph_ps(_mm_set1_epi16(*(const uint16_t*) &params->scalar.max));
    $else:
      const __m256 voutput_min = _mm256_set1_ps(params->scalar.min);
      const __m256 voutput_max = _mm256_set1_ps(params->scalar.max);
    // XNN_FORCE_REALIZATION(vinput_zero_point);
    // XNN_FORCE_REALIZATION(vinput_inv_scale);
    // XNN_FORCE_REALIZATION(voutput_min);
    // XNN_FORCE_REALIZATION(voutput_max);
    $if DATATYPE in ["QC4_F16", "QC4_F32"]:
      const __m256i vmask = _mm256_set1_epi8(0xF0);
      XNN_FORCE_REALIZATION(vmask);
      $if GFNI:
        const __m256i vshl4 = _mm256_set1_epi64(0x01020408);
        XNN_FORCE_REALIZATION(vshl4);
  $else:
    $if VARIANT != "AVXVNNIINT8":
      const __m256i vsign_mask = _mm256_set1_epi8(0x80);
      XNN_FORCE_REALIZATION(vsign_mask);
    $if DATATYPE != "QC8":
      const __m256 vscale = _mm256_load_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_epi32(params->${PARAMS_STRUCT}.output_zero_point);
    const __m128i voutput_min = _mm_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);
  do {
    $if DATATYPE in ["QD8_F16", "QD8_F32", "QC4_F16", "QC4_F32"]:
      const __m256i vksum01234567 = _mm256_load_si256(w);
      const __m256i vsum0x01234567 = _mm256_mullo_epi32(vksum01234567, vinput_zero_point);
      __m256i vacc0x0123 = _mm256_cvtepu32_epi64(_mm256_extracti128_si256(vsum0x01234567, 0));
      __m256i vacc0x4567 = _mm256_cvtepu32_epi64(_mm256_extracti128_si256(vsum0x01234567, 1));
    $else:
      __m256i vacc0x0123 = _mm256_cvtepu32_epi64(_mm_load_si128((const __m128i*) w));
      __m256i vacc0x4567 = _mm256_cvtepu32_epi64(_mm_load_si128((const __m128i*) ((const int32_t*) w + 4)));
    $for M in range(1, MR):
      __m256i vacc${M}x0123 = vacc0x0123;
      __m256i vacc${M}x4567 = vacc0x4567;
    $if MR < 3:
      $for M in range(MR):
        __m256i vacc1x${M}x0123 = _mm256_setzero_si256();
        __m256i vacc1x${M}x4567 = _mm256_setzero_si256();
    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 = kc;
      while (k >= 16 * sizeof(int8_t)) {
        $for M in range(MR):
          $if VARIANT == "AVXVNNIINT8" or DATATYPE in ["QD8_F16", "QD8_F32", "QC4_F16", "QC4_F32"]:
            const __m256i va${M}x01234567 = _mm256_set1_epi64x((int64_t) unaligned_load_u64(a${M}));
            const __m256i va${M}x89ABCDEF = _mm256_set1_epi64x((int64_t) unaligned_load_u64(a${M} + 8));
          $else:
            const __m256i va${M}x01234567 = _mm256_xor_si256(_mm256_set1_epi64x((int64_t) unaligned_load_u64(a${M})), vsign_mask);
            const __m256i va${M}x89ABCDEF = _mm256_xor_si256(_mm256_set1_epi64x((int64_t) unaligned_load_u64(a${M} + 8)), vsign_mask);
          a${M} += 16;

        $if DATATYPE in ["QC4_F16", "QC4_F32"]:
          const __m256i vbb01234567x01234567 = _mm256_load_si256(w);
          const __m256i vbb89ABCDEFx01234567 = _mm256_load_si256((const __m256i*) ((const ${XINT8_T}*) w + 32));
          $if GFNI:
            const __m256i vb01234567x0123 = _mm256_gf2p8affine_epi64_epi8(vbb01234567x01234567, vshl4, 0);
            const __m256i vb89ABCDEFx0123 = _mm256_gf2p8affine_epi64_epi8(vbb89ABCDEFx01234567, vshl4, 0);
            const __m256i vb01234567x4567 = _mm256_and_si256(vbb01234567x01234567, vvalue_mask);
            const __m256i vb89ABCDEFx4567 = _mm256_and_si256(vbb89ABCDEFx01234567, vvalue_mask);
          $else:
            const __m256i vbs01234567x0123 = _mm256_slli_epi32(vbb01234567x01234567, 4);
            const __m256i vbs89ABCDEFx0123 = _mm256_slli_epi32(vbb89ABCDEFx01234567, 4);
            const __m256i vb01234567x4567 = _mm256_and_si256(vbb01234567x01234567, vvalue_mask);
            const __m256i vb89ABCDEFx4567 = _mm256_and_si256(vbb89ABCDEFx01234567, vvalue_mask);
            const __m256i vb01234567x0123 = _mm256_and_si256(vbs01234567x0123, vvalue_mask);
            const __m256i vb89ABCDEFx0123 = _mm256_and_si256(vbs89ABCDEFx0123, vvalue_mask);
        $else:
          const __m256i vb01234567x0123 = _mm256_load_si256(w);
          const __m256i vb89ABCDEFx0123 = _mm256_load_si256((const __m256i*) ((const ${XINT8_T}*) w + 32));
          const __m256i vb01234567x4567 = _mm256_load_si256((const __m256i*) ((const ${XINT8_T}*) w + 64));
          const __m256i vb89ABCDEFx4567 = _mm256_load_si256((const __m256i*) ((const ${XINT8_T}*) w + 96));
          $if PREFETCH:
            xnn_prefetch_to_l1((const ${XINT8_T}*) w + 896);

        $for M in range(MR):
          vacc${M}x0123 = ${_MM256_DPBUSD_EPI32}(vacc${M}x0123, va${M}x01234567, vb01234567x0123);
          vacc${M}x4567 = ${_MM256_DPBUSD_EPI32}(vacc${M}x4567, va${M}x01234567, vb89ABCDEFx0123);
        $if PREFETCH:
          xnn_prefetch_to_l1((const ${XINT8_T}*) w + 960);
        $for M in range(MR):
          $if MR < 3:
            vacc1x${M}x0123 = ${_MM256_DPBUSD_EPI32}(vacc1x${M}x0123, va${M}x89ABCDEF, vb01234567x4567);
            vacc1x${M}x4567 = ${_MM256_DPBUSD_EPI32}(vacc1x${M}x4567, va${M}x89ABCDEF, vb89ABCDEFx4567);
          $else:
            vacc${M}x0123 = ${_MM256_DPBUSD_EPI32}(vacc${M}x0123, va${M}x89ABCDEF, vb01234567x4567);
            vacc${M}x4567 = ${_MM256_DPBUSD_EPI32}(vacc${M}x4567, va${M}x89ABCDEF, vb89ABCDEFx4567);

        $if DATATYPE in ["QC4_F16", "QC4_F32"]:
          w = (const ${XINT8_T}*) w + 64;
        $else:
          w = (const ${XINT8_T}*) w + 128;
        k -= 16 * sizeof(${XINT8_T});
      }

      if (k != 0) {
        $for M in range(MR):
          $if VARIANT == "AVXVNNIINT8" or DATATYPE in ["QD8_F16", "QD8_F32", "QC4_F16", "QC4_F32"]:
            const __m256i va${M}x01234567 = _mm256_set1_epi64x((int64_t) unaligned_load_u64(a${M}));
          $else:
            const __m256i va${M}x01234567 = _mm256_xor_si256(_mm256_set1_epi64x((int64_t) unaligned_load_u64(a${M})), vsign_mask);
          a${M} += 8;

        $if DATATYPE in ["QC4_F16", "QC4_F32"]:
          const __m256i vbb01234567x01234567 = _mm256_load_si256(w);
          const __m256i vbb89ABCDEFx01234567 = _mm256_load_si256((const __m256i*) ((const ${XINT8_T}*) w + 32));
          $if GFNI:
            const __m256i vb01234567x0123 = _mm256_gf2p8affine_epi64_epi8(vbb01234567x01234567, vshl4, 0);
            const __m256i vb89ABCDEFx0123 = _mm256_gf2p8affine_epi64_epi8(vbb89ABCDEFx01234567, vshl4, 0);
          $else:
            const __m256i vb01234567x0123 = _mm256_slli_epi32(vbb01234567x01234567, 4);
            const __m256i vb89ABCDEFx0123 = _mm256_slli_epi32(vbb89ABCDEFx01234567, 4);
        $else:
          const __m256i vb01234567x0123 = _mm256_load_si256(w);
          const __m256i vb89ABCDEFx0123 = _mm256_load_si256((const __m256i*) ((const ${XINT8_T}*) w + 32));

        $for M in range(MR):
          vacc${M}x0123 = ${_MM256_DPBUSD_EPI32}(vacc${M}x0123, va${M}x01234567, vb01234567x0123);
          vacc${M}x4567 = ${_MM256_DPBUSD_EPI32}(vacc${M}x4567, va${M}x01234567, vb89ABCDEFx0123);
        $if PREFETCH:
          xnn_prefetch_to_l1((const ${XINT8_T}*) w + 960);

        w = (const ${XINT8_T}*) w + 64;
        k -= 8 * sizeof(${XINT8_T});
      }

      p -= ${MR} * sizeof(void*);
    } while (p != 0);

    $if MR < 3:
      $for M in range(MR):
        vacc${M}x0123 = _mm256_add_epi32(vacc${M}x0123, vacc1x${M}x0123);
        vacc${M}x4567 = _mm256_add_epi32(vacc${M}x4567, vacc1x${M}x4567);

    // Add adjacent pairs
    $for M in range(MR):
      const __m256i vsum${M}x02134657 = _mm256_hadd_epi32(vacc${M}x0123, vacc${M}x4567);
      __m256i vacc${M}x01234567 = _mm256_permute4x64_epi64(vsum${M}x02134657, _MM_SHUFFLE(3, 1, 2, 0));

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

    $if DATATYPE in ["QD8_F16", "QD8_F32", "QC4_F16", "QC4_F32"]:
      $for M in range(MR):
        vout${M}x01234567 = _mm256_mul_ps(vout${M}x01234567, vinput_inv_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);

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

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

      $if DATATYPE in ["QC4_F16", "QD8_F16"]:
        $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);
                c${M} += 4;
                vfp16out${M}x01234567 = _mm_unpackhi_epi64(vfp16out${M}x01234567, vfp16out${M}x01234567);
            }
            if (nc & 2) {
              $for M in reversed(range(MR)):
                _mm_storeu_si32(c${M}, vfp16out${M}x01234567);
                vfp16out${M}x01234567 = _mm_srli_epi64(vfp16out${M}x01234567, 32);
                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:
        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);
                c${M} += 4;
                vout${M}x0123 = _mm256_extractf128_ps(vout${M}x01234567, 1);
            }
            if (nc & 2) {
              $for M in reversed(range(MR)):
                _mm_storel_pi((__m64*) c${M}, vout${M}x0123);
                c${M} += 2;
                vout${M}x0123 = _mm_movehl_ps(vout${M}x0123, vout${M}x0123);
            }
            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:
      $if DATATYPE == "QC8":
        const __m256 vscale01234567 = _mm256_load_ps(w);
        w = (const float*) w + 8;
        $for M in range(MR):
          vout${M}x01234567 = _mm256_mul_ps(vout${M}x01234567, vscale01234567);
      $else:
        $for M in range(MR):
          vout${M}x01234567 = _mm256_mul_ps(vout${M}x01234567, vscale);

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

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

      $for M in range(MR):
        vacc${M}x01234567 = _mm256_add_epi32(vacc${M}x01234567, voutput_zero_point);

      $if AVX == 2:
        $for M in range(MR):
          vacc${M}x01234567 = _mm256_packs_epi32(vacc${M}x01234567, _mm256_castsi128_si256(_mm256_extracti128_si256(vacc${M}x01234567, 1)));
          __m128i voutb${M}x01234567 = _mm256_castsi256_si128(_mm256_packs_epi16(vacc${M}x01234567, vacc${M}x01234567));
      $else:
        $for M in range(MR):
          __m128i voutb${M}x01234567 = ${_MM256_CVTXEPI32_EPI8}(vacc${M}x01234567);

      $for M in range(MR):
        voutb${M}x01234567 = ${_MM_MAX_EPX8}(voutb${M}x01234567, voutput_min);

      if (nc >= 8) {
        $for M in reversed(range(MR)):
          _mm_storel_epi64((__m128i*) c${M}, voutb${M}x01234567);
          c${M} = (${OUT_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_storeu_si32(c${M}, voutb${M}x01234567);
              c${M} += 4;
            $for M in reversed(range(MR)):
              voutb${M}x01234567 = _mm_srli_epi64(voutb${M}x01234567, 32);
          }
          if (nc & 2) {
            $for M in reversed(range(MR)):
              unaligned_store_u16(c${M}, (uint16_t) _mm_extract_epi16(voutb${M}x01234567, 0));
              c${M} += 2;
            $for M in reversed(range(MR)):
              voutb${M}x01234567 = _mm_srli_epi32(voutb${M}x01234567, 16);
          }
          if (nc & 1) {
            $for M in reversed(range(MR)):
              *c${M} = (${XINT8_T}) _mm_extract_epi8(voutb${M}x01234567, 0);
          }
        $else:
          // Prepare mask for valid 8-bit elements (depends on nc).
          const __mmask16 vmask = _cvtu32_mask16((UINT32_C(1) << nc) - UINT32_C(1));
          $for M in reversed(range(MR)):
            _mm_mask_storeu_epi8(c${M}, vmask, voutb${M}x01234567);
        nc = 0;
      }
  } while (nc != 0);
}
