"""
07_array_code.py -- the machine code for array accesses, traced
================================================================

[Questions this demo answers]
  - How does `z[digit]` become one `movl` with a scaled-index operand, and
    why is there a `movslq` in front of it?
  - pgh[index][dig] (nested) and univ[index][dig] (multi-level) look the same
    in C. How many memory reads does each one cost?
  - Why does a fixed-size 16x16 matrix need a shift, but a variable-size n x n
    matrix a multiply?
  - How does the compiler walk a column of a matrix in a loop?

[How to run]
  python3 07_array_code.py

[How to read the output]
  Each part prints clang's -Og listing and a trace. Memory reads are listed
  with the symbol they hit ("pgh+52" = 52 bytes into pgh). The last column of
  the checks compares the simulator with the real x86-64 machine code.

[Systems link / CS:APP 3.8]
  An array access is an address computation (often folded into ONE operand,
  D(Rb,Ri,S)) plus a memory access. Counting memory accesses matters: in
  Lectures 9-10 you will see that a memory access can cost 100x more than an
  add.
"""

import os
import subprocess

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

os.chdir(os.path.dirname(os.path.abspath(__file__)))

HEAP = 0x10000       # where the demo puts matrices in the simulator's memory


def oracle(lines):
    binary = "build/oracle_x86"
    if not os.path.exists(binary):
        return ["(not built)"] * len(lines)
    out = subprocess.run([binary], input="\n".join(lines) + "\n", capture_output=True,
                         text=True, check=True).stdout
    return out.split("\n")[:len(lines)]


def reads_of(m, prog):
    """Data memory reads of the last traced call (not stack reads by ret)."""
    out = []
    for st in m.trace:
        if st.text.startswith(("ret", "retq", "pop")):
            continue
        for addr, size in st.mem_reads:
            out.append("%s (%d bytes)" % (frames.symbolize(prog, addr) or hex(addr), size))
    return out


def part_a(prog):
    print("PART A: get_digit(cmu, digit) -- one scaled-index load")
    print(x86sim.listing(prog, "get_digit"))
    m = x86sim.Machine(prog)
    r = m.call("get_digit", prog.address_of("cmu"), 3, trace=True)
    print(x86sim.format_trace(m.trace))
    print("  get_digit(cmu, 3) = %d; memory read: %s" % (r, ", ".join(reads_of(m, prog))))
    print("  `digit` is an int (4 bytes), but an address needs 64 bits, so clang first")
    print("  sign-extends it with movslq. The slides' listing omits that step.\n")


def part_b(prog):
    print("PART B: zincr(z) -- a loop over an array (z[i]++ for i = 0..4)")
    print(x86sim.listing(prog, "zincr"))
    m = x86sim.Machine(prog)
    for k, v in enumerate([1, 5, 2, 1, 3]):
        m.mem.write(HEAP + 4 * k, 4, v)
    m.call("zincr", HEAP, trace=True)
    after = [m.mem.peek(HEAP + 4 * k, 4) for k in range(5)]
    incs = [st for st in m.trace if st.text.startswith("incl")]
    print("  %d executions of `incl (%%rdi,%%rax,4)`; the array becomes %s" % (len(incs), after))
    print("  One instruction reads, adds 1 and writes back each element; %rax is i and")
    print("  the scale 4 turns it into a byte offset. (The final `movl $5, %eax` only")
    print("  keeps i visible to a debugger -- an -Og artifact, not part of the C code.)\n")


def part_c(prog):
    print("PART C: nested vs multi-level -- same C syntax, different machine work")
    for name in ("get_pgh_digit", "get_univ_digit"):
        print("  %s:" % name)
        print(x86sim.listing(prog, name))
    rows = [("get_pgh_digit", 1, 2), ("get_pgh_digit", 3, 4), ("get_univ_digit", 1, 2),
            ("get_univ_digit", 2, 0)]
    real = oracle(["%s %d %d" % r for r in rows])
    print("\n  %-22s %-6s %-6s %-48s %s" % ("call", "sim", "real", "memory reads (in order)", "count"))
    for (name, i, j), rr in zip(rows, real):
        m = x86sim.Machine(prog)
        r = m.call(name, i, j, trace=True)
        reads = reads_of(m, prog)
        print("  %-22s %-6d %-6s %-48s %d" % ("%s(%d, %d)" % (name, i, j), r, rr, ", ".join(reads),
                                              len(reads)))
    print("  pgh[1][2] is at pgh + 4*(5*1 + 2) = pgh+28: computed by two leas, then ONE")
    print("  read. univ[1][2] first READS the row pointer univ[1] (at univ+8, holding")
    print("  &cmu), then reads cmu+8: TWO reads, the first one feeding the second.\n")


def fill_matrix(m, base, n, f):
    for r in range(n):
        for c in range(n):
            m.mem.write(base + 4 * (n * r + c), 4, f(r, c) & 0xFFFFFFFF)


def part_d(prog):
    print("PART D: fixed 16x16 vs variable n x n matrices")
    print("  fix_ele(A, i, j)  with  typedef int fix_matrix[16][16]:")
    print(x86sim.listing(prog, "fix_ele"))
    print("  var_ele(n, A, i, j)  with  int A[n][n]:")
    print(x86sim.listing(prog, "var_ele"))
    m = x86sim.Machine(prog)
    fill_matrix(m, HEAP, 16, lambda r, c: 100 * r + c)
    cases = [(i, j) for i in range(16) for j in range(16)]
    real = oracle(["fix_ele %d %d" % c for c in cases])
    ok = sum(str(x86sim.to_signed(m.call("fix_ele", HEAP, i, j), 4)) == rr
             for (i, j), rr in zip(cases, real))
    print("  fix_ele on F[r][c] = 100r + c, all 256 (i, j): %d of 256 agree with x86-64" % ok)
    ok = total = 0
    for n in (1, 3, 5, 7):
        m = x86sim.Machine(prog)
        fill_matrix(m, HEAP, n, lambda r, c: 1000 * r + c)
        cases = [(i, j) for i in range(n) for j in range(n)]
        real = oracle(["var_ele %d %d %d" % (n, i, j) for i, j in cases])
        ok += sum(str(x86sim.to_signed(m.call("var_ele", n, HEAP, i, j), 4)) == rr
                  for (i, j), rr in zip(cases, real))
        total += len(cases)
    print("  var_ele on V[r][c] = 1000r + c, n = 1, 3, 5, 7, all (i, j): %d of %d agree" % (ok, total))
    print("  Row length 16*4 = 64 bytes is a power of two: `shlq $6` (x64). With n")
    print("  known only at run time, the row length 4n needs `imulq` -- C99 variable-")
    print("  length arrays make the compiler do the index arithmetic you would")
    print("  otherwise write by hand as A[i*n + j].\n")


def part_e():
    print("PART E: fix_prod_ele(A, B, i, k) -- a dot product of row i and column k")
    print("  for (j = 0; j < 16; j++) result += A[i][j] * B[j][k];")
    for opt in ("-Og", "-O1"):
        prog = x86sim.Program.from_file(x86sim.compile_to_asm("procs.c", opt=opt))
        print("  clang %s:" % opt)
        print(x86sim.listing(prog, "fix_prod_ele"))
        m = x86sim.Machine(prog)
        P, Q = HEAP, HEAP + 0x1000
        fill_matrix(m, P, 16, lambda r, c: (7 * r + 3 * c) % 11 - 5)
        fill_matrix(m, Q, 16, lambda r, c: (5 * r + 2 * c) % 13 - 6)
        cases = [(i, k) for i in range(16) for k in range(16)]
        real = oracle(["fix_prod_ele %d %d" % c for c in cases])
        ok = sum(str(x86sim.to_signed(m.call("fix_prod_ele", P, Q, i, k), 4)) == rr
                 for (i, k), rr in zip(cases, real))
        print("    all 256 (i, k): %d of 256 agree with x86-64" % ok)
    print("  Neither version computes B + 64*j + 4*k from scratch: a pointer starts at")
    print("  &B[0][k] and moves `addq $64` (one row) per iteration -- CS:APP's")
    print("  \"strength reduction\" of an index into a running pointer.\n")


def main():
    print("=== Demo 07: array code ===\n")
    if not os.path.exists("build/oracle_x86"):
        subprocess.run(["make", "-s", "build/oracle_x86"], check=False)
    prog = x86sim.Program.from_file(x86sim.compile_to_asm("procs.c"))
    part_a(prog)
    part_b(prog)
    part_c(prog)
    part_d(prog)
    part_e()
    print("Observations:")
    print("  * 1-D access: one operand (%rdi,%rcx,4) does base + 4*index; int indexes")
    print("    are sign-extended to 64 bits first.")
    print("  * Nested arrays: the row offset is arithmetic (lea, shl or imul) and the")
    print("    element costs one read. Multi-level arrays: one extra read per level.")
    print("  * Fixed sizes let the compiler use shifts; variable sizes need imul.")
    print("  * In loops, compilers replace index arithmetic by pointers that step by")
    print("    the element (4) or row (64) size.")


if __name__ == "__main__":
    main()
