// 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 >= 1
$ABC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#include <assert.h>

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


$ACC_SUFFIX = "" if ACCUMULATORS == 1 else "_acc%d" % ACCUMULATORS
void xnn_f32_rsum_ukernel__scalar_u${BATCH_TILE}${ACC_SUFFIX}(
    size_t batch,
    const float* input,
    float* output,
    const struct xnn_f32_scale_params params[restrict XNN_MIN_ELEMENTS(1)])
{
  assert(batch != 0);
  assert(batch % sizeof(float) == 0);
  assert(input != NULL);
  assert(output != NULL);

  $for A in range(ACCUMULATORS):
    float vacc${A} = 0.0f;
  $if BATCH_TILE == 1:
    do {
      const float vt = *input++;
      vacc0 += vt;
      batch -= sizeof(float);
    } while (batch != 0);
  $else:
    for (; batch >= ${BATCH_TILE} * sizeof(float); batch -= ${BATCH_TILE} * sizeof(float)) {
      $for N in range(BATCH_TILE):
        const float vt${N} = input[${N}];
      input += ${BATCH_TILE};

      $for N in range(BATCH_TILE):
        vacc${N % ACCUMULATORS} += vt${N};
    }
    $if ACCUMULATORS > 1:
      $ACC_SLICE = 1
      $while ACC_SLICE < ACCUMULATORS:
        $for A in range(0, ACCUMULATORS, ACC_SLICE * 2):
          $if A + ACC_SLICE < ACCUMULATORS:
            vacc${A} += vacc${A + ACC_SLICE};
        $ACC_SLICE *= 2

    if XNN_UNLIKELY(batch != 0) {
      $if BATCH_TILE == 2:
        const float vt = *input;
        vacc0 += vt;
      $else:
        do {
          const float vt = *input++;
          vacc0 += vt;
          batch -= sizeof(float);
        } while (batch != 0);
    }
  const float vscale = params->scalar.scale;
  vacc0 *= vscale;
  *output += vacc0;
}
