#!/usr/bin/env python3
"""Lower small equality-only libc comparisons from LLVM IR or bitcode to bitcode."""

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


ROOT = Path(__file__).resolve().parents[1]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", type=Path, metavar="INPUT")
    parser.add_argument("-o", "--output", type=Path, required=True)
    parser.add_argument("--function", action="append", default=[], metavar="NAME",
                        help="only lower calls inside the named function, repeatable")
    parser.add_argument("--assume-standard-libc", action="store_true", required=True,
                        help="assert that eligible extern memcmp and bcmp resolve to standard libc")
    args = parser.parse_args()
    output = args.output.resolve()
    if args.input.resolve() == output:
        parser.error("input and output require separate paths")

    llvm_config = os.environ.get("GRAAL_LLVM_CONFIG", "llvm-config")

    def config(*options):
        return subprocess.check_output([llvm_config, *options], text=True).strip()

    try:
        cxx = os.environ.get("GRAAL_CXX") or str(Path(config("--bindir")) / "clang++")
        library = config("--libdir")
        flags = shlex.split(config("--cxxflags"))
        libraries = shlex.split(config("--link-shared", "--libs", "analysis", "core",
                                       "irreader", "bitwriter"))
        with tempfile.TemporaryDirectory(prefix=".lower-small-compares-", dir=output.parent) as work:
            helper = Path(work) / "lower-small-compares"
            bitcode = Path(work) / "lowered.bc"
            # The pinned Graal LLVM distribution exports libstdc++'s old string ABI.
            subprocess.run([cxx, *flags, "-D_GLIBCXX_USE_CXX11_ABI=0", "-O2",
                            str(ROOT / "c/lower-small-compares.cpp"),
                            f"-L{library}", f"-Wl,-rpath,{library}", *libraries, "-o", str(helper)],
                           check=True)
            subprocess.run([str(helper), str(args.input), str(bitcode), *args.function], check=True)
            bitcode.replace(output)
        return 0
    except subprocess.CalledProcessError as error:
        return error.returncode if error.returncode > 0 else 128 - error.returncode
    except OSError as error:
        print(f"lower-small-compares: {error}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
