// 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.

$assert BATCH_TILE % 32 == 0
$assert BATCH_TILE >= 32
$SIMD_TILE = BATCH_TILE // 32
$ABC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#include <assert.h>

#include <immintrin.h>

#include "xnnpack/common.h"
#include "xnnpack/microparams.h"
#include "xnnpack/vunary.h"


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

#if defined(__AVX512FP16__)
  const uint16_t* i = (const uint16_t*) input;
  uint16_t* o = (uint16_t*) output;
  $if BATCH_TILE > 32:
    for (; batch >= ${BATCH_TILE} * sizeof(uint16_t); batch -= ${BATCH_TILE} * sizeof(uint16_t)) {
      __m512h vacc${ABC[0]} = _mm512_loadu_ph(i);
      $for N in range(1, SIMD_TILE):
        __m512h vacc${ABC[N]} = _mm512_loadu_ph(i + ${N*32});
      i += ${BATCH_TILE};

      $for N in range(SIMD_TILE):
        vacc${ABC[N]} = _mm512_sqrt_ph(vacc${ABC[N]});

      _mm512_storeu_ph(o, vacc${ABC[0]});
      $for N in range(1, SIMD_TILE):
        _mm512_storeu_ph(o + ${N*32}, vacc${ABC[N]});
      o += ${BATCH_TILE};
    }
  for (; batch >= 32 * sizeof(uint16_t); batch -= 32 * sizeof(uint16_t)) {
    __m512h vacc = _mm512_loadu_ph(i);
    i += 32;
    vacc = _mm512_sqrt_ph(vacc);
    _mm512_storeu_ph(o, vacc);
    o += 32;
  }
  if XNN_UNLIKELY(batch != 0) {
    assert(batch >= 1 * sizeof(uint16_t));
    assert(batch <= 31 * sizeof(uint16_t));

    // Prepare mask for valid elements (depends on batch).
    batch >>= XNN_LOG2_SIZEOF_HALF;
    const __mmask32 vmask = _cvtu32_mask32((uint32_t) ((UINT32_C(1) << batch) - UINT32_C(1)));

    __m512h vacc = _mm512_castsi512_ph(_mm512_maskz_loadu_epi16(vmask, i));
    vacc = _mm512_mask_sqrt_ph(vacc, vmask, vacc);

    _mm512_mask_storeu_epi16(o, vmask, _mm512_castph_si512(vacc));
  }
#endif  // defined(__AVX512FP16__)
}
