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, RoundMode, UnaryOp};
6use unpopped::kernel::{AtomicOp, BufferRole, CollectiveKind, 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 type: the compute dtype, except in a float kernel, whose buffers may also hold
42 /// the other float width and the 32-bit integers a `Cast` converts.
43 pub elem: ElementKind,
44 /// The element count of a shared array; `0` for a buffer.
45 pub len: u32,
46 /// `true` for a per-thread (`Private`) array, `false` for a buffer or a workgroup array.
47 pub private: bool,
48 /// `true` when the dialect types atomics ([`Dialect::typed_atomics`]) and the kernel applies an
49 /// atomic to this buffer or array: every access to it is then an atomic one.
50 pub atomic: bool,
51 /// For a scalar parameter lowered as a specialization constant (`SpecId` = `binding`): the local
52 /// that reads it. `None` for a buffer or an array.
53 pub spec_local: Option<u32>,
54 /// For an array whose extent is a scalar parameter: the identifier of that specialization
55 /// constant (`len` is then `0`).
56 pub len_spec: Option<String>,
57}
58
59/// Everything the prologue needs.
60#[derive(Clone, Debug)]
61pub struct Layout {
62 /// The kernel's name.
63 pub name: String,
64 /// `true` for an `I32` kernel, `false` for `U32`.
65 pub signed: bool,
66 /// The workgroup size.
67 pub block: [u32; 3],
68 /// The storage buffers, in parameter order.
69 pub buffers: Vec<Decl>,
70 /// The workgroup and per-thread arrays, in allocation order (`Decl::private` tells them apart).
71 pub shared: Vec<Decl>,
72 /// The `(local, constant identifier)` of each scalar parameter lowered as a specialization
73 /// constant; the local starts at its value instead of zero.
74 pub spec_locals: Vec<(u32, String)>,
75 /// How many locals the body declares (`l0..`).
76 pub locals: usize,
77 /// The element type of each local (the compute dtype, except in a float kernel).
78 pub local_elems: Vec<ElementKind>,
79 /// The widths (16/32/64) at which the body does a rounding float conversion, so the module must
80 /// declare the round-to-nearest-even mode there.
81 pub rte: Vec<u32>,
82 /// Whether any statement is a subgroup barrier or fence (a GLSL extension line).
83 pub subgroup: bool,
84}
85
86impl Layout {
87 /// The specialization constant `local` starts at, when it is a scalar parameter's local.
88 #[must_use]
89 pub fn spec_init(&self, local: usize) -> Option<&str> {
90 self.spec_locals
91 .iter()
92 .find(|(l, _)| usize::try_from(*l).is_ok_and(|l| l == local))
93 .map(|(_, n)| n.as_str())
94 }
95}
96
97/// One **subgroup collective** (board 506 "A", narrowed) for a dialect to spell: the ruled reductions, shuffles, votes and broadcasts
98/// of [`crate::collective_is_ruled`]. The walker has already lowered the value and the operand to text, and the checker
99/// (`check_kernel`) has already refused a collective after a lane-divergent `Return` (`CollectiveAfterReturn`) or under
100/// lane-divergent control (`BarrierDivergent`).
101///
102/// Lifted by CireSnave 2026-11-26 (board 506 A) as his risk call: "outside as read" is a reading of public documents, not a clearance;
103/// no attorney; findings, not advice.
104#[derive(Clone, Debug)]
105pub struct SubgroupCollective<'a> {
106 /// Which collective (a ruled one).
107 pub kind: &'a CollectiveKind,
108 /// The text of the value every lane contributes.
109 pub value: String,
110 /// The element type of the value.
111 pub value_elem: ElementKind,
112 /// The text of the shuffle operand or the broadcast lane, when the kind has one.
113 pub operand: Option<String>,
114 /// The operand's value when it is a constant (`ConstInt`), else `None`.
115 pub operand_const: Option<i64>,
116 /// Whether the kernel's integers are signed (`I32`) rather than unsigned (`U32`).
117 pub signed: bool,
118 /// The launch's stated subgroup size range, `(min, max)`, when the launch states one.
119 pub subgroup: Option<(u32, u32)>,
120}
121
122/// The spellings of one target language.
123///
124/// A method that cannot spell something returns `None` (or an `Err` text), and the walker turns that
125/// into a typed decline naming it; nothing is approximated.
126pub trait Dialect {
127 /// The backend name used in decline texts (`glsl`, `wgsl`).
128 fn name(&self) -> &'static str;
129 /// Whether this dialect instance lowers 64-bit integer kernels (`I64`/`U64`). The default is no:
130 /// such a kernel is then a typed decline naming the dialect. A dialect that says yes types every
131 /// spelling at 64 bits and spells [`Self::cast_to_compute`]; an execution id stays the `u32` the IR
132 /// types it as, reached through a `Cast`.
133 fn wide(&self) -> bool {
134 false
135 }
136 /// Why this dialect cannot lower a float kernel at all, named in the decline of one (`None`: no
137 /// reason beyond the generic one). Only asked of a dialect whose [`Self::float`] is false.
138 fn float_refusal(&self) -> Option<&'static str> {
139 None
140 }
141 /// Why this dialect has no 8- or 16-bit integer buffers or locals at all, named in the decline of a
142 /// kernel that holds one (`None`: no reason beyond the generic one). Only asked of a dialect whose
143 /// [`Self::narrow_ints`] is false.
144 fn narrow_refusal(&self) -> Option<&'static str> {
145 None
146 }
147 /// Whether an `I32`/`U32` kernel may hold `I8`/`U8`/`I16`/`U16` buffers and locals (reached by a
148 /// wrapping `Cast`, spelled by [`Self::convert`]). The default is no: such a kernel is then a typed
149 /// decline naming the buffer.
150 fn narrow_ints(&self) -> bool {
151 false
152 }
153 /// Whether this dialect instance lowers float kernels (`F32`, or `F64` when [`Self::double`]). The default is no: such a kernel is then a
154 /// typed decline naming the dialect. A dialect that says yes spells [`Self::lit_float`],
155 /// [`Self::float_unary`] and [`Self::float_minmax`], keeps every float add, subtract and multiply
156 /// unfused ([`Self::temp_typed`]) and keeps an execution id the `u32` the IR types it as.
157 fn float(&self) -> bool {
158 false
159 }
160 /// Whether the float kernel this instance lowers is `F64` rather than `F32` (only asked when
161 /// [`Self::float`] is true).
162 fn double(&self) -> bool {
163 false
164 }
165 /// Whether the float kernel this instance lowers is `F16` (only asked when [`Self::float`] is
166 /// true): literals must then be exact halves.
167 fn half(&self) -> bool {
168 false
169 }
170 /// Whether the float kernel this instance lowers is `Bf16` (only asked when [`Self::float`] is
171 /// true): literals must then be exact `bfloat`s (an `f32` whose low 16 bits are zero). The
172 /// default is no, so no existing dialect changes.
173 fn bfloat(&self) -> bool {
174 false
175 }
176 /// Whether one kernel may use float types of two widths (`F32` and `F64` together). The default
177 /// is yes; a dialect whose float-control declarations cannot name two widths says no, and such a
178 /// kernel is a typed decline.
179 fn mixed_float_widths(&self) -> bool {
180 true
181 }
182 /// A float literal for `v`, already known to be a finite value exact at the kernel's float width, or `None`.
183 fn lit_float(&self, _v: f64) -> Option<String> {
184 None
185 }
186 /// `x` of type `from` converted to `to` (both `F32`, `F64`, `I32` or `U32` in a float kernel), the
187 /// rounding of a float to integer conversion being `round`; the walker has already checked the
188 /// combination is one it lowers. A float to integer conversion maps NaN to 0 and clamps to the
189 /// destination range, an integer to float or float narrowing rounds to nearest even.
190 fn convert(
191 &self,
192 _x: &str,
193 _from: ElementKind,
194 _to: ElementKind,
195 _round: RoundMode,
196 ) -> Option<String> {
197 None
198 }
199 /// A float unary op on `x`, or `None` when there is no exact spelling (the walker declines by name).
200 fn float_unary(&self, _op: UnaryOp, _x: &str) -> Option<String> {
201 None
202 }
203 /// NaN-propagating max (`is_max`) or min of `a` and `b`, `a` on ties; `None` when not spelled.
204 fn float_minmax(&self, _is_max: bool, _a: &str, _b: &str) -> Option<String> {
205 None
206 }
207 /// The type name of `t` in a float kernel (`float`, `uint`, `int`), or `None`.
208 fn type_name(&self, _t: ElementKind) -> Option<String> {
209 None
210 }
211 /// A boolean spelling of `value != 0` for a value of element type `t` in a float kernel (a float
212 /// compares against a float zero, an integer leaf against an integer zero).
213 fn truthy_of(&self, value: &str, _t: ElementKind) -> String {
214 format!("({value} != 0)")
215 }
216 /// A hoisted temporary of type `ty` (from [`Self::type_name`]) holding `rhs`. A float one must be
217 /// one a compiler may not fuse or reassociate the operations of (GLSL `precise`): the value of a
218 /// float expression is pinned in such a temporary before it is stored.
219 fn temp_typed(&self, ty: &str, name: &str, rhs: &str) -> String {
220 format!("const {ty} {name} = {rhs};")
221 }
222 /// `x`, of integer type `from`, converted (wrapping) to the compute dtype, or `None` when there is
223 /// no spelling. Only asked of a dialect whose [`Self::wide`] is true.
224 fn cast_to_compute(&self, _x: &str, _from: ElementKind) -> Option<String> {
225 None
226 }
227 /// Whether this dialect lowers the **ruled subgroup collectives** (board 506 "A": reductions, shuffles, votes, broadcasts at subgroup
228 /// scope). The default is no: every `Collective` is then refused by name with the board 434 C marker, as before. A dialect that says yes
229 /// spells them in [`Self::subgroup_collective`]; scans, user combines, `CollectiveTuple` and block scope stay refused by name whatever it says.
230 fn subgroup_collectives(&self) -> bool {
231 false
232 }
233 /// The expression a ruled subgroup collective evaluates to (assigned to the statement's result local), or the reason this dialect cannot
234 /// spell it exactly (the walker turns that into a typed decline naming the statement). Only asked when [`Self::subgroup_collectives`] is true.
235 ///
236 /// # Errors
237 /// The reason, in the dialect's terms.
238 fn subgroup_collective(&self, _c: &SubgroupCollective<'_>) -> Result<String, String> {
239 Err("this dialect has no spelling for a subgroup collective".to_string())
240 }
241 /// [`Self::prologue`] for a kernel that does (`collectives`) or does not use a subgroup collective: a dialect whose spelling needs a
242 /// directive or an entry parameter (WGSL `enable subgroups;`) adds it here. The default ignores the flag.
243 fn prologue_for(&self, layout: &Layout, _collectives: bool) -> String {
244 self.prologue(layout)
245 }
246 /// The header, buffer and shared declarations and the opening of the entry function, with the
247 /// locals declared (one line each) at the top of the entry.
248 fn prologue(&self, layout: &Layout) -> String;
249 /// The closing of the entry function.
250 fn epilogue(&self) -> &'static str;
251 /// An integer literal in the compute dtype.
252 fn lit(&self, v: i64, signed: bool) -> String;
253 /// The element `idx` of the buffer or shared array `name`.
254 fn index(&self, name: &str, idx: &str, is_buffer: bool) -> String;
255 /// The spelling of an execution id, or `None` when the dialect has none.
256 fn exec(&self, id: ExecId, signed: bool) -> Option<String>;
257 /// A binary op on two integers, or `None` when there is no spelling.
258 fn binary(&self, op: BinaryOp, a: &str, b: &str, signed: bool) -> Option<String>;
259 /// `a + b`, `a - b`, `a * b` (wrapping); `None` for a division.
260 fn arith(&self, op: ArithOp, a: &str, b: &str) -> Option<String> {
261 let sym = match op {
262 ArithOp::Add => "+",
263 ArithOp::Sub => "-",
264 ArithOp::Mul => "*",
265 _ => return None,
266 };
267 Some(format!("({a} {sym} {b})"))
268 }
269 /// `cond != 0 ? a : b`.
270 fn select(&self, cond: &str, a: &str, b: &str, signed: bool) -> String;
271 /// A boolean spelling of `value != 0`.
272 fn truthy(&self, value: &str, signed: bool) -> String {
273 format!("({value} != {})", self.lit(0, signed))
274 }
275 /// A hoisted temporary declaration line (no indentation, no newline).
276 fn temp(&self, name: &str, rhs: &str, signed: bool) -> String;
277 /// The `For` counter's bound and step constants, declared once before the loop.
278 fn bound(&self, name: &str, rhs: &str, signed: bool) -> String;
279 /// A statement that synchronizes `scope` (and orders memory), or `None` when there is none.
280 fn barrier(&self, scope: Scope) -> Option<String>;
281 /// An expression applying atomic `op` to the element `elem` with `value`, giving the old value;
282 /// `None` when the dialect has no spelling (the default).
283 fn atomic_rmw(&self, _op: AtomicOp, _elem: &str, _value: &str) -> Option<String> {
284 None
285 }
286 /// An expression compare-exchanging the element `elem`, giving the value found; `None` when
287 /// the dialect has no spelling (the default).
288 fn atomic_cas(&self, _elem: &str, _expected: &str, _desired: &str) -> Option<String> {
289 None
290 }
291 /// Whether the dialect declares an atomically accessed buffer or array with a different type (WGSL
292 /// `atomic<u32>`), so plain access to it goes through [`Self::atomic_load`] / [`Self::atomic_store`].
293 fn typed_atomics(&self) -> bool {
294 false
295 }
296 /// Whether an atomic at `scope` can be spelled (the default: every scope).
297 fn atomic_scope_ok(&self, _scope: Scope) -> bool {
298 true
299 }
300 /// An expression reading the element `elem` of an atomically typed buffer or array.
301 fn atomic_load(&self, _elem: &str) -> Option<String> {
302 None
303 }
304 /// A statement writing `value` to the element `elem` of an atomically typed buffer or array.
305 fn atomic_store(&self, _elem: &str, _value: &str) -> Option<String> {
306 None
307 }
308 /// The lines compare-exchanging `elem` and writing the value found to `dest`, if any. The default
309 /// is one assignment of [`Self::atomic_cas`]; a dialect whose exchange can fail spuriously
310 /// overrides it with a retry loop, because the IR's compare-exchange cannot.
311 fn atomic_cas_lines(
312 &self,
313 elem: &str,
314 expected: &str,
315 desired: &str,
316 dest: Option<&str>,
317 ) -> Option<Vec<String>> {
318 let call = self.atomic_cas(elem, expected, desired)?;
319 Some(vec![match dest {
320 Some(l) => format!("{l} = {call};"),
321 None => format!("{call};"),
322 }])
323 }
324 /// A memory fence at `scope`, or `None` when the dialect has none without a barrier.
325 fn fence(&self, scope: Scope, order: MemoryOrder) -> Option<String>;
326}