"""
05_switch_jump_tables.py -- switch statements: jump tables and decision trees
=============================================================================

[Questions this demo answers]
  - How can a switch with many cases take the SAME time for every case?
    (A jump table: one array lookup and one indirect jump.)
  - How are fall-through, shared labels (case 5: case 6:), missing cases and
    default handled?
  - Why does ONE unsigned comparison send both x < 1 and x > 6 to default?
  - What does the compiler do when the cases are far apart? (Compare them in
    a binary-search tree instead.)

[How to run]
  make                      (builds build/oracle_x86 for the check in PART C)
  python3 05_switch_jump_tables.py

[How to read the output]
  PART A decodes clang's jump table straight from simulator memory. PART B
  runs the slides' gcc version (absolute addresses, jmp *.L4(,%rdi,8)) as
  text. PART C runs x = -2..8 through clang's code, gcc's code and the real
  binary. PART D shows the sparse switch's comparison tree.

[Systems link / CS:APP 3.6.8]
  A jump table is an array of code addresses indexed by the switch value.
  It is the reason C restricts case labels to integer constants: the
  compiler must lay them out at compile time.
"""

import os
import subprocess

import course_path
course_path.use("lecture03")
import x86sim                                         # noqa: E402

os.chdir(os.path.dirname(os.path.abspath(__file__)))
M64 = x86sim.MASK[8]

# The slides' gcc version of switch_eg (Lecture 4, slides 34-41), fed to the
# simulator as text: a table of 8-byte ABSOLUTE addresses, indexed by x * 8.
GCC_SWITCH = """
switch_eg:
        movq   %rdx, %rcx           # save z: cqto/idivq will overwrite %rdx
        cmpq   $6, %rdi             # x : 6
        ja     .L8                  # unsigned: x > 6 OR x < 0  -> default
        jmp    *.L4(,%rdi,8)        # goto *JTab[x]
.L3:    movq   %rsi, %rax           # case 1
        imulq  %rdx, %rax           #   y * z
        ret
.L5:    movq   %rsi, %rax           # case 2
        cqto
        idivq  %rcx                 #   y / z
        jmp    .L6                  #   goto merge
.L9:    movl   $1, %eax             # case 3: w = 1
.L6:    addq   %rcx, %rax           # merge: w += z
        ret
.L7:    movl   $1, %eax             # case 5, 6: w = 1
        subq   %rdx, %rax           #   w -= z
        ret
.L8:    movl   $2, %eax             # default: 2
        ret
        .section .rodata
        .align 8
.L4:    .quad .L8, .L3, .L5, .L9, .L8, .L7, .L7    # x = 0 .. 6
"""

C_SOURCE = """    long switch_eg(long x, long y, long z) {
        long w = 1;
        switch (x) {
        case 1:  w = y * z;  break;
        case 2:  w = y / z;  /* Fall Through */
        case 3:  w += z;     break;
        case 5:
        case 6:  w -= z;     break;
        default: w = 2;
        }
        return w;
    }"""


def main():
    print("=== Demo 05: switch statements ===\n")
    print(C_SOURCE + "\n")
    prog = x86sim.Program.from_file(x86sim.compile_to_asm("control.c"))
    m = x86sim.Machine(prog)

    print("PART A: clang's version -- a table of 4-byte RELATIVE offsets")
    print(x86sim.listing(prog, "switch_eg"))
    table = next(a for n, a in prog.labels.items() if n.startswith("LJTI"))
    names = {}
    for n, a in prog.labels.items():
        if n.startswith("LBB"):
            names.setdefault(a, n)
    print("\n  the table at %s (0x%x), read from memory:" % (
        next(n for n, a in prog.labels.items() if a == table and n.startswith("LJTI")), table))
    for k in range(6):
        off = x86sim.to_signed(m.mem.read(table + 4 * k, 4), 4)
        target = table + off
        print("    entry %d (x = %d): offset %+5d -> 0x%x = %s" % (k, k + 1, off, target,
                                                                names.get(target, "?")))
    print("  leaq -1(%rdi), %rcx shifts the cases 1..6 to indices 0..5. Then")
    print("  cmpq $5, %rcx; ja -> default catches x-1 > 5 as UNSIGNED numbers: x = 0")
    print("  gives x-1 = -1 = 0xff..ff, which is 'above' 5, so ONE comparison rejects")
    print("  both x < 1 and x > 6. movslq + addq turn the offset into an address,")
    print("  and jmpq *%rcx is the indirect jump. Default returns 2, preloaded in %eax.\n")

    print("PART B: the slides' gcc version -- 8-byte absolute addresses")
    gprog = x86sim.Program(GCC_SWITCH, name="gcc (slides)")
    g = x86sim.Machine(gprog)
    print(x86sim.listing(gprog, "switch_eg"))
    print("  jmp *.L4(,%rdi,8): read the 8-byte entry at .L4 + 8*x and jump there.\n")

    print("PART C: x = -2..8 (y = 17, z = 5) through clang, gcc and the real binary")
    xs = list(range(-2, 9))
    real = []
    exe = os.path.join("build", "oracle_x86")
    if os.path.exists(exe):
        out = subprocess.run([exe], input="".join("switch_eg %d 17 5\n" % x for x in xs),
                             capture_output=True, text=True).stdout.split()
        real = [int(v) for v in out]
    expected = {1: 17 * 5, 2: 17 // 5 + 5, 3: 1 + 5, 5: 1 - 5, 6: 1 - 5}
    print("    x   C says  clang-sim  gcc-sim  hardware   path in gcc's code")
    for i, x in enumerate(xs):
        c = expected.get(x, 2)
        rc = x86sim.to_signed(m.call("switch_eg", x & M64, 17, 5), 8)
        rg = x86sim.to_signed(g.call("switch_eg", x & M64, 17, 5, trace=True), 8)
        labels = {a: n for n, a in gprog.labels.items() if n.startswith(".L")}
        path = [labels[s.addr] for s in g.trace if s.addr in labels]
        hw = real[i] if real else "-"
        print("  %3d %7d %10d %8d %9s   %s" % (x, c, rc, rg, hw, " -> ".join(path) or "(entry)"))
    print("  x = 2 runs case 2 then FALLS THROUGH into the merge block of case 3.\n")

    print("PART D: sparse_switch -- cases 0, 100, 200, 1000, 10000")
    print(x86sim.listing(prog, "sparse_switch"))
    print("\n  compare instructions executed for each case value:")
    for x in (0, 100, 200, 1000, 10000, 7, 5000):
        r = m.call("sparse_switch", x, trace=True)
        ncmp = sum(1 for s in m.trace if s.text.startswith(("cmp", "test")))
        print("    x = %5d -> returns %3d after %d comparisons" % (x, x86sim.to_signed(r, 8), ncmp))
    print("  A table would need 10001 entries, almost all 'default'. Instead clang")
    print("  splits the range at 199 and searches each half: a decision tree.\n")

    print("Observations:")
    print("  * A dense switch costs the same for every case: bound check, table load,")
    print("    indirect jump. Its table is data -- gcc stores absolute addresses, clang")
    print("    stores 32-bit offsets from the table (smaller, position-independent).")
    print("  * Fall-through is just code placement; shared labels share a table entry;")
    print("    missing cases point at default.")
    print("  * Treating x - 1 as unsigned folds 'too small' and 'too large' into one test.")
    print("  * Sparse cases get a tree of comparisons instead (~log2 of the case count).")


if __name__ == "__main__":
    main()
