"""
05_condition_codes.py -- cmp, test, the four flags, set<cc> and j<cc>
=====================================================================

[Questions this demo answers]
  - cmp b, a computes a - b and throws the result away. What does it keep?
    (Four 1-bit condition codes: CF ZF SF OF.)
  - Why does "signed less than" (jl) test SF ^ OF instead of just SF?
  - Why are there two families of comparisons: g/l (signed) and a/b
    (unsigned, "above"/"below")?
  - Is the slide's j<cc> table right? (We check it on ALL 65,536 pairs of
    bytes against Python's own signed and unsigned comparisons.)
  - How does if/else become test + je + jmp? (decision())

[How to run]
  python3 05_condition_codes.py     (PART C takes a few seconds)

[Systems link / CS:APP 3.6.1-3.6.3]
  CF = carry out of the top bit   -> unsigned overflow (Lecture 2 section 7.2)
  ZF = result is zero
  SF = top bit of the result      -> "negative" if read as signed
  OF = two's-complement overflow  -> same-sign operands, different-sign result
  Every comparison in C becomes cmp/test, then one instruction that reads a
  combination of these four bits.
"""

import os

import x86sim

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

M64 = x86sim.MASK[8]
TMIN, TMAX = -(1 << 63), (1 << 63) - 1
SHOWN = ["e", "ne", "g", "ge", "l", "le", "a", "b"]


def flags_after_cmp(m, a, b):
    """Run 'cmpq %rsi, %rdi' (computes a - b) and return the flags dict."""
    m.call("f", a & M64, b & M64)
    return dict(m.flags)


def part_a():
    print("PART A: cmpq %rsi, %rdi computes  a - b  (a in %rdi, b in %rsi)")
    m = x86sim.Machine(x86sim.Program("f: cmpq %rsi, %rdi\n ret"))
    pairs = [(3, 2), (2, 3), (2, 2), (-1, 2), (TMIN, 1), (TMAX, -1)]
    print("  %-22s %-22s CF ZF SF OF   true conditions" % ("a", "b"))
    for a, b in pairs:
        f = flags_after_cmp(m, a, b)
        true = [c for c in SHOWN if x86sim.CONDITIONS[c](f)]
        print("  %-22d %-22d %d  %d  %d  %d    %s" % (a, b, f["CF"], f["ZF"], f["SF"], f["OF"],
                                                       " ".join(true)))
    print("  -> (-1, 2): signed -1 < 2 (l), but as unsigned 0xff..ff > 2 (a): same")
    print("     flags, two readings. That is why C's signedness picks jl vs jb.")
    print("  -> (TMin, 1): TMin - 1 overflows to TMax, so SF = 0 'looks positive',")
    print("     but OF = 1 says the sign is wrong: a < b is SF ^ OF = 1. Correct.")
    print("  -> (TMax, -1): TMax - (-1) overflows to TMin: SF = 1, OF = 1 -> g holds.\n")


def part_b(prog):
    print("PART B: test %rdi, %rdi (= AND with itself) sets only ZF and SF")
    m = x86sim.Machine(prog)
    print(x86sim.listing(prog, "is_zero"))
    for x in (0, 42, -42):
        r = m.call("is_zero", x & M64, trace=True)
        test_step = [s for s in m.trace if s.text.startswith("test")][0]
        print("    x = %4d: ZF=%d SF=%d -> sete gives %d" % (x, test_step.flags["ZF"],
                                                          test_step.flags["SF"], r))
    print("  -> 'xorl %eax,%eax' comes FIRST: sete writes only %al, so %eax must be")
    print("     zeroed beforehand; and xor itself changes the flags, so it cannot")
    print("     come between test and sete.\n")


def part_c():
    print("PART C: checking the j<cc> table on every pair of bytes (cmpb)")
    m = x86sim.Machine(x86sim.Program("f: cmpb %sil, %dil\n ret"))
    checks = {
        "e":  lambda sa, sb, ua, ub: sa == sb,
        "ne": lambda sa, sb, ua, ub: sa != sb,
        "g":  lambda sa, sb, ua, ub: sa > sb,
        "ge": lambda sa, sb, ua, ub: sa >= sb,
        "l":  lambda sa, sb, ua, ub: sa < sb,
        "le": lambda sa, sb, ua, ub: sa <= sb,
        "a":  lambda sa, sb, ua, ub: ua > ub,
        "ae": lambda sa, sb, ua, ub: ua >= ub,
        "b":  lambda sa, sb, ua, ub: ua < ub,
        "be": lambda sa, sb, ua, ub: ua <= ub,
    }
    wrong = {c: 0 for c in checks}
    naive_sf = 0                                    # "jl = SF" (ignoring OF)
    for ua in range(256):
        for ub in range(256):
            m.call("f", ua, ub)
            f = m.flags
            sa, sb = x86sim.to_signed(ua, 1), x86sim.to_signed(ub, 1)
            for c, truth in checks.items():
                if bool(x86sim.CONDITIONS[c](f)) != truth(sa, sb, ua, ub):
                    wrong[c] += 1
            if bool(f["SF"]) != (sa < sb):
                naive_sf += 1
    for c in checks:
        print("    j%-3s disagrees with Python's comparison in %d of 65536 cases" % (c, wrong[c]))
    print("    a naive 'less = SF' rule would be wrong in %d cases (all overflows)\n" % naive_sf)


def part_d(prog):
    print("PART D: if/else in assembly -- decision(x) { if (x) return op1(x); else return op2(x); }")
    print(x86sim.listing(prog, "decision"))
    m = x86sim.Machine(prog)
    for x in (5, 0):
        r = m.call("decision", x, trace=True)
        path = []
        for st in m.trace:
            path.append(st.text.split()[0] + (" (%s)" % st.note if st.note else ""))
        print("    x = %d: %s  ->  returns %d" % (x, " ; ".join(path), x86sim.to_signed(r, 8)))
    print("  -> 'jmp _op1' is a TAIL CALL: decision's last act is to call op1, so the")
    print("     compiler jumps there and lets op1's ret return straight to our caller.")
    print("     In the x = 0 branch it passes the KNOWN value 0 with xorl %edi,%edi.\n")


def main():
    print("=== Demo 05: condition codes ===\n")
    prog = x86sim.Program.from_file(x86sim.compile_to_asm("funcs.c"))
    part_a()
    part_b(prog)
    part_c()
    part_d(prog)
    print("Observations:")
    print("  * cmp/test compute a result only to set CF ZF SF OF; j<cc>, set<cc> and")
    print("    cmov<cc> then read a combination of those 4 bits.")
    print("  * The SAME flags answer both signed (g, l: SF, OF, ZF) and unsigned (a, b:")
    print("    CF, ZF) questions; the C types decide which instruction is emitted.")
    print("  * Signed 'less' must be SF ^ OF: SF alone is wrong whenever the")
    print("    subtraction overflowed. The slide's table is right on all 65536 pairs.")
    print("  * if/else is just a conditional jump around code -- assembly 'has goto'.")


if __name__ == "__main__":
    main()
