|
| 1 | +from cuda.core.experimental._module import ObjectCode |
| 2 | +from cuda.core.experimental._utils import check_or_create_options |
| 3 | +from dataclasses import dataclass |
| 4 | +from typing import Optional |
| 5 | +from cuda.bindings import nvjitlink |
| 6 | + |
| 7 | + |
| 8 | +@dataclass |
| 9 | +class LinkerOptions: |
| 10 | + arch: str # /**< -arch=sm_<N> Pass SM architecture value. See nvcc for valid values of <N>. Can use compute_<N> value instead if only generating PTX. This is a required option. */ |
| 11 | + max_register_count: Optional[int] = None # /**< -maxrregcount=<N> Maximum register count. */ |
| 12 | + time: Optional[bool] = None # /**< -time Print timing information to InfoLog. */ |
| 13 | + verbose: Optional[bool] = None # /**< -verbose Print verbose messages to InfoLog. */ |
| 14 | + link_time_optimization: Optional[bool] = None # /**< -lto Do link time optimization. */ |
| 15 | + ptx: Optional[bool] = None # /**< -ptx Emit ptx after linking instead of cubin; only supported with -lto. */ |
| 16 | + optimization_level: Optional[int] = None # /**< -O<N> Optimization level. Only 0 and 3 are accepted. */ |
| 17 | + debug: Optional[bool] = None # /**< -g Generate debug information. */ |
| 18 | + lineinfo: Optional[bool] = None # /**< -lineinfo Generate line information. */ |
| 19 | + ftz: Optional[bool] = None # /**< -ftz=<n> Flush to zero. */ |
| 20 | + prec_div: Optional[bool] = None # /**< -prec-div=<n> Precise divide. */ |
| 21 | + prec_sqrt: Optional[bool] = None # /**< -prec-sqrt=<n> Precise square root. */ |
| 22 | + fma: Optional[bool] = None # /**< -fma=<n> Fast multiply add. */ |
| 23 | + kernels_used: Optional[list[str]] = None # /**< -kernels-used=<name> Pass list of kernels that are used; any not in the list can be removed. This option can be specified multiple times. */ |
| 24 | + variables_used: Optional[list[str]] = None # /**< -variables-used=<name> Pass list of variables that are used; any not in the list can be removed. This option can be specified multiple times. */ |
| 25 | + optimize_unused_variables: Optional[bool] = None # /**< -optimize-unused-variables Normally device code optimization is limited by not knowing what the host code references. With this option it can assume that if a variable is not referenced in device code then it can be removed. */ |
| 26 | + xptxas: Optional[list[str]] = None # /**< -Xptxas=<opt> Pass <opt> to ptxas. This option can be called multiple times. */ |
| 27 | + split_compile: Optional[int] = None # /**< -split-compile=<N> Split compilation maximum thread count. Use 0 to use all available processors. Value of 1 disables split compilation (default). */ |
| 28 | + split_compile_extended: Optional[int] = None # /**< -split-compile-extended=<N> A more aggressive form of split compilation available in LTO mode only. Accepts a maximum thread count value. Use 0 to use all available processors. Value of 1 disables extended split compilation (default). Note: This option can potentially impact performance of the compiled binary. */ |
| 29 | + jump_table_density: Optional[int] = None # /**< -jump-table-density=<N> When doing LTO, specify the case density percentage in switch statements, and use it as a minimal threshold to determine whether jump table(brx.idx instruction) will be used to implement a switch statement. Default value is 101. The percentage ranges from 0 to 101 inclusively. */ |
| 30 | + no_cache: Optional[bool] = None # /**< -no-cache Don’t cache the intermediate steps of nvJitLink. */ |
| 31 | + device_stack_protector: Optional[bool] = None # /**< -device-stack-protector Enable stack canaries in device code. Stack canaries make it more difficult to exploit certain types of memory safety bugs involving stack-local variables. The compiler uses heuristics to assess the risk of such a bug in each function. Only those functions which are deemed high-risk make use of a stack canary. */ |
| 32 | + |
| 33 | + |
| 34 | + def __post_init__(self): |
| 35 | + self.formatted_options = [] |
| 36 | + if self.arch is not None: |
| 37 | + self.formatted_options.append(f"-arch={self.arch}") |
| 38 | + if self.max_register_count is not None: |
| 39 | + self.formatted_options.append(f"-maxrregcount={self.max_register_count}") |
| 40 | + if self.time is not None: |
| 41 | + self.formatted_options.append("-time") |
| 42 | + if self.verbose is not None: |
| 43 | + self.formatted_options.append("-verbose") |
| 44 | + if self.link_time_optimization is not None: |
| 45 | + self.formatted_options.append("-lto") |
| 46 | + if self.ptx is not None: |
| 47 | + self.formatted_options.append("-ptx") |
| 48 | + if self.optimization_level is not None: |
| 49 | + self.formatted_options.append(f"-O{self.optimization_level}") |
| 50 | + if self.debug is not None: |
| 51 | + self.formatted_options.append("-g") |
| 52 | + if self.lineinfo is not None: |
| 53 | + self.formatted_options.append("-lineinfo") |
| 54 | + if self.ftz is not None: |
| 55 | + self.formatted_options.append(f"-ftz={'true' if self.ftz else 'false'}") |
| 56 | + if self.prec_div is not None: |
| 57 | + self.formatted_options.append(f"-prec-div={'true' if self.prec_div else 'false'}") |
| 58 | + if self.prec_sqrt is not None: |
| 59 | + self.formatted_options.append(f"-prec-sqrt={'true' if self.prec_sqrt else 'false'}") |
| 60 | + if self.fma is not None: |
| 61 | + self.formatted_options.append(f"-fma={'true' if self.fma else 'false'}") |
| 62 | + if self.kernels_used is not None: |
| 63 | + for kernel in self.kernels_used: |
| 64 | + self.formatted_options.append(f"-kernels-used={kernel}") |
| 65 | + if self.variables_used is not None: |
| 66 | + for variable in self.variables_used: |
| 67 | + self.formatted_options.append(f"-variables-used={variable}") |
| 68 | + if self.optimize_unused_variables is not None: |
| 69 | + self.formatted_options.append("-optimize-unused-variables") |
| 70 | + if self.xptxas is not None: |
| 71 | + for opt in self.xptxas: |
| 72 | + self.formatted_options.append(f"-Xptxas={opt}") |
| 73 | + if self.split_compile is not None: |
| 74 | + self.formatted_options.append(f"-split-compile={self.split_compile}") |
| 75 | + if self.split_compile_extended is not None: |
| 76 | + self.formatted_options.append(f"-split-compile-extended={self.split_compile_extended}") |
| 77 | + if self.jump_table_density is not None: |
| 78 | + self.formatted_options.append(f"-jump-table-density={self.jump_table_density}") |
| 79 | + if self.no_cache is not None: |
| 80 | + self.formatted_options.append("-no-cache") |
| 81 | + if self.device_stack_protector is not None: |
| 82 | + self.formatted_options.append("-device-stack-protector") |
| 83 | + |
| 84 | + |
| 85 | +class Linker: |
| 86 | + |
| 87 | + __slots__ = ("_handle") |
| 88 | + |
| 89 | + def __init__(self, options: LinkerOptions, object_codes = None): |
| 90 | + self._handle = None |
| 91 | + options = check_or_create_options(LinkerOptions, options, "Linker options") |
| 92 | + self._handle = nvjitlink.create(len(options.formatted_options), options.formatted_options) |
| 93 | + |
| 94 | + if object_codes is not None: |
| 95 | + if object_codes.__iter__: |
| 96 | + for code in object_codes: |
| 97 | + self.add_code_object(code) |
| 98 | + else: |
| 99 | + self.add_code_object(object_codes) |
| 100 | + |
| 101 | + |
| 102 | + def add_code_object(self, object_code: ObjectCode): |
| 103 | + data = object_code._module |
| 104 | + assert isinstance(data, bytes) |
| 105 | + nvjitlink.add_data( |
| 106 | + self._handle, |
| 107 | + self._input_type_from_code_type(object_code._code_type), |
| 108 | + data, |
| 109 | + len(data), |
| 110 | + f"{object_code._handle}_{object_code._code_type}", |
| 111 | + ) |
| 112 | + |
| 113 | + |
| 114 | + def link(self, target_type) -> ObjectCode: |
| 115 | + nvjitlink.complete(self._handle) |
| 116 | + if target_type not in ["cubin", "ptx"]: |
| 117 | + raise ValueError(f"Unsupported target type: {target_type}") |
| 118 | + code = None |
| 119 | + if target_type == "cubin": |
| 120 | + cubin_size = nvjitlink.get_linked_cubin_size(self._handle) |
| 121 | + code = bytearray(cubin_size) |
| 122 | + nvjitlink.get_linked_cubin(self._handle, code) |
| 123 | + else: |
| 124 | + ptx_size = nvjitlink.get_linked_ptx_size(self._handle) |
| 125 | + code = bytearray(ptx_size) |
| 126 | + nvjitlink.get_linked_ptx(self._handle, code) |
| 127 | + |
| 128 | + return ObjectCode(bytes(code), target_type) |
| 129 | + |
| 130 | + |
| 131 | + def get_error_log(self) -> str: |
| 132 | + log_size = nvjitlink.get_error_log_size(self._handle) |
| 133 | + log = bytearray(log_size) |
| 134 | + nvjitlink.get_error_log(self._handle, log) |
| 135 | + return log.decode() |
| 136 | + |
| 137 | + |
| 138 | + def get_info_log(self) -> str: |
| 139 | + log_size = nvjitlink.get_info_log_size(self._handle) |
| 140 | + log = bytearray(log_size) |
| 141 | + nvjitlink.get_info_log(self._handle, log) |
| 142 | + return log.decode() |
| 143 | + |
| 144 | + |
| 145 | + def _input_type_from_code_type(self, code_type: str) -> nvjitlink.InputType: |
| 146 | + # this list is based on the supported values for code_type in the ObjectCode class definition. nvjitlink supports other options for input type |
| 147 | + if code_type == "ptx": |
| 148 | + return nvjitlink.InputType.PTX |
| 149 | + elif code_type == "cubin": |
| 150 | + return nvjitlink.InputType.CUBIN |
| 151 | + elif code_type == "fatbin": |
| 152 | + return nvjitlink.InputType.FATBIN |
| 153 | + elif code_type == "ltoir": |
| 154 | + return nvjitlink.InputType.LTOIR |
| 155 | + elif code_type == "object": |
| 156 | + return nvjitlink.InputType.OBJECT |
| 157 | + else: |
| 158 | + raise ValueError( |
| 159 | + f"Unknown code_type associated with ObjectCode: {code_type}" |
| 160 | + ) |
| 161 | + |
| 162 | + |
| 163 | + @property |
| 164 | + def handle(self) -> int: |
| 165 | + return self._handle |
| 166 | + |
| 167 | + def __del__(self): |
| 168 | + if self._handle is not None: |
| 169 | + nvjitlink.destroy(self._handle) |
| 170 | + self._handle = None |
0 commit comments