Debian Codegraph @

tensilelite/Tensile/Toolchain/Component.py

raw symbols SCIP
1 ################################################################################
2 #
3 # Copyright (C) 2025 Advanced Micro Devices, Inc. All rights reserved.
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in the Software without restriction, including without limitation the rights
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 # copies of the Software, and to permit persons to whom the Software is
10 # furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 # SOFTWARE.
22 #
23 # SPDX-License-Identifier: MIT
24 ################################################################################
25 from os import name as os_name
26 from os import environ
27 from pathlib import Path
28 from re import search, IGNORECASE
29 from shlex import split
30 from subprocess import check_output, STDOUT, CalledProcessError, PIPE, run
31 from typing import List
32
33 from Tensile.Common import SemanticVersion, print2
34 from .Validators import ToolchainDefaults, validateToolchain
35
36 def _invoke(args: List[str], desc: str=""):
37 """Invokes a command with the provided arguments in a subprocess.
38 Args:
39 args: A list of arguments to pass to the subprocess.
40 desc: A description of the subprocess invocation.
41 Raises:
42 RuntimeError: If the subprocess invocation fails.
43 Return:
44 subprocess output
45 """
46 print2(f"{desc}: {' '.join(args)}")
47 try:
48 out = check_output(args, stderr=STDOUT)
49 except CalledProcessError as err:
50 raise RuntimeError(
51 f"Error with {desc}: {err.output}\n"
52 f"Failed command: {' '.join(args)}"
53 )
54 return out
55
56
57 def _getVersion(executable: str, versionFlag: str, regex: str) -> str:
58 """Compute the version string of a toolchain component.
59
60 Args:
61 executable: The toolchain component to check the version of.
62 versionFlag: The flag to pass to the executable to get the version.
63 regex: pattern used to extract version string.
64 Raises:
65 RuntimeError: If querying executable for version fails.
66 Return:
67 Executable version
68 """
69 executable = validateToolchain(executable)
70 args = f'"{executable}" "{versionFlag}"'
71 try:
72 output = run(args, stdout=PIPE, shell=True).stdout.decode().strip()
73 match = search(regex, output, IGNORECASE)
74 if match:
75 result = match.group(1)
76 return SemanticVersion(*[int(c.split("-")[0]) for c in result.split(".")[:3]])
77 raise Exception(f"No version from {output} matches regex {regex}")
78 except Exception as e:
79 raise RuntimeError(f"Failed to get version when calling {args}: {e}")
80
81
82 def get_rocm_version() -> str:
83 """Compute the ROCm version string using hipconfig.
84
85 Raises:
86 RuntimeError: If hipconfig fails to execute.
87 Return:
88 ROCm version string
89 """
90 return _getVersion(ToolchainDefaults.HIP_CONFIG, "--version", r'(.+)')
91
92
93 class Component:
94 """A class used to represent a ROCm toolchain component such as clang++"""
95
96 _rocm_version = get_rocm_version()
97
98 def __init__(self, component_path: Path, version_flag: str="--version", version_regex: str=r"version\s+([\d.]+)"):
99 self._version = _getVersion(str(component_path), version_flag, version_regex)
100 self._component_path = component_path
101
102 def __str__(self):
103 result = f"ROCm {Component._rocm_version.major}.{Component._rocm_version.minor}.{Component._rocm_version.patch} "
104 result += f"Component path: {self._component_path} version: {self._version.major}.{self._version.minor}.{self._version.patch}"
105 return result
106
107 @property
108 def path(self):
109 return self._component_path
110
111 @property
112 def version(self):
113 return self._version
114
115 @property
116 def rocm_version(self):
117 return Component._rocm_version
118
119
120 class Assembler(Component):
121 """
122 ROCm assembler class used to build objects from assembly source files.
123
124 ...
125
126 Attributes
127 ----------
128 version : str
129 the version of the component
130 rocm_version : str
131 the ROCm version
132 path : str
133 path to assembler
134
135 Methods
136 -------
137 __call__(self, targetGfx: str, wavefrontSize: int, debug: bool, srcPath: str, destPath: str)
138 Invokes the assembler on the provided arguments
139 """
140
141 def __init__(self, component_path: Path, co_version: str, debug: bool=False):
142 """Constructs an instance of an Assembler.
143
144 Args:
145 assembler_path: The path to the assember.
146 co_version: The code object version to use.
147 """
148
149 super(Assembler, self).__init__(component_path)
150 self._code_object_version = co_version
151
152 self._default_args = [
153 *split(environ.get('Tensile_ASM_COMPILER_LAUNCHER', '')),
154 str(component_path),
155 "-x", "assembler",
156 "--target=amdgcn-amd-amdhsa",
157 "-g" if debug else "",
158 f"-mcode-object-version={co_version}",
159 "-c",
160 ]
161
162 def __call__(self, targetGfx: str, wavefrontSize: int, srcPath: str, destPath: str):
163 """Assemble an assembly source file into an object file.
164 Args:
165 targetGfx: The target GPU gfx architecture.
166 wavefrontSize: The wavefront size to use.
167 debug: add debug flags if True.
168 srcPath: The path to the assembly source file.
169 destPath: The destination path for the generated object file.
170 """
171 args = self._default_args
172 args = [
173 *args,
174 f"-mcpu={targetGfx}",
175 "-mwavefrontsize64" if wavefrontSize == 64 else "-mno-wavefrontsize64",
176 srcPath,
177 "-o",
178 destPath
179 ]
180 return _invoke(args, "Assembling assembly source code into object file (.s -> .o)")
181
182 @property
183 def code_object_version(self):
184 return self._code_object_version
185
186 class Compiler(Component):
187 """
188 ROCm compiler class used to build objects from C++ source files.
189
190 ...
191
192 Attributes
193 ----------
194 version : str
195 the version of the component
196 rocm_version : str
197 the ROCm version
198 path : str
199 path to compiler
200
201 Methods
202 -------
203 __call__(self, include_path: str, target_list: List[str], srcPath: str, destPath: str):
204 Invokes the compiler on the provided arguments
205 """
206
207 def __init__(self, compiler_path: Path, build_id_kind: str, asan_build: bool=False, save_temps: bool=False):
208 """Constructs an instance of a Compiler."""
209 super(Compiler, self).__init__(compiler_path)
210
211 self.default_args = [
212 *split(environ.get("Tensile_CXX_COMPILER_LAUNCHER", "")),
213 compiler_path,
214 "-D__HIP_HCC_COMPAT_MODE__=1",
215 "--offload-device-only",
216 "-x", "hip", "-O3",
217 "-Xoffload-linker", f"--build-id={build_id_kind}",
218 "-std=c++17",
219 ]
220
221 if asan_build:
222 self.default_args.extend(["-fsanitize=address", "-shared-libasan", "-fuse-ld=lld"])
223 if save_temps:
224 self.default_args.append("--save-temps")
225 if os_name == "nt": # should we use fPIIC on all arches?
226 self.default_args.extend(["-fms-extensions", "-fms-compatibility", "-fPIC", "-Wno-deprecated-declarations"])
227
228
229 def __call__(self, include_path: str, target_list: List[str], srcPath: str, destPath: str):
230 """Compiles a source file into an object file.
231
232 Args:
233 include_path: Path appened to "-I" to directory with required include files.
234 target_list: List of offload architectures of the form gfxXYZ e.g. gfx942.
235 sercPath: The path to the source file.
236 destPath: Path to the object file output during compilation.
237 Raises:
238 RuntimeError: If the compilation command fails.
239 """
240 archFlags = [f"--offload-arch={gfx}" for gfx in target_list]
241 args = [
242 *(self.default_args), "-I", include_path, *archFlags, srcPath, "-c", "-o", destPath
243 ]
244 return _invoke(args, f"Compiling HIP source kernels into objects (.cpp -> .o)")
245
246
247 class Bundler(Component):
248 """
249 ROCm bundler class used to unbundle objects into code object files.
250
251 ...
252
253 Attributes
254 ----------
255 version : str
256 the version of the component
257 rocm_version : str
258 the ROCm version
259 Methods
260 -------
261 __call__(self, targetGfx: str, wavefrontSize: int, debug: bool, srcPath: str, destPath: str)
262 Invokes the assembler on the provided arguments
263 def targets(self, objFile: str):
264 returns a list of target triple strings of the form amdgcn-amd--gfx942
265 def compress(self, srcPath: str, destPath: str, target: str):
266 Compresses a code object file using the provided bundler.
267 """
268
269 def __init__(self, bundler_path: Path):
270 """Constructs an instance of a Bunder."""
271 super(Bundler, self).__init__(bundler_path)
272
273 def targets(self, objFile: str):
274 """returns a list of target triple strings of the form amdgcn-amd--gfx942"""
275 args = [self._component_path, "--type=o", f"--input={objFile}", "-list"]
276 return _invoke(args, f"Listing target triples in object file").decode().split("\n")
277
278 def compress(self, srcPath: str, destPath: str, target: str):
279 """Compresses a code object file using the provided bundler.
280
281 Args:
282 srcPath: The source path of the code object file to be compressed.
283 destPath: The destination path for the compressed code object file.
284 gfx: The target GPU architecture.
285
286 Raises:
287 RuntimeError: If compressing the code object file fails.
288 """
289 devnull = "/dev/null" if os_name != "nt" else "NUL"
290 args = [
291 self._component_path,
292 "--compress",
293 "--type=o",
294 "--bundle-align=4096",
295 f"--targets=host-x86_64-unknown-linux-gnu,hipv4-amdgcn-amd-amdhsa-unknown-{target}",
296 f"--input={devnull}",
297 f"--input={srcPath}",
298 f"--output={destPath}",
299 ]
300
301 return _invoke(args, "Bundling/compressing code object file (.co -> .co)")
302
303 def __call__(self, target: str, srcPath: str, destPath: str):
304 """Unbundles source code object files using the Clang Offload Bundler.
305 Args:
306 target: The target triple, see https://llvm.org/docs/AMDGPUUsage.html#target-triples.
307 srcPath: The path to the input object file.
308 destPath: The path to the unbundled code object.
309 Raises:
310 RuntimeError: If unbundling the source code object file fails.
311 """
312 args = [
313 self._component_path,
314 "--type=o",
315 f"--targets={target}",
316 f"--input={srcPath}",
317 f"--output={destPath}",
318 "--unbundle",
319 ]
320 return _invoke(args, f"Unbundling source code object file")
321
322
323 class Linker(Component):
324 """
325 ROCm Linker class used to link objects into code object files.
326
327 ...
328
329 Attributes
330 ----------
331 version : str
332 the version of the component
333 rocm_version : str
334 the ROCm version
335 Methods
336 -------
337 __call__(self, srcPaths: List[str], destPath: str):
338 Invokes the linker on the provided arguments
339 """
340
341 def __init__(self, linker_path: Path, build_id_kind: str):
342 """Constructs an instance of a Linker."""
343 super(Linker, self).__init__(linker_path)
344 self.default_args = [
345 self._component_path,
346 "--target=amdgcn-amd-amdhsa",
347 "-Xlinker", f"--build-id={build_id_kind}",
348 ]
349
350 def _response_file_args(self, srcPaths: List[str], destPath: str) -> List[str]:
351 """
352 Create a response file and return the arguments to pass to the linker.
353
354 Since it is possible for the character limit of the operating system to be exceeded
355 when invoking the linker, LLVM allows the provision of arguments via a "response file"
356 Reference: https://llvm.org/docs/CommandLine.html#response-files
357 """
358 with open(Path.cwd() / "clang_args.txt", "wt") as file:
359 file.write(" ".join(srcPaths).replace('\\', '\\\\') if os_name == "nt" else " ".join(srcPaths))
360 return [*(self.default_args), "-o", destPath, "@clang_args.txt"]
361
362 def _use_response_file(self, args: List[str]) -> bool:
363 """
364 Determine if a response file should be used for the linker arguments.
365
366 On Windows: always use response file due to 8191 char limit
367 On Unix: check against system argument length limit
368 """
369 if os_name == "nt":
370 return True
371 from os import sysconf
372 line_length = sum(len(arg) for arg in args) + len(args) - 1
373 return line_length >= sysconf("SC_ARG_MAX")
374
375 def __call__(self, srcPaths: List[str], destPath: str):
376 """
377 Links object files into a code object file.
378
379 Args:
380 srcPaths: A list of paths to object files.
381 destPath: A destination path for the generated code object file.
382 Raises:
383 RuntimeError: If linker invocation fails.
384 """
385 args = [*(self.default_args), *srcPaths, "-o", destPath]
386 if self._use_response_file(args):
387 args = self._response_file_args(srcPaths, destPath)
388 return _invoke(args, "Linking assembly object files into code object (*.o -> .co)")
389
390
391 # class DeviceEnumerator(Component):
392 # """
393 # ROCm amdgpu-arch or rocm_agent_enumerator class used to inspect system for current architecture.
394
395 # ...
396
397 # Attributes
398 # ----------
399 # version : str
400 # the version of the component
401 # rocm_version : str
402 # the ROCm version
403 # path : str
404 # path to component
405
406 # Methods
407 # -------
408 # __call__(self)
409 # Invokes component.
410 # """
411 # def __init__(self, component_path: Path):
412 # """Constructs instance of SystemInterogator.
413
414 # Args:
415 # component_path: The path to amdgpu-arch or rocm_agent_enumeraor.
416 # """
417 # super(Assembler, self).__init__(component_path)
418 # self._default_args = [str(component_path)]
419
420 # def __call__(self):
421 # """Run component without args to detect system settings."""
422
423 # return _invoke(self._default_args, "running system inspection")