Skip to main content

gcn_assembler/
lib.rs

1#![warn(missing_docs)]
2
3pub mod instructions;
4pub mod program;
5
6use crate::{instructions::GcnInstruction, program::GcnProgram};
7use gaia_types::Result;
8
9/// GCN 汇编器/写入器
10pub struct GcnWriter {}
11
12impl GcnWriter {
13    pub fn new() -> Self {
14        Self {}
15    }
16
17    pub fn write(&self, program: &GcnProgram) -> Result<Vec<u8>> {
18        let mut code = String::new();
19        for kernel in &program.kernels {
20            code.push_str(&format!(".text\n.globl {}\n{}:\n", kernel.name, kernel.name));
21            for inst in &kernel.instructions {
22                code.push_str("    ");
23                code.push_str(&self.format_instruction(inst));
24                code.push('\n');
25            }
26        }
27
28        // 模拟生成二进制 (ELF Magic + 汇编内容)
29        let mut binary = Vec::from("\x7fELF".as_bytes());
30        binary.extend_from_slice(code.as_bytes());
31        Ok(binary)
32    }
33
34    fn format_instruction(&self, inst: &GcnInstruction) -> String {
35        match inst {
36            GcnInstruction::VAddF32 { dst, src0, src1 } => format!("v_add_f32 {}, {}, {}", dst, src0, src1),
37            GcnInstruction::VMulF32 { dst, src0, src1 } => format!("v_mul_f32 {}, {}, {}", dst, src0, src1),
38            GcnInstruction::VDot2F32F16 { dst, src0, src1 } => format!("v_dot2_f32_f16 {}, {}, {}", dst, src0, src1),
39            GcnInstruction::GlobalLoadDword { dst, addr, offset } => {
40                format!("global_load_dword {}, {}, offset:{}", dst, addr, offset)
41            }
42            GcnInstruction::GlobalStoreDword { addr, src, offset } => {
43                format!("global_store_dword {}, {}, offset:{}", addr, src, offset)
44            }
45            GcnInstruction::SEndPgm => "s_endpgm".to_string(),
46            GcnInstruction::SNop(n) => format!("s_nop {}", n),
47        }
48    }
49}