Debian Codegraph @

Tools/jit/_llvm.py

raw ◀ ▶
1 Debian patch touch this file
1 """Utilities for invoking LLVM tools."""
2
3 import asyncio
4 import functools
5 import os
6 import re
7 import shlex
8 import subprocess
9 import typing
10
11 import _targets
12
•13 _LLVM_VERSION = 21
14 _EXTERNALS_LLVM_TAG = "llvm-19.1.7.0"
15
16 _P = typing.ParamSpec("_P")
17 _R = typing.TypeVar("_R")
18 _C = typing.Callable[_P, typing.Awaitable[_R]]
19
20
21 def _async_cache(f: _C[_P, _R]) -> _C[_P, _R]:
22 cache = {}
23 lock = asyncio.Lock()
24
25 @functools.wraps(f)
26 async def wrapper(
27 *args: _P.args, **kwargs: _P.kwargs # pylint: disable = no-member
28 ) -> _R:
29 async with lock:
30 if args not in cache:
31 cache[args] = await f(*args, **kwargs)
32 return cache[args]
33
34 return wrapper
35
36
37 _CORES = asyncio.BoundedSemaphore(os.cpu_count() or 1)
38
39
40 async def _run(tool: str, args: typing.Iterable[str], echo: bool = False) -> str | None:
41 command = [tool, *args]
42 async with _CORES:
43 if echo:
44 print(shlex.join(command))
45 try:
46 process = await asyncio.create_subprocess_exec(
47 *command, stdout=subprocess.PIPE
48 )
49 except FileNotFoundError:
50 return None
51 out, _ = await process.communicate()
52 if process.returncode:
53 raise RuntimeError(f"{tool} exited with return code {process.returncode}")
54 return out.decode()
55
56
57 @_async_cache
•58 async def _check_tool_version(
59 name: str, llvm_version: str, *, echo: bool = False
60 ) -> bool:
61 output = await _run(name, ["--version"], echo=echo)
•62 _llvm_version_pattern = re.compile(rf"version\s+{llvm_version}\.\d+\.\d+\S*\s+")
63 return bool(output and _llvm_version_pattern.search(output))
64
65
66 @_async_cache
•67 async def _get_brew_llvm_prefix(llvm_version: str, *, echo: bool = False) -> str | None:
68 output = await _run("brew", ["--prefix", f"llvm@{llvm_version}"], echo=echo)
69 return output and output.removesuffix("\n")
70
71
72 @_async_cache
•73 async def _find_tool(tool: str, llvm_version: str, *, echo: bool = False) -> str | None:
74 # Unversioned executables:
75 path = tool
•76 if await _check_tool_version(path, llvm_version, echo=echo):
77 return path
78 # Versioned executables:
•79 path = f"{tool}-{llvm_version}"
80 if await _check_tool_version(path, llvm_version, echo=echo):
81 return path
82 # PCbuild externals:
83 externals = os.environ.get("EXTERNALS_DIR", _targets.EXTERNALS)
84 path = os.path.join(externals, _EXTERNALS_LLVM_TAG, "bin", tool)
•85 if await _check_tool_version(path, llvm_version, echo=echo):
86 return path
87 # Homebrew-installed executables:
•88 prefix = await _get_brew_llvm_prefix(llvm_version, echo=echo)
89 if prefix is not None:
90 path = os.path.join(prefix, "bin", tool)
•91 if await _check_tool_version(path, llvm_version, echo=echo):
92 return path
93 # Nothing found:
94 return None
95
96
97 async def maybe_run(
•98 tool: str,
99 args: typing.Iterable[str],
100 echo: bool = False,
101 llvm_version: str = _LLVM_VERSION,
102 ) -> str | None:
103 """Run an LLVM tool if it can be found. Otherwise, return None."""
•104
105 path = await _find_tool(tool, llvm_version, echo=echo)
106 return path and await _run(path, args, echo=echo)
107
108
•109 async def run(
110 tool: str,
111 args: typing.Iterable[str],
112 echo: bool = False,
113 llvm_version: str = _LLVM_VERSION,
114 ) -> str:
115 """Run an LLVM tool if it can be found. Otherwise, raise RuntimeError."""
•116
117 output = await maybe_run(tool, args, echo=echo, llvm_version=llvm_version)
118 if output is None:
•119 raise RuntimeError(f"Can't find {tool}-{llvm_version}!")
120 return output