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

#include <immintrin.h>

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


void xnn_x8_lut_ukernel__avx512vbmi_vpermx2b_u${BATCH_TILE}(
    size_t batch,
    const uint8_t* input,
    uint8_t* output,
    const uint8_t table[restrict XNN_MIN_ELEMENTS(256)])
{
  assert(batch != 0);
  assert(batch % sizeof(uint8_t) == 0);
  assert(input != NULL);
  assert(output != NULL);

  const __m512i vtable0 = _mm512_loadu_si512(table);
  $for T in range(1, 4):
    const __m512i vtable${ABC[T]} = _mm512_loadu_si512(table + ${T * 64});

  $if BATCH_TILE > 64:
    for (; batch >= ${BATCH_TILE} * sizeof(uint8_t); batch -= ${BATCH_TILE} * sizeof(uint8_t)) {
      const __m512i vx0 = _mm512_loadu_si512(input);
      $for N in range(1, SIMD_TILE):
        const __m512i vx${N} = _mm512_loadu_si512(input + ${N * 64});
      input += ${BATCH_TILE};

      $for N in range(SIMD_TILE):
        __m512i vy${N} = _mm512_permutex2var_epi8(vtable0, vx${N}, vtable1);
        const __mmask64 vm${N} = _mm512_movepi8_mask(vx${N});

      $for N in range(SIMD_TILE):
        const __m512i vt${N} = _mm512_permutex2var_epi8(vtable2, vx${N}, vtable3);

      $for N in range(SIMD_TILE):
        vy${N} = _mm512_mask_mov_epi8(vy${N}, vm${N}, vt${N});

      _mm512_storeu_si512(output, vy0);
      $for N in range(1, SIMD_TILE):
        _mm512_storeu_si512(output + ${N * 64}, vy${N});
      output += ${BATCH_TILE};
    }
  for (; batch >= 64 * sizeof(uint8_t); batch -= 64 * sizeof(uint8_t)) {
    __m512i vx = _mm512_loadu_si512(input);
    input += 64;

    __m512i vy = _mm512_permutex2var_epi8(vtable0, vx, vtable1);
    const __mmask64 vm = _mm512_movepi8_mask(vx);
    const __m512i vt = _mm512_permutex2var_epi8(vtable2, vx, vtable3);
    vy = _mm512_mask_mov_epi8(vy, vm, vt);

    _mm512_storeu_si512(output, vy);
    output += 64;
  }
  if XNN_UNLIKELY(batch != 0) {
    assert(batch < 64);
    const __mmask64 vmask = _cvtu64_mask64((uint64_t) ((UINT64_C(1) << batch) - UINT64_C(1)));

    __m512i vx = _mm512_maskz_loadu_epi8(vmask, input);

    __m512i vy = _mm512_maskz_permutex2var_epi8(vmask, vtable0, vx, vtable1);
    const __mmask64 vm = _mm512_movepi8_mask(vx);
    const __m512i vt = _mm512_maskz_permutex2var_epi8(vmask, vtable2, vx, vtable3);
    vy = _mm512_mask_mov_epi8(vy, vm, vt);

    _mm512_mask_storeu_epi8(output, vmask, vy);
  }
}
