#!/bin/sh
# tms-clang -- C IR pipeline: clang IR, the --bitptr semantic barrier, optimize,
# scale the late byte-indexed GEPs, lower the barrier, and restore the M0
# pointer-difference folding.
#
# Usage: tms-clang [-O0|-O2] [-g] [-I dir] -o OUT.ll IN.c
#
# -O0: clang IR -> --bitptr -> --lower-bitptr -> OUT (bit-addressed).
# -O2 (the default): clang IR -> --bitptr -> opt -> --scale -> --lower-bitptr
#                    -> opt -passes=instcombine -> OUT.
#
# -g passes clang -g through to the IR; the barrier passes copy !dbg
# locations, so llc -filetype=obj emits the DWARF `.debug_*` sections.  The
# asm path still has no GSPA-assemblable debug directives.
#
# The barrier is required by the M0/M2 pointer model: pointers are bit
# addresses, so `(int)(p + n) - (int)p` must be 8n at run time (the optimizer's
# DataLayout would otherwise fold it to n).  `--bitptr` replaces every GEP (and
# an inttoptr of a bit addend over a ptrtoint base) with an opaque
# @__tms_bitptr(i32 bitoff, ptr base) call, so InstCombine cannot canonicalize
# the already-scaled bit offset back into a byte-indexed GEP; the M6 post-opt
# `--scale` then multiplied that index by 8 again (the `p += n` over-scale, and
# the reason the shim's memmove used constant end-pointer steps).
#
# The optimizer still creates genuinely byte-indexed GEPs (SROA aggregate
# splits, switch tables), so the post-opt `--scale` is needed for those.  By
# then every original GEP is a call, so the pass only sees optimizer-created
# byte GEPs.  `--normalize` is not used there: it would treat those byte
# offsets as already-scaled bits, which an aggregate return's `.fca.N.gep`
# load (+4 bytes, not +4 bits) turns into an 8x address bug.
#
# `--lower-bitptr` then replaces each call with inttoptr(add(ptrtoint base,
# bitoff)) and the final instcombine restores the M0 pointer-difference folding
# (`int_diff` 8/32, the pointer-difference divide) and canonicalizes the
# lowered bit GEPs, which llc already treats as bit offsets.
set -eu

ROOT=$(cd "$(dirname "$0")/.." && pwd)
# The fork build (TMS34010 target + clang bit-address changes).  The older
# `build/llvm-build` tree is a stock clang without the target and has no
# matching opt, so it is not a usable default.
TMS_CLANG=${TMS_CLANG:-$ROOT/build/llvm-clean-build/bin/clang}
TMS_OPT=${TMS_OPT:-$ROOT/build/llvm-clean-build/bin/opt}
TMS_BITADDR=${TMS_BITADDR:-$ROOT/tools/tms-bitaddr/tms-bitaddr}
# Extra language flags from the caller (M4_EXTRA_CFLAGS).  The conformance
# c-torture sweep uses this for -std=gnu89; shipped gates leave it empty.
TMS_CLANG_EXTRA_FLAGS=${TMS_CLANG_EXTRA_FLAGS:-}

for tool in "$TMS_CLANG" "$TMS_OPT" "$TMS_BITADDR"; do
    if [ ! -x "$tool" ]; then
        echo "tms-clang: missing tool: $tool" >&2
        echo "tms-clang: build the fork (build/llvm-clean-build/bin) or set" \
             "TMS_CLANG/TMS_OPT/TMS_BITADDR" >&2
        exit 1
    fi
done

OPTIMIZE=1
DEBUG_FLAGS=
INCLUDES=
OUT=
IN=

usage() {
    echo "usage: $0 [-O0|-O2] [-g] [-I dir] -o OUT.ll IN.c" >&2
    exit 2
}

while [ $# -gt 0 ]; do
    case "$1" in
    -O0) OPTIMIZE=0; shift ;;
    -O2) OPTIMIZE=1; shift ;;
    -g) DEBUG_FLAGS=-g; shift ;;
    -I) [ $# -ge 2 ] || usage; INCLUDES="$INCLUDES -I $2"; shift 2 ;;
    -I*) INCLUDES="$INCLUDES $1"; shift ;;
    -o) [ $# -ge 2 ] || usage; OUT=$2; shift 2 ;;
    -*) usage ;;
    *) [ -z "$IN" ] || usage; IN=$1; shift ;;
    esac
done

[ -n "$IN" ] || usage
[ -n "$OUT" ] || usage

TMP=$(mktemp -d "${TMPDIR:-/tmp}/tms-clang.XXXXXX")
trap 'rm -rf "$TMP"' EXIT HUP INT TERM

# shellcheck disable=SC2086
"$TMS_CLANG" --target=tms34010-unknown-none -O0 -Xclang -disable-O0-optnone \
    $DEBUG_FLAGS -S -emit-llvm -ffreestanding -fno-builtin -nostdinc $INCLUDES \
    $TMS_CLANG_EXTRA_FLAGS \
    -o "$TMP/step1.ll" "$IN"

# A `static` variadic definition is local, so DeadArgumentElimination removes
# its `...` when nothing keeps the varargs alive and rewrites every call site
# to drop the extra arguments.  The M4 contiguous-stack walk in the body still
# reads those slots, so -O2 silently miscompiles it.  Reject that shape before
# opt, but leave a definition that genuinely uses a va_list alone (M6):
# llvm.va_start/va_arg keep `...` through DAE, and the target lowers the walk
# from the named argument area rather than the last fixed parameter.  -O0
# (which M4's varargs gate uses) and external definitions such as sprintf are
# unaffected.
if [ "$OPTIMIZE" -eq 1 ]; then
    STATIC_VARARG=$(awk '
        /^define / {
            in_def = 1
            sig = $0
            va_start = 0
            next
        }
        in_def && /llvm\.va_start|va_arg ptr/ { va_start = 1 }
        in_def && /^}/ {
            if (!va_start &&
                sig ~ /[^A-Za-z0-9_](internal|private)[^A-Za-z0-9_]/ &&
                sig ~ /\.\.\./) {
                print sig
                exit
            }
            in_def = 0
        }
    ' "$TMP/step1.ll")
    if [ -n "$STATIC_VARARG" ]; then
        NAME=$(printf '%s\n' "$STATIC_VARARG" |
            sed -n 's/.*@\([A-Za-z0-9_.$-]*\)(.*/\1/p')
        echo "tms-clang: error: static variadic definition '${NAME:-?}' loses its" \
            "'...' arguments at -O2 (dead argument elimination); remove 'static'" \
            "or compile with -O0" >&2
        exit 1
    fi
fi

# Hide every source GEP (and source pointer-int arithmetic) behind the opaque
# bit-pointer barrier before the optimizer, so the bit-addressed model survives
# without being re-canonicalized into byte GEPs.
run_bitaddr() { # run_bitaddr MODE IN OUT
    if ! "$TMS_BITADDR" "$1" "$2" "$3" 2> "$TMP/bitaddr.err"; then
        cat "$TMP/bitaddr.err" >&2
        echo "tms-clang: error: tms-bitaddr $1 failed on $2" >&2
        exit 1
    fi
    cp "$TMP/bitaddr.err" "$TMP/bitaddr-$1.log"
}

run_bitaddr --bitptr "$TMP/step1.ll" "$TMP/bitptr.ll"

mkdir -p "$(dirname "$OUT")"

if [ "$OPTIMIZE" -eq 1 ]; then
    # i64 exists since M6, but IndVarSimplify's exit-value replacement still
    # rewrites a loop's final value into a closed-form i33 multiply (e.g.
    # n*(n+1)/2 for sumto), which is an unsupported shape for this 32-bit
    # target.  -replexitval is an option of IndVarSimplify; disabling only that
    # rewrite keeps the loop, which is what ordinary -O2 code needs.  This is a
    # driver policy, not a target TTI policy: opt runs without a target machine
    # here.  llc diagnoses the raw i33 shape reached by an opt run that omits
    # this flag (m5-policy.ll).
    "$TMS_OPT" -passes='default<O2>' -replexitval=never \
        -S "$TMP/bitptr.ll" -o "$TMP/opt.ll"
    # The optimizer may create new byte-indexed GEPs (SROA aggregate splits,
    # switch tables), so scale those.  Every source GEP is still an opaque call,
    # so this pass cannot see (and re-scale) an already-bit offset.
    run_bitaddr --scale "$TMP/opt.ll" "$TMP/scaled.ll"
    # Lower the barrier and restore the M0 pointer-difference folding.  The
    # lowered inttoptr(add) shapes canonicalize to GEPs whose index is already
    # a bit count; llc treats a GEP index as a bit offset, and no scale follows.
    # `no-verify-fixpoint` suppresses only InstCombine's idempotence check: the
    # M6 shim's emit_uint64 has a `zext i32 %base to i64` that a second run
    # would re-mark `nneg`, which the verifier reports as "did not reach a
    # fixpoint".  The first run's output is the intended IR and all gates pass
    # with it; the flag is the documented escape for this known shape.
    run_bitaddr --lower-bitptr "$TMP/scaled.ll" "$TMP/lowered.ll"
    "$TMS_OPT" -passes='instcombine<no-verify-fixpoint>' \
        -S "$TMP/lowered.ll" -o "$OUT"
else
    # No optimizer, so no byte GEPs can be created; lower the barrier directly
    # back to the historical bit-addressed inttoptr(add) form.
    run_bitaddr --lower-bitptr "$TMP/bitptr.ll" "$OUT"
fi
