"""
02_branches_and_cmov.py -- if/else as a jump, or as a conditional move
======================================================================

[Questions this demo answers]
  - absdiff(x, y) has an if/else, yet its assembly has NO jump. How?
    (Compute both answers, then pick one with cmov.)
  - When must the compiler use a real branch instead? (When a branch has a
    side effect, or computing it could fault -- e.g. dereferencing NULL.)
  - What does the "goto version" of an if/else look like?

[How to run]
  python3 02_branches_and_cmov.py

[How to read the output]
  For each function: the clang -Og assembly, then a trace for two inputs
  that take different directions. Notes on the right say which "branch"
  each instruction belongs to.

[Systems link / CS:APP 3.6.5-3.6.6]
  Modern CPUs run far ahead of the instruction they are finishing, so they
  must GUESS which way each branch goes (branch prediction). A wrong guess
  throws away ~15-20 cycles of work. A conditional move has no direction to
  guess, so for short, safe, unpredictable conditions it is faster -- see
  03_branch_prediction.c for the measurement.
"""

import os

import course_path
course_path.use("lecture03")
import x86sim                                         # noqa: E402  (after the path setup)

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


def show_trace(m, name, args, label):
    r = m.call(name, *[a & M64 for a in args], trace=True)
    print("    %s:" % label)
    for st in m.trace:
        parts = ["%%%s=%d" % (reg, x86sim.to_signed(new, 8)) for reg, old, new in st.reg_changes
                 if reg != "rsp"]
        names = {addr: label for label, addr in m.prog.labels.items()}   # address -> symbol
        parts += ["M[%s] %d->%d" % (names.get(a, hex(a)), x86sim.to_signed(o, s),
                                    x86sim.to_signed(n, s))
                  for a, s, o, n in (st.mem_changes or [])]
        if st.note and "Machine.call" not in st.note:
            parts.append("(%s)" % st.note)
        print("      %-24s %s" % (st.text, "  ".join(parts)))
    return x86sim.to_signed(r, 8)


def main():
    print("=== Demo 02: branches vs conditional moves ===\n")
    prog = x86sim.Program.from_file(x86sim.compile_to_asm("control.c"))
    m = x86sim.Machine(prog)

    print("PART A: absdiff(x, y) = |x - y|  -- no jump at all")
    print(x86sim.listing(prog, "absdiff"))
    for x, y in ((3, 10), (10, 3)):
        r = show_trace(m, "absdiff", (x, y), "x=%d, y=%d" % (x, y))
        print("      -> %d" % r)
    print("  Both x - y (in %rax) and y - x (in %rsi) are ALWAYS computed. cmovge reads")
    print("  the flags of the LAST flag-setting instruction, subq %rdi, %rsi (= y - x):")
    print("  it copies y - x into %rax exactly when y - x >= 0; otherwise %rax keeps x - y.\n")

    print("PART B: absdiff_se -- each branch increments a global counter")
    print(x86sim.listing(prog, "absdiff_se"))
    lt, ge = prog.address_of("lt_cnt"), prog.address_of("ge_cnt")
    for x, y in ((3, 10), (10, 3)):
        m.mem.write(lt, 8, 0)
        m.mem.write(ge, 8, 0)
        r = show_trace(m, "absdiff_se", (x, y), "x=%d, y=%d" % (x, y))
        print("      -> %d   lt_cnt=%d ge_cnt=%d" % (r, m.mem.read(lt, 8), m.mem.read(ge, 8)))
    print("  A cmov version would have to do BOTH increments -- wrong -- so the")
    print("  compiler emits a conditional jump (jge) around the 'then' part.")
    print("  incq _lt_cnt(%rip) updates a global in place: a memory operand addressed")
    print("  relative to the instruction pointer.\n")

    print("PART C: cond_deref(p) = p ? *p : 0  -- computing *p early could crash")
    print(x86sim.listing(prog, "cond_deref"))
    m.mem.write(0x5000, 8, 42)
    for p, label in ((0x5000, "p points to 42"), (0, "p = NULL")):
        r = show_trace(m, "cond_deref", (p,), label)
        print("      -> %d" % r)
    print("  With p = NULL the load movq (%rdi), %rax is never executed. A cmov")
    print("  version would execute it first and fault (segmentation fault).\n")

    print("The 'goto version' of absdiff_se, as the compiler built it:")
    print("    long absdiff_se(long x, long y) {")
    print("        long result = x - y;          // subq sets the flags")
    print("        if (x - y >= 0) goto ge;      // jge LBB1_2")
    print("        lt_cnt++;  return y - x;")
    print("    ge: ge_cnt++;  return result;")
    print("    }\n")

    print("Observations:")
    print("  * An if/else needs no jump if both sides are cheap, safe and free of side")
    print("    effects: compute both, then cmov selects (absdiff).")
    print("  * Side effects (absdiff_se) or possible faults (cond_deref) force a real")
    print("    conditional jump; only one side may run.")
    print("  * In assembly, every structured if/else is 'test, then goto'.")


if __name__ == "__main__":
    main()
