Skip to main content

vulkane_kernel_text/
dialect.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! What a target language supplies to the walker.
3
4use unpopped::exec::{ExecId, Scope};
5use unpopped::ir::{ArithOp, BinaryOp};
6use unpopped::kernel::{AtomicOp, BufferRole, MemoryOrder};
7use unpopped_vocab::ElementKind;
8
9/// The comparisons both dialects spell with the same operator text; each gives `1` or `0` in the dtype.
10pub const COMPARISONS: &[(BinaryOp, &str)] = &[
11    (BinaryOp::CmpEq, "=="),
12    (BinaryOp::CmpNe, "!="),
13    (BinaryOp::CmpLt, "<"),
14    (BinaryOp::CmpLe, "<="),
15    (BinaryOp::CmpGt, ">"),
16    (BinaryOp::CmpGe, ">="),
17];
18
19/// The bitwise operators both dialects spell with the same operator text.
20pub const BIT_OPS: &[(BinaryOp, &str)] = &[
21    (BinaryOp::BitAnd, "&"),
22    (BinaryOp::BitOr, "|"),
23    (BinaryOp::BitXor, "^"),
24];
25
26/// The operator text `op` has in `table`, if any.
27#[must_use]
28pub fn operator(table: &[(BinaryOp, &'static str)], op: BinaryOp) -> Option<&'static str> {
29    table.iter().find(|(o, _)| *o == op).map(|(_, s)| *s)
30}
31
32/// A buffer or shared array the prologue declares.
33#[derive(Clone, Debug)]
34pub struct Decl {
35    /// The identifier the body uses (`b0`, `a0`).
36    pub name: String,
37    /// The binding slot of a buffer; unused for a shared array.
38    pub binding: u32,
39    /// The access of a buffer; `ReadWrite` for a shared array.
40    pub role: BufferRole,
41    /// The element count of a shared array; `0` for a buffer.
42    pub len: u32,
43    /// `true` for a per-thread (`Private`) array, `false` for a buffer or a workgroup array.
44    pub private: bool,
45    /// `true` when the dialect types atomics ([`Dialect::typed_atomics`]) and the kernel applies an
46    /// atomic to this buffer or array: every access to it is then an atomic one.
47    pub atomic: bool,
48    /// For a scalar parameter lowered as a specialization constant (`SpecId` = `binding`): the local
49    /// that reads it. `None` for a buffer or an array.
50    pub spec_local: Option<u32>,
51    /// For an array whose extent is a scalar parameter: the identifier of that specialization
52    /// constant (`len` is then `0`).
53    pub len_spec: Option<String>,
54}
55
56/// Everything the prologue needs.
57#[derive(Clone, Debug)]
58pub struct Layout {
59    /// The kernel's name.
60    pub name: String,
61    /// `true` for an `I32` kernel, `false` for `U32`.
62    pub signed: bool,
63    /// The workgroup size.
64    pub block: [u32; 3],
65    /// The storage buffers, in parameter order.
66    pub buffers: Vec<Decl>,
67    /// The workgroup and per-thread arrays, in allocation order (`Decl::private` tells them apart).
68    pub shared: Vec<Decl>,
69    /// The `(local, constant identifier)` of each scalar parameter lowered as a specialization
70    /// constant; the local starts at its value instead of zero.
71    pub spec_locals: Vec<(u32, String)>,
72    /// How many locals the body declares (`l0..`).
73    pub locals: usize,
74    /// Whether any statement is a subgroup barrier or fence (a GLSL extension line).
75    pub subgroup: bool,
76}
77
78impl Layout {
79    /// The specialization constant `local` starts at, when it is a scalar parameter's local.
80    #[must_use]
81    pub fn spec_init(&self, local: usize) -> Option<&str> {
82        self.spec_locals
83            .iter()
84            .find(|(l, _)| usize::try_from(*l).is_ok_and(|l| l == local))
85            .map(|(_, n)| n.as_str())
86    }
87}
88
89/// The spellings of one target language.
90///
91/// A method that cannot spell something returns `None` (or an `Err` text), and the walker turns that
92/// into a typed decline naming it; nothing is approximated.
93pub trait Dialect {
94    /// The backend name used in decline texts (`glsl`, `wgsl`).
95    fn name(&self) -> &'static str;
96    /// Whether this dialect instance lowers 64-bit integer kernels (`I64`/`U64`). The default is no:
97    /// such a kernel is then a typed decline naming the dialect. A dialect that says yes types every
98    /// spelling at 64 bits and spells [`Self::cast_to_compute`]; an execution id stays the `u32` the IR
99    /// types it as, reached through a `Cast`.
100    fn wide(&self) -> bool {
101        false
102    }
103    /// `x`, of integer type `from`, converted (wrapping) to the compute dtype, or `None` when there is
104    /// no spelling. Only asked of a dialect whose [`Self::wide`] is true.
105    fn cast_to_compute(&self, _x: &str, _from: ElementKind) -> Option<String> {
106        None
107    }
108    /// The header, buffer and shared declarations and the opening of the entry function, with the
109    /// locals declared (one line each) at the top of the entry.
110    fn prologue(&self, layout: &Layout) -> String;
111    /// The closing of the entry function.
112    fn epilogue(&self) -> &'static str;
113    /// An integer literal in the compute dtype.
114    fn lit(&self, v: i64, signed: bool) -> String;
115    /// The element `idx` of the buffer or shared array `name`.
116    fn index(&self, name: &str, idx: &str, is_buffer: bool) -> String;
117    /// The spelling of an execution id, or `None` when the dialect has none.
118    fn exec(&self, id: ExecId, signed: bool) -> Option<String>;
119    /// A binary op on two integers, or `None` when there is no spelling.
120    fn binary(&self, op: BinaryOp, a: &str, b: &str, signed: bool) -> Option<String>;
121    /// `a + b`, `a - b`, `a * b` (wrapping); `None` for a division.
122    fn arith(&self, op: ArithOp, a: &str, b: &str) -> Option<String> {
123        let sym = match op {
124            ArithOp::Add => "+",
125            ArithOp::Sub => "-",
126            ArithOp::Mul => "*",
127            _ => return None,
128        };
129        Some(format!("({a} {sym} {b})"))
130    }
131    /// `cond != 0 ? a : b`.
132    fn select(&self, cond: &str, a: &str, b: &str, signed: bool) -> String;
133    /// A boolean spelling of `value != 0`.
134    fn truthy(&self, value: &str, signed: bool) -> String {
135        format!("({value} != {})", self.lit(0, signed))
136    }
137    /// A hoisted temporary declaration line (no indentation, no newline).
138    fn temp(&self, name: &str, rhs: &str, signed: bool) -> String;
139    /// The `For` counter's bound and step constants, declared once before the loop.
140    fn bound(&self, name: &str, rhs: &str, signed: bool) -> String;
141    /// A statement that synchronizes `scope` (and orders memory), or `None` when there is none.
142    fn barrier(&self, scope: Scope) -> Option<String>;
143    /// An expression applying atomic `op` to the element `elem` with `value`, giving the old value;
144    /// `None` when the dialect has no spelling (the default).
145    fn atomic_rmw(&self, _op: AtomicOp, _elem: &str, _value: &str) -> Option<String> {
146        None
147    }
148    /// An expression compare-exchanging the element `elem`, giving the value found; `None` when
149    /// the dialect has no spelling (the default).
150    fn atomic_cas(&self, _elem: &str, _expected: &str, _desired: &str) -> Option<String> {
151        None
152    }
153    /// Whether the dialect declares an atomically accessed buffer or array with a different type (WGSL
154    /// `atomic<u32>`), so plain access to it goes through [`Self::atomic_load`] / [`Self::atomic_store`].
155    fn typed_atomics(&self) -> bool {
156        false
157    }
158    /// Whether an atomic at `scope` can be spelled (the default: every scope).
159    fn atomic_scope_ok(&self, _scope: Scope) -> bool {
160        true
161    }
162    /// An expression reading the element `elem` of an atomically typed buffer or array.
163    fn atomic_load(&self, _elem: &str) -> Option<String> {
164        None
165    }
166    /// A statement writing `value` to the element `elem` of an atomically typed buffer or array.
167    fn atomic_store(&self, _elem: &str, _value: &str) -> Option<String> {
168        None
169    }
170    /// The lines compare-exchanging `elem` and writing the value found to `dest`, if any. The default
171    /// is one assignment of [`Self::atomic_cas`]; a dialect whose exchange can fail spuriously
172    /// overrides it with a retry loop, because the IR's compare-exchange cannot.
173    fn atomic_cas_lines(
174        &self,
175        elem: &str,
176        expected: &str,
177        desired: &str,
178        dest: Option<&str>,
179    ) -> Option<Vec<String>> {
180        let call = self.atomic_cas(elem, expected, desired)?;
181        Some(vec![match dest {
182            Some(l) => format!("{l} = {call};"),
183            None => format!("{call};"),
184        }])
185    }
186    /// A memory fence at `scope`, or `None` when the dialect has none without a barrier.
187    fn fence(&self, scope: Scope, order: MemoryOrder) -> Option<String>;
188}