// 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"]
$assert CHANNEL_TILE % 16 == 0
$assert CHANNEL_TILE >= 16
$assert KERNEL_TILE >= 2
#include <assert.h>

#include <immintrin.h>

#include "xnnpack/dwconv.h"
#include "xnnpack/unaligned.h"


$DATATYPE_SPEC = {"QS8": "qs8", "QC8": "qs8_qc8w"}[DATATYPE]
$PARAMS_STRUCT = REQUANTIZATION.lower() + "_scalar"
$PARAMS_TYPE = {"QC8": "union xnn_qs8_qc8w_conv_minmax_params", "QS8": "union xnn_qs8_conv_minmax_params"}[DATATYPE]
void xnn_${DATATYPE_SPEC}_dwconv_minmax_${REQUANTIZATION.lower()}_ukernel_${KERNEL_TILE}p${CHANNEL_TILE}c__avx2_mul16_vpmovsx(
    size_t channels,
    size_t output_width,
    const int8_t** input,
    const void* weights,
    int8_t* output,
    intptr_t input_stride,
    size_t output_increment,
    size_t input_offset,
    const int8_t* zero,
    const ${PARAMS_TYPE} params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS
{
  assert(channels != 0);
  assert(output_width != 0);

  $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 __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 {
    $for K in range(KERNEL_TILE):
      const int8_t* i${K} = input[${K}];
      assert(i${K} != NULL);
      if XNN_UNPREDICTABLE(i${K} != zero) {
        i${K} = (const int8_t*) ((uintptr_t) i${K} + input_offset);
      }
    input = (const int8_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*) ((uintptr_t) w + ${C} * sizeof(int32_t)));

      $for K in range(KERNEL_TILE):

        $for C in range(0, CHANNEL_TILE, 16):
          $if C == 0:
            const __m256i vi${K}x${ABC[0:16]} = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i${K}));
          $else:
            const __m256i vi${K}x${ABC[C:C+16]} = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i${K} + ${C})));
          const __m256i vk${K}x${ABC[C:C+16]} = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + ${CHANNEL_TILE} * sizeof(int32_t) + ${K * CHANNEL_TILE + C} * sizeof(int8_t))));
        i${K} += ${CHANNEL_TILE};

        $for C in range(0, CHANNEL_TILE, 16):
          const __m256i vprod${K}x${ABC[C:C+16]} =  _mm256_mullo_epi16(vi${K}x${ABC[C:C+16]}, vk${K}x${ABC[C:C+16]});
          const __m128i vprod${K}x${ABC[C+8:C+16]} = _mm256_extracti128_si256(vprod${K}x${ABC[C:C+16]}, 1);
          vacc${ABC[C:C+8]} = _mm256_add_epi32(vacc${ABC[C:C+8]}, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod${K}x${ABC[C:C+16]})));
          vacc${ABC[C+8:C+16]} = _mm256_add_epi32(vacc${ABC[C+8:C+16]}, _mm256_cvtepi16_epi32(vprod${K}x${ABC[C+8:C+16]}));

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

      $for C in range(0, CHANNEL_TILE, 8):
        __m256 vfpacc${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*) ((uintptr_t) w + ${C} * sizeof(float)));
        w = (const void*) ((uintptr_t) w + ${CHANNEL_TILE} * sizeof(float));
        $for C in range(0, CHANNEL_TILE, 8):
          vfpacc${ABC[C:C+8]} = _mm256_mul_ps(vfpacc${ABC[C:C+8]}, vscale${ABC[C:C+8]});
      $else:
        $for C in range(0, CHANNEL_TILE, 8):
          vfpacc${ABC[C:C+8]} = _mm256_mul_ps(vfpacc${ABC[C:C+8]}, vscale);

      $for C in range(0, CHANNEL_TILE, 8):
        vfpacc${ABC[C:C+8]} = _mm256_min_ps(vfpacc${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(vfpacc${ABC[C:C+8]});

      $for C in range(0, CHANNEL_TILE, 16):
        const __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);

      $for C in range(0, CHANNEL_TILE, 16):
        __m128i vout${ABC[C:C+16]} = _mm_shuffle_epi32(_mm_packs_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));

      $for C in range(0, CHANNEL_TILE, 16):
        vout${ABC[C:C+16]} = _mm_max_epi8(vout${ABC[C:C+16]}, voutput_min);

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

        $for K in range(KERNEL_TILE):

          const __m256i vi${K}x${ABC[0:16]} = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i${K}));
          $if CHANNEL_TILE > 16:
            $if K == 0:
              const __m256i vk${K}x${ABC[0:16]} = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) k));
            $else:
              const __m256i vk${K}x${ABC[0:16]} = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + ${K * CHANNEL_TILE})));
          $else:
            const __m256i vk${K}x${ABC[0:16]} = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + ${CHANNEL_TILE} * sizeof(int32_t) + ${K * CHANNEL_TILE} * sizeof(int8_t))));
          $if CHANNEL_TILE > 16:
            i${K} += 16;

          const __m256i vprod${K}x${ABC[0:16]} = _mm256_mullo_epi16(vi${K}x${ABC[0:16]}, vk${K}x${ABC[0:16]});
          const __m128i vprod${K}x${ABC[8:16]} = _mm256_extracti128_si256(vprod${K}x${ABC[0:16]}, 1);
          vacc${ABC[0:8]} = _mm256_add_epi32(vacc${ABC[0:8]}, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod${K}x${ABC[0:16]})));
          vacc${ABC[8:16]} = _mm256_add_epi32(vacc${ABC[8:16]}, _mm256_cvtepi16_epi32(vprod${K}x${ABC[8:16]}));

        $if CHANNEL_TILE > 16:
          k += 16;

        __m256 vfpacc${ABC[0:8]} = _mm256_cvtepi32_ps(vacc${ABC[0:8]});
        __m256 vfpacc${ABC[8:16]} = _mm256_cvtepi32_ps(vacc${ABC[8:16]});

        $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(int8_t)));
          const __m256 vscale${ABC[8:16]} = _mm256_loadu_ps((const float*) ((uintptr_t) w + ${CHANNEL_TILE} * sizeof(int32_t) + ${CHANNEL_TILE * KERNEL_TILE} * sizeof(int8_t) + 8 * sizeof(float)));
          vfpacc${ABC[0:8]} = _mm256_mul_ps(vfpacc${ABC[0:8]}, vscale${ABC[0:8]});
          vfpacc${ABC[8:16]} = _mm256_mul_ps(vfpacc${ABC[8:16]}, vscale${ABC[8:16]});
        $else:
          vfpacc${ABC[0:8]} = _mm256_mul_ps(vfpacc${ABC[0:8]}, vscale);
          vfpacc${ABC[8:16]} = _mm256_mul_ps(vfpacc${ABC[8:16]}, vscale);

        vfpacc${ABC[0:8]} = _mm256_min_ps(vfpacc${ABC[0:8]}, voutput_max_less_zero_point);
        vfpacc${ABC[8:16]} = _mm256_min_ps(vfpacc${ABC[8:16]}, voutput_max_less_zero_point);

        vacc${ABC[0:8]} = _mm256_cvtps_epi32(vfpacc${ABC[0:8]});
        vacc${ABC[8:16]} = _mm256_cvtps_epi32(vfpacc${ABC[8:16]});

        $if CHANNEL_TILE > 16:
          w = (const void*) ((uintptr_t) w + 16 * sizeof(int32_t));

        __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)), _mm256_castsi256_si128(voutput_zero_point));
        __m128i vout${ABC[8:16]} = _mm_adds_epi16(_mm_packs_epi32(_mm256_castsi256_si128(vacc${ABC[8:16]}), _mm256_extracti128_si256(vacc${ABC[8:16]}, 1)), _mm256_castsi256_si128(voutput_zero_point));

        __m128i vout${ABC[0:16]} = _mm_packs_epi16(vout${ABC[0:8]}, vout${ABC[8:16]});
        vout${ABC[0:16]} = _mm_max_epi8(vout${ABC[0:16]}, voutput_min);

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

    output = (int8_t*) ((uintptr_t) output + output_increment);
  } while (--output_width != 0);
}
