// Copyright 2021 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 KERNEL_TILE >= 2
$assert REQUANTIZATION == "FP32"
$assert VARIANT in ["FMAGIC", "IMAGIC", "LRINTF"]
$assert DATATYPE in ["QC8", "QS8", "QU8"]
#include <assert.h>
$if VARIANT == "LRINTF":
  #include <math.h>

#include <xnnpack/dwconv.h>
#include <xnnpack/math.h>
$if CHANNEL_TILE % 4 != 0:
  #include <xnnpack/unaligned.h>


$PARAMS_STRUCT = REQUANTIZATION.lower() + "_scalar" + ("_" + VARIANT.lower() if VARIANT else "")
$PARAMS_UNION = "xnn_%s_conv_minmax_params" % DATATYPE.lower()
$XINT8_T = "uint8_t" if DATATYPE == "QU8" else "int8_t"
$MIN_F32 = "__builtin_wasm_min_f32" if WASM else "math_min_f32"
$MAX_F32 = "__builtin_wasm_max_f32" if WASM else "math_max_f32"
void xnn_${DATATYPE.lower()}_dwconv_minmax_${REQUANTIZATION.lower()}_ukernel_up${CHANNEL_TILE}x${KERNEL_TILE}__${"wasm" if WASM else "scalar"}_${VARIANT.lower()}(
    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)])
{
  assert(channels != 0);
  assert(output_width != 0);

  $if DATATYPE != "QC8":
    const float vscale = params->${PARAMS_STRUCT}.scale;
  $if VARIANT == "FMAGIC":
    const float voutput_min_less_zero_point = params->${PARAMS_STRUCT}.output_min_less_zero_point;
    const float voutput_max_less_zero_point = params->${PARAMS_STRUCT}.output_max_less_zero_point;
    const float vmagic_bias = params->${PARAMS_STRUCT}.magic_bias;
    const int32_t vmagic_bias_less_output_zero_point = params->${PARAMS_STRUCT}.magic_bias_less_output_zero_point;
  $elif VARIANT == "IMAGIC":
    const float vmagic_bias = params->${PARAMS_STRUCT}.magic_bias;
    const int32_t vmagic_min = params->${PARAMS_STRUCT}.magic_min;
    const int32_t vmagic_max = params->${PARAMS_STRUCT}.magic_max;
    const int32_t vmagic_bias_less_zero_point = params->${PARAMS_STRUCT}.magic_bias_less_zero_point;
  $elif VARIANT == "LRINTF":
    const float voutput_min_less_zero_point = params->${PARAMS_STRUCT}.output_min_less_zero_point;
    const float voutput_max_less_zero_point = params->${PARAMS_STRUCT}.output_max_less_zero_point;
    const int32_t voutput_zero_point = params->${PARAMS_STRUCT}.output_zero_point;
  $if DATATYPE == "QU8":
    const int32_t vkernel_zero_point = 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;
    $if CHANNEL_TILE == 1:
      do {
        int32_t vacc = unaligned_load_s32(w);

        $for K in range(KERNEL_TILE):
          $if DATATYPE == "QU8":
            const int32_t vi${K} = (int32_t) (uint32_t) *i${K}++;
          $else:
            const int32_t vi${K} = (int32_t) *i${K}++;
          $if DATATYPE == "QU8":
            const int32_t vk${K} = (int32_t) (uint32_t) ((const ${XINT8_T}*) ((uintptr_t) w + sizeof(int32_t)))[${K}] - vkernel_zero_point;
          $else:
            const int32_t vk${K} = ((const ${XINT8_T}*) ((uintptr_t) w + sizeof(int32_t)))[${K}];
          vacc += vi${K} * vk${K};

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

        $if DATATYPE == "QC8":
          $if CHANNEL_TILE % 4 != 0:
            const float vscale = unaligned_load_f32(w);
            w = (const void*) ((const float*) w + 1);
          $else:
            const float vscale = *((const float*) w);
            w = (const void*) ((const float*) w + 1);
        float vfpacc = (float) vacc * vscale;

        $if VARIANT == "FMAGIC":
          vfpacc = ${MAX_F32}(vfpacc, voutput_min_less_zero_point);
          vfpacc = ${MIN_F32}(vfpacc, voutput_max_less_zero_point);
          vfpacc += vmagic_bias;
          int32_t vout = (int32_t) float_as_uint32(vfpacc) - vmagic_bias_less_output_zero_point;
        $elif VARIANT == "IMAGIC":
          vfpacc += vmagic_bias;
          int32_t vout = (int32_t) float_as_uint32(vfpacc);
          vout = math_max_s32(vout, vmagic_min);
          vout = math_min_s32(vout, vmagic_max);
          vout -= vmagic_bias_less_zero_point;
        $elif VARIANT == "LRINTF":
          vfpacc = ${MAX_F32}(vfpacc, voutput_min_less_zero_point);
          vfpacc = ${MIN_F32}(vfpacc, voutput_max_less_zero_point);
          const int32_t vrndacc = (int32_t) lrintf(vfpacc);
          int32_t vout = vrndacc + voutput_zero_point;

        *output++ = (${XINT8_T}) vout;
      } while (--c != 0);
    $else:
      for (; c >= ${CHANNEL_TILE}; c -= ${CHANNEL_TILE}) {
        $if CHANNEL_TILE % 4 != 0:
          $for C in range(CHANNEL_TILE):
            int32_t vacc${C} = unaligned_indexed_load_s32(w, ${C});
        $else:
          $for C in range(CHANNEL_TILE):
            int32_t vacc${C} = ((const int32_t*) w)[${C}];

        $for K in range(KERNEL_TILE):

          $for C in range(CHANNEL_TILE):
            $if DATATYPE == "QU8":
              const int32_t vi${K}x${C} = (int32_t) (uint32_t) i${K}[${C}];
            $else:
              const int32_t vi${K}x${C} = (int32_t) i${K}[${C}];
          i${K} += ${CHANNEL_TILE};

          $for C in range(CHANNEL_TILE):
            $if DATATYPE == "QU8":
              const int32_t vk${K}x${C} = (int32_t) (uint32_t) ((const ${XINT8_T}*) ((uintptr_t) w + ${CHANNEL_TILE} * sizeof(int32_t)))[${K * CHANNEL_TILE + C}] - vkernel_zero_point;
            $else:
              const int32_t vk${K}x${C} = (int32_t) ((const ${XINT8_T}*) ((uintptr_t) w + ${CHANNEL_TILE} * sizeof(int32_t)))[${K * CHANNEL_TILE + C}];

          $for C in range(CHANNEL_TILE):
            vacc${C} += vi${K}x${C} * vk${K}x${C};

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

        $for C in range(CHANNEL_TILE):
          float vfpacc${C} = (float) vacc${C};

        $if DATATYPE == "QC8":
          $if CHANNEL_TILE % 4 != 0:
            $for C in range(CHANNEL_TILE):
              const float vscale${C} = unaligned_indexed_load_f32(w, ${C});
          $else:
            $for C in range(CHANNEL_TILE):
              const float vscale${C} = ((const float*) w)[${C}];
          w = (const void*) ((const float*) w + ${CHANNEL_TILE});

          $for C in range(CHANNEL_TILE):
            vfpacc${C} *= vscale${C};
        $else:
          $for C in range(CHANNEL_TILE):
            vfpacc${C} *= vscale;

        $if VARIANT == "FMAGIC":
          $for C in range(CHANNEL_TILE):
            vfpacc${C} = ${MAX_F32}(vfpacc${C}, voutput_min_less_zero_point);

          $for C in range(CHANNEL_TILE):
            vfpacc${C} = ${MIN_F32}(vfpacc${C}, voutput_max_less_zero_point);

          $for C in range(CHANNEL_TILE):
            vfpacc${C} += vmagic_bias;

          $for C in range(CHANNEL_TILE):
            int32_t vout${C} = (int32_t) float_as_uint32(vfpacc${C}) - vmagic_bias_less_output_zero_point;
        $elif VARIANT == "IMAGIC":
          $for C in range(CHANNEL_TILE):
            vfpacc${C} += vmagic_bias;

          $for C in range(CHANNEL_TILE):
            int32_t vout${C} = (int32_t) float_as_uint32(vfpacc${C});

          $for C in range(CHANNEL_TILE):
            vout${C} = math_max_s32(vout${C}, vmagic_min);

          $for C in range(CHANNEL_TILE):
            vout${C} = math_min_s32(vout${C}, vmagic_max);

          $for C in range(CHANNEL_TILE):
            vout${C} -= vmagic_bias_less_zero_point;
        $elif VARIANT == "LRINTF":
          $for C in range(CHANNEL_TILE):
            vfpacc${C} = ${MAX_F32}(vfpacc${C}, voutput_min_less_zero_point);

          $for C in range(CHANNEL_TILE):
            vfpacc${C} = ${MIN_F32}(vfpacc${C}, voutput_max_less_zero_point);

          $for C in range(CHANNEL_TILE):
            const int32_t vrndacc${C} = (int32_t) lrintf(vfpacc${C});

          $for C in range(CHANNEL_TILE):
            int32_t vout${C} = (int32_t) vrndacc${C} + voutput_zero_point;

        $for C in range(CHANNEL_TILE):
          output[${C}] = (${XINT8_T}) vout${C};
        output += ${CHANNEL_TILE};
      }
      if XNN_UNLIKELY(c != 0) {
        $if CHANNEL_TILE == 2:
          int32_t vacc = unaligned_load_s32(w);

          $for K in range(KERNEL_TILE):
            $if DATATYPE == "QU8":
              const int32_t vi${K} = (int32_t) (uint32_t) *i${K};
            $else:
              const int32_t vi${K} = (int32_t) *i${K};
            $if DATATYPE == "QU8":
              const int32_t vk${K} = (int32_t) (uint32_t) ((const ${XINT8_T}*) ((uintptr_t) w + ${CHANNEL_TILE} * sizeof(int32_t)))[${K * CHANNEL_TILE}] - vkernel_zero_point;
            $else:
              const int32_t vk${K} = (int32_t) ((const ${XINT8_T}*) ((uintptr_t) w + ${CHANNEL_TILE} * sizeof(int32_t)))[${K * CHANNEL_TILE}];
            vacc += vi${K} * vk${K};

          $if DATATYPE == "QC8":
            $if CHANNEL_TILE % 4 != 0:
              typedef XNN_UNALIGNED float unaligned_float;
              const float vscale = *((const unaligned_float*) ((uintptr_t) w + ${CHANNEL_TILE} * sizeof(int32_t) + ${KERNEL_TILE * CHANNEL_TILE} * sizeof(${XINT8_T})));
            $else:
              const float vscale = *((const float*) ((uintptr_t) w + ${CHANNEL_TILE} * sizeof(int32_t) + ${KERNEL_TILE * CHANNEL_TILE} * sizeof(${XINT8_T})));
          float vfpacc = (float) vacc * vscale;

          $if VARIANT == "FMAGIC":
            vfpacc = ${MAX_F32}(vfpacc, voutput_min_less_zero_point);
            vfpacc = ${MIN_F32}(vfpacc, voutput_max_less_zero_point);
            vfpacc += vmagic_bias;
            int32_t vout = (int32_t) float_as_uint32(vfpacc) - vmagic_bias_less_output_zero_point;
          $elif VARIANT == "IMAGIC":
            vfpacc += vmagic_bias;
            int32_t vout = (int32_t) float_as_uint32(vfpacc);
            vout = math_max_s32(vout, vmagic_min);
            vout = math_min_s32(vout, vmagic_max);
            vout -= vmagic_bias_less_zero_point;
          $elif VARIANT == "LRINTF":
            vfpacc = ${MAX_F32}(vfpacc, voutput_min_less_zero_point);
            vfpacc = ${MIN_F32}(vfpacc, voutput_max_less_zero_point);
            const int32_t vrndacc = (int32_t) lrintf(vfpacc);
            int32_t vout = vrndacc + voutput_zero_point;

          *output++ = (${XINT8_T}) vout;
        $else:
          const ${XINT8_T}* k = (const ${XINT8_T}*) ((uintptr_t) w + ${CHANNEL_TILE} * sizeof(int32_t));
          do {
            int32_t vacc = *((const int32_t*) w);
            w = (const void*) ((uintptr_t) w + sizeof(int32_t));

            $for K in range(KERNEL_TILE):
              $if DATATYPE == "QU8":
                const int32_t vi${K} = (int32_t) (uint32_t) *i${K}++;
              $else:
                const int32_t vi${K} = (int32_t) *i${K}++;
              $if DATATYPE == "QU8":
                const int32_t vk${K} = (int32_t) (uint32_t) k[${K * CHANNEL_TILE}] - vkernel_zero_point;
              $else:
                const int32_t vk${K} = (int32_t) k[${K * CHANNEL_TILE}];
              vacc += vi${K} * vk${K};
            k += 1;

            $if DATATYPE == "QC8":
              $if CHANNEL_TILE % 4 != 0:
                const float vscale = unaligned_load_f32((const void*) ((uintptr_t) w + ${CHANNEL_TILE - 1} * sizeof(int32_t) + ${KERNEL_TILE * CHANNEL_TILE} * sizeof(${XINT8_T})));
              $else:
                const float vscale = *((const float*) ((uintptr_t) w + ${CHANNEL_TILE - 1} * sizeof(int32_t) + ${KERNEL_TILE * CHANNEL_TILE} * sizeof(${XINT8_T})));
            float vfpacc = (float) vacc * vscale;

            $if VARIANT == "FMAGIC":
              vfpacc = ${MAX_F32}(vfpacc, voutput_min_less_zero_point);
              vfpacc = ${MIN_F32}(vfpacc, voutput_max_less_zero_point);
              vfpacc += vmagic_bias;
              int32_t vout = (int32_t) float_as_uint32(vfpacc) - vmagic_bias_less_output_zero_point;
            $elif VARIANT == "IMAGIC":
              vfpacc += vmagic_bias;
              int32_t vout = (int32_t) float_as_uint32(vfpacc);
              vout = math_max_s32(vout, vmagic_min);
              vout = math_min_s32(vout, vmagic_max);
              vout -= vmagic_bias_less_zero_point;
            $elif VARIANT == "LRINTF":
              vfpacc = ${MAX_F32}(vfpacc, voutput_min_less_zero_point);
              vfpacc = ${MIN_F32}(vfpacc, voutput_max_less_zero_point);
              const int32_t vrndacc = (int32_t) lrintf(vfpacc);
              int32_t vout = vrndacc + voutput_zero_point;

            *output++ = (${XINT8_T}) vout;
          } while (--c != 0);
      }

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