"""
06_crosscheck.py -- is the simulator telling the truth?
=======================================================

[Questions this demo answers]
  - Every other demo trusts x86sim. Does it compute the same answers as a
    real x86-64 processor running the same machine code?
  - Does the native build (arm64 on Apple Silicon) agree with both? It
    should: different ISA, same C semantics (for code without undefined
    behavior).

[How to run]
  make              (builds build/oracle and build/oracle_x86)
  python3 06_crosscheck.py

[How to read the output]
  One row per function: how many test inputs, and how many times the
  simulator (sim) or the native build disagreed with the real x86-64 run.
  Every count should be 0.

[Method]
  For each function we generate inputs: edge values (0, 1, -1, TMin, TMax,
  ...) plus seeded random ones. The same lines go to
    build/oracle_x86   -- the real compiled funcs.c, x86-64 (Rosetta 2 on a Mac)
    build/oracle       -- the real compiled funcs.c for this machine
    x86sim             -- the compiler's x86-64 assembly, simulated
  Inputs for arith/m12/decision/plus are kept small enough that the C code
  never overflows: signed overflow is undefined behavior (Lecture 2), so a
  disagreement there would teach nothing.
"""

import os
import random
import subprocess
import sys

import x86sim

os.chdir(os.path.dirname(os.path.abspath(__file__)))
M64 = x86sim.MASK[8]
TMIN, TMAX = -(1 << 63), (1 << 63) - 1
EDGE = [0, 1, -1, 2, -2, 7, 8, 100, -100, TMIN, TMAX, TMIN + 1, TMAX - 1,
        0x7FFFFFFF, -0x80000000, 0xFFFFFFFF, 0x0123456789ABCDEF]


def inputs(rng, kind, n=300):
    """
    [Returns] a list of argument tuples.
    kind: 'any1'/'any2' = any 64-bit values; 'small3' = values in +-2^20
      (no overflow possible in arith); 'small1'/'small2' similar; 'idx' = 0..7.
    """
    out = []
    if kind == "idx":
        return [(i,) for i in range(8)]
    arity = int(kind[-1])
    small = kind.startswith("small")
    pool = [e for e in EDGE if not small or abs(e) < (1 << 20)]
    for _ in range(n):
        args = []
        for _ in range(arity):
            if rng.random() < 0.3:
                args.append(rng.choice(pool))
            elif small:
                args.append(rng.randint(-(1 << 20), 1 << 20))
            else:
                args.append(rng.randint(TMIN, TMAX))
        out.append(tuple(args))
    return out


def run_oracle(exe, lines):
    if not os.path.exists(exe):
        return None
    res = subprocess.run([exe], input="".join(lines), capture_output=True, text=True)
    return [l.strip() for l in res.stdout.splitlines()]


def sim_result(m, name, args):
    """Run one test in the simulator and format it like oracle.c does."""
    if name == "swap":
        m.mem.write(0x1000, 8, args[0])
        m.mem.write(0x1008, 8, args[1])
        m.call("swap", 0x1000, 0x1008)
        return "%d %d" % (x86sim.to_signed(m.mem.read(0x1000, 8), 8),
                          x86sim.to_signed(m.mem.read(0x1008, 8), 8))
    if name == "load_idx":
        for k in range(8):
            m.mem.write(0x2000 + 8 * k, 8, 10 * (k + 1))
        return str(x86sim.to_signed(m.call("load_idx", 0x2000, args[0]), 8))
    if name == "sumstore":
        m.mem.write(0x3000, 8, 0)
        m.call("sumstore", args[0] & M64, args[1] & M64, 0x3000)
        return str(x86sim.to_signed(m.mem.read(0x3000, 8), 8))
    r = m.call(name, *[a & M64 for a in args])
    if name in ("gt", "below", "is_zero"):
        return str(x86sim.to_signed(r, 4))           # these return int
    if name == "shr3":
        return str(r)                                # unsigned long
    return str(x86sim.to_signed(r, 8))


def main():
    print("=== Demo 06: simulator vs real hardware ===\n")
    if not os.path.exists("build/oracle_x86"):
        subprocess.run(["make", "-s", "all"])
    prog = x86sim.Program.from_file(x86sim.compile_to_asm("funcs.c"))
    m = x86sim.Machine(prog)
    rng = random.Random(15213)
    tests = [("arith", "small3"), ("m12", "small1"), ("logic", "any2"), ("sar3", "any1"),
             ("shr3", "any1"), ("gt", "any2"), ("below", "any2"), ("is_zero", "any1"),
             ("decision", "small1"), ("plus", "small2"), ("swap", "any2"),
             ("load_idx", "idx"), ("sumstore", "small2"),
             ("alias_movl", "any1"), ("alias_movw", "any1"), ("alias_movb", "any1")]
    print("  %-11s %6s   %-16s %-16s" % ("function", "cases", "sim != x86 HW", "native != x86 HW"))
    total_sim = total_native = 0
    for name, kind in tests:
        cases = inputs(rng, kind)
        lines = ["%s %s\n" % (name, " ".join(str(a) for a in args)) for args in cases]
        hw = run_oracle("build/oracle_x86", lines)
        native = run_oracle("build/oracle", lines)
        if hw is None:
            print("  build/oracle_x86 is missing (no x86-64 compiler?) -- cannot cross-check")
            sys.exit(1)
        sim = [sim_result(m, name, args) for args in cases]
        bad_sim = sum(1 for s, h in zip(sim, hw) if s != h)
        bad_nat = (sum(1 for nv, h in zip(native, hw) if nv != h)
                   if native and native[0] != "n/a" else None)
        total_sim += bad_sim
        total_native += bad_nat or 0
        print("  %-11s %6d   %-16d %-16s" % (name, len(cases), bad_sim,
                                            "n/a (x86 only)" if bad_nat is None else bad_nat))
    print()
    print("Observations:")
    print("  * Total disagreements: simulator %d, native build %d. The simulator" % (total_sim, total_native))
    print("    reproduces the real x86-64 results bit for bit on these functions,")
    print("    including partial-register writes and flag-based setcc.")
    print("  * The arm64 build agrees too: a different ISA implements the same C,")
    print("    as long as the C has no undefined behavior.")


if __name__ == "__main__":
    main()
