// 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.
#include <assert.h>
#include <math.h>

#include <immintrin.h>

#include "xnnpack/unaligned.h"
#include "xnnpack/common.h"
#include "xnnpack/reduce.h"
#include "xnnpack/math.h"


void xnn_qs8_rdsum_ukernel_${ACCUMULATORS}p${ACCUMULATORS}x__avx2_c${CHANNELS}(
    size_t rows,
    size_t channels,
    const int8_t* input,
    size_t input_stride,
    const int8_t* zero,
    int32_t* output,
    const struct xnn_qs8_rsum_params params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS
{
  assert(rows != 0);
  assert(channels != 0);
  assert(input != NULL);
  assert(output != NULL);

  size_t input_increment = ${ACCUMULATORS} * input_stride;
  for (; channels >= ${CHANNELS}; channels -= ${CHANNELS}) {
    const int8_t* i0 = input;
    $for ACC in range(1, ACCUMULATORS):
      const int8_t* i${ACC} = (const int8_t*) ((uintptr_t) input + ${ACC} * input_stride);

    $for C in range(0, CHANNELS, 8):
      __m256i vacc${C} = _mm256_setzero_si256();

    // 256 int8s may be summed into an int16 before overflowing
    // To prevent handling the tails of the inner 256 loop, we round 256 down to
    // the nearest integer multiple of ACCUMULATORS.
    $OVERFLOW = (256 // ACCUMULATORS) * ACCUMULATORS
    int r = rows;
    while (r > 0) {
      $for C in range(0, CHANNELS, 16):
        __m256i vacc16_${C} = _mm256_setzero_si256();
      for (int current_batch = min(r, ${OVERFLOW}); current_batch > 0; current_batch -= ${ACCUMULATORS}) {
        $for N in range(1, ACCUMULATORS, 2):
          if XNN_UNPREDICTABLE(current_batch < ${N+1}) {
            i${N} = zero;
          }
          if XNN_UNPREDICTABLE(current_batch <= ${N+1}) {
            i${N+1} = zero;
          }
        $for C in range(0, CHANNELS, 16):
          __m256i vin${C};
        $for ACC in range(ACCUMULATORS):
          $for C in range(0, CHANNELS, 16):
            vin${C} = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) &i${ACC}[${C}]));
          $for C in range(0, CHANNELS, 16):
            vacc16_${C} = _mm256_add_epi16(vacc16_${C}, vin${C});
        $for N in range(0, ACCUMULATORS):
          i${N} = (const int8_t*) ((uintptr_t) i${N} + input_increment);
      }
      $for C in range(0, CHANNELS, 16):
        vacc${C} = _mm256_add_epi32(vacc${C}, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vacc16_${C})));
        vacc${C+8} = _mm256_add_epi32(vacc${C+8}, _mm256_cvtepi16_epi32(_mm256_extractf128_si256(vacc16_${C}, 1)));
      r = doz(r, ${OVERFLOW});
    }

    const int32_t* o = output;
    $for C in range(0, CHANNELS, 8):
      __m256i vo${C} = _mm256_loadu_si256((const __m256i*) o); o += 8;
    $for C in range(0, CHANNELS, 8):
      vo${C} = _mm256_add_epi32(vo${C}, vacc${C});
    $for C in range(0, CHANNELS, 8):
      _mm256_storeu_si256((__m256i*) output, vo${C}); output += 8;

    input = (const int8_t*) ((uintptr_t) input + ${CHANNELS} * sizeof(int8_t));
  }
  if (channels != 0) {
    input_increment = ${ACCUMULATORS} * input_stride;
    // 256 int8s may be summed into an int16 before overflowing.
    do {
      int num_batches = floor((rows + ${OVERFLOW - 1}) / ${OVERFLOW});
      int r = rows;
      const int8_t* i0 = input;
      $for ACC in range(1, ACCUMULATORS):
        const int8_t* i${ACC} = (const int8_t*) ((uintptr_t) input + ${ACC} * input_stride);

      __m256i vacc0 = _mm256_setzero_si256();
      __m256i vacc1 = _mm256_setzero_si256();

      for (; num_batches > 0; --num_batches) {
        __m256i vacc16 = _mm256_setzero_si256();
        for (int current_batch = min(r, ${OVERFLOW}); current_batch > 0; current_batch -= ${ACCUMULATORS}) {
          $for N in range(1, ACCUMULATORS, 2):
            if XNN_UNPREDICTABLE(current_batch < ${N+1}) {
              i${N} = zero;
            }
            if XNN_UNPREDICTABLE(current_batch <= ${N+1}) {
              i${N+1} = zero;
            }

          $for ACC in range(ACCUMULATORS):
            __m256i vin${ACC} = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*)&i${ACC}[0]));
          $for ACC in range(ACCUMULATORS):
            vacc16 = _mm256_add_epi16(vacc16, vin${ACC});
          $for N in range(ACCUMULATORS):
            i${N} = (const int8_t*) ((uintptr_t) i${N} + input_increment);
        }
        vacc0 = _mm256_add_epi32(vacc0, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vacc16)));
        vacc1 = _mm256_add_epi32(vacc1, _mm256_cvtepi16_epi32(_mm256_extractf128_si256(vacc16, 1)));
        r = doz(r, ${OVERFLOW});
      }

      if XNN_LIKELY(channels >= 8) {
        __m256i vo = _mm256_loadu_si256((const __m256i*) output);
        vo = _mm256_add_epi32(vo, vacc0);
        _mm256_storeu_si256((__m256i*) output, vo); output += 8;
        channels -= 8;
        input = (const int8_t*) ((uintptr_t) input + 8 * sizeof(int8_t));
      } else {
        __m128i vacc = _mm256_castsi256_si128(vacc0);
        if (channels & 4) {
          __m128i vo = _mm_loadu_si128((const __m128i*) output);
          vo = _mm_add_epi32(vo, vacc);
          _mm_storeu_si128((__m128i*) output, vo); output += 4;
          vacc = _mm256_extractf128_si256(vacc0, 1);
        }
        if (channels & 2) {
          __m128i vo = _mm_loadl_epi64((const __m128i*) output);
          vo = _mm_add_epi32(vo, vacc);
          _mm_storel_epi64((__m128i*) output, vo); output += 2;
          vacc = _mm_srli_si128(vacc, 8);
        }
        if (channels & 1) {
          *output += _mm_cvtsi128_si32(vacc);
        }
        channels = 0;
      }
    } while (channels != 0);
  }
}
