Skip to main content

vulkane_kernel_text/
scalarize.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Packed values (`LocalDecl::packed`, `ScalarExpr::Pack` / `Extract`) lowered by scalarization.
3//!
4//! `unpopped`'s shared `lower_dag` has no seam for a packed value (it returns "packed values have no
5//! lowering seam yet"), so an emitter cannot spell a vector type through it. A packed value of the
6//! kernel IR is a lane-wise scalar computation, though: `Add`, `Sub`, `Mul`, `Div`, `Min`/`Max`,
7//! `Select` (scalar condition) and `Cast` apply to each lane alone, with exactly the scalar rules. So a
8//! packed local of `n` lanes becomes `n` scalar locals, `Pack(xs)` is `xs[k]` in lane `k`, `Extract(v, k)`
9//! is lane `k` of `v`, and a lane-wise operator is that operator applied to each lane. The result is
10//! the same bits as a native vector would give, with the same float controls (they are per dtype).
11//!
12//! An assignment to a packed local evaluates **every** lane into a fresh temporary before it writes
13//! any lane, so `v = Pack(Extract(v, 1), Extract(v, 0))` swaps the lanes rather than copying one.
14//!
15//! What is not rewritten (a packed `Bitcast`, a `Qualified` packed operation, a packed operand of an
16//! operator that does not apply lane-wise, an `Extract` inside a statement this pass does not walk) is
17//! left alone or refused by name, and the emitter declines it as it did before.
18
19use unpopped::backend::LowerError;
20use unpopped::ir::ScalarExpr as E;
21use unpopped::kernel::{Block, KernelFn, LocalDecl, Place, Stmt};
22
23fn refuse(kernel: &KernelFn, what: impl std::fmt::Display) -> LowerError {
24    LowerError::UnsupportedKernel {
25        detail: format!("packed values: {what} (kernel `{}`)", kernel.name),
26    }
27}
28
29struct Pass<'k> {
30    kernel: &'k KernelFn,
31    locals: Vec<LocalDecl>,
32    /// For a packed local, the scalar local of each lane (lane 0 is the local itself).
33    lanes: std::collections::BTreeMap<u32, Vec<u32>>,
34}
35
36/// `kernel` with every packed local, `Pack` and `Extract` replaced by scalars, or `None` when it has
37/// no packed local (the common case: nothing to do).
38///
39/// # Errors
40///
41/// [`LowerError::UnsupportedKernel`] naming a packed construct that has no lane-wise rewrite.
42pub fn scalarize(kernel: &KernelFn) -> Result<Option<KernelFn>, LowerError> {
43    if kernel.locals.iter().all(|l| l.lanes == 1) {
44        return Ok(None);
45    }
46    let mut pass = Pass {
47        kernel,
48        locals: kernel.locals.clone(),
49        lanes: std::collections::BTreeMap::new(),
50    };
51    for (i, l) in kernel.locals.iter().enumerate() {
52        if l.lanes > 1 {
53            let id = u32::try_from(i).expect("local id fits u32");
54            let mut ids = vec![id];
55            for _ in 1..l.lanes {
56                ids.push(pass.fresh(l.elem));
57            }
58            pass.locals[i] = LocalDecl::scalar(l.elem);
59            pass.lanes.insert(id, ids);
60        }
61    }
62    let body = pass.block(&kernel.body)?;
63    let mut out = kernel.clone();
64    out.locals = pass.locals;
65    out.body = body;
66    Ok(Some(out))
67}
68
69impl Pass<'_> {
70    fn fresh(&mut self, elem: unpopped_vocab::ElementKind) -> u32 {
71        self.locals.push(LocalDecl::scalar(elem));
72        u32::try_from(self.locals.len() - 1).expect("local id fits u32")
73    }
74
75    fn no(&self, what: impl std::fmt::Display) -> LowerError {
76        refuse(self.kernel, what)
77    }
78
79    /// Lane `k` of the packed expression `e`.
80    fn lane(&self, e: &E, k: usize) -> Result<E, LowerError> {
81        let b = |x: &E| self.lane(x, k).map(Box::new);
82        Ok(match e {
83            E::Local(v) => match self.lanes.get(v) {
84                Some(ids) => E::Local(*ids.get(k).ok_or_else(|| self.no("a lane out of range"))?),
85                None => return Err(self.no(format!("local {v} is not packed"))),
86            },
87            E::Pack(xs) => self.scalar(xs.get(k).ok_or_else(|| self.no("a lane out of range"))?)?,
88            E::Add(x, y) => E::Add(b(x)?, b(y)?),
89            E::Sub(x, y) => E::Sub(b(x)?, b(y)?),
90            E::Mul(x, y) => E::Mul(b(x)?, b(y)?),
91            E::Div(x, y) => E::Div(b(x)?, b(y)?),
92            E::Binary(op, x, y) => E::Binary(*op, b(x)?, b(y)?),
93            E::Fma(x, y, z) => E::Fma(b(x)?, b(y)?, b(z)?),
94            E::Select(c, x, y) => E::Select(Box::new(self.scalar(c)?), b(x)?, b(y)?),
95            E::Cast(x, spec) => E::Cast(b(x)?, *spec),
96            other => {
97                let name = format!("{other:?}");
98                let name = name.split(['(', '{']).next().unwrap_or("an expression");
99                return Err(self.no(format!(
100                    "`{name}` of a packed value has no lane-wise lowering"
101                )));
102            }
103        })
104    }
105
106    /// `e` (scalar) with every `Extract` replaced by the lane it names.
107    fn scalar(&self, e: &E) -> Result<E, LowerError> {
108        let b = |x: &E| self.scalar(x).map(Box::new);
109        Ok(match e {
110            E::Extract(x, i) => self.lane(x, usize::from(*i))?,
111            E::Add(x, y) => E::Add(b(x)?, b(y)?),
112            E::Sub(x, y) => E::Sub(b(x)?, b(y)?),
113            E::Mul(x, y) => E::Mul(b(x)?, b(y)?),
114            E::Div(x, y) => E::Div(b(x)?, b(y)?),
115            E::Unary(op, x) => E::Unary(*op, b(x)?),
116            E::Binary(op, x, y) => E::Binary(*op, b(x)?, b(y)?),
117            E::Fma(x, y, z) => E::Fma(b(x)?, b(y)?, b(z)?),
118            E::Select(c, x, y) => E::Select(b(c)?, b(x)?, b(y)?),
119            E::Cast(x, spec) => E::Cast(b(x)?, *spec),
120            other => other.clone(),
121        })
122    }
123
124    fn place(&self, p: &Place) -> Result<Place, LowerError> {
125        Ok(match p {
126            Place::Logical { buffer, coords } => Place::Logical {
127                buffer: *buffer,
128                coords: coords
129                    .iter()
130                    .map(|c| self.scalar(c))
131                    .collect::<Result<_, _>>()?,
132            },
133            Place::Alloc { alloc, index } => Place::Alloc {
134                alloc: *alloc,
135                index: self.scalar(index)?,
136            },
137            other => other.clone(),
138        })
139    }
140
141    fn block(&mut self, block: &Block) -> Result<Block, LowerError> {
142        let mut out = Vec::new();
143        for s in &block.0 {
144            self.stmt(s, &mut out)?;
145        }
146        Ok(Block(out))
147    }
148
149    fn stmt(&mut self, s: &Stmt, out: &mut Vec<Stmt>) -> Result<(), LowerError> {
150        match s {
151            Stmt::Let { local, init } if self.lanes.contains_key(local) => {
152                let ids = self.lanes[local].clone();
153                for (k, id) in ids.into_iter().enumerate() {
154                    out.push(Stmt::Let {
155                        local: id,
156                        init: self.lane(init, k)?,
157                    });
158                }
159            }
160            Stmt::Assign { local, value } if self.lanes.contains_key(local) => {
161                // Every lane into a temporary first: the value may read the lanes it overwrites.
162                let ids = self.lanes[local].clone();
163                let elem = self.kernel.locals[usize::try_from(*local).expect("local id")].elem;
164                let mut temps = Vec::new();
165                for k in 0..ids.len() {
166                    let t = self.fresh(elem);
167                    out.push(Stmt::Let {
168                        local: t,
169                        init: self.lane(value, k)?,
170                    });
171                    temps.push(t);
172                }
173                for (id, t) in ids.into_iter().zip(temps) {
174                    out.push(Stmt::Assign {
175                        local: id,
176                        value: E::Local(t),
177                    });
178                }
179            }
180            Stmt::Let { local, init } => out.push(Stmt::Let {
181                local: *local,
182                init: self.scalar(init)?,
183            }),
184            Stmt::Assign { local, value } => out.push(Stmt::Assign {
185                local: *local,
186                value: self.scalar(value)?,
187            }),
188            Stmt::Load { local, place } => out.push(Stmt::Load {
189                local: *local,
190                place: self.place(place)?,
191            }),
192            Stmt::Store { place, value } => out.push(Stmt::Store {
193                place: self.place(place)?,
194                value: self.scalar(value)?,
195            }),
196            Stmt::If { cond, then, els } => out.push(Stmt::If {
197                cond: self.scalar(cond)?,
198                then: self.block(then)?,
199                els: self.block(els)?,
200            }),
201            Stmt::While { cond, body } => out.push(Stmt::While {
202                cond: self.scalar(cond)?,
203                body: self.block(body)?,
204            }),
205            Stmt::For {
206                local,
207                start,
208                end,
209                step,
210                unroll,
211                body,
212            } => out.push(Stmt::For {
213                local: *local,
214                start: self.scalar(start)?,
215                end: self.scalar(end)?,
216                step: self.scalar(step)?,
217                unroll: *unroll,
218                body: self.block(body)?,
219            }),
220            other => out.push(other.clone()),
221        }
222        Ok(())
223    }
224}