Stage-A selfhost emitter fixes and LLVM opt toggle

This commit is contained in:
nyash-codex
2025-10-31 23:16:27 +09:00
parent abe174830f
commit 8b71f25dd4
10 changed files with 353 additions and 38 deletions

View File

@ -31,6 +31,50 @@ except Exception:
ROOT = _env_root or _default_root
PY_BUILDER = ROOT / "src" / "llvm_py" / "llvm_builder.py"
_OPT_ENV_KEYS = ("HAKO_LLVM_OPT_LEVEL", "NYASH_LLVM_OPT_LEVEL")
def _parse_opt_level_env() -> int:
"""Parse optimization level from env (0-3, default 2)."""
for key in _OPT_ENV_KEYS:
raw = os.environ.get(key)
if not raw:
continue
value = raw.strip()
if not value:
continue
upper = value.upper()
if upper.startswith("O"):
value = upper[1:]
try:
lvl = int(value)
except ValueError:
continue
if lvl < 0:
lvl = 0
if lvl > 3:
lvl = 3
return lvl
return 2
def _resolve_llvm_opt_level():
level = _parse_opt_level_env()
try:
import llvmlite.binding as llvm_binding
names = {0: "None", 1: "Less", 2: "Default", 3: "Aggressive"}
attr = names.get(level, "Default")
enum = getattr(llvm_binding, "CodeGenOptLevel")
return getattr(enum, attr)
except Exception:
return level
def _maybe_trace_opt(source: str) -> None:
if os.environ.get("NYASH_CLI_VERBOSE") == "1":
try:
level = _parse_opt_level_env()
print(f"[llvmlite harness] opt-level={level} ({source})", file=sys.stderr)
except Exception:
pass
def run_dummy(out_path: str) -> None:
# Minimal llvmlite program: ny_main() -> i32 0
import llvmlite.ir as ir
@ -52,7 +96,8 @@ def run_dummy(out_path: str) -> None:
m = llvm.parse_assembly(str(mod))
m.verify()
target = llvm.Target.from_default_triple()
tm = target.create_target_machine()
tm = target.create_target_machine(opt=_resolve_llvm_opt_level())
_maybe_trace_opt("dummy")
obj = tm.emit_object(m)
Path(out_path).parent.mkdir(parents=True, exist_ok=True)
with open(out_path, "wb") as f: