// 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"
$assert DATATYPE in ["QC8", "QS8", "QU8"]
$assert CHANNEL_TILE % 8 == 0
$assert CHANNEL_TILE >= 8
$assert KERNEL_TILE >= 2
#include <assert.h>

#include <immintrin.h>

#include <xnnpack/dwconv.h>
#include <xnnpack/unaligned.h>


$PARAMS_STRUCT = REQUANTIZATION.lower() + "_avx2"
$PARAMS_UNION = "xnn_%s_conv_minmax_params" % DATATYPE.lower()
$XINT8_T = "uint8_t" if DATATYPE == "QU8" else "int8_t"
$_MM256_CVTEPX8_EPI32 = "_mm256_cvtepu8_epi32" if DATATYPE == "QU8" else "_mm256_cvtepi8_epi32"
$_MM_PACKXS_EPI16 = "_mm_packus_epi16" if DATATYPE == "QU8" else "_mm_packs_epi16"
$_MM_MIN_EPX8 = "_mm_min_epu8" if DATATYPE == "QU8" else "_mm_min_epi8"
$_MM_MAX_EPX8 = "_mm_max_epu8" if DATATYPE == "QU8" else "_mm_max_epi8"
void xnn_${DATATYPE.lower()}_dwconv_minmax_${REQUANTIZATION.lower()}_ukernel_up${CHANNEL_TILE}x${KERNEL_TILE}__avx2_mul32(
    size_t channels,
    size_t output_width,
    const ${XINT8_T}** input,
    const void* weights,
    ${XINT8_T}* output,
    size_t input_stride,
    size_t output_increment,
    size_t input_offset,
    const ${XINT8_T}* zero,
    const union ${PARAMS_UNION} params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS
{
  assert(channels != 0);
  assert(output_width != 0);

  $if DATATYPE == "QU8":
    const __m256i vk_zero_point = _mm256_cvtepu16_epi32(_mm_load_si128((const __m128i*) params->${PARAMS_STRUCT}.kernel_zero_point));
  do {
    $for K in range(KERNEL_TILE):
      const ${XINT8_T}* i${K} = input[${K}];
      assert(i${K} != NULL);
      if XNN_UNPREDICTABLE(i${K} != zero) {
        i${K} = (const ${XINT8_T}*) ((uintptr_t) i${K} + input_offset);
      }
    input = (const ${XINT8_T}**) ((uintptr_t) input + input_stride);

    size_t c = channels;
    const void* w = weights;
    for (; c >= ${CHANNEL_TILE}; c -= ${CHANNEL_TILE}) {
      __m256i vacc${ABC[0:8]} = _mm256_loadu_si256((const __m256i*) w);
      $for C in range(8, CHANNEL_TILE, 8):
        __m256i vacc${ABC[C:C+8]} = _mm256_loadu_si256((const __m256i*) ((const int32_t*) w + ${C}));

      $for K in range(KERNEL_TILE):

        $for C in range(0, CHANNEL_TILE, 8):
          $if C == 0:
            const __m256i vi${K}x${ABC[0:8]} = ${_MM256_CVTEPX8_EPI32}(_mm_loadl_epi64((const __m128i*) i${K}));
          $else:
            const __m256i vi${K}x${ABC[C:C+8]} = ${_MM256_CVTEPX8_EPI32}(_mm_loadl_epi64((const __m128i*) (i${K} + ${C})));
          $if DATATYPE == "QU8":
            const __m256i vk${K}x${ABC[C:C+8]} = _mm256_sub_epi32(_mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*) ((uintptr_t) w + ${CHANNEL_TILE} * sizeof(int32_t) + ${K * CHANNEL_TILE + C} * sizeof(${XINT8_T})))), vk_zero_point);
          $else:
            const __m256i vk${K}x${ABC[C:C+8]} = _mm256_cvtepi8_epi32(_mm_loadl_epi64((const __m128i*) ((uintptr_t) w + ${CHANNEL_TILE} * sizeof(int32_t) + ${K * CHANNEL_TILE + C} * sizeof(${XINT8_T}))));
        i${K} += ${CHANNEL_TILE};

        $for C in range(0, CHANNEL_TILE, 8):
          vacc${ABC[C:C+8]} = _mm256_add_epi32(vacc${ABC[C:C+8]}, _mm256_mullo_epi32(vi${K}x${ABC[C:C+8]}, vk${K}x${ABC[C:C+8]}));

      w = (const void*) ((uintptr_t) w + ${CHANNEL_TILE} * sizeof(int32_t) + ${KERNEL_TILE * CHANNEL_TILE} * sizeof(${XINT8_T}));

      $for C in range(0, CHANNEL_TILE, 8):
        __m256 vscaled${ABC[C:C+8]} = _mm256_cvtepi32_ps(vacc${ABC[C:C+8]});

      $if DATATYPE == "QC8":
        const __m256 vscale${ABC[0:8]} = _mm256_loadu_ps((const float*) w);
        $for C in range(8, CHANNEL_TILE, 8):
          const __m256 vscale${ABC[C:C+8]} = _mm256_loadu_ps((const float*) w + ${C});
        w = (const void*) ((const float*) w + ${CHANNEL_TILE});
        $for C in range(0, CHANNEL_TILE, 8):
          vscaled${ABC[C:C+8]} = _mm256_mul_ps(vscaled${ABC[C:C+8]}, vscale${ABC[C:C+8]});
      $else:
        const __m256 vscale = _mm256_load_ps(params->fp32_avx2.scale);
        $for C in range(0, CHANNEL_TILE, 8):
          vscaled${ABC[C:C+8]} = _mm256_mul_ps(vscaled${ABC[C:C+8]}, vscale);

      const __m256 voutput_max_less_zero_point = _mm256_load_ps(params->${PARAMS_STRUCT}.output_max_less_zero_point);
      $for C in range(0, CHANNEL_TILE, 8):
        vscaled${ABC[C:C+8]} = _mm256_min_ps(vscaled${ABC[C:C+8]}, voutput_max_less_zero_point);

      $for C in range(0, CHANNEL_TILE, 8):
        vacc${ABC[C:C+8]} = _mm256_cvtps_epi32(vscaled${ABC[C:C+8]});

      $if CHANNEL_TILE > 8:
        const __m256i voutput_zero_point = _mm256_load_si256((const __m256i*) params->${PARAMS_STRUCT}.output_zero_point);
      $else:
        const __m128i voutput_zero_point = _mm_load_si128((const __m128i*) params->${PARAMS_STRUCT}.output_zero_point);
      $for C in range(0, CHANNEL_TILE, 16):
        $if C + 8 < CHANNEL_TILE:
          __m256i vout${ABC[C:C+4]}${ABC[C+8:C+12]}${ABC[C+4:C+8]}${ABC[C+12:C+16]} = _mm256_adds_epi16(_mm256_packs_epi32(vacc${ABC[C:C+8]}, vacc${ABC[C+8:C+16]}), voutput_zero_point);
        $elif CHANNEL_TILE > 8:
          __m128i vout${ABC[C:C+8]} = _mm_adds_epi16(_mm_packs_epi32(_mm256_castsi256_si128(vacc${ABC[C:C+8]}), _mm256_extracti128_si256(vacc${ABC[C:C+8]}, 1)), _mm256_castsi256_si128(voutput_zero_point));
        $else:
          __m128i vout${ABC[C:C+8]} = _mm_adds_epi16(_mm_packs_epi32(_mm256_castsi256_si128(vacc${ABC[C:C+8]}), _mm256_extracti128_si256(vacc${ABC[C:C+8]}, 1)), voutput_zero_point);

      $for C in range(0, CHANNEL_TILE, 16):
        $if C + 8 < CHANNEL_TILE:
          __m128i vout${ABC[C:C+16]} = _mm_shuffle_epi32(${_MM_PACKXS_EPI16}(_mm256_castsi256_si128(vout${ABC[C:C+4]}${ABC[C+8:C+12]}${ABC[C+4:C+8]}${ABC[C+12:C+16]}), _mm256_extracti128_si256(vout${ABC[C:C+4]}${ABC[C+8:C+12]}${ABC[C+4:C+8]}${ABC[C+12:C+16]}, 1)), _MM_SHUFFLE(3, 1, 2, 0));
        $else:
          __m128i vout${ABC[C:C+8]}${ABC[C:C+8]} = ${_MM_PACKXS_EPI16}(vout${ABC[C:C+8]}, vout${ABC[C:C+8]});

      const __m128i voutput_min = _mm_load_si128((const __m128i*) params->${PARAMS_STRUCT}.output_min);
      $for C in range(0, CHANNEL_TILE, 16):
        $if C + 8 < CHANNEL_TILE:
          vout${ABC[C:C+16]} = ${_MM_MAX_EPX8}(vout${ABC[C:C+16]}, voutput_min);
        $else:
          vout${ABC[C:C+8]}${ABC[C:C+8]} = ${_MM_MAX_EPX8}(vout${ABC[C:C+8]}${ABC[C:C+8]}, voutput_min);

      $if CHANNEL_TILE > 8:
        _mm_storeu_si128((__m128i*) output, vout${ABC[0:16]});
      $else:
        _mm_storel_epi64((__m128i*) output, vout${ABC[0:8]}${ABC[C:C+8]});
      $for C in range(16, CHANNEL_TILE, 16):
        $if C + 8 < CHANNEL_TILE:
          _mm_storeu_si128((__m128i*) (output + ${C}), vout${ABC[C:C+16]});
        $else:
          _mm_storel_epi64((__m128i*) (output + ${C}), vout${ABC[C:C+8]}${ABC[C:C+8]});
      output += ${CHANNEL_TILE};
    }
    if XNN_UNLIKELY(c != 0) {
      $if CHANNEL_TILE > 8:
        const ${XINT8_T}* k = (const ${XINT8_T}*) ((const int32_t*) w + ${CHANNEL_TILE});
      ${"do " if CHANNEL_TILE > 8 else ""}{
        __m256i vacc${ABC[0:8]} = _mm256_loadu_si256((const __m256i*) w);

        $for K in range(KERNEL_TILE):

          const __m256i vi${K}x${ABC[0:8]} = ${_MM256_CVTEPX8_EPI32}(_mm_loadl_epi64((const __m128i*) i${K}));
          $if DATATYPE == "QU8":
            $if CHANNEL_TILE > 8:
              $if K == 0:
                const __m256i vk${K}x${ABC[0:8]} = _mm256_sub_epi32(_mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*) k)), vk_zero_point);
              $else:
                const __m256i vk${K}x${ABC[0:8]} = _mm256_sub_epi32(_mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*) (k + ${K * CHANNEL_TILE}))), vk_zero_point);
            $else:
              const __m256i vk${K}x${ABC[0:8]} = _mm256_sub_epi32(_mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*) ((uintptr_t) w + ${CHANNEL_TILE} * sizeof(int32_t) + ${K * CHANNEL_TILE} * sizeof(${XINT8_T})))), vk_zero_point);
          $else:
            $if CHANNEL_TILE > 8:
              $if K == 0:
                const __m256i vk${K}x${ABC[0:8]} = _mm256_cvtepi8_epi32(_mm_loadl_epi64((const __m128i*) k));
              $else:
                const __m256i vk${K}x${ABC[0:8]} = _mm256_cvtepi8_epi32(_mm_loadl_epi64((const __m128i*) (k + ${K * CHANNEL_TILE})));
            $else:
              const __m256i vk${K}x${ABC[0:8]} = _mm256_cvtepi8_epi32(_mm_loadl_epi64((const __m128i*) ((uintptr_t) w + ${CHANNEL_TILE} * sizeof(int32_t) + ${K * CHANNEL_TILE} * sizeof(${XINT8_T}))));
          $if CHANNEL_TILE > 8:
            i${K} += 8;

          vacc${ABC[0:8]} = _mm256_add_epi32(vacc${ABC[0:8]}, _mm256_mullo_epi32(vi${K}x${ABC[0:8]}, vk${K}x${ABC[0:8]}));

        $if CHANNEL_TILE > 8:
          k += 8;

        __m256 vscaled${ABC[0:8]} = _mm256_cvtepi32_ps(vacc${ABC[0:8]});
        $if DATATYPE == "QC8":
          const __m256 vscale${ABC[0:8]} = _mm256_loadu_ps((const float*) ((uintptr_t) w + ${CHANNEL_TILE} * sizeof(int32_t) + ${CHANNEL_TILE * KERNEL_TILE} * sizeof(${XINT8_T})));
          vscaled${ABC[0:8]} = _mm256_mul_ps(vscaled${ABC[0:8]}, vscale${ABC[0:8]});
        $else:
          vscaled${ABC[0:8]} = _mm256_mul_ps(vscaled${ABC[0:8]}, _mm256_load_ps(params->fp32_avx2.scale));
        vscaled${ABC[0:8]} = _mm256_min_ps(vscaled${ABC[0:8]}, _mm256_load_ps(params->${PARAMS_STRUCT}.output_max_less_zero_point));
        vacc${ABC[0:8]} = _mm256_cvtps_epi32(vscaled${ABC[0:8]});

        $if CHANNEL_TILE > 8:
          w = (const void*) ((const int32_t*) w + 8);

        const __m128i voutput_zero_point = _mm_load_si128((const __m128i*) params->${PARAMS_STRUCT}.output_zero_point);
        __m128i vout${ABC[0:8]} = _mm_adds_epi16(_mm_packs_epi32(_mm256_castsi256_si128(vacc${ABC[0:8]}), _mm256_extracti128_si256(vacc${ABC[0:8]}, 1)), voutput_zero_point);

        __m128i vout${ABC[0:8]}${ABC[0:8]} = ${_MM_PACKXS_EPI16}(vout${ABC[0:8]}, vout${ABC[0:8]});

        const __m128i voutput_min = _mm_load_si128((const __m128i*) params->${PARAMS_STRUCT}.output_min);
        vout${ABC[0:8]}${ABC[0:8]} = ${_MM_MAX_EPX8}(vout${ABC[0:8]}${ABC[0:8]}, voutput_min);

        $if CHANNEL_TILE > 8:
          if XNN_LIKELY(c >= 8) {
            _mm_storel_epi64((__m128i*) output, vout${ABC[0:8]}${ABC[0:8]});
            output += 8;
            c -= 8;
          } else {
            if (c & 4) {
              unaligned_store_u32(output, (uint32_t) _mm_cvtsi128_si32(vout${ABC[0:8]}${ABC[0:8]}));
              vout${ABC[0:8]}${ABC[0:8]} = _mm_srli_epi64(vout${ABC[0:8]}${ABC[0:8]}, 32);
              output += 4;
            }
            if (c & 2) {
              unaligned_store_u16(output, (uint16_t) _mm_extract_epi16(vout${ABC[0:8]}${ABC[0:8]}, 0));
              vout${ABC[0:8]}${ABC[0:8]} = _mm_srli_epi32(vout${ABC[0:8]}${ABC[0:8]}, 16);
              output += 2;
            }
            if (c & 1) {
              *output = (${XINT8_T}) _mm_extract_epi8(vout${ABC[0:8]}${ABC[0:8]}, 0);
              output += 1;
            }
            c = 0;
          }
        $else:
          if (c & 4) {
            unaligned_store_u32(output, (uint32_t) _mm_cvtsi128_si32(vout${ABC[0:8]}${ABC[0:8]}));
            vout${ABC[0:8]}${ABC[0:8]} = _mm_srli_epi64(vout${ABC[0:8]}${ABC[0:8]}, 32);
            output += 4;
          }
          if (c & 2) {
            unaligned_store_u16(output, (uint16_t) _mm_extract_epi16(vout${ABC[0:8]}${ABC[0:8]}, 0));
            vout${ABC[0:8]}${ABC[0:8]} = _mm_srli_epi32(vout${ABC[0:8]}${ABC[0:8]}, 16);
            output += 2;
          }
          if (c & 1) {
            *output = (${XINT8_T}) _mm_extract_epi8(vout${ABC[0:8]}${ABC[0:8]}, 0);
            output += 1;
          }
      }${" while (c != 0);" if CHANNEL_TILE > 8 else ""}
    }

    output = (${XINT8_T}*) ((uintptr_t) output + output_increment);
  } while (--output_width != 0);
}
