/* =============================================================================
 * 02_blockers.c  --  an optimization blocker you can time: a call in a loop
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - The compiler usually cannot move a function call out of a loop, because
 *     it cannot prove the call has no side effects (or that its result is
 *     invariant). A strlen in a loop CONDITION turns an O(n) loop into O(n^2).
 *     How bad is that, measured, and does hoisting the call by hand fix it?
 *
 * [How to build & run]
 *   make && ./build/02_blockers            (native)
 *
 * [How to read the output]
 *   A lowercase routine is timed with strlen() in the loop condition vs with
 *   the length hoisted into a local, over growing string lengths. The
 *   strlen-in-loop time quadruples when n doubles (O(n^2)); the hoisted time
 *   doubles (O(n)). Times vary run to run; the growth RATES are the point.
 *
 *   The OTHER great blocker, memory aliasing, is shown in 01_compiler_opts.py
 *   (it forces a runtime alias check that `restrict` removes); on this CPU its
 *   run-time cost is largely hidden by store-to-load forwarding, so it is best
 *   seen in the generated code rather than a stopwatch.
 *
 * [Systems link / CS:APP 5.2, 5.12]
 *   The compiler will not hoist, reorder or remove a call it cannot prove is
 *   pure. A call in a loop's test is re-evaluated every iteration -- the
 *   classic accidental-quadratic bug.
 * -------------------------------------------------------------------------- */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "timer.h"

/* strlen(s) in the loop condition: recomputed every iteration -> O(n) per
 * check -> O(n^2) total. The compiler cannot hoist it: the loop writes s[i],
 * so in general the length could change. */
__attribute__((noinline))
static void lower_quadratic(char *s) {
    for (size_t i = 0; i < strlen(s); i++)
        if (s[i] >= 'A' && s[i] <= 'Z')
            s[i] += 'a' - 'A';
}

/* Hoist the length into a local -> O(n). The programmer knows the length does
 * not change; the compiler does not. */
__attribute__((noinline))
static void lower_linear(char *s) {
    size_t n = strlen(s);
    for (size_t i = 0; i < n; i++)
        if (s[i] >= 'A' && s[i] <= 'Z')
            s[i] += 'a' - 'A';
}

static double time_lower(void (*f)(char *), size_t n) {
    char *s = malloc(n + 1);
    memset(s, 'A', n);
    s[n] = 0;
    double t0 = wall_seconds();
    f(s);
    double dt = wall_seconds() - t0;
    free(s);
    return dt;
}

int main(void) {
#if defined(__x86_64__)
    const char *arch = "x86-64";
#else
    const char *arch = "arm64";
#endif
    printf("=== Demo 02: a function call in a loop (%s) ===\n\n", arch);
    printf("  Lowercasing a string, strlen() in the loop condition vs hoisted:\n\n");
    printf("  %-10s %-16s %-14s %s\n", "length n", "strlen-in-loop", "hoisted", "growth (vs prev n)");
    double prev_q = 0;
    for (size_t n = 25000; n <= 200000; n *= 2) {
        double q = time_lower(lower_quadratic, n);
        double l = time_lower(lower_linear, n);
        char ratio[32] = "";
        if (prev_q > 0)
            snprintf(ratio, sizeof ratio, "%.1fx", q / prev_q);
        printf("  %-10zu %-16.2f %-14.4f %s\n", n, q * 1e3, l * 1e3, ratio);
        prev_q = q;
    }
    printf("  (times in ms.) Doubling n makes the strlen-in-loop version ~4x slower:\n");
    printf("  that is O(n^2). The hoisted version grows ~2x (linear) and is thousands\n");
    printf("  of times faster at the largest size.\n\n");
    printf("Observations:\n");
    printf("  * A function call in a loop condition is re-evaluated every iteration; if\n"
           "    it is O(n), the loop is O(n^2). strlen-in-a-loop is the classic example.\n");
    printf("  * The compiler cannot hoist the call: it cannot prove strlen's result is\n"
           "    invariant (the loop writes the string). You must hoist it by hand.\n");
    printf("  * With memory aliasing (demo 01), these are the two blockers the slides\n"
           "    stress -- procedure calls and memory references.\n");
    return 0;
}
