/*
 * Small integer workloads used to compare -O2 and -Os on the same CVE2 core.
 * The same source is compiled twice; BENCH_PREFIX selects the exported names.
 */
#include <stdint.h>

#ifndef BENCH_PREFIX
#define BENCH_PREFIX bench
#endif

#define CAT2_(a, b) a##b
#define CAT2(a, b) CAT2_(a, b)
#define FN(name) CAT2(BENCH_PREFIX, name)

uint32_t FN(_crc32)(const uint8_t *buf, uint32_t n)
{
    uint32_t crc = 0xFFFFFFFFu;
    uint32_t i, j;
    for (i = 0; i < n; ++i) {
        crc ^= buf[i];
        for (j = 0; j < 8; ++j)
            crc = (crc >> 1) ^ (0xEDB88320u & (0u - (crc & 1u)));
    }
    return crc ^ 0xFFFFFFFFu;
}

uint32_t FN(_memcpy_sum)(const uint8_t *src, uint8_t *dst, uint32_t n, uint32_t reps)
{
    uint32_t r, i, sum = 0;
    for (r = 0; r < reps; ++r) {
        for (i = 0; i < n; ++i)
            dst[i] = src[i];
        for (i = 0; i < n; i += 16)
            sum += dst[i];
    }
    return sum;
}

uint32_t FN(_matmul)(const int32_t *a, const int32_t *b, int32_t *c, uint32_t n)
{
    uint32_t i, j, k, sum = 0;
    for (i = 0; i < n; ++i) {
        for (j = 0; j < n; ++j) {
            int32_t acc = 0;
            for (k = 0; k < n; ++k)
                acc += a[i * n + k] * b[k * n + j];
            c[i * n + j] = acc;
            sum += (uint32_t)acc;
        }
    }
    return sum;
}

uint32_t FN(_sieve)(uint8_t *flags, uint32_t n)
{
    uint32_t i, j, count = 0;
    for (i = 0; i < n; ++i)
        flags[i] = 1;
    flags[0] = 0;
    if (n > 1) flags[1] = 0;
    for (i = 2; i * i < n; ++i) {
        if (flags[i]) {
            for (j = i * i; j < n; j += i)
                flags[j] = 0;
        }
    }
    for (i = 0; i < n; ++i)
        count += flags[i];
    return count;
}
