"""
04_recursion.py -- recursion needs nothing new: one frame per active call
==========================================================================

[Questions this demo answers]
  - pcount_r calls itself. How can several "copies" of the same function be
    active at once without overwriting each other's values?
  - How much stack does a recursive call cost, and how does that grow with
    the input?
  - What changes when the recursion is a TAIL call, and what does an
    optimizing compiler do with recursion?

[How to run]
  python3 04_recursion.py

[How to read the output]
  PART A stops pcount_r(13) at its deepest point and draws the whole stack:
  one frame per active call, each holding the CALLER's saved registers.
  PART B measures depth and stack use for several inputs, checked against
  the real x86-64 code. PART C runs the slides' gcc version as text. PART D
  is the tail-recursive popcount_t, and PART E shows clang -O1 turning all
  three recursive functions into loops.

[Systems link / CS:APP 3.7.6]
  Recursion works "for free" because of three things you have already seen:
  each call gets its own frame (private storage), callee-saved registers are
  saved in that frame (so an inner call cannot destroy an outer call's
  values), and the stack is last-in first-out like the calls themselves.
"""

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__)))

# The slides' gcc -Og listing of pcount_r ("Recursive Function"), run as text.
GCC_PCOUNT_R = """
pcount_r:
  movl    $0, %eax
  testq   %rdi, %rdi
  je      .L6
  pushq   %rbx
  movq    %rdi, %rbx
  andl    $1, %ebx
  shrq    %rdi
  call    pcount_r
  addq    %rbx, %rax
  popq    %rbx
.L6:
  rep; ret
"""


def run_measured(prog, name, *args):
    """
    Run name(*args); [Returns] (result, number of calls to `name` including
    the first, deepest stack use in bytes below the initial return address).
    """
    m = x86sim.Machine(prog)
    m.start(name, *args)
    entry = m.regs["rsp"]
    lowest, calls = entry, 1
    target = prog.address_of(name)
    while not m.halted:
        ins = prog.instrs[prog.by_addr[m.rip]]
        m.step()
        if ins.op == "call" and m.rip == target:
            calls += 1
        lowest = min(lowest, m.regs["rsp"])
    return m.regs["rax"], calls, entry - lowest


def oracle(binary, lines):
    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 part_a(prog):
    print("PART A: pcount_r(13) at its deepest point (13 = 0b1101)")
    print(x86sim.listing(prog, "pcount_r"))
    m = x86sim.Machine(prog)
    m.regs["r14"], m.regs["rbx"] = 0xAAAA, 0xBBBB     # the outside caller's values
    m.start("pcount_r", 13)
    target = prog.address_of("pcount_r")
    entries = [m.regs["rsp"]]                          # entry %rsp of each activation
    xs = [13]
    while True:
        ins = prog.instrs[prog.by_addr[m.rip]]
        m.step()
        if ins.op == "call" and m.rip == target:
            entries.append(m.regs["rsp"])
            xs.append(m.regs["rdi"])
            if m.regs["rdi"] == 0:
                break
    notes = {}
    for depth, e in enumerate(entries[1:], 1):
        caller_x = xs[depth - 1]
        notes[e - 8] = "pcount_r(%d)'s frame: saved %%r14 = %d = x&1 of its caller, pcount_r(%d)" \
            % (xs[depth], caller_x & 1, caller_x)
        notes[e - 16] = "saved %%rbx = %d = x of its caller" % caller_x
        notes[e - 24] = "padding"
    notes[entries[0] - 8] = "pcount_r(13)'s frame: saved %r14 = 0xaaaa (outside caller's value)"
    notes[entries[0] - 16] = "saved %rbx = 0xbbbb (outside caller's value)"
    notes[entries[0] - 24] = "padding"
    print("\n  Stopped as the call with x = 0 begins: %d activations are alive"
          % len(entries))
    print("  (x = %s), so there are %d frames:"
          % (", ".join(str(x) for x in xs), len(entries)))
    print(frames.draw(m, notes=notes))
    print("  Each frame stores its CALLER's %r14 and %rbx: when an inner call needs")
    print("  those registers for its own x and x&1, the outer call's values wait")
    print("  safely in memory and come back with the pops on the way out.")
    while not m.halted:
        m.step()
    print("  pcount_r(13) = %d.\n" % m.regs["rax"])


def part_b(prog):
    print("PART B: stack use grows with the recursion depth (clang -Og)")
    xs = [0, 1, 13, 0xFF, 1 << 20, (1 << 64) - 1]
    real = oracle("build/oracle_x86", ["pcount_r %d" % x for x in xs])
    print("  %-22s %-7s %-9s %-7s %-12s %s" % ("x", "result", "real x86", "calls", "stack bytes",
                                              "bytes per call"))
    for x, r in zip(xs, real):
        res, calls, depth = run_measured(prog, "pcount_r", x)
        print("  %-22s %-7d %-9s %-7d %-12d %s" % (hex(x), res, r, calls, depth,
                                                   "%.0f" % ((depth + 8) / calls)))
    print("  calls = 1 + the position of the highest 1 bit; every call costs 32")
    print("  bytes (return address + %r14 + %rbx + 8 bytes of padding), so the")
    print("  deepest stack is 32 * calls bytes including the first return address.\n")


def part_c():
    print("PART C: the slides' gcc version (run as text)")
    print("  gcc tests x == 0 BEFORE saving %rbx, so the last call needs no saves at")
    print("  all, and it uses one callee-saved register, not two (clang -Og keeps x")
    print("  alive in %rbx for the debugger).")
    prog = x86sim.Program(GCC_PCOUNT_R, "slides-gcc")
    print("  %-22s %-7s %-7s %s" % ("x", "result", "calls", "stack bytes"))
    for x in [0, 1, 13, (1 << 64) - 1]:
        res, calls, depth = run_measured(prog, "pcount_r", x)
        print("  %-22s %-7d %-7d %d" % (hex(x), res, calls, depth))
    print("  16 bytes per call (return address + saved %rbx), except that the last")
    print("  call, with x = 0, saves nothing: 16 * (calls - 1) bytes in all.\n")


def part_d(prog):
    print("PART D: tail recursion -- popcount_t(x, s)")
    print("  long popcount_t(unsigned long x, long s) {")
    print("      if (x == 0) return s;  long b = x & 1UL;  return popcount_t(x >> 1, s + b); }")
    print(x86sim.listing(prog, "popcount_t"))
    print("  %-22s %-7s %-7s %s" % ("x", "result", "calls", "stack bytes"))
    for x in [0, 13, (1 << 64) - 1]:
        res, calls, depth = run_measured(prog, "popcount_t", x, 0)
        print("  %-22s %-7d %-7d %d" % (hex(x), res, calls, depth))
    print("  Nothing is left to do after the recursive call, so clang emits")
    print("  `jmp _popcount_t` instead of `call`: the callee REUSES the frame (and the")
    print("  return address) of the current call. Stack use: 0 bytes, for any x.\n")


def part_e():
    print("PART E: clang -O1 removes the recursion altogether")
    prog = x86sim.Program.from_file(x86sim.compile_to_asm("procs.c", opt="-O1"))
    print(x86sim.listing(prog, "pcount_r"))
    print("  %-12s %-22s %-7s %-7s %s" % ("function", "argument", "result", "calls", "stack bytes"))
    for name, args in [("pcount_r", ((1 << 64) - 1,)), ("popcount_t", ((1 << 64) - 1, 0)),
                       ("rfact", (20,))]:
        res, calls, depth = run_measured(prog, name, *args)
        print("  %-12s %-22s %-7d %-7d %d" % (name, ", ".join(hex(a) if a > 99 else str(a) for a in args),
                                              x86sim.to_signed(res, 8), calls, depth))
    print("  pcount_r is NOT tail recursive ((x&1) is added after the call returns),")
    print("  but + is associative, so the compiler rewrites it with an accumulator,")
    print("  exactly like popcount_t, and then the tail call becomes a loop. rfact gets")
    print("  the same treatment because * is associative too. The C language does not")
    print("  promise this; never rely on it for deep recursion.\n")


def main():
    print("=== Demo 04: recursion ===\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()
    part_d(prog)
    part_e()
    print("Observations:")
    print("  * Each active call has its own frame; the frames of a recursion are")
    print("    stacked exactly like the slides' yoo/who/amI picture.")
    print("  * Callee-saved registers are what keep one call's values safe from the")
    print("    next: every call saves its caller's copies before reusing the registers.")
    print("  * Stack use = (frame size) x (depth). Deep recursion can run out of stack")
    print("    (demo 05 measures the real limit); tail calls and loops do not grow it.")


if __name__ == "__main__":
    main()
