Skip to main content

wave_hip/
lib.rs

1// Copyright 2026 Ojima Abraham
2// SPDX-License-Identifier: Apache-2.0
3
4//! Public API for the WAVE HIP backend. Provides `compile()` to translate a complete
5//!
6//! WBIN binary file into HIP C++ source text, and `compile_kernel()` for translating
7//! a single kernel's code section. Targets AMD GPUs via ROCm/HIP with support for
8//! both RDNA (wavefront 32) and CDNA (wavefront 64) architectures.
9
10pub mod codegen;
11pub mod control_flow;
12pub mod intrinsics;
13pub mod kernel;
14pub mod memory;
15pub mod registers;
16
17use thiserror::Error;
18use wave_decode::{DecodeError, KernelInfo, WbinError, WbinFile};
19
20#[derive(Debug, Error)]
21pub enum CompileError {
22    #[error("WBIN parse error: {0}")]
23    Wbin(#[from] WbinError),
24
25    #[error("decode error: {0}")]
26    Decode(#[from] DecodeError),
27
28    #[error("no kernels found in WBIN file")]
29    NoKernels,
30
31    #[error("invalid kernel index: {0}")]
32    InvalidKernel(usize),
33
34    #[error("unsupported operation: {0}")]
35    UnsupportedOperation(String),
36}
37
38/// Compile a complete WBIN file into HIP C++ source.
39///
40/// # Errors
41///
42/// Returns `CompileError` if the WBIN file cannot be parsed, contains no kernels,
43/// or contains unsupported instructions.
44pub fn compile(wbin_data: &[u8]) -> Result<String, CompileError> {
45    let wbin = WbinFile::parse(wbin_data)?;
46    if wbin.kernels.is_empty() {
47        return Err(CompileError::NoKernels);
48    }
49
50    let mut output = kernel::emit_file_header();
51
52    for (i, kernel_info) in wbin.kernels.iter().enumerate() {
53        let code = wbin.kernel_code(i).ok_or(CompileError::InvalidKernel(i))?;
54        let instructions = wave_decode::decode_all(code)?;
55
56        let mut gen = codegen::CodeGenerator::new();
57        let kernel_hip = gen.generate(&instructions, kernel_info)?;
58        output.push_str(&kernel_hip);
59        output.push('\n');
60    }
61
62    Ok(output)
63}
64
65/// Compile a single kernel's code section into a HIP kernel function.
66///
67/// # Errors
68///
69/// Returns `CompileError` if the code cannot be decoded or contains unsupported instructions.
70pub fn compile_kernel(code: &[u8], kernel: &KernelInfo) -> Result<String, CompileError> {
71    let instructions = wave_decode::decode_all(code)?;
72    let mut gen = codegen::CodeGenerator::new();
73    let mut output = kernel::emit_file_header();
74    output.push_str(&gen.generate(&instructions, kernel)?);
75    Ok(output)
76}