compiler.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. from triton.backends.compiler import BaseBackend, GPUTarget, Language
  2. from triton._C.libtriton import ir, passes, llvm, amd
  3. from triton import knobs
  4. from dataclasses import dataclass
  5. from typing import Any, Dict, Tuple
  6. from types import ModuleType
  7. import hashlib
  8. import os
  9. import tempfile
  10. import re
  11. import functools
  12. import warnings
  13. from pathlib import Path
  14. # The file may be accessed in parallel
  15. def try_remove(path):
  16. if os.path.exists(path):
  17. try:
  18. os.remove(path)
  19. except OSError:
  20. import traceback
  21. traceback.print_exc()
  22. def get_min_dot_size(target: GPUTarget):
  23. # We fallback to use FMA and cast arguments if certain configurations is
  24. # not supported natively by matrix core units.
  25. return lambda lhs_type, rhs_type: (1, 1, 1)
  26. def is_pingpong_schedule_enabled(arch, use_async_copy):
  27. return (arch == "gfx942" or (arch == "gfx950" and use_async_copy is True)
  28. ) if knobs.amd.use_block_pingpong is None else knobs.amd.use_block_pingpong
  29. def is_in_thread_transpose_enabled(arch):
  30. return (arch == "gfx942") if knobs.amd.use_in_thread_transpose is None else knobs.amd.use_in_thread_transpose
  31. @dataclass(frozen=True)
  32. class HIPOptions:
  33. num_warps: int = 4
  34. waves_per_eu: int = 0
  35. num_stages: int = 2
  36. num_ctas: int = 1
  37. extern_libs: dict = None
  38. debug: bool = False
  39. sanitize_overflow: bool = True
  40. arch: str = None
  41. # We have native support for OCP fp8 variants since CDNA4/RDNA4. For earlier generations,
  42. # we software emulate the support for them.
  43. # UZ fp8 variants (fp8e4b8 and fp8e5b16) are natively supported for CDNA3. For other
  44. # architectures they are software emulated.
  45. supported_fp8_dtypes: Tuple[str] = ("fp8e4nv", "fp8e5", "fp8e5b16", "fp8e4b8")
  46. deprecated_fp8_dot_operand_dtypes: Tuple[str] = ()
  47. default_dot_input_precision: str = "ieee"
  48. allowed_dot_input_precisions: Tuple[str] = ("ieee", 'bf16x3', 'bf16x6')
  49. enable_fp_fusion: bool = True
  50. launch_cooperative_grid: bool = False
  51. matrix_instr_nonkdim: int = 0
  52. kpack: int = 1
  53. allow_flush_denorm: bool = False
  54. max_num_imprecise_acc_default: int = 0
  55. backend_name: str = 'hip'
  56. instrumentation_mode: str = ""
  57. # The following option provides hints to the AMDGPU backend regarding instruction scheduling
  58. # for all `tt.dot` operations in a kernel. The "none" variant preserves the default
  59. # instruction scheduling of the AMDGPU backend which aims at maximizing occupancy.
  60. # The option is experimental and may change at any time regarding its semantics and/or may
  61. # be gone entirely anytime.
  62. #
  63. # Current experimental scheduling variants:
  64. #
  65. # attention: enables a bunch of optimizations for attention kernels, including:
  66. # - iglp 2 and sched.barrier around it
  67. # - sink-insts-to-avoid-spills flag to avoid register spills
  68. # memory-bound-attention: enables custom scheduling strategy in llvm backend,
  69. # This option targets special FA variant, which is memory bound and
  70. # has a lot of elementwise operations from fused operand dequantizations.
  71. # Note that this option is highly experimental,
  72. # and will be removed as soon as default sceduler algorithm is fixed.
  73. #
  74. # Option allows to set multiple variants divided by commas:
  75. # schedule_hint="attention,memory-bound-attention"
  76. schedule_hint: str = 'none'
  77. def __post_init__(self):
  78. gfx_major = int(self.arch[3:-2]) # Drop "gfx" prefix and minor/patch number
  79. warp_size = 32 if gfx_major >= 10 else 64
  80. object.__setattr__(self, 'warp_size', warp_size)
  81. assert self.num_warps > 0 and (self.num_warps & (self.num_warps - 1)) == 0, \
  82. "num_warps must be a power of 2"
  83. if (self.arch == 'gfx950') and (self.kpack != 1):
  84. warnings.warn(
  85. f"kpack is deprecated starting from gfx950 and will be removed in later releases. So for now kpack = {self.kpack} will be overwritten to 1 to make transitioning easier."
  86. )
  87. object.__setattr__(self, 'kpack', 1)
  88. default_libdir = Path(__file__).parent / 'lib'
  89. extern_libs = {} if self.extern_libs is None else dict(self.extern_libs)
  90. for lib in ["ocml", "ockl"]:
  91. extern_libs[lib] = str(default_libdir / f'{lib}.bc')
  92. object.__setattr__(self, 'extern_libs', tuple(extern_libs.items()))
  93. def hash(self):
  94. key = '_'.join([f'{name}-{val}' for name, val in self.__dict__.items()])
  95. return hashlib.sha256(key.encode("utf-8")).hexdigest()
  96. class HIPBackend(BaseBackend):
  97. instrumentation = None
  98. supports_native_tensor_specialization = False
  99. @staticmethod
  100. def supports_target(target: GPUTarget):
  101. return target.backend == 'hip'
  102. def __init__(self, target: GPUTarget) -> None:
  103. super().__init__(target)
  104. assert isinstance(target.arch, str)
  105. self.binary_ext = "hsaco"
  106. def get_target_name(self, options) -> str:
  107. return f"hip:{options.arch}"
  108. def parse_options(self, opts) -> Any:
  109. args = {'arch': knobs.runtime.override_arch or self.target.arch}
  110. if opts.get("num_ctas", 1) > 1 and not amd.supports_multi_cta_launch(self.target.arch):
  111. raise ValueError(f"num_ctas > 1 not supported on {self.target.arch}")
  112. # Enable XF32 (TF32) for CDNA3 GPUs
  113. if self.target.arch == 'gfx942':
  114. allowed_dot_input_precisions = set(HIPOptions.allowed_dot_input_precisions)
  115. allowed_dot_input_precisions.update({'tf32'})
  116. args["allowed_dot_input_precisions"] = tuple(sorted(allowed_dot_input_precisions))
  117. if "supported_fp8_dtypes" not in opts:
  118. args["supported_fp8_dtypes"] = tuple(sorted(HIPOptions.supported_fp8_dtypes))
  119. if self.target.arch == 'gfx950':
  120. deprecated_fp8_dot_operand_dtypes = set(HIPOptions.deprecated_fp8_dot_operand_dtypes)
  121. deprecated_fp8_dot_operand_dtypes.update({"fp8e5b16", "fp8e4b8"})
  122. args["deprecated_fp8_dot_operand_dtypes"] = tuple(sorted(deprecated_fp8_dot_operand_dtypes))
  123. if "enable_fp_fusion" not in opts:
  124. args["enable_fp_fusion"] = knobs.language.default_fp_fusion
  125. args.update({k: opts[k] for k in HIPOptions.__dataclass_fields__.keys() if k in opts and opts[k] is not None})
  126. return HIPOptions(**args)
  127. def pack_metadata(self, metadata):
  128. return (
  129. metadata.num_warps,
  130. metadata.num_ctas,
  131. metadata.shared,
  132. )
  133. def get_codegen_implementation(self, options):
  134. return {"min_dot_size": get_min_dot_size(self.target)}
  135. def get_module_map(self) -> Dict[str, ModuleType]:
  136. from triton.language.extra.hip import libdevice
  137. return {"triton.language.extra.libdevice": libdevice}
  138. def load_dialects(self, ctx):
  139. amd.load_dialects(ctx)
  140. if HIPBackend.instrumentation:
  141. HIPBackend.instrumentation.load_dialects(ctx)
  142. @staticmethod
  143. def is_within_2gb(arg):
  144. import torch
  145. MAX_INT_32 = 2**31 - 1
  146. if hasattr(arg, "ptr_range"):
  147. return arg.ptr_range() <= MAX_INT_32
  148. if isinstance(arg, torch.Tensor) and hasattr(arg, "untyped_storage"):
  149. return arg.untyped_storage().size() <= MAX_INT_32
  150. return False
  151. @staticmethod
  152. def parse_attr(desc):
  153. ret = BaseBackend.parse_attr(desc)
  154. if "S" in desc:
  155. ret += [["tt.pointer_range", 32]]
  156. return ret
  157. @staticmethod
  158. def get_tensor_specialization(arg, **kwargs):
  159. ret = BaseBackend.get_tensor_specialization(arg, **kwargs)
  160. if knobs.amd.use_buffer_ops and HIPBackend.is_within_2gb(arg):
  161. ret += "S"
  162. return ret
  163. @staticmethod
  164. def make_ttir(mod, metadata, options):
  165. pm = ir.pass_manager(mod.context)
  166. pm.enable_debug()
  167. passes.common.add_inliner(pm)
  168. passes.ttir.add_rewrite_tensor_pointer(pm)
  169. passes.ttir.add_rewrite_tensor_descriptor_to_pointer(pm)
  170. passes.common.add_canonicalizer(pm)
  171. passes.ttir.add_combine(pm)
  172. passes.ttir.add_reorder_broadcast(pm)
  173. passes.common.add_cse(pm)
  174. passes.ttir.add_triton_licm(pm)
  175. passes.common.add_symbol_dce(pm)
  176. passes.ttir.add_loop_unroll(pm)
  177. pm.run(mod, 'make_ttir')
  178. return mod
  179. @staticmethod
  180. def make_ttgir(mod, metadata, options):
  181. pm = ir.pass_manager(mod.context)
  182. pm.enable_debug()
  183. passes.ttir.add_convert_to_ttgpuir(pm, f"hip:{options.arch}", options.num_warps, options.warp_size,
  184. options.num_ctas)
  185. pm.run(mod, 'make_ttgir_early')
  186. pm = ir.pass_manager(mod.context)
  187. pm.enable_debug()
  188. emuTF32 = False
  189. passes.ttgpuir.add_coalesce(pm)
  190. passes.ttgpuir.add_f32_dot_tc(pm, emuTF32)
  191. passes.ttgpuir.add_remove_layout_conversions(pm)
  192. passes.ttgpuir.add_optimize_thread_locality(pm)
  193. amd.passes.ttgpuir.add_accelerate_matmul(pm, options.arch, options.matrix_instr_nonkdim, options.kpack)
  194. passes.ttgpuir.add_remove_layout_conversions(pm)
  195. amd.passes.ttgpuir.add_optimize_epilogue(pm)
  196. amd.passes.ttgpuir.add_optimize_dot_operands(pm, options.arch)
  197. amd.passes.ttgpuir.add_hoist_layout_conversions(pm)
  198. passes.ttgpuir.add_fuse_nested_loops(pm)
  199. passes.common.add_canonicalizer(pm)
  200. passes.ttir.add_triton_licm(pm)
  201. passes.common.add_canonicalizer(pm)
  202. use_async_copy = knobs.amd.use_async_copy
  203. use_block_pingpong = is_pingpong_schedule_enabled(options.arch, use_async_copy)
  204. amd.passes.ttgpuir.add_schedule_loops(pm, options.num_stages)
  205. amd.passes.ttgpuir.add_pipeline(pm, use_async_copy, use_block_pingpong)
  206. if use_async_copy:
  207. amd.passes.ttgpuir.add_coalesce_async_copy(pm, options.arch)
  208. passes.common.add_canonicalizer(pm)
  209. if options.schedule_hint.lower() != "none":
  210. for hint in options.schedule_hint.split(","):
  211. amd.passes.ttgpuir.insert_instruction_sched_hints(pm, hint)
  212. passes.ttgpuir.add_remove_layout_conversions(pm)
  213. passes.ttgpuir.add_reduce_data_duplication(pm)
  214. if is_in_thread_transpose_enabled(options.arch):
  215. amd.passes.ttgpuir.add_in_thread_transpose(pm)
  216. passes.ttgpuir.add_remove_layout_conversions(pm)
  217. amd.passes.ttgpuir.add_reorder_instructions(pm)
  218. if use_block_pingpong and options.num_stages > 1:
  219. amd.passes.ttgpuir.add_block_pingpong(pm, options.num_stages)
  220. if knobs.amd.use_buffer_ops:
  221. amd.passes.ttgpuir.add_canonicalize_pointers(pm)
  222. passes.common.add_canonicalizer(pm)
  223. amd.passes.ttgpuir.add_convert_to_buffer_ops(
  224. pm,
  225. options.arch,
  226. knobs.amd.use_buffer_atomics,
  227. knobs.amd.buffer_ops_analyze_small_tensor_range,
  228. )
  229. amd.passes.ttgpuir.add_fold_true_cmpi(pm)
  230. passes.common.add_canonicalizer(pm)
  231. passes.common.add_cse(pm)
  232. passes.common.add_symbol_dce(pm)
  233. pm.run(mod, 'make_ttgir')
  234. metadata["tensordesc_meta"] = mod.get_tensordesc_metadata()
  235. return mod
  236. @staticmethod
  237. def gluon_to_ttgir(src, metadata, options):
  238. mod = src
  239. pm = ir.pass_manager(mod.context)
  240. pm.enable_debug()
  241. passes.gluon.add_inliner(pm)
  242. passes.gluon.add_resolve_auto_encodings(pm)
  243. passes.common.add_sccp(pm)
  244. passes.ttir.add_loop_aware_cse(pm)
  245. passes.gluon.add_canonicalizer(pm)
  246. passes.ttgpuir.add_combine_tensor_select_and_if(pm)
  247. pm.run(mod, 'gluon_to_ttgir')
  248. metadata["tensordesc_meta"] = mod.get_tensordesc_metadata()
  249. return mod
  250. @staticmethod
  251. def make_llir(src, metadata, options):
  252. mod = src
  253. # TritonGPU -> LLVM-IR (MLIR)
  254. pm = ir.pass_manager(mod.context)
  255. pm.enable_debug()
  256. amd.passes.ttgpuir.add_update_async_wait_count(pm, options.arch)
  257. # custom_lds_size is an experimental parameter that defines amount of LDS available
  258. # for one thread block. Measured in bytes.
  259. #
  260. # If custom_lds_size = 0, pass will consider all LDS is available for one threads block,
  261. # LDS size is determined by provided arch name.
  262. custom_lds_size = 0
  263. amd.passes.ttgpuir.add_optimize_lds_usage(pm, options.arch, custom_lds_size)
  264. passes.convert.add_scf_to_cf(pm)
  265. passes.gluon.add_inliner(pm)
  266. passes.convert.add_index_to_llvmir(pm)
  267. amd.passes.ttgpuir.add_allocate_shared_memory(pm)
  268. # instrumentation point here so we can override IRs above (e.g., ttir and ttgir)
  269. if HIPBackend.instrumentation:
  270. HIPBackend.instrumentation.patch("ttgpuir_to_llvmir", pm, mod.context)
  271. ## __HIP_FTZ is used to control the denorm flushing behavior of exp2 op as follows:
  272. ## 1. If __HIP_FTZ = 1, exp2 flushes denorms in input and output regardless
  273. ## of the value of kernel arg `allow_flush_denorm`.
  274. ## 2. If __HIP_FTZ = 0, whether exp2 flushes denorms in input and output
  275. ## depends on the value of kernel arg `allow_flush_denorm`.
  276. ## 3. __HIP_FTZ is default to 1 and not exposed as a kernel argument.
  277. ## For now it is used as a controller for developers only.
  278. __HIP_FTZ = True
  279. amd.passes.ttgpuir.add_to_llvmir(pm, options.arch, __HIP_FTZ)
  280. passes.common.add_canonicalizer(pm)
  281. passes.common.add_cse(pm)
  282. passes.convert.add_cf_to_llvmir(pm)
  283. passes.convert.add_arith_to_llvmir(pm)
  284. passes.common.add_canonicalizer(pm)
  285. passes.common.add_cse(pm)
  286. passes.common.add_symbol_dce(pm)
  287. if options.schedule_hint.lower() != "none":
  288. amd.passes.ttgpuir.lower_instruction_sched_hints(pm, options.arch, options.num_stages)
  289. # This can not be moved below the di_scope pass
  290. if HIPBackend.instrumentation:
  291. HIPBackend.instrumentation.patch("llvmir_to_llvm", pm, mod.context)
  292. if not knobs.compilation.disable_line_info and not knobs.compilation.dump_ir_extract_di_local_variables:
  293. passes.llvmir.add_di_scope(pm)
  294. amd.passes.ttgpuir.add_builtin_func_to_llvmir(pm, __HIP_FTZ)
  295. pm.run(mod, 'make_llir')
  296. if knobs.compilation.dump_ir_extract_di_local_variables:
  297. # comments below on why separate it
  298. if not knobs.compilation.disable_line_info:
  299. pm = ir.pass_manager(mod.context)
  300. pm.enable_debug()
  301. passes.llvmir.add_di_scope(pm)
  302. pm.run(mod, 'make_llir.disable_line_info')
  303. # insert dbg intrinsic with several DI Attribute including source
  304. # var name and type info note: unknown reason for now, but this
  305. # pass and add_di_scope has to be run separately, otherwise if we
  306. # put them into previous pipline, it trigger a segmentfault without
  307. # any error message; could be due to a bug in mlir or pybind11
  308. pm = ir.pass_manager(mod.context)
  309. pm.enable_debug()
  310. passes.llvmir.add_di_local_variable(pm)
  311. pm.run(mod, 'make_llir.dump_ir_extract_di_local_variables')
  312. # LLVM-IR (MLIR) -> LLVM-IR (LLVM)
  313. llvm.init_targets()
  314. context = llvm.context()
  315. llvm_mod = llvm.to_module(mod, context)
  316. amd.attach_target_triple(llvm_mod)
  317. target_features = ''
  318. if knobs.compilation.enable_asan:
  319. target_features = '+xnack'
  320. llvm.attach_datalayout(llvm_mod, amd.TARGET_TRIPLE, options.arch, target_features)
  321. # Set various control constants on the LLVM module so that device
  322. # libraries can resolve references to them.
  323. amd.set_isa_version(llvm_mod, options.arch)
  324. amd.set_abi_version(llvm_mod, 500)
  325. amd.set_bool_control_constant(llvm_mod, "__oclc_finite_only_opt", False)
  326. amd.set_bool_control_constant(llvm_mod, "__oclc_correctly_rounded_sqrt32", True)
  327. amd.set_bool_control_constant(llvm_mod, "__oclc_unsafe_math_opt", False)
  328. amd.set_bool_control_constant(llvm_mod, "__oclc_wavefrontsize64", options.warp_size == 64)
  329. # Set kernel attributes first given this may affect later optimizations.
  330. fns = [fn for fn in llvm_mod.get_functions() if not fn.is_declaration()]
  331. # The public kernel should be kernel 0.
  332. fns[0].set_calling_conv(amd.CALLING_CONV_AMDGPU_KERNEL)
  333. fns[0].add_fn_attr("amdgpu-flat-work-group-size", f"1,{options.num_warps*options.warp_size}")
  334. if "memory-bound-attention" in options.schedule_hint.split(','):
  335. fns[0].add_fn_attr("amdgpu-sched-strategy", "iterative-ilp")
  336. fns[0].add_fn_attr("uniform-work-group-size", "true")
  337. # LLVM AMDGPU backend supports the attribute "amdgpu-waves-per-eu"="<min>[, <max>]".
  338. # This attribute may be attached to a kernel function definition and is an optimization hint.
  339. # <min> parameter specifies the requested minimum number of waves per EU, and optional <max> parameter
  340. # specifies the requested maximum number of waves per EU (must be >= <min> if specified).
  341. # If <max> is omitted, then there is no restriction on the maximum number of waves per EU other than
  342. # the one dictated by the hardware for which the kernel is compiled. Passing 0, 0 as <min>, <max>
  343. # implies the default behavior (no limits).
  344. # Specifying N, N forces LLVM to focus on a single register count, simplifies some heuristics
  345. # and may improve scheduling.
  346. fns[0].add_fn_attr("amdgpu-waves-per-eu", f"{options.waves_per_eu}, {options.waves_per_eu}")
  347. denormal_mode = "preserve-sign" if options.allow_flush_denorm else "ieee"
  348. fns[0].add_fn_attr("denormal-fp-math-f32", denormal_mode)
  349. if knobs.compilation.enable_asan:
  350. fns[0].add_fn_target_feature("+xnack")
  351. fns[0].add_fn_asan_attr()
  352. # Hint the compiler that we'd like the firmware to set the kernel arguments
  353. # to user SGPRs so that the kernel does not need to s_load its arguments
  354. # from memory.
  355. amd.set_all_fn_arg_inreg(fns[0])
  356. if knobs.compilation.enable_asan:
  357. default_libdir = Path(__file__).parent / 'lib'
  358. paths = [
  359. str(default_libdir / 'asanrtl.bc'),
  360. str(default_libdir / "ocml.bc"),
  361. str(default_libdir / "ockl.bc")
  362. ]
  363. llvm.link_extern_libs(llvm_mod, paths)
  364. elif options.extern_libs:
  365. paths = [path for (name, path) in options.extern_libs if amd.need_extern_lib(llvm_mod, name)]
  366. if len(paths) > 0:
  367. llvm.link_extern_libs(llvm_mod, paths)
  368. llvm.optimize_module(llvm_mod, llvm.OPTIMIZE_O3, options.arch, '', [], options.enable_fp_fusion)
  369. # Architectures with architected SGPRs store the workgroup id in ttmp9 (X) and ttmp7 (Y[15:0], Z[31:16]).
  370. # These attributes are used to determine if Z should be masked out when loading Y. They are inferred during
  371. # optimize_module from calls to @llvm.amdgcn.workgroup.id.x/y/z(). We cannot rely on this because a
  372. # dispatch dimensions might be used even if there is no program_id() call for it.
  373. if amd.has_architected_sgprs(options.arch):
  374. fns[0].remove_fn_attr("amdgpu-no-workgroup-id-x")
  375. fns[0].remove_fn_attr("amdgpu-no-workgroup-id-y")
  376. fns[0].remove_fn_attr("amdgpu-no-workgroup-id-z")
  377. if knobs.amd.scalarize_packed_fops:
  378. amd.add_scalarize_packed_fops_llvm_pass(fns[0])
  379. # Get some metadata
  380. metadata["shared"] = src.get_int_attr("ttg.shared")
  381. metadata["profile_scratch_size"] = src.get_int_attr("ttg.profile_scratch_memory_size") or 0
  382. metadata["profile_scratch_align"] = src.get_int_attr("ttg.profile_scratch_memory_alignment") or 1
  383. amd.cleanup_bitcode_metadata(llvm_mod)
  384. # Disable inlining of print related functions,
  385. # because inlining of these function could slow down compilation significantly
  386. amd.disable_print_inline(llvm_mod)
  387. return str(llvm_mod)
  388. @staticmethod
  389. def make_amdgcn(src, metadata, options):
  390. # Find kernel names (there should only be one)
  391. # We get the name at the last possible step to accommodate `triton.compile`
  392. # on user-provided LLVM
  393. names = re.findall(r"define amdgpu_kernel void @([a-zA-Z_][a-zA-Z0-9_]*)", src)
  394. assert len(names) == 1
  395. metadata["name"] = names[0]
  396. # llvm -> hsaco
  397. flags = []
  398. features = '-real-true16' if 'gfx11' in options.arch else ''
  399. ir_hash = hashlib.sha256(src.encode("utf-8")).hexdigest()
  400. dump_file_id = names[0] + '_' + ir_hash
  401. _ = llvm.translate_to_mir(src, amd.TARGET_TRIPLE, options.arch, features, flags, options.enable_fp_fusion,
  402. dump_file_id)
  403. llvm.dump_sched_dag(src, amd.TARGET_TRIPLE, options.arch, features, flags, options.enable_fp_fusion,
  404. dump_file_id)
  405. amdgcn = llvm.translate_to_asm(src, amd.TARGET_TRIPLE, options.arch, features, flags, options.enable_fp_fusion,
  406. False)
  407. if knobs.amd.dump_amdgcn:
  408. print("// -----// AMDGCN Dump //----- //")
  409. print(amdgcn)
  410. return amdgcn
  411. @staticmethod
  412. def make_hsaco(src, metadata, options):
  413. target_features = ''
  414. if knobs.compilation.enable_asan:
  415. target_features = '+xnack'
  416. hsaco = amd.assemble_amdgcn(src, options.arch, target_features)
  417. # Use delete=False so the file can be reopened on Windows after closing.
  418. # Clean up with try_remove outside the context managers.
  419. with tempfile.NamedTemporaryFile(delete=False, mode='wb', suffix='.o') as tmp_in, \
  420. tempfile.NamedTemporaryFile(delete=False, mode='rb', suffix='.hsaco') as tmp_out:
  421. tmp_in.write(hsaco)
  422. tmp_in.flush()
  423. tmp_out_name = tmp_out.name
  424. tmp_in_name = tmp_in.name
  425. amd.link_hsaco(tmp_in_name, tmp_out_name)
  426. with open(tmp_out_name, 'rb') as f:
  427. ret = f.read()
  428. try_remove(tmp_in_name)
  429. try_remove(tmp_out_name)
  430. return ret
  431. def add_stages(self, stages, options, language):
  432. if language == Language.TRITON:
  433. stages["ttir"] = lambda src, metadata: self.make_ttir(src, metadata, options)
  434. stages["ttgir"] = lambda src, metadata: self.make_ttgir(src, metadata, options)
  435. elif language == Language.GLUON:
  436. stages["ttgir"] = lambda src, metadata: self.gluon_to_ttgir(src, metadata, options)
  437. stages["llir"] = lambda src, metadata: self.make_llir(src, metadata, options)
  438. stages["amdgcn"] = lambda src, metadata: self.make_amdgcn(src, metadata, options)
  439. stages["hsaco"] = lambda src, metadata: self.make_hsaco(src, metadata, options)
  440. if knobs.runtime.add_stages_inspection_hook is not None:
  441. knobs.runtime.add_stages_inspection_hook(self, stages, options, language, None)
  442. @functools.lru_cache()
  443. def hash(self):
  444. return f'{self.target}'