Debian Codegraph @

src/nouveau/compiler/nak/ssa_value.rs

raw
1 // Copyright © 2025 Collabora, Ltd.
2 // SPDX-License-Identifier: MIT
3
4 use crate::ir::{HasRegFile, RegFile};
5 use compiler::bitset::IntoBitIndex;
6 use std::array;
7 use std::fmt;
8 use std::num::NonZeroU32;
9 use std::ops::{Deref, DerefMut};
10
11 /// An SSA value
12 ///
13 /// Each SSA in NAK represents a single 32-bit or 1-bit (if a predicate) value
14 /// which must either be spilled to memory or allocated space in the specified
15 /// register file. Whenever more data is required such as a 64-bit memory
16 /// address, double-precision float, or a vec4 texture result, multiple SSA
17 /// values are used.
18 ///
19 /// Each SSA value logically contains two things: an index and a register file.
20 /// It is required that each index refers to a unique SSA value, regardless of
21 /// register file. This way the index can be used to index tightly-packed data
22 /// structures such as bitsets without having to determine separate ranges for
23 /// each register file.
24 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
25 pub struct SSAValue {
26 packed: NonZeroU32,
27 }
28
29 impl SSAValue {
30 /// Returns an SSA value with the given register file and index
31 fn new(file: RegFile, idx: u32) -> SSAValue {
32 assert!(
33 idx > 0
34 && idx < (1 << 29) - u32::try_from(SSARef::LARGE_SIZE).unwrap()
35 );
36 let mut packed = idx;
37 assert!(u8::from(file) < 8);
38 packed |= u32::from(u8::from(file)) << 29;
39 SSAValue {
40 packed: packed.try_into().unwrap(),
41 }
42 }
43
44 /// Returns the index of this SSA value
45 pub fn idx(&self) -> u32 {
46 self.packed.get() & 0x1fffffff
47 }
48 }
49
50 impl HasRegFile for SSAValue {
51 /// Returns the register file of this SSA value
52 fn file(&self) -> RegFile {
53 RegFile::try_from(self.packed.get() >> 29).unwrap()
54 }
55 }
56
57 impl IntoBitIndex for SSAValue {
58 fn into_bit_index(self) -> usize {
59 // Indices are guaranteed unique by the allocator
60 self.idx().try_into().unwrap()
61 }
62 }
63
64 impl fmt::Display for SSAValue {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 write!(f, "%{}{}", self.file().fmt_prefix(), self.idx())
67 }
68 }
69
70 impl fmt::Debug for SSAValue {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 fmt::Display::fmt(self, f)
73 }
74 }
75
76 #[derive(Clone, Eq, Hash, PartialEq)]
77 struct SSAValueArray<const SIZE: usize> {
78 v: [SSAValue; SIZE],
79 }
80
81 impl<const SIZE: usize> SSAValueArray<SIZE> {
82 /// Returns a new SSA reference.
83 ///
84 /// # Panics
85 ///
86 /// This method will panic if the number of `SSAValue`s in the slice is
87 /// greater than `SIZE`.
88 #[inline]
89 fn new(comps: &[SSAValue]) -> Self {
90 assert!(comps.len() > 0 && comps.len() <= SIZE);
91 let mut r = Self {
92 v: [SSAValue {
93 packed: NonZeroU32::MAX,
94 }; SIZE],
95 };
96
97 r.v[..comps.len()].copy_from_slice(comps);
98
99 if comps.len() < SIZE {
100 r.v[SIZE - 1].packed =
101 (comps.len() as u32).wrapping_neg().try_into().unwrap();
102 }
103 r
104 }
105
106 /// Returns the number of components in this SSA reference.
107 fn comps(&self) -> u8 {
108 let size: u8 = SIZE.try_into().unwrap();
109 if self.v[SIZE - 1].packed.get() >= u32::MAX - (u32::from(size) - 1) {
110 self.v[SIZE - 1].packed.get().wrapping_neg() as u8
111 } else {
112 size
113 }
114 }
115 }
116
117 impl<const SIZE: usize> Deref for SSAValueArray<SIZE> {
118 type Target = [SSAValue];
119
120 fn deref(&self) -> &[SSAValue] {
121 let comps = usize::from(self.comps());
122 &self.v[..comps]
123 }
124 }
125
126 impl<const SIZE: usize> DerefMut for SSAValueArray<SIZE> {
127 fn deref_mut(&mut self) -> &mut [SSAValue] {
128 let comps = usize::from(self.comps());
129 &mut self.v[..comps]
130 }
131 }
132
133 #[derive(Clone, Eq, Hash, PartialEq)]
134 enum SSARefInner {
135 Small(SSAValueArray<{ SSARef::SMALL_SIZE }>),
136 Large(Box<SSAValueArray<{ SSARef::LARGE_SIZE }>>),
137 }
138
139 /// A reference to one or more SSA values
140 ///
141 /// Because each SSA value represents a single 1 or 32-bit scalar, we need a way
142 /// to reference multiple SSA values for instructions which read or write
143 /// multiple registers in the same source. When the register allocator runs,
144 /// all the SSA values in a given SSA ref will be placed in consecutive
145 /// registers, with the base register aligned to the number of values, aligned
146 /// to the next power of two.
147 ///
148 /// An SSA reference can reference between 1 and 16 SSA values. It dereferences
149 /// to a slice for easy access to individual SSA values. The structure is
150 /// designed so that is always 16B, regardless of how many SSA values are
151 /// referenced so it's easy and fairly cheap to clone and embed in other
152 /// structures.
153 #[derive(Clone, Eq, Hash, PartialEq)]
154 pub struct SSARef {
155 v: SSARefInner,
156 }
157
158 #[cfg(target_arch = "x86_64")]
159 const _: () = {
160 debug_assert!(size_of::<SSARef>() == 16);
161 };
162
163 impl SSARef {
164 const SMALL_SIZE: usize = 4;
165 const LARGE_SIZE: usize = 16;
166
167 /// Returns a new SSA reference.
168 ///
169 /// # Panics
170 ///
171 /// This method will panic if the number of SSA values in the slice do not
172 /// fit in an SSARef.
173 #[inline]
174 pub fn new(comps: &[SSAValue]) -> SSARef {
175 SSARef {
176 v: if comps.len() > Self::SMALL_SIZE {
177 Self::cold();
178 SSARefInner::Large(Box::new(SSAValueArray::new(comps)))
179 } else {
180 SSARefInner::Small(SSAValueArray::new(comps))
181 },
182 }
183 }
184
185 /// Constructs an SSA reference from an iterator of SSA values.
186 ///
187 /// # Panics
188 ///
189 /// This method will panic if the number of SSA values in the slice do not
190 /// fit in an SSARef.
191 fn from_iter(mut it: impl ExactSizeIterator<Item = SSAValue>) -> Self {
192 let len = it.len();
193 assert!(len > 0 && len <= Self::LARGE_SIZE);
194 let v: [SSAValue; Self::LARGE_SIZE] = array::from_fn(|_| {
195 it.next().unwrap_or(SSAValue {
196 packed: NonZeroU32::MAX,
197 })
198 });
199 Self::new(&v[..len])
200 }
201
202 /// Returns the number of components in this SSA reference.
203 pub fn comps(&self) -> u8 {
204 match &self.v {
205 SSARefInner::Small(x) => x.comps(),
206 SSARefInner::Large(x) => {
207 Self::cold();
208 x.comps()
209 }
210 }
211 }
212
213 #[cold]
214 #[inline]
215 fn cold() {}
216 }
217
218 impl Deref for SSARef {
219 type Target = [SSAValue];
220
221 fn deref(&self) -> &[SSAValue] {
222 match &self.v {
223 SSARefInner::Small(x) => x.deref(),
224 SSARefInner::Large(x) => {
225 Self::cold();
226 x.deref()
227 }
228 }
229 }
230 }
231
232 impl DerefMut for SSARef {
233 fn deref_mut(&mut self) -> &mut [SSAValue] {
234 match &mut self.v {
235 SSARefInner::Small(x) => x.deref_mut(),
236 SSARefInner::Large(x) => {
237 Self::cold();
238 x.deref_mut()
239 }
240 }
241 }
242 }
243
244 impl TryFrom<&[SSAValue]> for SSARef {
245 type Error = &'static str;
246
247 fn try_from(comps: &[SSAValue]) -> Result<Self, Self::Error> {
248 if comps.len() == 0 {
249 Err("Empty vector")
250 } else if comps.len() > Self::LARGE_SIZE {
251 Err("Too many vector components")
252 } else {
253 Ok(SSARef::new(comps))
254 }
255 }
256 }
257
258 impl TryFrom<Vec<SSAValue>> for SSARef {
259 type Error = &'static str;
260
261 fn try_from(comps: Vec<SSAValue>) -> Result<Self, Self::Error> {
262 SSARef::try_from(&comps[..])
263 }
264 }
265
266 macro_rules! impl_ssa_ref_from_arr {
267 ($n: expr) => {
268 impl From<[SSAValue; $n]> for SSARef {
269 fn from(comps: [SSAValue; $n]) -> Self {
270 SSARef::new(&comps[..])
271 }
272 }
273 };
274 }
275 impl_ssa_ref_from_arr!(1);
276 impl_ssa_ref_from_arr!(2);
277 impl_ssa_ref_from_arr!(3);
278 impl_ssa_ref_from_arr!(4);
279
280 impl From<SSAValue> for SSARef {
281 fn from(val: SSAValue) -> Self {
282 [val].into()
283 }
284 }
285
286 impl fmt::Display for SSARef {
287 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288 if self.comps() == 1 {
289 write!(f, "{}", self[0])
290 } else {
291 write!(f, "{{")?;
292 for (i, v) in self.iter().enumerate() {
293 if i != 0 {
294 write!(f, " ")?;
295 }
296 write!(f, "{}", v)?;
297 }
298 write!(f, "}}")
299 }
300 }
301 }
302
303 impl HasRegFile for SSARef {
304 fn file(&self) -> RegFile {
305 (&self[..]).file()
306 }
307 }
308
309 #[test]
310 fn test_ssa_ref_round_trip() {
311 for len in 1..16 {
312 let vec: Vec<_> = (0..len)
313 .map(|i| SSAValue::new(RegFile::GPR, 1337 ^ i ^ len))
314 .collect();
315
316 let ssa_ref = SSARef::new(&vec);
317 assert_eq!(ssa_ref[..], vec[..]);
318 }
319 }
320
321 pub struct SSAValueAllocator {
322 count: u32,
323 }
324
325 /// An allocator for SSA values.
326 ///
327 /// This is the only valid way to create SSAValues. At most one SSA value
328 /// allocator may exist per shader to ensure the invariant that SSA value
329 /// indices are unique.
330 impl SSAValueAllocator {
331 /// Creates a new SSA value allocator.
332 pub fn new() -> SSAValueAllocator {
333 SSAValueAllocator { count: 0 }
334 }
335
336 #[allow(dead_code)]
337 pub fn max_idx(&self) -> u32 {
338 self.count
339 }
340
341 /// Allocates an SSA value.
342 pub fn alloc(&mut self, file: RegFile) -> SSAValue {
343 self.count += 1;
344 SSAValue::new(file, self.count)
345 }
346
347 /// Allocates multiple SSA values and returns them as an SSA reference.
348 pub fn alloc_vec(&mut self, file: RegFile, comps: u8) -> SSARef {
349 SSARef::from_iter((0..comps).map(|_| self.alloc(file)))
350 }
351 }
352
353 #[cfg(test)]
354 mod tests {
355 use super::*;
356
357 #[test]
358 fn test_ssa_value_print() {
359 let ssa = SSAValue::new(RegFile::UPred, 42);
360 assert_eq!(format!("{}", ssa), "%up42");
361 assert_eq!(format!("{:?}", ssa), "%up42");
362 }
363 }