"""
03_arith_and_lea.py -- addressing modes, lea, and the arith() example
=====================================================================

[Questions this demo answers]
  - The general memory operand D(Rb,Ri,S) means  D + Reg[Rb] + S*Reg[Ri].
    What addresses do the slide's four examples compute?
  - mov and lea take the SAME operand text. What is the difference?
  - How does the compiler compute arith(x, y, z) -- and why does y*48 need no
    multiply instruction, and x*12 not even a shift?

[How to run]
  python3 03_arith_and_lea.py

[How to read the output]
  PART A prints the slide's address-computation table, computed by the
  simulator's own effective_address(). PART B runs mov and lea on the same
  operand. PART C traces arith() with the C temporaries annotated.

[Systems link / CS:APP 3.4.1, 3.5.1]
  The scale factor S may only be 1, 2, 4 or 8 -- the sizes of C's basic
  types -- because the mode exists to index arrays: a[i] lives at
  a + sizeof(*a) * i. lea ("load effective address") computes that address
  WITHOUT touching memory, which makes it a free 3-operand adder that
  compilers love for ordinary arithmetic like x + 4*y + 4.
"""

import os

import x86sim

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


def part_a():
    print("PART A: address computation D(Rb,Ri,S) = D + Reg[Rb] + S*Reg[Ri]")
    print("        with %rdx = 0xf000 and %rcx = 0x0100 (the slide's values)")
    m = x86sim.Machine(x86sim.Program(""))      # an empty program: just a CPU
    m.set_reg("rdx", 0xF000)
    m.set_reg("rcx", 0x0100)
    rows = [("0x8(%rdx)", "0xf000 + 0x8"),
            ("(%rdx,%rcx)", "0xf000 + 0x100"),
            ("(%rdx,%rcx,4)", "0xf000 + 4*0x100"),
            ("0x80(,%rdx,2)", "2*0xf000 + 0x80")]
    print("  %-16s %-20s %s" % ("expression", "computation", "address"))
    for text, how in rows:
        op = x86sim.parse_operand(text, {})
        print("  %-16s %-20s 0x%x" % (text, how, m.effective_address(op)))
    print()


def part_b():
    print("PART B: same operand, mov reads MEMORY, lea only computes the ADDRESS")
    # A two-instruction program written by hand (x86sim accepts any AT&T text).
    prog = x86sim.Program("""
    f:  movq 8(%rdi,%rsi,8), %rax
        leaq 8(%rdi,%rsi,8), %rdx
        ret
    """)
    m = x86sim.Machine(prog)
    base, i = 0x1000, 2
    m.mem.write(base + 8 + 8 * i, 8, 777)          # put 777 at 0x1000 + 8 + 16
    m.call("f", base, i)
    print("  %%rdi = 0x%x, %%rsi = %d, memory at 0x%x holds 777" % (base, i, base + 8 + 8 * i))
    print("  movq 8(%%rdi,%%rsi,8), %%rax  ->  %%rax = %d       (the DATA at the address)"
          % m.regs["rax"])
    print("  leaq 8(%%rdi,%%rsi,8), %%rdx  ->  %%rdx = 0x%x  (the ADDRESS itself)"
          % m.regs["rdx"])
    print("  In C: rax = p[i+1] (a load)   vs   rdx = &p[i+1] (pointer arithmetic)\n")


def part_c(prog):
    print("PART C: arith(x, y, z) = (x + y + z) * (x + 4 + 48*y)")
    print(x86sim.listing(prog, "arith"))
    x, y, z = 5, 2, 11
    m = x86sim.Machine(prog)
    result = m.call("arith", x, y, z, trace=True)
    notes = ["t1 = x + y            (lea as an adder)",
             "t2 = z + t1",
             "t3 = x + 4  (computed... then never used!)",
             "y = y << 4  (y*16)",
             "y = y + 2*y (y*48 = t4)",
             "x + t4",
             "+ 4  -> t5 = (x + t4) + 4: re-associated",
             "rval = t2 * t5        (the ONE real multiply)",
             "return %rax"]
    print("\n  trace with x=%d, y=%d, z=%d:" % (x, y, z))
    for st, note in zip(m.trace, notes):
        changes = ", ".join("%%%s=%d" % (r, x86sim.to_signed(new, 8))
                            for r, old, new in st.reg_changes if r != "rsp")
        print("    %-26s %-24s %s" % (st.text, changes, note))
    expect = (x + y + z) * (x + 4 + 48 * y)
    print("  result %d, C formula gives %d\n" % (x86sim.to_signed(result, 8), expect))

    print("  m12(x) = x * 12:")
    print(x86sim.listing(prog, "m12"))
    m.call("m12", 7, trace=True)
    for st in m.trace[:-1]:
        print("    %-26s %s" % (st.text, ", ".join("%%%s=%d" % (r, n) for r, o, n in st.reg_changes)))
    print("  -> 4*x then (4x) + 2*(4x) = 12x, using only the address adder\n")


def main():
    print("=== Demo 03: addressing modes, lea and arithmetic ===\n")
    prog = x86sim.Program.from_file(x86sim.compile_to_asm("funcs.c"))
    part_a()
    part_b()
    part_c(prog)
    print("Observations:")
    print("  * D(Rb,Ri,S) is built for arrays: base pointer + scaled index + constant")
    print("    offset; S is 1, 2, 4 or 8 because those are the sizes of C's types.")
    print("  * lea computes the address and stops; mov goes on to read memory. lea")
    print("    sets no condition codes and has 3 operands, so compilers use it for")
    print("    plain arithmetic: x+y, x+4, 3*y, x+4y+4 all became lea here.")
    print("  * arith() needs one imul; y*48 became a shift and an lea, and x*12")
    print("    became two leas -- the same 'multiply by constants' trick as Lecture 2.")
    print("  * -Og is not fully optimized: clang computed t3 = x+4 into %r8 and then")
    print("    computed t5 as (x + t4) + 4 instead, so %r8 is dead work. The assembly")
    print("    need not follow your C statement by statement -- only its results.")


if __name__ == "__main__":
    main()
