#!/usr/bin/env python3
"""Coalesce the six audited stack slots in the pinned SQLite lookup region."""

import argparse
import hashlib
import json
from pathlib import Path
import re
import subprocess
import tempfile


AUDITED_INPUTS = {
    "7b02c047522d7f08fcf68ea6f471ff0745998e7792c165ede552a1f7752535f9": "lookup-wide",
    "b820612b5908789c86df7e9f6869d1d5f7ce93eb5fcdc644642087db4783c561": "lookup-wide-timed",
    "8694311bc251816d0ecc078d5e9acdc2eb84363e75ac29fe1a4d9f16c2dea546": "contract-wide",
    "4afdf47e32fa8f71b7d079e0d1c625bc9559a84ddd06a15ca9721b192500b5a4": "sqlite-api-shell-wide",
}
ENTRY = "define internal i32 @sqlite3VdbeExecLookup(ptr noundef %0) #0 {\n"
SLOTS = (
    ("i32", 4, 4),
    ("i32", 4, 4),
    ("%struct.sqlite3_value", 56, 8),
    ("%struct.sqlite3_value", 56, 8),
    ("i32", 4, 4),
    ("i64", 8, 8),
)


def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def rewrite(ir):
    if 'target triple = "x86_64-unknown-linux-gnu"\n' not in ir:
        raise ValueError("expected the audited x86-64 target")
    original = ENTRY + "".join(
        f"  %{index} = alloca {typ}, align {alignment}\n"
        for index, (typ, _, alignment) in enumerate(SLOTS, start=2)
    )
    if ir.count(original) != 1:
        raise ValueError("expected exactly one audited allocation prefix")

    reserved = 0
    distances = []
    for _, size, _ in SLOTS:
        reserved += (size + 7) & -8
        distances.append(reserved)
    offsets = [reserved - distance for distance in distances]
    replacement = ENTRY + f"  %guest.stack = alloca [{reserved} x i8], align 8\n"
    replacement += "".join(
        f"  %{index} = getelementptr inbounds i8, ptr %guest.stack, i64 {offset}\n"
        for index, offset in enumerate(offsets, start=2)
    )
    return ir.replace(original, replacement, 1), reserved, offsets


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", type=Path)
    parser.add_argument("--output", required=True, type=Path)
    parser.add_argument("--control", required=True, type=Path,
                        help="write the unmodified module through the same LLVM tools")
    parser.add_argument("--llvm-bin", type=Path, help="pinned LLVM 18.1.3 bin directory")
    args = parser.parse_args()
    source, control, output = (path.resolve() for path in (args.input, args.control, args.output))
    if len({source, control, output}) != 3:
        parser.error("input, control and output must have different paths")

    def llvm(tool):
        return str(args.llvm_bin.resolve() / tool) if args.llvm_bin else tool

    try:
        source_bytes = source.read_bytes()
        source_digest = hashlib.sha256(source_bytes).hexdigest()
        module = AUDITED_INPUTS.get(source_digest)
        if module is None:
            raise ValueError(f"unaudited input digest {source_digest}")
        version = subprocess.check_output([llvm("llvm-dis"), "--version"], text=True)
        if re.search(r"\bLLVM version 18\.1\.3\b", version) is None:
            raise ValueError("expected LLVM 18.1.3")
        with tempfile.TemporaryDirectory(prefix=".coalesce-lookup-", dir=output.parent) as work:
            scratch = Path(work)
            text = subprocess.run([llvm("llvm-dis"), "-o", "-"], input=source_bytes,
                                  check=True, stdout=subprocess.PIPE).stdout.decode()
            rewritten, reserved, offsets = rewrite(text)
            results = []
            for name, ir in (("control", text), ("coalesced", rewritten)):
                bitcode = scratch / f"{name}.bc"
                subprocess.run([llvm("llvm-as"), "-o", str(bitcode)], input=ir.encode(), check=True)
                subprocess.run([llvm("opt"), "-passes=verify", "-disable-output", str(bitcode)], check=True)
                results.append(bitcode)
            control.write_bytes(results[0].read_bytes())
            results[1].replace(output)
        print(json.dumps({"module": module, "function": "sqlite3VdbeExecLookup",
                          "input_sha256": source_digest, "control_sha256": digest(control),
                          "output_sha256": digest(output), "frame_bytes": reserved,
                          "slot_offsets": offsets}, indent=2))
    except (OSError, subprocess.CalledProcessError, ValueError) as error:
        parser.exit(1, f"coalesce-lookup-allocas: {error}\n")


if __name__ == "__main__":
    main()
