// Copyright 2020 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/math.h>
#include <xnnpack/vunary.h>


$MIN_F32 = "__builtin_wasm_min_f32" if WASM else "math_min_f32"
$MAX_F32 = "__builtin_wasm_max_f32" if WASM else "math_max_f32"
void xnn_f32_vclamp_ukernel__${"wasm" if WASM else "scalar"}_x${BATCH_TILE}(
    size_t n,
    const float* x,
    float* y,
    const union xnn_f32_minmax_params params[restrict XNN_MIN_ELEMENTS(1)])
{
  assert(n != 0);
  assert(n % sizeof(float) == 0);
  assert(x != NULL);
  assert(y != NULL);

  const float vy_min = params->scalar.min;
  const float vy_max = params->scalar.max;

  $if BATCH_TILE > 1:
    for (; n >= ${BATCH_TILE} * sizeof(float); n -= ${BATCH_TILE} * sizeof(float)) {
      $for N in range(BATCH_TILE):
        float vacc${ABC[N]} = x[${N}];
      x += ${BATCH_TILE};

      $for N in range(BATCH_TILE):
        vacc${ABC[N]} = ${MAX_F32}(vacc${ABC[N]}, vy_min);

      $for N in range(BATCH_TILE):
        vacc${ABC[N]} = ${MIN_F32}(vacc${ABC[N]}, vy_max);

      $for N in range(BATCH_TILE):
        y[${N}] = vacc${ABC[N]};
      y += ${BATCH_TILE};
    }
    if XNN_UNLIKELY(n != 0) {
      $if BATCH_TILE > 2:
        do {
          float vacc = *x++;
          vacc = ${MAX_F32}(vacc, vy_min);
          vacc = ${MIN_F32}(vacc, vy_max);
          *y++ = vacc;
          n -= sizeof(float);
        } while (n != 0);
      $else:
        float vacc = *x;
        vacc = ${MAX_F32}(vacc, vy_min);
        vacc = ${MIN_F32}(vacc, vy_max);
        *y = vacc;
    }
  $else:
    for (; n >= sizeof(float); n -= sizeof(float)) {
      float vacc = *x++;
      vacc = ${MAX_F32}(vacc, vy_min);
      vacc = ${MIN_F32}(vacc, vy_max);
      *y++ = vacc;
    }
}
