// 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"}_u${BATCH_TILE}(
    size_t batch,
    const float* input,
    float* output,
    const union xnn_f32_minmax_params params[restrict XNN_MIN_ELEMENTS(1)])
{
  assert(batch != 0);
  assert(batch % sizeof(float) == 0);
  assert(input != NULL);
  assert(output != NULL);

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

  $if BATCH_TILE > 1:
    for (; batch >= ${BATCH_TILE} * sizeof(float); batch -= ${BATCH_TILE} * sizeof(float)) {
      $for N in range(BATCH_TILE):
        float vacc${ABC[N]} = input[${N}];
      input += ${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):
        output[${N}] = vacc${ABC[N]};
      output += ${BATCH_TILE};
    }
    if XNN_UNLIKELY(batch != 0) {
      $if BATCH_TILE > 2:
        do {
          float vacc = *input++;
          vacc = ${MAX_F32}(vacc, vy_min);
          vacc = ${MIN_F32}(vacc, vy_max);
          *output++ = vacc;
          batch -= sizeof(float);
        } while (batch != 0);
      $else:
        float vacc = *input;
        vacc = ${MAX_F32}(vacc, vy_min);
        vacc = ${MIN_F32}(vacc, vy_max);
        *output = vacc;
    }
  $else:
    for (; batch >= sizeof(float); batch -= sizeof(float)) {
      float vacc = *input++;
      vacc = ${MAX_F32}(vacc, vy_min);
      vacc = ${MIN_F32}(vacc, vy_max);
      *output++ = vacc;
    }
}
