// Copyright 2023 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 BATCH_TILE % 8 == 0
$assert BATCH_TILE >= 8
$ABC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#include <assert.h>

#include <arm_neon.h>

#include "xnnpack/common.h"
#include "xnnpack/intrinsics-polyfill.h"
#include "xnnpack/vcvt.h"


void xnn_qs8_f16_vcvt_ukernel__neonfp16arith_u${BATCH_TILE}(
    size_t batch,
    const int8_t* input,
    xnn_float16* output,
    const struct xnn_qs8_f16_cvt_params params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS
{
  assert(batch != 0);
  assert(batch % sizeof(int8_t) == 0);
  assert(input != NULL);
  assert(output != NULL);

  uint16_t* o = (uint16_t*) output;
  const int16x8_t vminus_zero_point = vdupq_n_s16(-params->scalar.zero_point);
#ifdef XNN_COMPILER_MSVC
  const float16x8_t vscale = vreinterpretq_f16_u16(vdupq_n_u16(*(const uint16_t*) &params->scalar.scale));
#else
  const float16x8_t vscale = vreinterpretq_f16_u16(vld1q_dup_u16((const uint16_t*) &params->scalar.scale));
#endif
  $if BATCH_TILE > 8:
    for (; batch >= ${BATCH_TILE} * sizeof(int8_t); batch -= ${BATCH_TILE} * sizeof(int8_t)) {
      $for N in range(0, BATCH_TILE, 8):
        const int8x8_t vx${ABC[N:N+8]} = vld1_s8(input); input += 8;

      $for N in range(0, BATCH_TILE, 8):
        const int16x8_t vhx${ABC[N:N+8]} = vaddw_s8(vminus_zero_point, vx${ABC[N:N+8]});

      $for N in range(0, BATCH_TILE, 8):
        float16x8_t vy${ABC[N:N+8]} = vcvtq_f16_s16(vhx${ABC[N:N+8]});

      $for N in range(0, BATCH_TILE, 8):
        vy${ABC[N:N+8]} = vmulq_f16(vy${ABC[N:N+8]}, vscale);

      $for N in range(0, BATCH_TILE, 8):
        vst1q_u16(o, vreinterpretq_u16_f16(vy${ABC[N:N+8]})); o += 8;
    }
  for (; batch >= 8 * sizeof(int8_t); batch -= 8 * sizeof(int8_t)) {
    const int8x8_t vx = vld1_s8(input); input += 8;

    const int16x8_t vhx = vaddw_s8(vminus_zero_point, vx);

    float16x8_t vy = vcvtq_f16_s16(vhx);

    vy = vmulq_f16(vy, vscale);

    vst1q_u16(o, vreinterpretq_u16_f16(vy)); o += 8;
  }
  if XNN_UNLIKELY(batch != 0) {
    assert(batch >= 1 * sizeof(int8_t));
    assert(batch <= 7 * sizeof(int8_t));

    const int8x8_t vx = vld1_s8(input);

    const int16x8_t vhx = vaddw_s8(vminus_zero_point, vx);

    float16x8_t vy = vcvtq_f16_s16(vhx);
    vy = vmulq_f16(vy, vscale);

    float16x4_t vy_lo = vget_low_f16(vy);
    if (batch & (4 * sizeof(int8_t))) {
      vst1_u16(o, vreinterpret_u16_f16(vy_lo)); o += 4;
      vy_lo = vget_high_f16(vy);
    }
    if (batch & (2 * sizeof(int8_t))) {
      vst1_lane_u32((void*) o, vreinterpret_u32_f16(vy_lo), 0); o += 2;

      vy_lo = vext_f16(vy_lo, vy_lo, 2);
    }
    if (batch & (1 * sizeof(int8_t))) {
      vst1_lane_u16(o, vreinterpret_u16_f16(vy_lo), 0);
    }
  }
}
