"""
01_compiler_opts.py -- watch the compiler optimize
====================================================

[Questions this demo answers]
  - What do -O1/-O2 actually DO? The slides list constant folding, dead-code
    elimination, common-subexpression elimination, code motion and inlining.
    Can we see each one in the generated code?

[How to run]
  python3 01_compiler_opts.py

[How to read the output]
  Each function from src/opts.c is compiled at -O0 and -O2 (to x86-64, as the
  slides' listings are). The demo shows the instruction count at each level and
  the tell-tale sign of the optimization (a folded constant, a vanished
  multiply, a hoisted expression, a removed call).

[Systems link / CS:APP 5.1]
  Optimizations only change constant factors, never algorithmic complexity, and
  must not change observable behavior. Seeing them makes "write clear code and
  let the compiler optimize" (Lecture 8) concrete -- and sets up WHY some code
  defeats the compiler (demo 02).
"""

import os
import re
import subprocess

HERE = os.path.dirname(os.path.abspath(__file__))
SRC = os.path.join(HERE, "src", "opts.c")
BUILD = os.path.join(HERE, "build")
CC = os.environ.get("CC", "cc")
X86 = ["-arch", "x86_64"] if __import__("platform").system() == "Darwin" else []


def asm(opt):
    os.makedirs(BUILD, exist_ok=True)
    out = os.path.join(BUILD, "opts.%s.s" % opt.lstrip("-"))
    subprocess.run([CC, opt, "-S", "-fno-asynchronous-unwind-tables", "-fomit-frame-pointer"]
                   + X86 + [SRC, "-o", out], check=True)
    return open(out).read()


def func_body(text, name):
    """The instruction lines of one function (Mach-O/ELF label `name:` or `_name:`)."""
    lines, grab = [], False
    for line in text.splitlines():
        st = line.strip()
        if re.match(r"_?%s:(\s|$)" % re.escape(name), st):   # label may carry a trailing comment
            grab = True
            continue
        if not grab:
            continue
        if not st or st.startswith((".", "#")):               # blank / directive / comment
            continue
        if re.match(r"[A-Za-z_][\w$.]*:", st):                # a new real label -> function ended
            break
        lines.append(st)
        if re.match(r"ret", st):
            break
    return lines


def count(text, name):
    return len(func_body(text, name))


def main():
    print("=== Demo 01: compiler optimizations (x86-64) ===\n")
    o0, o2 = asm("-O0"), asm("-O2")
    rows = [
        ("const_fold", "#1 constant folding", "0xFF<<8 + 42 computed at compile time"),
        ("dead_code", "#2 dead-code elimination", "the unused x*x+12345 is gone"),
        ("cse", "#3 common-subexpression elim.", "x*y computed once, not three times"),
        ("code_motion", "#4 code motion", "n*i hoisted out of the loop"),
        ("inline_caller", "#5 inlining", "sq() folded in; no call left"),
    ]
    print("  %-16s %-30s %-8s %s" % ("function", "optimization", "-O0/-O2", "instrs"))
    for name, opt, _ in rows:
        c0, c2 = count(o0, name), count(o2, name)
        print("  %-16s %-30s %-8s %d -> %d" % (name, opt, "", c0, c2))
    print()
    # Show the constant actually folded, and the call removed by inlining.
    def imuls(body):
        return sum(1 for l in body if l.split()[0].startswith(("imul", "mul")))
    cf = func_body(o2, "const_fold")
    folded = next((l for l in cf if "mov" in l and ("$" in l or "#" in l)), cf[0] if cf else "")
    print("  #1 const_fold -O2 loads the literal: %s" % folded.split("##")[0].strip())
    print("     0xFF<<8 + 7*6 = %d, computed at compile time: no shift/mul/add left." % ((0xFF << 8) + 42))
    print("  #2 dead_code multiplies: -O0 %d -> -O2 %d (the unused x*x is gone)."
          % (imuls(func_body(o0, "dead_code")), imuls(func_body(o2, "dead_code"))))
    print("  #3 cse multiplies: -O0 %d -> -O2 %d (x*y computed once, reused)."
          % (imuls(func_body(o0, "cse")), imuls(func_body(o2, "cse"))))
    ic = func_body(o2, "inline_caller")
    print("  #5 inline_caller -O2 contains a call? %s (sq() inlined away)."
          % ("yes" if any("call" in l for l in ic) else "no"))
    print("  #4 code_motion: at -O2 the invariant base n*i is computed once and the")
    print("     loop is even vectorized -- its instruction count GREW (5 -> %d), yet it"
          % count(o2, "code_motion"))
    print("     is faster. Fewer instructions is common but not the goal; speed is.")
    cm = func_body(o2, "combine_mem")
    cr = func_body(o2, "combine_restrict")
    alias_checks = sum(1 for l in cm if l.startswith("setb"))
    print("  aliasing blocker: `*dest = *dest + src[i]` in a loop ->")
    print("     combine_mem (plain long*):     %d instrs, with a runtime alias check" % len(cm))
    print("     combine_restrict (restrict):   %d instrs, no check, clean vectorized loop" % len(cr))
    print("     Unable to assume dest and src don't overlap, the compiler emits a")
    print("     runtime check (%d setb) plus a scalar fallback. `restrict` promises no" % alias_checks)
    print("     overlap, so all of that vanishes. (demo 02 measures a related blocker.)")
    print()
    print("Observations:")
    print("  * -O2 transforms every function: constants folded, dead code dropped,")
    print("    repeated subexpressions reused, invariants hoisted, tiny calls inlined.")
    print("    Usually smaller, sometimes larger (vectorized) -- always faster.")
    print("  * None change what the function COMPUTES, only how fast -- the compiler's")
    print("    contract (Lecture 8: write clear code, let it optimize).")
    print("  * But the compiler must PROVE a transform is safe; demo 02 shows code where")
    print("    it cannot, and must leave slow code in place.")


if __name__ == "__main__":
    main()
