#!/usr/bin/env python3
"""Lower C translation units to LLVM bitcode and run them with Graal."""

import argparse
import os
from pathlib import Path
import subprocess
import sys
import tempfile


ROOT = Path(__file__).resolve().parent
SCALAR_PIPELINES = {
    "ssa": "function(mem2reg)",
    "sroa": "function(sroa)",
}


def lower(sources, output, flags, target, scalar_pipeline):
    clang = os.environ.get("GRAAL_CLANG", "clang")
    llvm_link = os.environ.get("GRAAL_LLVM_LINK", "llvm-link")
    opt = os.environ.get("GRAAL_OPT", "opt")
    promotion_flags = ["-Xclang", "-disable-O0-optnone"] if scalar_pipeline else []
    output = output.resolve()
    output.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(prefix=".cgraal-", dir=output.parent) as work:
        stage = Path(work)
        modules = []
        for index, source in enumerate(sources):
            source = source.resolve(strict=True)
            if source.suffix == ".bc":
                modules.append(source)
                continue
            if source.suffix != ".c":
                raise ValueError(f"expected a .c or .bc input: {source}")
            module = stage / f"tu{index}.bc"
            subprocess.run(
                [clang, f"--target={target}", "-std=gnu11", "-O0", "-fPIC",
                 *promotion_flags, *flags, "-emit-llvm", "-c", str(source), "-o", str(module)],
                check=True,
            )
            modules.append(module)
        linked = stage / "linked.bc"
        subprocess.run([llvm_link, "-o", str(linked), *map(str, modules)], check=True)
        if scalar_pipeline:
            promoted = stage / "promoted.bc"
            subprocess.run([opt, "-verify-each", f"-passes={SCALAR_PIPELINES[scalar_pipeline]}",
                            str(linked), "-o", str(promoted)], check=True)
            linked = promoted
        linked.replace(output)


def parse(argv):
    parser = argparse.ArgumentParser(
        description=__doc__,
        epilog="For run, place guest arguments after a standalone --.",
    )
    modes = parser.add_subparsers(dest="mode", required=True)
    for mode in ("build", "run"):
        command = modes.add_parser(mode)
        command.add_argument("sources", type=Path, nargs="+")
        command.add_argument("--cflag", action="append", default=[], metavar="FLAG",
                             help="forward one flag to Clang, for example --cflag=-DNAME=1")
        command.add_argument("--scalar-pipeline", choices=SCALAR_PIPELINES,
                             help="promote stack locals with LLVM mem2reg (ssa) or SROA after linking")
        command.add_argument("--target", default=os.environ.get(
            "GRAAL_C_TARGET", "x86_64-unknown-linux-gnu"))
        if mode == "build":
            command.add_argument("-o", "--output", type=Path, required=True)
        else:
            command.add_argument("--interpret", action="store_true")
            command.add_argument("--trace-compilation", action="store_true")
            command.add_argument("--library", action="append", default=[], metavar="PATH")
            command.add_argument("--argv0", type=Path, metavar="EXECUTABLE")
            command.add_argument("--runner", type=Path, default=Path(
                os.environ.get("GRAAL_C_RUNNER", ROOT / "dist" / "sqlite-api-shell")))
    guest_args = []
    if argv and argv[0] == "run" and "--" in argv:
        separator = argv.index("--")
        guest_args = argv[separator + 1:]
        argv = argv[:separator]
    return parser.parse_args(argv), guest_args


def main(argv):
    options, guest_args = parse(argv)
    try:
        if options.mode == "build":
            lower(options.sources, options.output, options.cflag, options.target, options.scalar_pipeline)
            return 0
        runner = options.runner.resolve(strict=True)
        with tempfile.TemporaryDirectory(prefix="cgraal-") as work:
            module = Path(work) / "program.bc"
            lower(options.sources, module, options.cflag, options.target, options.scalar_pipeline)
            command = [str(runner), "--run-module"]
            if options.interpret:
                command.append("--interpret")
            if options.trace_compilation:
                command.append("--trace-compilation")
            if options.library:
                command.append("--libraries=" + os.pathsep.join(options.library))
            if options.argv0:
                command.append("--argv0=" + str(options.argv0))
            result = subprocess.run([*command, str(module), *guest_args]).returncode
            return result if result >= 0 else 128 - result
    except (OSError, ValueError) as failure:
        print(f"cgraal: {failure}", file=sys.stderr)
        return 125
    except subprocess.CalledProcessError as failure:
        return failure.returncode if failure.returncode > 0 else 128 - failure.returncode


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
