Debian Codegraph @

src/nouveau/compiler/nak/ir.rs

raw
1 // Copyright © 2022 Collabora, Ltd.
2 // SPDX-License-Identifier: MIT
3
4 extern crate bitview;
5 extern crate nak_ir_proc;
6
7 use bitview::{BitMutView, BitMutViewable, BitView, BitViewable, SetField};
8 use nak_bindings::*;
9
10 pub use crate::builder::{Builder, InstrBuilder, SSABuilder, SSAInstrBuilder};
11 use crate::legalize::LegalizeBuilder;
12 use crate::sm20::ShaderModel20;
13 use crate::sm32::ShaderModel32;
14 use crate::sm50::ShaderModel50;
15 use crate::sm70::ShaderModel70;
16 use crate::sph::{OutputTopology, PixelImap};
17 pub use crate::ssa_value::*;
18 use compiler::as_slice::*;
19 use compiler::cfg::CFG;
20 use compiler::dataflow::ForwardDataflow;
21 use compiler::smallvec::SmallVec;
22 use nak_ir_proc::*;
23 use std::cmp::{max, min};
24 use std::fmt;
25 use std::fmt::Write;
26 use std::iter::Zip;
27 use std::ops::{BitAnd, BitOr, Deref, DerefMut, Index, IndexMut, Not, Range};
28 use std::slice;
29
30 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
31 pub struct Label {
32 idx: u32,
33 }
34
35 impl fmt::Display for Label {
36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 write!(f, "L{}", self.idx)
38 }
39 }
40
41 pub struct LabelAllocator {
42 count: u32,
43 }
44
45 impl LabelAllocator {
46 pub fn new() -> LabelAllocator {
47 LabelAllocator { count: 0 }
48 }
49
50 pub fn alloc(&mut self) -> Label {
51 let idx = self.count;
52 self.count += 1;
53 Label { idx: idx }
54 }
55 }
56
57 /// Represents a register file
58 #[repr(u8)]
59 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
60 pub enum RegFile {
61 /// The general-purpose register file
62 ///
63 /// General-purpose registers are 32 bits per SIMT channel.
64 GPR = 0,
65
66 /// The general-purpose uniform register file
67 ///
68 /// General-purpose uniform registers are 32 bits each and uniform across a
69 /// wave.
70 UGPR = 1,
71
72 /// The predicate reigster file
73 ///
74 /// Predicate registers are 1 bit per SIMT channel.
75 Pred = 2,
76
77 /// The uniform predicate reigster file
78 ///
79 /// Uniform predicate registers are 1 bit and uniform across a wave.
80 UPred = 3,
81
82 /// The carry flag register file
83 ///
84 /// Only one carry flag register exists in hardware, but representing it as
85 /// a reg file simplifies dependency tracking.
86 ///
87 /// This is used only on SM50.
88 Carry = 4,
89
90 /// The barrier register file
91 ///
92 /// This is a lane mask used for wave re-convergence instructions.
93 Bar = 5,
94
95 /// The memory register file
96 ///
97 /// This is a virtual register file for things which will get spilled to
98 /// local memory. Each memory location is 32 bits per SIMT channel.
99 Mem = 6,
100 }
101
102 const NUM_REG_FILES: usize = 7;
103
104 impl RegFile {
105 /// Returns true if the register file is uniform across a wave.
106 pub fn is_uniform(&self) -> bool {
107 match self {
108 RegFile::GPR
109 | RegFile::Pred
110 | RegFile::Carry
111 | RegFile::Bar
112 | RegFile::Mem => false,
113 RegFile::UGPR | RegFile::UPred => true,
114 }
115 }
116
117 /// Returns the uniform form of this register file, if any. For `GPR` and
118 /// `UGPR, this returns `UGPR` and for `Pred` and `UPred`, this returns
119 /// `UPred`.
120 pub fn to_uniform(self) -> Option<RegFile> {
121 match self {
122 RegFile::GPR | RegFile::UGPR => Some(RegFile::UGPR),
123 RegFile::Pred | RegFile::UPred => Some(RegFile::UPred),
124 RegFile::Carry | RegFile::Bar | RegFile::Mem => None,
125 }
126 }
127
128 /// Returns warp-wide version of this register file.
129 pub fn to_warp(self) -> RegFile {
130 match self {
131 RegFile::GPR | RegFile::UGPR => RegFile::GPR,
132 RegFile::Pred | RegFile::UPred => RegFile::Pred,
133 RegFile::Carry | RegFile::Bar | RegFile::Mem => self,
134 }
135 }
136
137 /// Returns true if the register file is GPR or UGPR.
138 pub fn is_gpr(&self) -> bool {
139 match self {
140 RegFile::GPR | RegFile::UGPR => true,
141 RegFile::Pred
142 | RegFile::UPred
143 | RegFile::Carry
144 | RegFile::Bar
145 | RegFile::Mem => false,
146 }
147 }
148
149 /// Returns true if the register file is a predicate register file.
150 pub fn is_predicate(&self) -> bool {
151 match self {
152 RegFile::GPR
153 | RegFile::UGPR
154 | RegFile::Carry
155 | RegFile::Bar
156 | RegFile::Mem => false,
157 RegFile::Pred | RegFile::UPred => true,
158 }
159 }
160
161 pub fn fmt_prefix(&self) -> &'static str {
162 match self {
163 RegFile::GPR => "r",
164 RegFile::UGPR => "ur",
165 RegFile::Pred => "p",
166 RegFile::UPred => "up",
167 RegFile::Carry => "c",
168 RegFile::Bar => "b",
169 RegFile::Mem => "m",
170 }
171 }
172 }
173
174 impl fmt::Display for RegFile {
175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176 match self {
177 RegFile::GPR => write!(f, "GPR"),
178 RegFile::UGPR => write!(f, "UGPR"),
179 RegFile::Pred => write!(f, "Pred"),
180 RegFile::UPred => write!(f, "UPred"),
181 RegFile::Carry => write!(f, "Carry"),
182 RegFile::Bar => write!(f, "Bar"),
183 RegFile::Mem => write!(f, "Mem"),
184 }
185 }
186 }
187
188 impl From<RegFile> for u8 {
189 fn from(value: RegFile) -> u8 {
190 value as u8
191 }
192 }
193
194 impl TryFrom<u32> for RegFile {
195 type Error = &'static str;
196
197 fn try_from(value: u32) -> Result<Self, Self::Error> {
198 match value {
199 0 => Ok(RegFile::GPR),
200 1 => Ok(RegFile::UGPR),
201 2 => Ok(RegFile::Pred),
202 3 => Ok(RegFile::UPred),
203 4 => Ok(RegFile::Carry),
204 5 => Ok(RegFile::Bar),
205 6 => Ok(RegFile::Mem),
206 _ => Err("Invalid register file number"),
207 }
208 }
209 }
210
211 impl TryFrom<u16> for RegFile {
212 type Error = &'static str;
213
214 fn try_from(value: u16) -> Result<Self, Self::Error> {
215 RegFile::try_from(u32::from(value))
216 }
217 }
218
219 impl TryFrom<u8> for RegFile {
220 type Error = &'static str;
221
222 fn try_from(value: u8) -> Result<Self, Self::Error> {
223 RegFile::try_from(u32::from(value))
224 }
225 }
226
227 /// A trait for things which have an associated register file
228 pub trait HasRegFile {
229 fn file(&self) -> RegFile;
230
231 fn is_uniform(&self) -> bool {
232 self.file().is_uniform()
233 }
234
235 fn is_gpr(&self) -> bool {
236 self.file().is_gpr()
237 }
238
239 fn is_predicate(&self) -> bool {
240 self.file().is_predicate()
241 }
242 }
243
244 impl HasRegFile for &[SSAValue] {
245 fn file(&self) -> RegFile {
246 let comps = self.len();
247 let file = self[0].file();
248 for i in 1..comps {
249 if self[i].file() != file {
250 panic!("Illegal mix of RegFiles")
251 }
252 }
253 file
254 }
255 }
256
257 #[derive(Clone)]
258 pub struct RegFileSet {
259 bits: u8,
260 }
261
262 impl RegFileSet {
263 pub fn new() -> RegFileSet {
264 RegFileSet { bits: 0 }
265 }
266
267 pub fn len(&self) -> usize {
268 self.bits.count_ones() as usize
269 }
270
271 pub fn contains(&self, file: RegFile) -> bool {
272 self.bits & (1 << (file as u8)) != 0
273 }
274
275 pub fn insert(&mut self, file: RegFile) -> bool {
276 let has_file = self.contains(file);
277 self.bits |= 1 << (file as u8);
278 !has_file
279 }
280
281 pub fn is_empty(&self) -> bool {
282 self.bits == 0
283 }
284
285 #[allow(dead_code)]
286 pub fn iter(&self) -> RegFileSet {
287 self.clone()
288 }
289
290 pub fn remove(&mut self, file: RegFile) -> bool {
291 let has_file = self.contains(file);
292 self.bits &= !(1 << (file as u8));
293 has_file
294 }
295 }
296
297 impl FromIterator<RegFile> for RegFileSet {
298 fn from_iter<T: IntoIterator<Item = RegFile>>(iter: T) -> Self {
299 let mut set = RegFileSet::new();
300 for file in iter {
301 set.insert(file);
302 }
303 set
304 }
305 }
306
307 impl Iterator for RegFileSet {
308 type Item = RegFile;
309
310 fn next(&mut self) -> Option<RegFile> {
311 if self.is_empty() {
312 None
313 } else {
314 let file = self.bits.trailing_zeros().try_into().unwrap();
315 self.remove(file);
316 Some(file)
317 }
318 }
319
320 fn size_hint(&self) -> (usize, Option<usize>) {
321 let len = self.len();
322 (len, Some(len))
323 }
324 }
325
326 /// A container mapping register files to items.
327 ///
328 /// This is used by several passes which need to replicate a data structure
329 /// per-register-file.
330 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
331 pub struct PerRegFile<T> {
332 per_file: [T; NUM_REG_FILES],
333 }
334
335 impl<T> PerRegFile<T> {
336 /// Creates a new per-register-file container.
337 ///
338 /// Because this container assumes it always has an item for each register
339 /// file, it takes a callback which maps register files to initial values
340 /// to avoid adding a bunch of `Option<T>` or requiring `T` to implement
341 /// `Default`. If `T` does implement `Default`, then so does
342 /// `PerRefFile<T>`.
343 pub fn new_with<F: Fn(RegFile) -> T>(f: F) -> Self {
344 PerRegFile {
345 per_file: [
346 f(RegFile::GPR),
347 f(RegFile::UGPR),
348 f(RegFile::Pred),
349 f(RegFile::UPred),
350 f(RegFile::Carry),
351 f(RegFile::Bar),
352 f(RegFile::Mem),
353 ],
354 }
355 }
356
357 /// Iterates over the values in this container.
358 pub fn values(&self) -> slice::Iter<'_, T> {
359 self.per_file.iter()
360 }
361
362 /// Iterates over the mutable values in this container.
363 pub fn values_mut(&mut self) -> slice::IterMut<'_, T> {
364 self.per_file.iter_mut()
365 }
366 }
367
368 impl<T: Default> Default for PerRegFile<T> {
369 fn default() -> Self {
370 PerRegFile {
371 per_file: Default::default(),
372 }
373 }
374 }
375
376 impl<T> Index<RegFile> for PerRegFile<T> {
377 type Output = T;
378
379 fn index(&self, idx: RegFile) -> &T {
380 &self.per_file[idx as u8 as usize]
381 }
382 }
383
384 impl<T> IndexMut<RegFile> for PerRegFile<T> {
385 fn index_mut(&mut self, idx: RegFile) -> &mut T {
386 &mut self.per_file[idx as u8 as usize]
387 }
388 }
389
390 /// A reference to a contiguous range of registers in a particular register
391 /// file.
392 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
393 pub struct RegRef {
394 packed: u32,
395 }
396
397 impl RegRef {
398 pub const MAX_IDX: u32 = (1 << 26) - 1;
399
400 /// Creates a new register reference.
401 ///
402 /// # Panics
403 ///
404 /// This method panics if `base_idx > RegRef::MAX_IDX` or if `comps > 8`.
405 pub fn new(file: RegFile, base_idx: u32, comps: u8) -> RegRef {
406 assert!(base_idx <= Self::MAX_IDX);
407 let mut packed = base_idx;
408 assert!(comps > 0 && comps <= 8);
409 packed |= u32::from(comps - 1) << 26;
410 assert!(u8::from(file) < 8);
411 packed |= u32::from(u8::from(file)) << 29;
412 RegRef { packed: packed }
413 }
414
415 /// Returns the index of the first register referenced.
416 pub fn base_idx(&self) -> u32 {
417 self.packed & 0x03ffffff
418 }
419
420 /// Returns the range of register indices referenced.
421 pub fn idx_range(&self) -> Range<u32> {
422 let start = self.base_idx();
423 let end = start + u32::from(self.comps());
424 start..end
425 }
426
427 /// Returns the number of registers referenced.
428 pub fn comps(&self) -> u8 {
429 (((self.packed >> 26) & 0x7) + 1).try_into().unwrap()
430 }
431
432 /// Returns a reference to the single register at `base_idx() + c`.
433 pub fn comp(&self, c: u8) -> RegRef {
434 assert!(c < self.comps());
435 RegRef::new(self.file(), self.base_idx() + u32::from(c), 1)
436 }
437 }
438
439 impl HasRegFile for RegRef {
440 fn file(&self) -> RegFile {
441 ((self.packed >> 29) & 0x7).try_into().unwrap()
442 }
443 }
444
445 impl fmt::Display for RegRef {
446 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
447 write!(f, "{}{}", self.file().fmt_prefix(), self.base_idx())?;
448 if self.comps() > 1 {
449 write!(f, "..{}", self.idx_range().end)?;
450 }
451 Ok(())
452 }
453 }
454
455 #[derive(Clone)]
456 pub enum Dst {
457 None,
458 SSA(SSARef),
459 Reg(RegRef),
460 }
461
462 impl Dst {
463 pub fn is_none(&self) -> bool {
464 matches!(self, Dst::None)
465 }
466
467 pub fn as_reg(&self) -> Option<&RegRef> {
468 match self {
469 Dst::Reg(r) => Some(r),
470 _ => None,
471 }
472 }
473
474 pub fn as_ssa(&self) -> Option<&SSARef> {
475 match self {
476 Dst::SSA(r) => Some(r),
477 _ => None,
478 }
479 }
480
481 #[allow(dead_code)]
482 pub fn to_ssa(self) -> SSARef {
483 match self {
484 Dst::SSA(r) => r,
485 _ => panic!("Expected ssa"),
486 }
487 }
488
489 pub fn iter_ssa(&self) -> slice::Iter<'_, SSAValue> {
490 match self {
491 Dst::None | Dst::Reg(_) => &[],
492 Dst::SSA(ssa) => ssa.deref(),
493 }
494 .iter()
495 }
496
497 pub fn iter_ssa_mut(&mut self) -> slice::IterMut<'_, SSAValue> {
498 match self {
499 Dst::None | Dst::Reg(_) => &mut [],
500 Dst::SSA(ssa) => ssa.deref_mut(),
501 }
502 .iter_mut()
503 }
504
505 pub fn comps(&self) -> u8 {
506 match self {
507 Dst::None => 0,
508 Dst::SSA(ssa) => ssa.comps(),
509 Dst::Reg(reg) => reg.comps(),
510 }
511 }
512
513 pub fn file(&self) -> Option<RegFile> {
514 match self {
515 Dst::None => None,
516 Dst::SSA(ssa) => Some(ssa.file()),
517 Dst::Reg(reg) => Some(reg.file()),
518 }
519 }
520 }
521
522 impl From<RegRef> for Dst {
523 fn from(reg: RegRef) -> Dst {
524 Dst::Reg(reg)
525 }
526 }
527
528 impl<T: Into<SSARef>> From<T> for Dst {
529 fn from(ssa: T) -> Dst {
530 Dst::SSA(ssa.into())
531 }
532 }
533
534 impl From<Option<SSAValue>> for Dst {
535 fn from(ssa: Option<SSAValue>) -> Dst {
536 match ssa {
537 Some(ssa) => Dst::SSA(ssa.into()),
538 None => Dst::None,
539 }
540 }
541 }
542
543 impl fmt::Display for Dst {
544 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
545 match self {
546 Dst::None => write!(f, "null")?,
547 Dst::SSA(v) => v.fmt(f)?,
548 Dst::Reg(r) => r.fmt(f)?,
549 }
550 Ok(())
551 }
552 }
553
554 #[derive(Clone, Eq, Hash, PartialEq)]
555 pub enum CBuf {
556 Binding(u8),
557 BindlessSSA([SSAValue; 2]),
558 BindlessUGPR(RegRef),
559 }
560
561 impl fmt::Display for CBuf {
562 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
563 match self {
564 CBuf::Binding(idx) => write!(f, "c[{:#x}]", idx),
565 CBuf::BindlessSSA(v) => write!(f, "cx[{{{}, {}}}]", v[0], v[1]),
566 CBuf::BindlessUGPR(r) => write!(f, "cx[{}]", r),
567 }
568 }
569 }
570
571 #[derive(Clone, Eq, Hash, PartialEq)]
572 pub struct CBufRef {
573 pub buf: CBuf,
574 pub offset: u16,
575 }
576
577 impl CBufRef {
578 pub fn offset(self, offset: u16) -> CBufRef {
579 CBufRef {
580 buf: self.buf,
581 offset: self.offset + offset,
582 }
583 }
584 }
585
586 impl fmt::Display for CBufRef {
587 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
588 write!(f, "{}[{:#x}]", self.buf, self.offset)
589 }
590 }
591
592 #[derive(Clone, Eq, Hash, PartialEq)]
593 pub enum SrcRef {
594 Zero,
595 True,
596 False,
597 Imm32(u32),
598 CBuf(CBufRef),
599 SSA(SSARef),
600 Reg(RegRef),
601 }
602
603 impl SrcRef {
604 pub fn is_alu(&self) -> bool {
605 match self {
606 SrcRef::Zero | SrcRef::Imm32(_) | SrcRef::CBuf(_) => true,
607 SrcRef::SSA(ssa) => ssa.is_gpr(),
608 SrcRef::Reg(reg) => reg.is_gpr(),
609 SrcRef::True | SrcRef::False => false,
610 }
611 }
612
613 pub fn is_bindless_cbuf(&self) -> bool {
614 match self {
615 SrcRef::CBuf(cbuf) => {
616 matches!(cbuf.buf, CBuf::BindlessSSA(_) | CBuf::BindlessUGPR(_))
617 }
618 _ => false,
619 }
620 }
621
622 pub fn is_predicate(&self) -> bool {
623 match self {
624 SrcRef::Zero | SrcRef::Imm32(_) | SrcRef::CBuf(_) => false,
625 SrcRef::True | SrcRef::False => true,
626 SrcRef::SSA(ssa) => ssa.is_predicate(),
627 SrcRef::Reg(reg) => reg.is_predicate(),
628 }
629 }
630
631 pub fn is_carry(&self) -> bool {
632 match self {
633 SrcRef::SSA(ssa) => ssa.file() == RegFile::Carry,
634 SrcRef::Reg(reg) => reg.file() == RegFile::Carry,
635 _ => false,
636 }
637 }
638
639 pub fn is_barrier(&self) -> bool {
640 match self {
641 SrcRef::SSA(ssa) => ssa.file() == RegFile::Bar,
642 SrcRef::Reg(reg) => reg.file() == RegFile::Bar,
643 _ => false,
644 }
645 }
646
647 pub fn as_reg(&self) -> Option<&RegRef> {
648 match self {
649 SrcRef::Reg(r) => Some(r),
650 _ => None,
651 }
652 }
653
654 pub fn as_ssa(&self) -> Option<&SSARef> {
655 match self {
656 SrcRef::SSA(r) => Some(r),
657 _ => None,
658 }
659 }
660
661 pub fn to_ssa(self) -> SSARef {
662 match self {
663 SrcRef::SSA(r) => r,
664 _ => panic!(),
665 }
666 }
667
668 pub fn as_u32(&self) -> Option<u32> {
669 match self {
670 SrcRef::Zero => Some(0),
671 SrcRef::Imm32(u) => Some(*u),
672 SrcRef::CBuf(_) | SrcRef::SSA(_) | SrcRef::Reg(_) => None,
673 _ => panic!("Invalid integer source"),
674 }
675 }
676
677 pub fn get_reg(&self) -> Option<&RegRef> {
678 match self {
679 SrcRef::Zero
680 | SrcRef::True
681 | SrcRef::False
682 | SrcRef::Imm32(_)
683 | SrcRef::SSA(_) => None,
684 SrcRef::CBuf(cb) => match &cb.buf {
685 CBuf::Binding(_) | CBuf::BindlessSSA(_) => None,
686 CBuf::BindlessUGPR(reg) => Some(reg),
687 },
688 SrcRef::Reg(reg) => Some(reg),
689 }
690 }
691
692 pub fn iter_ssa(&self) -> slice::Iter<'_, SSAValue> {
693 match self {
694 SrcRef::Zero
695 | SrcRef::True
696 | SrcRef::False
697 | SrcRef::Imm32(_)
698 | SrcRef::Reg(_) => &[],
699 SrcRef::CBuf(cb) => match &cb.buf {
700 CBuf::Binding(_) | CBuf::BindlessUGPR(_) => &[],
701 CBuf::BindlessSSA(ssa) => &ssa[..],
702 },
703 SrcRef::SSA(ssa) => ssa.deref(),
704 }
705 .iter()
706 }
707
708 pub fn iter_ssa_mut(&mut self) -> slice::IterMut<'_, SSAValue> {
709 match self {
710 SrcRef::Zero
711 | SrcRef::True
712 | SrcRef::False
713 | SrcRef::Imm32(_)
714 | SrcRef::Reg(_) => &mut [],
715 SrcRef::CBuf(cb) => match &mut cb.buf {
716 CBuf::Binding(_) | CBuf::BindlessUGPR(_) => &mut [],
717 CBuf::BindlessSSA(ssa) => &mut ssa[..],
718 },
719 SrcRef::SSA(ssa) => ssa.deref_mut(),
720 }
721 .iter_mut()
722 }
723 }
724
725 impl From<bool> for SrcRef {
726 fn from(b: bool) -> SrcRef {
727 if b {
728 SrcRef::True
729 } else {
730 SrcRef::False
731 }
732 }
733 }
734
735 impl From<u32> for SrcRef {
736 fn from(u: u32) -> SrcRef {
737 if u == 0 {
738 SrcRef::Zero
739 } else {
740 SrcRef::Imm32(u)
741 }
742 }
743 }
744
745 impl From<f32> for SrcRef {
746 fn from(f: f32) -> SrcRef {
747 f.to_bits().into()
748 }
749 }
750
751 impl From<PrmtSel> for SrcRef {
752 fn from(sel: PrmtSel) -> SrcRef {
753 u32::from(sel.0).into()
754 }
755 }
756
757 impl From<CBufRef> for SrcRef {
758 fn from(cb: CBufRef) -> SrcRef {
759 SrcRef::CBuf(cb)
760 }
761 }
762
763 impl From<RegRef> for SrcRef {
764 fn from(reg: RegRef) -> SrcRef {
765 SrcRef::Reg(reg)
766 }
767 }
768
769 impl<T: Into<SSARef>> From<T> for SrcRef {
770 fn from(ssa: T) -> SrcRef {
771 SrcRef::SSA(ssa.into())
772 }
773 }
774
775 impl From<PredRef> for SrcRef {
776 fn from(value: PredRef) -> Self {
777 match value {
778 PredRef::None => SrcRef::True,
779 PredRef::Reg(reg) => SrcRef::Reg(reg),
780 PredRef::SSA(ssa) => SrcRef::SSA(ssa.into()),
781 }
782 }
783 }
784
785 impl fmt::Display for SrcRef {
786 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
787 match self {
788 SrcRef::Zero => write!(f, "rZ"),
789 SrcRef::True => write!(f, "pT"),
790 SrcRef::False => write!(f, "pF"),
791 SrcRef::Imm32(u) => write!(f, "{:#x}", u),
792 SrcRef::CBuf(c) => c.fmt(f),
793 SrcRef::SSA(v) => v.fmt(f),
794 SrcRef::Reg(r) => r.fmt(f),
795 }
796 }
797 }
798
799 #[derive(Clone, Copy, PartialEq)]
800 pub enum SrcMod {
801 None,
802 FAbs,
803 FNeg,
804 FNegAbs,
805 INeg,
806 BNot,
807 }
808
809 impl SrcMod {
810 pub fn is_none(&self) -> bool {
811 matches!(self, SrcMod::None)
812 }
813
814 pub fn has_fabs(&self) -> bool {
815 match self {
816 SrcMod::None | SrcMod::FNeg => false,
817 SrcMod::FAbs | SrcMod::FNegAbs => true,
818 _ => panic!("Not a float modifier"),
819 }
820 }
821
822 pub fn has_fneg(&self) -> bool {
823 match self {
824 SrcMod::None | SrcMod::FAbs => false,
825 SrcMod::FNeg | SrcMod::FNegAbs => true,
826 _ => panic!("Not a float modifier"),
827 }
828 }
829
830 pub fn is_ineg(&self) -> bool {
831 match self {
832 SrcMod::None => false,
833 SrcMod::INeg => true,
834 _ => panic!("Not an integer modifier"),
835 }
836 }
837
838 pub fn is_bnot(&self) -> bool {
839 match self {
840 SrcMod::None => false,
841 SrcMod::BNot => true,
842 _ => panic!("Not a bitwise modifier"),
843 }
844 }
845
846 pub fn fabs(self) -> SrcMod {
847 match self {
848 SrcMod::None | SrcMod::FAbs | SrcMod::FNeg | SrcMod::FNegAbs => {
849 SrcMod::FAbs
850 }
851 _ => panic!("Not a float source modifier"),
852 }
853 }
854
855 pub fn fneg(self) -> SrcMod {
856 match self {
857 SrcMod::None => SrcMod::FNeg,
858 SrcMod::FAbs => SrcMod::FNegAbs,
859 SrcMod::FNeg => SrcMod::None,
860 SrcMod::FNegAbs => SrcMod::FAbs,
861 _ => panic!("Not a float source modifier"),
862 }
863 }
864
865 pub fn ineg(self) -> SrcMod {
866 match self {
867 SrcMod::None => SrcMod::INeg,
868 SrcMod::INeg => SrcMod::None,
869 _ => panic!("Not an integer source modifier"),
870 }
871 }
872
873 pub fn bnot(self) -> SrcMod {
874 match self {
875 SrcMod::None => SrcMod::BNot,
876 SrcMod::BNot => SrcMod::None,
877 _ => panic!("Not a boolean source modifier"),
878 }
879 }
880
881 pub fn modify(self, other: SrcMod) -> SrcMod {
882 match other {
883 SrcMod::None => self,
884 SrcMod::FAbs => self.fabs(),
885 SrcMod::FNeg => self.fneg(),
886 SrcMod::FNegAbs => self.fabs().fneg(),
887 SrcMod::INeg => self.ineg(),
888 SrcMod::BNot => self.bnot(),
889 }
890 }
891 }
892
893 #[derive(Clone, Copy, PartialEq)]
894 pub enum SrcSwizzle {
895 None,
896 Xx,
897 Yy,
898 }
899
900 impl SrcSwizzle {
901 pub fn is_none(&self) -> bool {
902 matches!(self, SrcSwizzle::None)
903 }
904 }
905
906 impl fmt::Display for SrcSwizzle {
907 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
908 match self {
909 SrcSwizzle::None => Ok(()),
910 SrcSwizzle::Xx => write!(f, ".xx"),
911 SrcSwizzle::Yy => write!(f, ".yy"),
912 }
913 }
914 }
915
916 #[derive(Clone, PartialEq)]
917 pub struct Src {
918 pub src_ref: SrcRef,
919 pub src_mod: SrcMod,
920 pub src_swizzle: SrcSwizzle,
921 }
922
923 impl Src {
924 pub const ZERO: Src = Src {
925 src_ref: SrcRef::Zero,
926 src_mod: SrcMod::None,
927 src_swizzle: SrcSwizzle::None,
928 };
929
930 pub fn new_imm_u32(u: u32) -> Src {
931 u.into()
932 }
933
934 pub fn new_imm_bool(b: bool) -> Src {
935 b.into()
936 }
937
938 pub fn is_unmodified(&self) -> bool {
939 self.src_mod.is_none() && self.src_swizzle.is_none()
940 }
941
942 pub fn fabs(self) -> Src {
943 Src {
944 src_ref: self.src_ref,
945 src_mod: self.src_mod.fabs(),
946 src_swizzle: self.src_swizzle,
947 }
948 }
949
950 pub fn fneg(self) -> Src {
951 Src {
952 src_ref: self.src_ref,
953 src_mod: self.src_mod.fneg(),
954 src_swizzle: self.src_swizzle,
955 }
956 }
957
958 pub fn ineg(self) -> Src {
959 Src {
960 src_ref: self.src_ref,
961 src_mod: self.src_mod.ineg(),
962 src_swizzle: self.src_swizzle,
963 }
964 }
965
966 pub fn bnot(self) -> Src {
967 Src {
968 src_ref: self.src_ref,
969 src_mod: self.src_mod.bnot(),
970 src_swizzle: self.src_swizzle,
971 }
972 }
973
974 pub fn modify(mut self, src_mod: SrcMod) -> Src {
975 self.src_mod = self.src_mod.modify(src_mod);
976 self
977 }
978
979 pub fn as_u32(&self, src_type: SrcType) -> Option<u32> {
980 let u = match &self.src_ref {
981 SrcRef::Zero => 0,
982 SrcRef::Imm32(u) => *u,
983 _ => return None,
984 };
985
986 if self.is_unmodified() {
987 return Some(u);
988 }
989
990 assert!(src_type == SrcType::F16v2 || self.src_swizzle.is_none());
991
992 // INeg affects more than just the 32 bits of input data so it can't be
993 // trivially folded. In fact, -imm may not be representable as a 32-bit
994 // immediate at all.
995 if src_type == SrcType::I32 {
996 return None;
997 }
998
999 Some(match src_type {
1000 SrcType::F16 => {
1001 let low = u & 0xFFFF;
1002
1003 match self.src_mod {
1004 SrcMod::None => low,
1005 SrcMod::FAbs => low & !(1_u32 << 15),
1006 SrcMod::FNeg => low ^ (1_u32 << 15),
1007 SrcMod::FNegAbs => low | (1_u32 << 15),
1008 _ => panic!("Not a float source modifier"),
1009 }
1010 }
1011 SrcType::F16v2 => {
1012 let u = match self.src_swizzle {
1013 SrcSwizzle::None => u,
1014 SrcSwizzle::Xx => (u << 16) | (u & 0xffff),
1015 SrcSwizzle::Yy => (u & 0xffff0000) | (u >> 16),
1016 };
1017
1018 match self.src_mod {
1019 SrcMod::None => u,
1020 SrcMod::FAbs => u & 0x7FFF7FFF,
1021 SrcMod::FNeg => u ^ 0x80008000,
1022 SrcMod::FNegAbs => u | 0x80008000,
1023 _ => panic!("Not a float source modifier"),
1024 }
1025 }
1026 SrcType::F32 | SrcType::F64 => match self.src_mod {
1027 SrcMod::None => u,
1028 SrcMod::FAbs => u & !(1_u32 << 31),
1029 SrcMod::FNeg => u ^ (1_u32 << 31),
1030 SrcMod::FNegAbs => u | (1_u32 << 31),
1031 _ => panic!("Not a float source modifier"),
1032 },
1033 SrcType::I32 => match self.src_mod {
1034 SrcMod::None => u,
1035 SrcMod::INeg => -(u as i32) as u32,
1036 _ => panic!("Not an integer source modifier"),
1037 },
1038 SrcType::B32 => match self.src_mod {
1039 SrcMod::None => u,
1040 SrcMod::BNot => !u,
1041 _ => panic!("Not a bitwise source modifier"),
1042 },
1043 _ => {
1044 assert!(self.is_unmodified());
1045 u
1046 }
1047 })
1048 }
1049
1050 pub fn as_ssa(&self) -> Option<&SSARef> {
1051 if self.is_unmodified() {
1052 self.src_ref.as_ssa()
1053 } else {
1054 None
1055 }
1056 }
1057
1058 pub fn to_ssa(self) -> SSARef {
1059 if self.is_unmodified() {
1060 self.src_ref.to_ssa()
1061 } else {
1062 panic!("Did not expect src_mod");
1063 }
1064 }
1065
1066 pub fn as_bool(&self) -> Option<bool> {
1067 match &self.src_ref {
1068 SrcRef::True => Some(!self.src_mod.is_bnot()),
1069 SrcRef::False => Some(self.src_mod.is_bnot()),
1070 SrcRef::SSA(vec) => {
1071 assert!(vec.is_predicate() && vec.comps() == 1);
1072 None
1073 }
1074 SrcRef::Reg(reg) => {
1075 assert!(reg.is_predicate() && reg.comps() == 1);
1076 None
1077 }
1078 _ => panic!("Not a boolean source"),
1079 }
1080 }
1081
1082 pub fn as_imm_not_i20(&self) -> Option<u32> {
1083 match self.src_ref {
1084 SrcRef::Imm32(i) => {
1085 assert!(self.is_unmodified());
1086 let top = i & 0xfff80000;
1087 if top == 0 || top == 0xfff80000 {
1088 None
1089 } else {
1090 Some(i)
1091 }
1092 }
1093 _ => None,
1094 }
1095 }
1096
1097 pub fn as_imm_not_f20(&self) -> Option<u32> {
1098 match self.src_ref {
1099 SrcRef::Imm32(i) => {
1100 assert!(self.is_unmodified());
1101 if (i & 0xfff) == 0 {
1102 None
1103 } else {
1104 Some(i)
1105 }
1106 }
1107 _ => None,
1108 }
1109 }
1110
1111 pub fn iter_ssa(&self) -> slice::Iter<'_, SSAValue> {
1112 self.src_ref.iter_ssa()
1113 }
1114
1115 pub fn iter_ssa_mut(&mut self) -> slice::IterMut<'_, SSAValue> {
1116 self.src_ref.iter_ssa_mut()
1117 }
1118
1119 pub fn is_uniform(&self) -> bool {
1120 match &self.src_ref {
1121 SrcRef::Zero
1122 | SrcRef::True
1123 | SrcRef::False
1124 | SrcRef::Imm32(_)
1125 | SrcRef::CBuf(_) => true,
1126 SrcRef::SSA(ssa) => ssa.is_uniform(),
1127 SrcRef::Reg(reg) => reg.is_uniform(),
1128 }
1129 }
1130
1131 pub fn is_bindless_cbuf(&self) -> bool {
1132 self.src_ref.is_bindless_cbuf()
1133 }
1134
1135 pub fn is_upred_reg(&self) -> bool {
1136 match &self.src_ref {
1137 SrcRef::SSA(ssa) => ssa.file() == RegFile::UPred,
1138 SrcRef::Reg(reg) => reg.file() == RegFile::UPred,
1139 _ => false,
1140 }
1141 }
1142
1143 pub fn is_predicate(&self) -> bool {
1144 self.src_ref.is_predicate()
1145 }
1146
1147 pub fn is_zero(&self) -> bool {
1148 match self.src_ref {
1149 SrcRef::Zero | SrcRef::Imm32(0) => match self.src_mod {
1150 SrcMod::None | SrcMod::FAbs => true,
1151 SrcMod::FNeg | SrcMod::FNegAbs | SrcMod::BNot => false,
1152 // INeg affects more than just the 32 bits of input data so -0
1153 // may not be equivalent to 0.
1154 SrcMod::INeg => false,
1155 },
1156 _ => false,
1157 }
1158 }
1159
1160 pub fn is_nonzero(&self) -> bool {
1161 assert!(self.is_unmodified());
1162 matches!(self.src_ref, SrcRef::Imm32(x) if x != 0)
1163 }
1164
1165 pub fn is_true(&self) -> bool {
1166 self.as_bool() == Some(true)
1167 }
1168
1169 pub fn is_fneg_zero(&self, src_type: SrcType) -> bool {
1170 match self.as_u32(src_type) {
1171 Some(0x00008000) => src_type == SrcType::F16,
1172 Some(0x80000000) => {
1173 src_type == SrcType::F32 || src_type == SrcType::F64
1174 }
1175 Some(0x80008000) => src_type == SrcType::F16v2,
1176 _ => false,
1177 }
1178 }
1179
1180 #[allow(dead_code)]
1181 pub fn supports_type(&self, src_type: &SrcType) -> bool {
1182 match src_type {
1183 SrcType::SSA => {
1184 if !self.is_unmodified() {
1185 return false;
1186 }
1187
1188 matches!(self.src_ref, SrcRef::SSA(_) | SrcRef::Reg(_))
1189 }
1190 SrcType::GPR => {
1191 if !self.is_unmodified() {
1192 return false;
1193 }
1194
1195 matches!(
1196 self.src_ref,
1197 SrcRef::Zero | SrcRef::SSA(_) | SrcRef::Reg(_)
1198 )
1199 }
1200 SrcType::ALU => self.is_unmodified() && self.src_ref.is_alu(),
1201 SrcType::F16 | SrcType::F32 | SrcType::F64 | SrcType::F16v2 => {
1202 match self.src_mod {
1203 SrcMod::None
1204 | SrcMod::FAbs
1205 | SrcMod::FNeg
1206 | SrcMod::FNegAbs => (),
1207 _ => return false,
1208 }
1209
1210 self.src_ref.is_alu()
1211 }
1212 SrcType::I32 => {
1213 match self.src_mod {
1214 SrcMod::None | SrcMod::INeg => (),
1215 _ => return false,
1216 }
1217
1218 self.src_ref.is_alu()
1219 }
1220 SrcType::B32 => {
1221 match self.src_mod {
1222 SrcMod::None | SrcMod::BNot => (),
1223 _ => return false,
1224 }
1225
1226 self.src_ref.is_alu()
1227 }
1228 SrcType::Pred => {
1229 match self.src_mod {
1230 SrcMod::None | SrcMod::BNot => (),
1231 _ => return false,
1232 }
1233
1234 self.src_ref.is_predicate()
1235 }
1236 SrcType::Carry => self.is_unmodified() && self.src_ref.is_carry(),
1237 SrcType::Bar => self.is_unmodified() && self.src_ref.is_barrier(),
1238 }
1239 }
1240 }
1241
1242 impl<T: Into<SrcRef>> From<T> for Src {
1243 fn from(value: T) -> Src {
1244 Src {
1245 src_ref: value.into(),
1246 src_mod: SrcMod::None,
1247 src_swizzle: SrcSwizzle::None,
1248 }
1249 }
1250 }
1251
1252 impl From<Pred> for Src {
1253 fn from(value: Pred) -> Self {
1254 Src {
1255 src_ref: value.pred_ref.into(),
1256 src_mod: if value.pred_inv {
1257 SrcMod::BNot
1258 } else {
1259 SrcMod::None
1260 },
1261 src_swizzle: SrcSwizzle::None,
1262 }
1263 }
1264 }
1265
1266 impl fmt::Display for Src {
1267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1268 match self.src_mod {
1269 SrcMod::None => write!(f, "{}{}", self.src_ref, self.src_swizzle),
1270 SrcMod::FAbs => write!(f, "|{}{}|", self.src_ref, self.src_swizzle),
1271 SrcMod::FNeg => write!(f, "-{}{}", self.src_ref, self.src_swizzle),
1272 SrcMod::FNegAbs => {
1273 write!(f, "-|{}{}|", self.src_ref, self.src_swizzle)
1274 }
1275 SrcMod::INeg => write!(f, "-{}{}", self.src_ref, self.src_swizzle),
1276 SrcMod::BNot => write!(f, "!{}{}", self.src_ref, self.src_swizzle),
1277 }
1278 }
1279 }
1280
1281 #[repr(u8)]
1282 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1283 pub enum SrcType {
1284 SSA,
1285 GPR,
1286 ALU,
1287 F16,
1288 F16v2,
1289 F32,
1290 F64,
1291 I32,
1292 B32,
1293 Pred,
1294 Carry,
1295 Bar,
1296 }
1297
1298 impl SrcType {
1299 const DEFAULT: SrcType = SrcType::GPR;
1300 }
1301
1302 pub type SrcTypeList = AttrList<SrcType>;
1303
1304 pub trait SrcsAsSlice: AsSlice<Src, Attr = SrcType> {
1305 fn srcs_as_slice(&self) -> &[Src] {
1306 self.as_slice()
1307 }
1308
1309 fn srcs_as_mut_slice(&mut self) -> &mut [Src] {
1310 self.as_mut_slice()
1311 }
1312
1313 fn src_types(&self) -> SrcTypeList {
1314 self.attrs()
1315 }
1316
1317 fn src_idx(&self, src: &Src) -> usize {
1318 let r = self.srcs_as_slice().as_ptr_range();
1319 assert!(r.contains(&(src as *const Src)));
1320 unsafe { (src as *const Src).offset_from(r.start) as usize }
1321 }
1322 }
1323
1324 impl<T: AsSlice<Src, Attr = SrcType>> SrcsAsSlice for T {}
1325
1326 fn all_dsts_uniform(dsts: &[Dst]) -> bool {
1327 let mut uniform = None;
1328 for dst in dsts {
1329 let dst_uniform = match dst {
1330 Dst::None => continue,
1331 Dst::Reg(r) => r.is_uniform(),
1332 Dst::SSA(r) => r.file().is_uniform(),
1333 };
1334 assert!(uniform.is_none() || uniform == Some(dst_uniform));
1335 uniform = Some(dst_uniform);
1336 }
1337 uniform == Some(true)
1338 }
1339
1340 #[repr(u8)]
1341 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1342 pub enum DstType {
1343 Pred,
1344 GPR,
1345 F16,
1346 F16v2,
1347 F32,
1348 F64,
1349 Carry,
1350 Bar,
1351 Vec,
1352 }
1353
1354 impl DstType {
1355 const DEFAULT: DstType = DstType::Vec;
1356 }
1357
1358 pub type DstTypeList = AttrList<DstType>;
1359
1360 pub trait DstsAsSlice: AsSlice<Dst, Attr = DstType> {
1361 fn dsts_as_slice(&self) -> &[Dst] {
1362 self.as_slice()
1363 }
1364
1365 fn dsts_as_mut_slice(&mut self) -> &mut [Dst] {
1366 self.as_mut_slice()
1367 }
1368
1369 // Currently only used by test code
1370 #[allow(dead_code)]
1371 fn dst_types(&self) -> DstTypeList {
1372 self.attrs()
1373 }
1374
1375 fn dst_idx(&self, dst: &Dst) -> usize {
1376 let r = self.dsts_as_slice().as_ptr_range();
1377 assert!(r.contains(&(dst as *const Dst)));
1378 unsafe { (dst as *const Dst).offset_from(r.start) as usize }
1379 }
1380 }
1381
1382 impl<T: AsSlice<Dst, Attr = DstType>> DstsAsSlice for T {}
1383
1384 pub trait IsUniform {
1385 fn is_uniform(&self) -> bool;
1386 }
1387
1388 impl<T: DstsAsSlice> IsUniform for T {
1389 fn is_uniform(&self) -> bool {
1390 all_dsts_uniform(self.dsts_as_slice())
1391 }
1392 }
1393
1394 fn fmt_dst_slice(f: &mut fmt::Formatter<'_>, dsts: &[Dst]) -> fmt::Result {
1395 if dsts.is_empty() {
1396 return Ok(());
1397 }
1398
1399 // Figure out the last non-null dst
1400 //
1401 // Note: By making the top inclusive and starting at 0, we ensure that
1402 // at least one dst always gets printed.
1403 let mut last_dst = 0;
1404 for (i, dst) in dsts.iter().enumerate() {
1405 if !dst.is_none() {
1406 last_dst = i;
1407 }
1408 }
1409
1410 for i in 0..(last_dst + 1) {
1411 if i != 0 {
1412 write!(f, " ")?;
1413 }
1414 write!(f, "{}", &dsts[i])?;
1415 }
1416 Ok(())
1417 }
1418
1419 #[allow(dead_code)]
1420 #[derive(Clone, Copy)]
1421 pub enum FoldData {
1422 Pred(bool),
1423 Carry(bool),
1424 U32(u32),
1425 Vec2([u32; 2]),
1426 }
1427
1428 pub struct OpFoldData<'a> {
1429 pub dsts: &'a mut [FoldData],
1430 pub srcs: &'a [FoldData],
1431 }
1432
1433 impl OpFoldData<'_> {
1434 #[allow(dead_code)]
1435 pub fn get_pred_src(&self, op: &impl SrcsAsSlice, src: &Src) -> bool {
1436 let i = op.src_idx(src);
1437 let b = match src.src_ref {
1438 SrcRef::Zero | SrcRef::Imm32(_) => panic!("Expected a predicate"),
1439 SrcRef::True => true,
1440 SrcRef::False => false,
1441 _ => {
1442 if let FoldData::Pred(b) = self.srcs[i] {
1443 b
1444 } else {
1445 panic!("FoldData is not a predicate");
1446 }
1447 }
1448 };
1449 b ^ src.src_mod.is_bnot()
1450 }
1451
1452 pub fn get_u32_src(&self, op: &impl SrcsAsSlice, src: &Src) -> u32 {
1453 let i = op.src_idx(src);
1454 match src.src_ref {
1455 SrcRef::Zero => 0,
1456 SrcRef::Imm32(imm) => imm,
1457 SrcRef::True | SrcRef::False => panic!("Unexpected predicate"),
1458 _ => {
1459 if let FoldData::U32(u) = self.srcs[i] {
1460 u
1461 } else {
1462 panic!("FoldData is not a U32");
1463 }
1464 }
1465 }
1466 }
1467
1468 #[allow(dead_code)]
1469 pub fn get_u32_bnot_src(&self, op: &impl SrcsAsSlice, src: &Src) -> u32 {
1470 let x = self.get_u32_src(op, src);
1471 if src.src_mod.is_bnot() {
1472 !x
1473 } else {
1474 x
1475 }
1476 }
1477
1478 #[allow(dead_code)]
1479 pub fn get_carry_src(&self, op: &impl SrcsAsSlice, src: &Src) -> bool {
1480 assert!(src.src_ref.as_ssa().is_some());
1481 let i = op.src_idx(src);
1482 if let FoldData::Carry(b) = self.srcs[i] {
1483 b
1484 } else {
1485 panic!("FoldData is not a predicate");
1486 }
1487 }
1488
1489 #[allow(dead_code)]
1490 pub fn get_f32_src(&self, op: &impl SrcsAsSlice, src: &Src) -> f32 {
1491 f32::from_bits(self.get_u32_src(op, src))
1492 }
1493
1494 #[allow(dead_code)]
1495 pub fn get_f64_src(&self, op: &impl SrcsAsSlice, src: &Src) -> f64 {
1496 let i = op.src_idx(src);
1497 match src.src_ref {
1498 SrcRef::Zero => 0.0,
1499 SrcRef::Imm32(imm) => f64::from_bits(u64::from(imm) << 32),
1500 SrcRef::True | SrcRef::False => panic!("Unexpected predicate"),
1501 _ => {
1502 if let FoldData::Vec2(v) = self.srcs[i] {
1503 let u = u64::from(v[0]) | (u64::from(v[1]) << 32);
1504 f64::from_bits(u)
1505 } else {
1506 panic!("FoldData is not a U32");
1507 }
1508 }
1509 }
1510 }
1511
1512 #[allow(dead_code)]
1513 pub fn set_pred_dst(&mut self, op: &impl DstsAsSlice, dst: &Dst, b: bool) {
1514 self.dsts[op.dst_idx(dst)] = FoldData::Pred(b);
1515 }
1516
1517 #[allow(dead_code)]
1518 pub fn set_carry_dst(&mut self, op: &impl DstsAsSlice, dst: &Dst, b: bool) {
1519 self.dsts[op.dst_idx(dst)] = FoldData::Carry(b);
1520 }
1521
1522 pub fn set_u32_dst(&mut self, op: &impl DstsAsSlice, dst: &Dst, u: u32) {
1523 self.dsts[op.dst_idx(dst)] = FoldData::U32(u);
1524 }
1525
1526 #[allow(dead_code)]
1527 pub fn set_f32_dst(&mut self, op: &impl DstsAsSlice, dst: &Dst, f: f32) {
1528 self.set_u32_dst(op, dst, f.to_bits());
1529 }
1530
1531 #[allow(dead_code)]
1532 pub fn set_f64_dst(&mut self, op: &impl DstsAsSlice, dst: &Dst, f: f64) {
1533 let u = f.to_bits();
1534 let v = [u as u32, (u >> 32) as u32];
1535 self.dsts[op.dst_idx(dst)] = FoldData::Vec2(v);
1536 }
1537 }
1538
1539 pub trait Foldable: SrcsAsSlice + DstsAsSlice {
1540 // Currently only used by test code
1541 #[allow(dead_code)]
1542 fn fold(&self, sm: &ShaderModelInfo, f: &mut OpFoldData<'_>);
1543 }
1544
1545 pub trait DisplayOp: DstsAsSlice {
1546 fn fmt_dsts(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1547 fmt_dst_slice(f, self.dsts_as_slice())
1548 }
1549
1550 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
1551 }
1552
1553 // Hack struct so we can re-use Formatters. Shamelessly stolen from
1554 // https://users.rust-lang.org/t/reusing-an-fmt-formatter/8531/4
1555 pub struct Fmt<F>(pub F)
1556 where
1557 F: Fn(&mut fmt::Formatter) -> fmt::Result;
1558
1559 impl<F> fmt::Display for Fmt<F>
1560 where
1561 F: Fn(&mut fmt::Formatter) -> fmt::Result,
1562 {
1563 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1564 (self.0)(f)
1565 }
1566 }
1567
1568 macro_rules! impl_display_for_op {
1569 ($op: ident) => {
1570 impl fmt::Display for $op {
1571 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1572 let mut s = String::new();
1573 write!(s, "{}", Fmt(|f| self.fmt_dsts(f)))?;
1574 if !s.is_empty() {
1575 write!(f, "{} = ", s)?;
1576 }
1577 self.fmt_op(f)
1578 }
1579 }
1580 };
1581 }
1582
1583 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
1584 pub enum PredSetOp {
1585 And,
1586 Or,
1587 Xor,
1588 }
1589
1590 impl PredSetOp {
1591 #[allow(dead_code)]
1592 pub fn eval(&self, a: bool, b: bool) -> bool {
1593 match self {
1594 PredSetOp::And => a & b,
1595 PredSetOp::Or => a | b,
1596 PredSetOp::Xor => a ^ b,
1597 }
1598 }
1599
1600 pub fn is_trivial(&self, accum: &Src) -> bool {
1601 if let Some(b) = accum.as_bool() {
1602 match self {
1603 PredSetOp::And => b,
1604 PredSetOp::Or => !b,
1605 PredSetOp::Xor => !b,
1606 }
1607 } else {
1608 false
1609 }
1610 }
1611 }
1612
1613 impl fmt::Display for PredSetOp {
1614 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1615 match self {
1616 PredSetOp::And => write!(f, ".and"),
1617 PredSetOp::Or => write!(f, ".or"),
1618 PredSetOp::Xor => write!(f, ".xor"),
1619 }
1620 }
1621 }
1622
1623 #[allow(dead_code)]
1624 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
1625 pub enum FloatCmpOp {
1626 OrdEq,
1627 OrdNe,
1628 OrdLt,
1629 OrdLe,
1630 OrdGt,
1631 OrdGe,
1632 UnordEq,
1633 UnordNe,
1634 UnordLt,
1635 UnordLe,
1636 UnordGt,
1637 UnordGe,
1638 IsNum,
1639 IsNan,
1640 }
1641
1642 impl FloatCmpOp {
1643 pub fn flip(self) -> FloatCmpOp {
1644 match self {
1645 FloatCmpOp::OrdEq | FloatCmpOp::OrdNe => self,
1646 FloatCmpOp::OrdLt => FloatCmpOp::OrdGt,
1647 FloatCmpOp::OrdLe => FloatCmpOp::OrdGe,
1648 FloatCmpOp::OrdGt => FloatCmpOp::OrdLt,
1649 FloatCmpOp::OrdGe => FloatCmpOp::OrdLe,
1650 FloatCmpOp::UnordEq | FloatCmpOp::UnordNe => self,
1651 FloatCmpOp::UnordLt => FloatCmpOp::UnordGt,
1652 FloatCmpOp::UnordLe => FloatCmpOp::UnordGe,
1653 FloatCmpOp::UnordGt => FloatCmpOp::UnordLt,
1654 FloatCmpOp::UnordGe => FloatCmpOp::UnordLe,
1655 FloatCmpOp::IsNum | FloatCmpOp::IsNan => panic!("Cannot flip unop"),
1656 }
1657 }
1658 }
1659
1660 impl fmt::Display for FloatCmpOp {
1661 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1662 match self {
1663 FloatCmpOp::OrdEq => write!(f, ".eq"),
1664 FloatCmpOp::OrdNe => write!(f, ".ne"),
1665 FloatCmpOp::OrdLt => write!(f, ".lt"),
1666 FloatCmpOp::OrdLe => write!(f, ".le"),
1667 FloatCmpOp::OrdGt => write!(f, ".gt"),
1668 FloatCmpOp::OrdGe => write!(f, ".ge"),
1669 FloatCmpOp::UnordEq => write!(f, ".equ"),
1670 FloatCmpOp::UnordNe => write!(f, ".neu"),
1671 FloatCmpOp::UnordLt => write!(f, ".ltu"),
1672 FloatCmpOp::UnordLe => write!(f, ".leu"),
1673 FloatCmpOp::UnordGt => write!(f, ".gtu"),
1674 FloatCmpOp::UnordGe => write!(f, ".geu"),
1675 FloatCmpOp::IsNum => write!(f, ".num"),
1676 FloatCmpOp::IsNan => write!(f, ".nan"),
1677 }
1678 }
1679 }
1680
1681 #[allow(dead_code)]
1682 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
1683 pub enum IntCmpOp {
1684 False,
1685 True,
1686 Eq,
1687 Ne,
1688 Lt,
1689 Le,
1690 Gt,
1691 Ge,
1692 }
1693
1694 impl IntCmpOp {
1695 pub fn flip(self) -> IntCmpOp {
1696 match self {
1697 IntCmpOp::False | IntCmpOp::True => self,
1698 IntCmpOp::Eq | IntCmpOp::Ne => self,
1699 IntCmpOp::Lt => IntCmpOp::Gt,
1700 IntCmpOp::Le => IntCmpOp::Ge,
1701 IntCmpOp::Gt => IntCmpOp::Lt,
1702 IntCmpOp::Ge => IntCmpOp::Le,
1703 }
1704 }
1705 }
1706
1707 impl fmt::Display for IntCmpOp {
1708 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1709 match self {
1710 IntCmpOp::False => write!(f, ".f"),
1711 IntCmpOp::True => write!(f, ".t"),
1712 IntCmpOp::Eq => write!(f, ".eq"),
1713 IntCmpOp::Ne => write!(f, ".ne"),
1714 IntCmpOp::Lt => write!(f, ".lt"),
1715 IntCmpOp::Le => write!(f, ".le"),
1716 IntCmpOp::Gt => write!(f, ".gt"),
1717 IntCmpOp::Ge => write!(f, ".ge"),
1718 }
1719 }
1720 }
1721
1722 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
1723 pub enum IntCmpType {
1724 U32,
1725 I32,
1726 }
1727
1728 impl IntCmpType {
1729 pub fn is_signed(&self) -> bool {
1730 match self {
1731 IntCmpType::U32 => false,
1732 IntCmpType::I32 => true,
1733 }
1734 }
1735 }
1736
1737 impl fmt::Display for IntCmpType {
1738 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1739 match self {
1740 IntCmpType::U32 => write!(f, ".u32"),
1741 IntCmpType::I32 => write!(f, ".i32"),
1742 }
1743 }
1744 }
1745
1746 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
1747 pub enum LogicOp2 {
1748 And,
1749 Or,
1750 Xor,
1751 PassB,
1752 }
1753
1754 impl fmt::Display for LogicOp2 {
1755 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1756 match self {
1757 LogicOp2::And => write!(f, "and"),
1758 LogicOp2::Or => write!(f, "or"),
1759 LogicOp2::Xor => write!(f, "xor"),
1760 LogicOp2::PassB => write!(f, "pass_b"),
1761 }
1762 }
1763 }
1764
1765 impl LogicOp2 {
1766 pub fn to_lut(self) -> LogicOp3 {
1767 match self {
1768 LogicOp2::And => LogicOp3::new_lut(&|x, y, _| x & y),
1769 LogicOp2::Or => LogicOp3::new_lut(&|x, y, _| x | y),
1770 LogicOp2::Xor => LogicOp3::new_lut(&|x, y, _| x ^ y),
1771 LogicOp2::PassB => LogicOp3::new_lut(&|_, b, _| b),
1772 }
1773 }
1774 }
1775
1776 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
1777 pub struct LogicOp3 {
1778 pub lut: u8,
1779 }
1780
1781 impl LogicOp3 {
1782 pub const SRC_MASKS: [u8; 3] = [0xf0, 0xcc, 0xaa];
1783
1784 #[inline]
1785 pub fn new_lut<F: Fn(u8, u8, u8) -> u8>(f: &F) -> LogicOp3 {
1786 LogicOp3 {
1787 lut: f(
1788 LogicOp3::SRC_MASKS[0],
1789 LogicOp3::SRC_MASKS[1],
1790 LogicOp3::SRC_MASKS[2],
1791 ),
1792 }
1793 }
1794
1795 pub fn new_const(val: bool) -> LogicOp3 {
1796 LogicOp3 {
1797 lut: if val { !0 } else { 0 },
1798 }
1799 }
1800
1801 pub fn src_used(&self, src_idx: usize) -> bool {
1802 let mask = LogicOp3::SRC_MASKS[src_idx];
1803 let shift = LogicOp3::SRC_MASKS[src_idx].trailing_zeros();
1804 self.lut & !mask != (self.lut >> shift) & !mask
1805 }
1806
1807 pub fn fix_src(&mut self, src_idx: usize, val: bool) {
1808 let mask = LogicOp3::SRC_MASKS[src_idx];
1809 let shift = LogicOp3::SRC_MASKS[src_idx].trailing_zeros();
1810 if val {
1811 let t_bits = self.lut & mask;
1812 self.lut = t_bits | (t_bits >> shift)
1813 } else {
1814 let f_bits = self.lut & !mask;
1815 self.lut = (f_bits << shift) | f_bits
1816 };
1817 }
1818
1819 pub fn invert_src(&mut self, src_idx: usize) {
1820 let mask = LogicOp3::SRC_MASKS[src_idx];
1821 let shift = LogicOp3::SRC_MASKS[src_idx].trailing_zeros();
1822 let t_bits = self.lut & mask;
1823 let f_bits = self.lut & !mask;
1824 self.lut = (f_bits << shift) | (t_bits >> shift);
1825 }
1826
1827 pub fn eval<
1828 T: BitAnd<Output = T> + BitOr<Output = T> + Copy + Not<Output = T>,
1829 >(
1830 &self,
1831 x: T,
1832 y: T,
1833 z: T,
1834 ) -> T {
1835 let mut res = x & !x; // zero
1836 if (self.lut & (1 << 0)) != 0 {
1837 res = res | (!x & !y & !z);
1838 }
1839 if (self.lut & (1 << 1)) != 0 {
1840 res = res | (!x & !y & z);
1841 }
1842 if (self.lut & (1 << 2)) != 0 {
1843 res = res | (!x & y & !z);
1844 }
1845 if (self.lut & (1 << 3)) != 0 {
1846 res = res | (!x & y & z);
1847 }
1848 if (self.lut & (1 << 4)) != 0 {
1849 res = res | (x & !y & !z);
1850 }
1851 if (self.lut & (1 << 5)) != 0 {
1852 res = res | (x & !y & z);
1853 }
1854 if (self.lut & (1 << 6)) != 0 {
1855 res = res | (x & y & !z);
1856 }
1857 if (self.lut & (1 << 7)) != 0 {
1858 res = res | (x & y & z);
1859 }
1860 res
1861 }
1862 }
1863
1864 impl fmt::Display for LogicOp3 {
1865 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1866 write!(f, "LUT[{:#x}]", self.lut)
1867 }
1868 }
1869
1870 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
1871 pub enum FloatType {
1872 F16,
1873 F32,
1874 F64,
1875 }
1876
1877 impl FloatType {
1878 pub fn from_bits(bytes: usize) -> FloatType {
1879 match bytes {
1880 16 => FloatType::F16,
1881 32 => FloatType::F32,
1882 64 => FloatType::F64,
1883 _ => panic!("Invalid float type size"),
1884 }
1885 }
1886
1887 pub fn bits(&self) -> usize {
1888 match self {
1889 FloatType::F16 => 16,
1890 FloatType::F32 => 32,
1891 FloatType::F64 => 64,
1892 }
1893 }
1894 }
1895
1896 impl fmt::Display for FloatType {
1897 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1898 match self {
1899 FloatType::F16 => write!(f, ".f16"),
1900 FloatType::F32 => write!(f, ".f32"),
1901 FloatType::F64 => write!(f, ".f64"),
1902 }
1903 }
1904 }
1905
1906 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
1907 pub enum FRndMode {
1908 NearestEven,
1909 NegInf,
1910 PosInf,
1911 Zero,
1912 }
1913
1914 impl fmt::Display for FRndMode {
1915 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1916 match self {
1917 FRndMode::NearestEven => write!(f, ".re"),
1918 FRndMode::NegInf => write!(f, ".rm"),
1919 FRndMode::PosInf => write!(f, ".rp"),
1920 FRndMode::Zero => write!(f, ".rz"),
1921 }
1922 }
1923 }
1924
1925 #[derive(Clone, Copy, Eq, PartialEq)]
1926 pub struct TexCBufRef {
1927 pub idx: u8,
1928 pub offset: u16,
1929 }
1930
1931 #[derive(Clone, Copy, Eq, PartialEq)]
1932 pub enum TexRef {
1933 Bound(u16),
1934 CBuf(TexCBufRef),
1935 Bindless,
1936 }
1937
1938 impl fmt::Display for TexRef {
1939 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1940 match self {
1941 TexRef::Bound(idx) => write!(f, "tex[{idx}]"),
1942 TexRef::CBuf(TexCBufRef { idx, offset }) => {
1943 write!(f, "c[{idx:#x}][{offset:#x}]")
1944 }
1945 TexRef::Bindless => write!(f, "bindless"),
1946 }
1947 }
1948 }
1949
1950 #[derive(Clone, Copy, Eq, PartialEq)]
1951 pub enum TexDim {
1952 _1D,
1953 Array1D,
1954 _2D,
1955 Array2D,
1956 _3D,
1957 Cube,
1958 ArrayCube,
1959 }
1960
1961 impl fmt::Display for TexDim {
1962 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1963 match self {
1964 TexDim::_1D => write!(f, ".1d"),
1965 TexDim::Array1D => write!(f, ".a1d"),
1966 TexDim::_2D => write!(f, ".2d"),
1967 TexDim::Array2D => write!(f, ".a2d"),
1968 TexDim::_3D => write!(f, ".3d"),
1969 TexDim::Cube => write!(f, ".cube"),
1970 TexDim::ArrayCube => write!(f, ".acube"),
1971 }
1972 }
1973 }
1974
1975 #[derive(Clone, Copy, Eq, PartialEq)]
1976 pub enum TexLodMode {
1977 Auto,
1978 Zero,
1979 Bias,
1980 Lod,
1981 Clamp,
1982 BiasClamp,
1983 }
1984
1985 impl TexLodMode {
1986 pub fn is_explicit_lod(&self) -> bool {
1987 match self {
1988 TexLodMode::Auto
1989 | TexLodMode::Bias
1990 | TexLodMode::Clamp
1991 | TexLodMode::BiasClamp => false,
1992 TexLodMode::Zero | TexLodMode::Lod => true,
1993 }
1994 }
1995 }
1996
1997 impl fmt::Display for TexLodMode {
1998 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1999 match self {
2000 TexLodMode::Auto => write!(f, ""),
2001 TexLodMode::Zero => write!(f, ".lz"),
2002 TexLodMode::Bias => write!(f, ".lb"),
2003 TexLodMode::Lod => write!(f, ".ll"),
2004 TexLodMode::Clamp => write!(f, ".lc"),
2005 TexLodMode::BiasClamp => write!(f, ".lb.lc"),
2006 }
2007 }
2008 }
2009
2010 /// Derivative behavior for tex ops and FSwzAdd
2011 ///
2012 /// The descriptions here may not be wholly accurate as they come from cobbling
2013 /// together a bunch of pieces. This is my (Faith's) best understanding of how
2014 /// these things work.
2015 #[allow(dead_code)]
2016 #[derive(Clone, Copy, Eq, PartialEq)]
2017 pub enum TexDerivMode {
2018 /// Automatic
2019 ///
2020 /// For partial (not full) quads, the derivative will default to the value
2021 /// of DEFAULT_PARTIAL in SET_SHADER_CONTROL.
2022 ///
2023 /// On Volta and earlier GPUs or on Blackwell B and later, derivatives in
2024 /// all non-fragment shaders stages are assumed to be partial.
2025 Auto,
2026
2027 /// Assume a non-divergent (full) derivative
2028 ///
2029 /// Partial derivative checks are skipped and the hardware does the
2030 /// derivative anyway, possibly on rubbish data.
2031 NonDivergent,
2032
2033 /// Force the derivative to be considered divergent (partial)
2034 ///
2035 /// This only exists as a separate thing on Blackwell A. On Hopper and
2036 /// earlier, there is a .fdv that's part of the LodMode, but only for
2037 /// LodMode::Clamp. On Blackwell B, it appears (according to the
2038 /// disassembler) to be removed again in favor of DerivXY.
2039 ForceDivergent,
2040
2041 /// Attempt an X/Y derivative, ignoring shader stage
2042 ///
2043 /// This is (I think) identical to Auto except that it ignores the shader
2044 /// stage checks. This is new on Blackwell B+.
2045 DerivXY,
2046 }
2047
2048 impl fmt::Display for TexDerivMode {
2049 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2050 match self {
2051 TexDerivMode::Auto => Ok(()),
2052 TexDerivMode::NonDivergent => write!(f, ".ndv"),
2053 TexDerivMode::ForceDivergent => write!(f, ".fdv"),
2054 TexDerivMode::DerivXY => write!(f, ".dxy"),
2055 }
2056 }
2057 }
2058
2059 #[derive(Clone, Copy, Eq, PartialEq)]
2060 pub struct ChannelMask(u8);
2061
2062 impl ChannelMask {
2063 pub fn new(mask: u8) -> Self {
2064 assert!(mask != 0 && (mask & !0xf) == 0);
2065 ChannelMask(mask)
2066 }
2067
2068 pub fn for_comps(comps: u8) -> Self {
2069 assert!(comps > 0 && comps <= 4);
2070 ChannelMask((1 << comps) - 1)
2071 }
2072
2073 pub fn to_bits(self) -> u8 {
2074 self.0
2075 }
2076 }
2077
2078 impl fmt::Display for ChannelMask {
2079 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2080 write!(f, ".")?;
2081 for (i, c) in ['r', 'g', 'b', 'a'].into_iter().enumerate() {
2082 if self.0 & (1 << i) != 0 {
2083 write!(f, "{c}")?;
2084 }
2085 }
2086 Ok(())
2087 }
2088 }
2089
2090 #[derive(Clone, Copy, Eq, PartialEq)]
2091 pub enum TexOffsetMode {
2092 None,
2093 AddOffI,
2094 PerPx, // tld4 only
2095 }
2096
2097 impl fmt::Display for TexOffsetMode {
2098 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2099 match self {
2100 TexOffsetMode::None => write!(f, ""),
2101 TexOffsetMode::AddOffI => write!(f, ".aoffi"),
2102 TexOffsetMode::PerPx => write!(f, ".ptp"),
2103 }
2104 }
2105 }
2106
2107 #[derive(Clone, Copy, Eq, PartialEq)]
2108 pub enum TexQuery {
2109 Dimension,
2110 TextureType,
2111 SamplerPos,
2112 }
2113
2114 impl fmt::Display for TexQuery {
2115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2116 match self {
2117 TexQuery::Dimension => write!(f, "dimension"),
2118 TexQuery::TextureType => write!(f, "texture_type"),
2119 TexQuery::SamplerPos => write!(f, "sampler_pos"),
2120 }
2121 }
2122 }
2123
2124 #[derive(Clone, Copy, Eq, PartialEq)]
2125 pub enum ImageDim {
2126 _1D,
2127 _1DBuffer,
2128 _1DArray,
2129 _2D,
2130 _2DArray,
2131 _3D,
2132 }
2133
2134 impl ImageDim {
2135 pub fn coord_comps(&self) -> u8 {
2136 match self {
2137 ImageDim::_1D => 1,
2138 ImageDim::_1DBuffer => 1,
2139 ImageDim::_1DArray => 2,
2140 ImageDim::_2D => 2,
2141 ImageDim::_2DArray => 3,
2142 ImageDim::_3D => 3,
2143 }
2144 }
2145 }
2146
2147 impl fmt::Display for ImageDim {
2148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2149 match self {
2150 ImageDim::_1D => write!(f, ".1d"),
2151 ImageDim::_1DBuffer => write!(f, ".buf"),
2152 ImageDim::_1DArray => write!(f, ".a1d"),
2153 ImageDim::_2D => write!(f, ".2d"),
2154 ImageDim::_2DArray => write!(f, ".a2d"),
2155 ImageDim::_3D => write!(f, ".3d"),
2156 }
2157 }
2158 }
2159
2160 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
2161 pub enum IntType {
2162 U8,
2163 I8,
2164 U16,
2165 I16,
2166 U32,
2167 I32,
2168 U64,
2169 I64,
2170 }
2171
2172 impl IntType {
2173 pub fn from_bits(bits: usize, is_signed: bool) -> IntType {
2174 match bits {
2175 8 => {
2176 if is_signed {
2177 IntType::I8
2178 } else {
2179 IntType::U8
2180 }
2181 }
2182 16 => {
2183 if is_signed {
2184 IntType::I16
2185 } else {
2186 IntType::U16
2187 }
2188 }
2189 32 => {
2190 if is_signed {
2191 IntType::I32
2192 } else {
2193 IntType::U32
2194 }
2195 }
2196 64 => {
2197 if is_signed {
2198 IntType::I64
2199 } else {
2200 IntType::U64
2201 }
2202 }
2203 _ => panic!("Invalid integer type size"),
2204 }
2205 }
2206
2207 pub fn is_signed(&self) -> bool {
2208 match self {
2209 IntType::U8 | IntType::U16 | IntType::U32 | IntType::U64 => false,
2210 IntType::I8 | IntType::I16 | IntType::I32 | IntType::I64 => true,
2211 }
2212 }
2213
2214 pub fn bits(&self) -> usize {
2215 match self {
2216 IntType::U8 | IntType::I8 => 8,
2217 IntType::U16 | IntType::I16 => 16,
2218 IntType::U32 | IntType::I32 => 32,
2219 IntType::U64 | IntType::I64 => 64,
2220 }
2221 }
2222 }
2223
2224 impl fmt::Display for IntType {
2225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2226 match self {
2227 IntType::U8 => write!(f, ".u8"),
2228 IntType::I8 => write!(f, ".i8"),
2229 IntType::U16 => write!(f, ".u16"),
2230 IntType::I16 => write!(f, ".i16"),
2231 IntType::U32 => write!(f, ".u32"),
2232 IntType::I32 => write!(f, ".i32"),
2233 IntType::U64 => write!(f, ".u64"),
2234 IntType::I64 => write!(f, ".i64"),
2235 }
2236 }
2237 }
2238
2239 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
2240 pub enum MemAddrType {
2241 A32,
2242 A64,
2243 }
2244
2245 impl fmt::Display for MemAddrType {
2246 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2247 match self {
2248 MemAddrType::A32 => write!(f, ".a32"),
2249 MemAddrType::A64 => write!(f, ".a64"),
2250 }
2251 }
2252 }
2253
2254 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
2255 pub enum MemType {
2256 U8,
2257 I8,
2258 U16,
2259 I16,
2260 B32,
2261 B64,
2262 B128,
2263 }
2264
2265 impl MemType {
2266 pub fn from_size(size: u8, is_signed: bool) -> MemType {
2267 match size {
2268 1 => {
2269 if is_signed {
2270 MemType::I8
2271 } else {
2272 MemType::U8
2273 }
2274 }
2275 2 => {
2276 if is_signed {
2277 MemType::I16
2278 } else {
2279 MemType::U16
2280 }
2281 }
2282 4 => MemType::B32,
2283 8 => MemType::B64,
2284 16 => MemType::B128,
2285 _ => panic!("Invalid memory load/store size"),
2286 }
2287 }
2288
2289 #[allow(dead_code)]
2290 pub fn bits(&self) -> usize {
2291 match self {
2292 MemType::U8 | MemType::I8 => 8,
2293 MemType::U16 | MemType::I16 => 16,
2294 MemType::B32 => 32,
2295 MemType::B64 => 64,
2296 MemType::B128 => 128,
2297 }
2298 }
2299 }
2300
2301 impl fmt::Display for MemType {
2302 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2303 match self {
2304 MemType::U8 => write!(f, ".u8"),
2305 MemType::I8 => write!(f, ".i8"),
2306 MemType::U16 => write!(f, ".u16"),
2307 MemType::I16 => write!(f, ".i16"),
2308 MemType::B32 => write!(f, ".b32"),
2309 MemType::B64 => write!(f, ".b64"),
2310 MemType::B128 => write!(f, ".b128"),
2311 }
2312 }
2313 }
2314
2315 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
2316 pub enum MemOrder {
2317 Constant,
2318 Weak,
2319 Strong(MemScope),
2320 }
2321
2322 impl fmt::Display for MemOrder {
2323 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2324 match self {
2325 MemOrder::Constant => write!(f, ".constant"),
2326 MemOrder::Weak => write!(f, ".weak"),
2327 MemOrder::Strong(scope) => write!(f, ".strong{}", scope),
2328 }
2329 }
2330 }
2331
2332 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
2333 pub enum MemScope {
2334 CTA,
2335 GPU,
2336 System,
2337 }
2338
2339 impl fmt::Display for MemScope {
2340 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2341 match self {
2342 MemScope::CTA => write!(f, ".cta"),
2343 MemScope::GPU => write!(f, ".gpu"),
2344 MemScope::System => write!(f, ".sys"),
2345 }
2346 }
2347 }
2348
2349 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
2350 pub enum MemSpace {
2351 Global(MemAddrType),
2352 Local,
2353 Shared,
2354 }
2355
2356 impl MemSpace {
2357 pub fn addr_type(&self) -> MemAddrType {
2358 match self {
2359 MemSpace::Global(t) => *t,
2360 MemSpace::Local => MemAddrType::A32,
2361 MemSpace::Shared => MemAddrType::A32,
2362 }
2363 }
2364 }
2365
2366 impl fmt::Display for MemSpace {
2367 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2368 match self {
2369 MemSpace::Global(t) => write!(f, ".global{t}"),
2370 MemSpace::Local => write!(f, ".local"),
2371 MemSpace::Shared => write!(f, ".shared"),
2372 }
2373 }
2374 }
2375
2376 #[allow(dead_code)]
2377 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
2378 pub enum MemEvictionPriority {
2379 First,
2380 Normal,
2381 Last,
2382 LastUse,
2383 Unchanged,
2384 NoAllocate,
2385 }
2386
2387 impl fmt::Display for MemEvictionPriority {
2388 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2389 match self {
2390 MemEvictionPriority::First => write!(f, ".ef"),
2391 MemEvictionPriority::Normal => Ok(()),
2392 MemEvictionPriority::Last => write!(f, ".el"),
2393 MemEvictionPriority::LastUse => write!(f, ".lu"),
2394 MemEvictionPriority::Unchanged => write!(f, ".eu"),
2395 MemEvictionPriority::NoAllocate => write!(f, ".na"),
2396 }
2397 }
2398 }
2399
2400 /// Memory load cache ops used by Kepler
2401 #[allow(dead_code)]
2402 #[expect(clippy::enum_variant_names)]
2403 #[derive(Clone, Copy, Default, Eq, Hash, PartialEq)]
2404 pub enum LdCacheOp {
2405 #[default]
2406 CacheAll,
2407 CacheGlobal,
2408 /// This cache mode not officially documented by NVIDIA. What we do know is
2409 /// that the Cuda C programming gude says:
2410 ///
2411 /// > The read-only data cache load function is only supported by devices
2412 /// > of compute capability 5.0 and higher.
2413 /// > ```c
2414 /// > T __ldg(const T* address);
2415 /// > ```
2416 ///
2417 /// and we know that `__ldg()` compiles to `ld.global.nc` in PTX which
2418 /// compiles to `ld.ci`. The PTX 5.0 docs say:
2419 ///
2420 /// > Load register variable `d` from the location specified by the source
2421 /// > address operand `a` in the global state space, and optionally cache in
2422 /// > non-coherent texture cache. Since the cache is non-coherent, the data
2423 /// > should be read-only within the kernel's process.
2424 ///
2425 /// Since `.nc` means "non-coherent", the name "incoherent" seems about
2426 /// right. The quote above also seems to imply that these loads got loaded
2427 /// through the texture cache but we don't fully understand the implications
2428 /// of that.
2429 CacheIncoherent,
2430 CacheStreaming,
2431 CacheInvalidate,
2432 }
2433
2434 impl fmt::Display for LdCacheOp {
2435 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2436 match self {
2437 LdCacheOp::CacheAll => write!(f, ".ca"),
2438 LdCacheOp::CacheGlobal => write!(f, ".cg"),
2439 LdCacheOp::CacheIncoherent => write!(f, ".ci"),
2440 LdCacheOp::CacheStreaming => write!(f, ".cs"),
2441 LdCacheOp::CacheInvalidate => write!(f, ".cv"),
2442 }
2443 }
2444 }
2445
2446 impl LdCacheOp {
2447 pub fn select(
2448 sm: &dyn ShaderModel,
2449 space: MemSpace,
2450 order: MemOrder,
2451 _eviction_priority: MemEvictionPriority,
2452 ) -> Self {
2453 match space {
2454 MemSpace::Global(_) => match order {
2455 MemOrder::Constant => {
2456 if sm.sm() >= 50 {
2457 // This is undocumented in the CUDA docs but NVIDIA uses
2458 // it for constant loads.
2459 LdCacheOp::CacheIncoherent
2460 } else {
2461 LdCacheOp::CacheAll
2462 }
2463 }
2464 MemOrder::Strong(MemScope::System) => {
2465 LdCacheOp::CacheInvalidate
2466 }
2467 _ => {
2468 // From the CUDA 10.2 docs:
2469 //
2470 // "The default load instruction cache operation is
2471 // ld.ca, which allocates cache lines in all levels (L1
2472 // and L2) with normal eviction policy. Global data is
2473 // coherent at the L2 level, but multiple L1 caches are
2474 // not coherent for global data. If one thread stores to
2475 // global memory via one L1 cache, and a second thread
2476 // loads that address via a second L1 cache with ld.ca,
2477 // the second thread may get stale L1 cache data"
2478 //
2479 // and
2480 //
2481 // "L1 caching in Kepler GPUs is reserved only for local
2482 // memory accesses, such as register spills and stack
2483 // data. Global loads are cached in L2 only (or in the
2484 // Read-Only Data Cache)."
2485 //
2486 // We follow suit and use CacheGlobal for all global memory
2487 // access on Kepler. On Maxwell, it appears safe to use
2488 // CacheAll for everything.
2489 if sm.sm() >= 50 {
2490 LdCacheOp::CacheAll
2491 } else {
2492 LdCacheOp::CacheGlobal
2493 }
2494 }
2495 },
2496 MemSpace::Local | MemSpace::Shared => LdCacheOp::CacheAll,
2497 }
2498 }
2499 }
2500
2501 /// Memory store cache ops used by Kepler
2502 #[allow(dead_code)]
2503 #[derive(Clone, Copy, Default, Eq, Hash, PartialEq)]
2504 pub enum StCacheOp {
2505 #[default]
2506 WriteBack,
2507 CacheGlobal,
2508 CacheStreaming,
2509 WriteThrough,
2510 }
2511
2512 impl fmt::Display for StCacheOp {
2513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2514 match self {
2515 StCacheOp::WriteBack => write!(f, ".wb"),
2516 StCacheOp::CacheGlobal => write!(f, ".cg"),
2517 StCacheOp::CacheStreaming => write!(f, ".cs"),
2518 StCacheOp::WriteThrough => write!(f, ".wt"),
2519 }
2520 }
2521 }
2522
2523 impl StCacheOp {
2524 pub fn select(
2525 sm: &dyn ShaderModel,
2526 space: MemSpace,
2527 order: MemOrder,
2528 _eviction_priority: MemEvictionPriority,
2529 ) -> Self {
2530 match space {
2531 MemSpace::Global(_) => match order {
2532 MemOrder::Constant => panic!("Cannot store to constant"),
2533 MemOrder::Strong(MemScope::System) => StCacheOp::WriteThrough,
2534 _ => {
2535 // See the corresponding comment in LdCacheOp::select()
2536 if sm.sm() >= 50 {
2537 StCacheOp::WriteBack
2538 } else {
2539 StCacheOp::CacheGlobal
2540 }
2541 }
2542 },
2543 MemSpace::Local | MemSpace::Shared => StCacheOp::WriteBack,
2544 }
2545 }
2546 }
2547
2548 #[derive(Clone)]
2549 pub struct MemAccess {
2550 pub mem_type: MemType,
2551 pub space: MemSpace,
2552 pub order: MemOrder,
2553 pub eviction_priority: MemEvictionPriority,
2554 }
2555
2556 impl fmt::Display for MemAccess {
2557 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2558 write!(
2559 f,
2560 "{}{}{}{}",
2561 self.space, self.order, self.eviction_priority, self.mem_type,
2562 )
2563 }
2564 }
2565
2566 impl MemAccess {
2567 pub fn ld_cache_op(&self, sm: &dyn ShaderModel) -> LdCacheOp {
2568 LdCacheOp::select(sm, self.space, self.order, self.eviction_priority)
2569 }
2570
2571 pub fn st_cache_op(&self, sm: &dyn ShaderModel) -> StCacheOp {
2572 StCacheOp::select(sm, self.space, self.order, self.eviction_priority)
2573 }
2574 }
2575
2576 #[allow(dead_code)]
2577 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
2578 pub enum AtomType {
2579 F16x2,
2580 U32,
2581 I32,
2582 F32,
2583 U64,
2584 I64,
2585 F64,
2586 }
2587
2588 impl AtomType {
2589 pub fn F(bits: u8) -> AtomType {
2590 match bits {
2591 16 => panic!("16-bit float atomics not yet supported"),
2592 32 => AtomType::F32,
2593 64 => AtomType::F64,
2594 _ => panic!("Invalid float atomic type"),
2595 }
2596 }
2597
2598 pub fn U(bits: u8) -> AtomType {
2599 match bits {
2600 32 => AtomType::U32,
2601 64 => AtomType::U64,
2602 _ => panic!("Invalid uint atomic type"),
2603 }
2604 }
2605
2606 pub fn I(bits: u8) -> AtomType {
2607 match bits {
2608 32 => AtomType::I32,
2609 64 => AtomType::I64,
2610 _ => panic!("Invalid int atomic type"),
2611 }
2612 }
2613
2614 pub fn bits(&self) -> usize {
2615 match self {
2616 AtomType::F16x2 | AtomType::F32 => 32,
2617 AtomType::U32 | AtomType::I32 => 32,
2618 AtomType::U64 | AtomType::I64 | AtomType::F64 => 64,
2619 }
2620 }
2621
2622 pub fn is_float(&self) -> bool {
2623 match self {
2624 AtomType::F16x2 | AtomType::F32 | AtomType::F64 => true,
2625 AtomType::U32 | AtomType::I32 | AtomType::U64 | AtomType::I64 => {
2626 false
2627 }
2628 }
2629 }
2630 }
2631
2632 impl fmt::Display for AtomType {
2633 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2634 match self {
2635 AtomType::F16x2 => write!(f, ".f16x2"),
2636 AtomType::U32 => write!(f, ".u32"),
2637 AtomType::I32 => write!(f, ".i32"),
2638 AtomType::F32 => write!(f, ".f32"),
2639 AtomType::U64 => write!(f, ".u64"),
2640 AtomType::I64 => write!(f, ".i64"),
2641 AtomType::F64 => write!(f, ".f64"),
2642 }
2643 }
2644 }
2645
2646 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
2647 pub enum AtomCmpSrc {
2648 /// The cmpr value is passed as a separate source
2649 Separate,
2650 /// The cmpr value is packed in with the data with cmpr coming first
2651 Packed,
2652 }
2653
2654 #[allow(dead_code)]
2655 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
2656 pub enum AtomOp {
2657 Add,
2658 Min,
2659 Max,
2660 Inc,
2661 Dec,
2662 And,
2663 Or,
2664 Xor,
2665 Exch,
2666 CmpExch(AtomCmpSrc),
2667 }
2668
2669 impl AtomOp {
2670 pub fn is_reduction(&self) -> bool {
2671 match self {
2672 AtomOp::Add
2673 | AtomOp::Min
2674 | AtomOp::Max
2675 | AtomOp::Inc
2676 | AtomOp::Dec
2677 | AtomOp::And
2678 | AtomOp::Or
2679 | AtomOp::Xor => true,
2680 AtomOp::Exch | AtomOp::CmpExch(_) => false,
2681 }
2682 }
2683 }
2684
2685 impl fmt::Display for AtomOp {
2686 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2687 match self {
2688 AtomOp::Add => write!(f, ".add"),
2689 AtomOp::Min => write!(f, ".min"),
2690 AtomOp::Max => write!(f, ".max"),
2691 AtomOp::Inc => write!(f, ".inc"),
2692 AtomOp::Dec => write!(f, ".dec"),
2693 AtomOp::And => write!(f, ".and"),
2694 AtomOp::Or => write!(f, ".or"),
2695 AtomOp::Xor => write!(f, ".xor"),
2696 AtomOp::Exch => write!(f, ".exch"),
2697 AtomOp::CmpExch(AtomCmpSrc::Separate) => write!(f, ".cmpexch"),
2698 AtomOp::CmpExch(AtomCmpSrc::Packed) => write!(f, ".cmpexch.packed"),
2699 }
2700 }
2701 }
2702
2703 #[derive(Clone, Copy, Eq, PartialEq)]
2704 pub enum InterpFreq {
2705 Pass,
2706 PassMulW,
2707 Constant,
2708 State,
2709 }
2710
2711 impl fmt::Display for InterpFreq {
2712 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2713 match self {
2714 InterpFreq::Pass => write!(f, ".pass"),
2715 InterpFreq::PassMulW => write!(f, ".pass_mul_w"),
2716 InterpFreq::Constant => write!(f, ".constant"),
2717 InterpFreq::State => write!(f, ".state"),
2718 }
2719 }
2720 }
2721 #[derive(Clone, Copy, Eq, PartialEq)]
2722 pub enum InterpLoc {
2723 Default,
2724 Centroid,
2725 Offset,
2726 }
2727
2728 impl fmt::Display for InterpLoc {
2729 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2730 match self {
2731 InterpLoc::Default => Ok(()),
2732 InterpLoc::Centroid => write!(f, ".centroid"),
2733 InterpLoc::Offset => write!(f, ".offset"),
2734 }
2735 }
2736 }
2737
2738 #[repr(C)]
2739 #[derive(SrcsAsSlice, DstsAsSlice)]
2740 pub struct OpFAdd {
2741 #[dst_type(F32)]
2742 pub dst: Dst,
2743
2744 #[src_type(F32)]
2745 pub srcs: [Src; 2],
2746
2747 pub saturate: bool,
2748 pub rnd_mode: FRndMode,
2749 pub ftz: bool,
2750 }
2751
2752 impl DisplayOp for OpFAdd {
2753 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2754 let sat = if self.saturate { ".sat" } else { "" };
2755 write!(f, "fadd{sat}")?;
2756 if self.rnd_mode != FRndMode::NearestEven {
2757 write!(f, "{}", self.rnd_mode)?;
2758 }
2759 if self.ftz {
2760 write!(f, ".ftz")?;
2761 }
2762 write!(f, " {} {}", self.srcs[0], self.srcs[1],)
2763 }
2764 }
2765 impl_display_for_op!(OpFAdd);
2766
2767 #[repr(C)]
2768 #[derive(SrcsAsSlice, DstsAsSlice)]
2769 pub struct OpFFma {
2770 #[dst_type(F32)]
2771 pub dst: Dst,
2772
2773 #[src_type(F32)]
2774 pub srcs: [Src; 3],
2775
2776 pub saturate: bool,
2777 pub rnd_mode: FRndMode,
2778 pub ftz: bool,
2779 pub dnz: bool,
2780 }
2781
2782 impl DisplayOp for OpFFma {
2783 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2784 let sat = if self.saturate { ".sat" } else { "" };
2785 write!(f, "ffma{sat}")?;
2786 if self.rnd_mode != FRndMode::NearestEven {
2787 write!(f, "{}", self.rnd_mode)?;
2788 }
2789 if self.dnz {
2790 write!(f, ".dnz")?;
2791 } else if self.ftz {
2792 write!(f, ".ftz")?;
2793 }
2794 write!(f, " {} {} {}", self.srcs[0], self.srcs[1], self.srcs[2])
2795 }
2796 }
2797 impl_display_for_op!(OpFFma);
2798
2799 #[repr(C)]
2800 #[derive(SrcsAsSlice, DstsAsSlice)]
2801 pub struct OpFMnMx {
2802 #[dst_type(F32)]
2803 pub dst: Dst,
2804
2805 #[src_type(F32)]
2806 pub srcs: [Src; 2],
2807
2808 #[src_type(Pred)]
2809 pub min: Src,
2810
2811 pub ftz: bool,
2812 }
2813
2814 impl DisplayOp for OpFMnMx {
2815 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2816 let ftz = if self.ftz { ".ftz" } else { "" };
2817 write!(
2818 f,
2819 "fmnmx{ftz} {} {} {}",
2820 self.srcs[0], self.srcs[1], self.min
2821 )
2822 }
2823 }
2824 impl_display_for_op!(OpFMnMx);
2825
2826 #[repr(C)]
2827 #[derive(SrcsAsSlice, DstsAsSlice)]
2828 pub struct OpFMul {
2829 #[dst_type(F32)]
2830 pub dst: Dst,
2831
2832 #[src_type(F32)]
2833 pub srcs: [Src; 2],
2834
2835 pub saturate: bool,
2836 pub rnd_mode: FRndMode,
2837 pub ftz: bool,
2838 pub dnz: bool,
2839 }
2840
2841 impl DisplayOp for OpFMul {
2842 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2843 let sat = if self.saturate { ".sat" } else { "" };
2844 write!(f, "fmul{sat}")?;
2845 if self.rnd_mode != FRndMode::NearestEven {
2846 write!(f, "{}", self.rnd_mode)?;
2847 }
2848 if self.dnz {
2849 write!(f, ".dnz")?;
2850 } else if self.ftz {
2851 write!(f, ".ftz")?;
2852 }
2853 write!(f, " {} {}", self.srcs[0], self.srcs[1],)
2854 }
2855 }
2856 impl_display_for_op!(OpFMul);
2857
2858 #[repr(C)]
2859 #[derive(SrcsAsSlice, DstsAsSlice)]
2860 pub struct OpFSet {
2861 #[dst_type(F32)]
2862 pub dst: Dst,
2863
2864 pub cmp_op: FloatCmpOp,
2865
2866 #[src_type(F32)]
2867 pub srcs: [Src; 2],
2868
2869 pub ftz: bool,
2870 }
2871
2872 impl DisplayOp for OpFSet {
2873 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2874 let ftz = if self.ftz { ".ftz" } else { "" };
2875 write!(
2876 f,
2877 "fset{}{ftz} {} {}",
2878 self.cmp_op, self.srcs[0], self.srcs[1]
2879 )
2880 }
2881 }
2882 impl_display_for_op!(OpFSet);
2883
2884 #[repr(C)]
2885 #[derive(SrcsAsSlice, DstsAsSlice)]
2886 pub struct OpFSetP {
2887 #[dst_type(Pred)]
2888 pub dst: Dst,
2889
2890 pub set_op: PredSetOp,
2891 pub cmp_op: FloatCmpOp,
2892
2893 #[src_type(F32)]
2894 pub srcs: [Src; 2],
2895
2896 #[src_type(Pred)]
2897 pub accum: Src,
2898
2899 pub ftz: bool,
2900 }
2901
2902 impl DisplayOp for OpFSetP {
2903 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2904 let ftz = if self.ftz { ".ftz" } else { "" };
2905 write!(f, "fsetp{}{ftz}", self.cmp_op)?;
2906 if !self.set_op.is_trivial(&self.accum) {
2907 write!(f, "{}", self.set_op)?;
2908 }
2909 write!(f, " {} {}", self.srcs[0], self.srcs[1])?;
2910 if !self.set_op.is_trivial(&self.accum) {
2911 write!(f, " {}", self.accum)?;
2912 }
2913 Ok(())
2914 }
2915 }
2916 impl_display_for_op!(OpFSetP);
2917
2918 #[allow(dead_code)]
2919 #[derive(Clone, Copy, Eq, PartialEq)]
2920 pub enum FSwzAddOp {
2921 Add,
2922 SubRight,
2923 SubLeft,
2924 MoveLeft,
2925 }
2926
2927 impl fmt::Display for FSwzAddOp {
2928 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2929 match self {
2930 FSwzAddOp::Add => write!(f, "add"),
2931 FSwzAddOp::SubRight => write!(f, "subr"),
2932 FSwzAddOp::SubLeft => write!(f, "sub"),
2933 FSwzAddOp::MoveLeft => write!(f, "mov2"),
2934 }
2935 }
2936 }
2937
2938 #[repr(C)]
2939 #[derive(SrcsAsSlice, DstsAsSlice)]
2940 pub struct OpFSwzAdd {
2941 #[dst_type(F32)]
2942 pub dst: Dst,
2943
2944 #[src_type(GPR)]
2945 pub srcs: [Src; 2],
2946
2947 pub rnd_mode: FRndMode,
2948 pub ftz: bool,
2949 pub deriv_mode: TexDerivMode,
2950
2951 pub ops: [FSwzAddOp; 4],
2952 }
2953
2954 impl DisplayOp for OpFSwzAdd {
2955 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2956 write!(f, "fswzadd",)?;
2957 if self.rnd_mode != FRndMode::NearestEven {
2958 write!(f, "{}", self.rnd_mode)?;
2959 }
2960 if self.ftz {
2961 write!(f, ".ftz")?;
2962 }
2963 write!(f, "{}", self.deriv_mode)?;
2964 write!(
2965 f,
2966 " {} {} [{}, {}, {}, {}]",
2967 self.srcs[0],
2968 self.srcs[1],
2969 self.ops[0],
2970 self.ops[1],
2971 self.ops[2],
2972 self.ops[3],
2973 )
2974 }
2975 }
2976 impl_display_for_op!(OpFSwzAdd);
2977
2978 /// Describes where the second src is taken before doing the ops
2979 #[allow(dead_code)]
2980 #[derive(Clone, Copy, Eq, PartialEq)]
2981 pub enum FSwzShuffle {
2982 Quad0,
2983 Quad1,
2984 Quad2,
2985 Quad3,
2986 // swap [0, 1] and [2, 3]
2987 SwapHorizontal,
2988 // swap [0, 2] and [1, 3]
2989 SwapVertical,
2990 }
2991
2992 impl fmt::Display for FSwzShuffle {
2993 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2994 match self {
2995 FSwzShuffle::Quad0 => write!(f, ".0000"),
2996 FSwzShuffle::Quad1 => write!(f, ".1111"),
2997 FSwzShuffle::Quad2 => write!(f, ".2222"),
2998 FSwzShuffle::Quad3 => write!(f, ".3333"),
2999 FSwzShuffle::SwapHorizontal => write!(f, ".1032"),
3000 FSwzShuffle::SwapVertical => write!(f, ".2301"),
3001 }
3002 }
3003 }
3004
3005 /// Op only present in Kepler and older
3006 /// It first does a shuffle on the second src and then applies
3007 /// src0 op src1, each thread on a quad might do a different operation.
3008 ///
3009 /// This is used to encode ddx/ddy
3010 /// ex: ddx
3011 /// src1 = shuffle swap horizontal src1
3012 /// ops = [sub, subr, sub, subr]
3013 #[repr(C)]
3014 #[derive(SrcsAsSlice, DstsAsSlice)]
3015 pub struct OpFSwz {
3016 #[dst_type(F32)]
3017 pub dst: Dst,
3018
3019 #[src_type(GPR)]
3020 pub srcs: [Src; 2],
3021
3022 pub rnd_mode: FRndMode,
3023 pub ftz: bool,
3024 pub deriv_mode: TexDerivMode,
3025 pub shuffle: FSwzShuffle,
3026
3027 pub ops: [FSwzAddOp; 4],
3028 }
3029
3030 impl DisplayOp for OpFSwz {
3031 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3032 write!(f, "fswz{}", self.shuffle)?;
3033 if self.rnd_mode != FRndMode::NearestEven {
3034 write!(f, "{}", self.rnd_mode)?;
3035 }
3036 write!(f, "{}", self.deriv_mode)?;
3037 if self.ftz {
3038 write!(f, ".ftz")?;
3039 }
3040 write!(
3041 f,
3042 " {} {} [{}, {}, {}, {}]",
3043 self.srcs[0],
3044 self.srcs[1],
3045 self.ops[0],
3046 self.ops[1],
3047 self.ops[2],
3048 self.ops[3],
3049 )
3050 }
3051 }
3052 impl_display_for_op!(OpFSwz);
3053
3054 pub enum RroOp {
3055 SinCos,
3056 Exp2,
3057 }
3058
3059 impl fmt::Display for RroOp {
3060 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3061 match self {
3062 RroOp::SinCos => write!(f, ".sincos"),
3063 RroOp::Exp2 => write!(f, ".exp2"),
3064 }
3065 }
3066 }
3067
3068 /// MuFu range reduction operator
3069 ///
3070 /// Not available on SM70+
3071 #[repr(C)]
3072 #[derive(SrcsAsSlice, DstsAsSlice)]
3073 pub struct OpRro {
3074 #[dst_type(F32)]
3075 pub dst: Dst,
3076
3077 pub op: RroOp,
3078
3079 #[src_type(F32)]
3080 pub src: Src,
3081 }
3082
3083 impl DisplayOp for OpRro {
3084 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3085 write!(f, "rro{} {}", self.op, self.src)
3086 }
3087 }
3088 impl_display_for_op!(OpRro);
3089
3090 #[allow(dead_code)]
3091 #[derive(Clone, Copy, Eq, PartialEq)]
3092 pub enum MuFuOp {
3093 Cos,
3094 Sin,
3095 Exp2,
3096 Log2,
3097 Rcp,
3098 Rsq,
3099 Rcp64H,
3100 Rsq64H,
3101 Sqrt,
3102 Tanh,
3103 }
3104
3105 impl fmt::Display for MuFuOp {
3106 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3107 match self {
3108 MuFuOp::Cos => write!(f, "cos"),
3109 MuFuOp::Sin => write!(f, "sin"),
3110 MuFuOp::Exp2 => write!(f, "exp2"),
3111 MuFuOp::Log2 => write!(f, "log2"),
3112 MuFuOp::Rcp => write!(f, "rcp"),
3113 MuFuOp::Rsq => write!(f, "rsq"),
3114 MuFuOp::Rcp64H => write!(f, "rcp64h"),
3115 MuFuOp::Rsq64H => write!(f, "rsq64h"),
3116 MuFuOp::Sqrt => write!(f, "sqrt"),
3117 MuFuOp::Tanh => write!(f, "tanh"),
3118 }
3119 }
3120 }
3121
3122 #[repr(C)]
3123 #[derive(SrcsAsSlice, DstsAsSlice)]
3124 pub struct OpMuFu {
3125 #[dst_type(F32)]
3126 pub dst: Dst,
3127
3128 pub op: MuFuOp,
3129
3130 #[src_type(F32)]
3131 pub src: Src,
3132 }
3133
3134 impl DisplayOp for OpMuFu {
3135 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3136 write!(f, "mufu.{} {}", self.op, self.src)
3137 }
3138 }
3139 impl_display_for_op!(OpMuFu);
3140
3141 #[repr(C)]
3142 #[derive(SrcsAsSlice, DstsAsSlice)]
3143 pub struct OpDAdd {
3144 #[dst_type(F64)]
3145 pub dst: Dst,
3146
3147 #[src_type(F64)]
3148 pub srcs: [Src; 2],
3149
3150 pub rnd_mode: FRndMode,
3151 }
3152
3153 impl DisplayOp for OpDAdd {
3154 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3155 write!(f, "dadd")?;
3156 if self.rnd_mode != FRndMode::NearestEven {
3157 write!(f, "{}", self.rnd_mode)?;
3158 }
3159 write!(f, " {} {}", self.srcs[0], self.srcs[1],)
3160 }
3161 }
3162 impl_display_for_op!(OpDAdd);
3163
3164 #[repr(C)]
3165 #[derive(SrcsAsSlice, DstsAsSlice)]
3166 pub struct OpDMul {
3167 #[dst_type(F64)]
3168 pub dst: Dst,
3169
3170 #[src_type(F64)]
3171 pub srcs: [Src; 2],
3172
3173 pub rnd_mode: FRndMode,
3174 }
3175
3176 impl DisplayOp for OpDMul {
3177 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3178 write!(f, "dmul")?;
3179 if self.rnd_mode != FRndMode::NearestEven {
3180 write!(f, "{}", self.rnd_mode)?;
3181 }
3182 write!(f, " {} {}", self.srcs[0], self.srcs[1],)
3183 }
3184 }
3185 impl_display_for_op!(OpDMul);
3186
3187 #[repr(C)]
3188 #[derive(SrcsAsSlice, DstsAsSlice)]
3189 pub struct OpDFma {
3190 #[dst_type(F64)]
3191 pub dst: Dst,
3192
3193 #[src_type(F64)]
3194 pub srcs: [Src; 3],
3195
3196 pub rnd_mode: FRndMode,
3197 }
3198
3199 impl DisplayOp for OpDFma {
3200 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3201 write!(f, "dfma")?;
3202 if self.rnd_mode != FRndMode::NearestEven {
3203 write!(f, "{}", self.rnd_mode)?;
3204 }
3205 write!(f, " {} {} {}", self.srcs[0], self.srcs[1], self.srcs[2])
3206 }
3207 }
3208 impl_display_for_op!(OpDFma);
3209
3210 #[repr(C)]
3211 #[derive(SrcsAsSlice, DstsAsSlice)]
3212 pub struct OpDMnMx {
3213 #[dst_type(F64)]
3214 pub dst: Dst,
3215
3216 #[src_type(F64)]
3217 pub srcs: [Src; 2],
3218
3219 #[src_type(Pred)]
3220 pub min: Src,
3221 }
3222
3223 impl DisplayOp for OpDMnMx {
3224 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3225 write!(f, "dmnmx {} {} {}", self.srcs[0], self.srcs[1], self.min)
3226 }
3227 }
3228 impl_display_for_op!(OpDMnMx);
3229
3230 #[repr(C)]
3231 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
3232 pub struct OpDSetP {
3233 #[dst_type(Pred)]
3234 pub dst: Dst,
3235
3236 pub set_op: PredSetOp,
3237 pub cmp_op: FloatCmpOp,
3238
3239 #[src_type(F64)]
3240 pub srcs: [Src; 2],
3241
3242 #[src_type(Pred)]
3243 pub accum: Src,
3244 }
3245
3246 impl Foldable for OpDSetP {
3247 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
3248 let a = f.get_f64_src(self, &self.srcs[0]);
3249 let b = f.get_f64_src(self, &self.srcs[1]);
3250 let accum = f.get_pred_src(self, &self.accum);
3251
3252 let ordered = !a.is_nan() && !b.is_nan();
3253 let cmp_res = match self.cmp_op {
3254 FloatCmpOp::OrdEq => ordered && a == b,
3255 FloatCmpOp::OrdNe => ordered && a != b,
3256 FloatCmpOp::OrdLt => ordered && a < b,
3257 FloatCmpOp::OrdLe => ordered && a <= b,
3258 FloatCmpOp::OrdGt => ordered && a > b,
3259 FloatCmpOp::OrdGe => ordered && a >= b,
3260 FloatCmpOp::UnordEq => !ordered || a == b,
3261 FloatCmpOp::UnordNe => !ordered || a != b,
3262 FloatCmpOp::UnordLt => !ordered || a < b,
3263 FloatCmpOp::UnordLe => !ordered || a <= b,
3264 FloatCmpOp::UnordGt => !ordered || a > b,
3265 FloatCmpOp::UnordGe => !ordered || a >= b,
3266 FloatCmpOp::IsNum => ordered,
3267 FloatCmpOp::IsNan => !ordered,
3268 };
3269 let res = self.set_op.eval(cmp_res, accum);
3270
3271 f.set_pred_dst(self, &self.dst, res);
3272 }
3273 }
3274
3275 impl DisplayOp for OpDSetP {
3276 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3277 write!(f, "dsetp{}", self.cmp_op)?;
3278 if !self.set_op.is_trivial(&self.accum) {
3279 write!(f, "{}", self.set_op)?;
3280 }
3281 write!(f, " {} {}", self.srcs[0], self.srcs[1])?;
3282 if !self.set_op.is_trivial(&self.accum) {
3283 write!(f, " {}", self.accum)?;
3284 }
3285 Ok(())
3286 }
3287 }
3288 impl_display_for_op!(OpDSetP);
3289
3290 #[repr(C)]
3291 #[derive(SrcsAsSlice, DstsAsSlice)]
3292 pub struct OpHAdd2 {
3293 #[dst_type(F16v2)]
3294 pub dst: Dst,
3295
3296 #[src_type(F16v2)]
3297 pub srcs: [Src; 2],
3298
3299 pub saturate: bool,
3300 pub ftz: bool,
3301 pub f32: bool,
3302 }
3303
3304 impl DisplayOp for OpHAdd2 {
3305 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3306 let sat = if self.saturate { ".sat" } else { "" };
3307 let f32 = if self.f32 { ".f32" } else { "" };
3308 write!(f, "hadd2{sat}{f32}")?;
3309 if self.ftz {
3310 write!(f, ".ftz")?;
3311 }
3312 write!(f, " {} {}", self.srcs[0], self.srcs[1])
3313 }
3314 }
3315 impl_display_for_op!(OpHAdd2);
3316
3317 #[repr(C)]
3318 #[derive(SrcsAsSlice, DstsAsSlice)]
3319 pub struct OpHSet2 {
3320 #[dst_type(F16v2)]
3321 pub dst: Dst,
3322
3323 pub set_op: PredSetOp,
3324 pub cmp_op: FloatCmpOp,
3325
3326 #[src_type(F16v2)]
3327 pub srcs: [Src; 2],
3328
3329 #[src_type(Pred)]
3330 pub accum: Src,
3331
3332 pub ftz: bool,
3333 }
3334
3335 impl DisplayOp for OpHSet2 {
3336 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3337 let ftz = if self.ftz { ".ftz" } else { "" };
3338 write!(f, "hset2{}{ftz}", self.cmp_op)?;
3339 if !self.set_op.is_trivial(&self.accum) {
3340 write!(f, "{}", self.set_op)?;
3341 }
3342 write!(f, " {} {}", self.srcs[0], self.srcs[1])?;
3343 if !self.set_op.is_trivial(&self.accum) {
3344 write!(f, " {}", self.accum)?;
3345 }
3346 Ok(())
3347 }
3348 }
3349 impl_display_for_op!(OpHSet2);
3350
3351 #[repr(C)]
3352 #[derive(SrcsAsSlice, DstsAsSlice)]
3353 pub struct OpHSetP2 {
3354 #[dst_type(Pred)]
3355 pub dsts: [Dst; 2],
3356
3357 pub set_op: PredSetOp,
3358 pub cmp_op: FloatCmpOp,
3359
3360 #[src_type(F16v2)]
3361 pub srcs: [Src; 2],
3362
3363 #[src_type(Pred)]
3364 pub accum: Src,
3365
3366 pub ftz: bool,
3367
3368 // When not set, each dsts get the result of each lanes.
3369 // When set, the first dst gets the result of both lanes (res0 && res1)
3370 // and the second dst gets the negation !(res0 && res1)
3371 // before applying the accumulator.
3372 pub horizontal: bool,
3373 }
3374
3375 impl DisplayOp for OpHSetP2 {
3376 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3377 let ftz = if self.ftz { ".ftz" } else { "" };
3378 write!(f, "hsetp2{}{ftz}", self.cmp_op)?;
3379 if !self.set_op.is_trivial(&self.accum) {
3380 write!(f, "{}", self.set_op)?;
3381 }
3382 write!(f, " {} {}", self.srcs[0], self.srcs[1])?;
3383 if !self.set_op.is_trivial(&self.accum) {
3384 write!(f, " {}", self.accum)?;
3385 }
3386 Ok(())
3387 }
3388 }
3389 impl_display_for_op!(OpHSetP2);
3390
3391 #[repr(C)]
3392 #[derive(SrcsAsSlice, DstsAsSlice)]
3393 pub struct OpHMul2 {
3394 #[dst_type(F16v2)]
3395 pub dst: Dst,
3396
3397 #[src_type(F16v2)]
3398 pub srcs: [Src; 2],
3399
3400 pub saturate: bool,
3401 pub ftz: bool,
3402 pub dnz: bool,
3403 }
3404
3405 impl DisplayOp for OpHMul2 {
3406 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3407 let sat = if self.saturate { ".sat" } else { "" };
3408 write!(f, "hmul2{sat}")?;
3409 if self.dnz {
3410 write!(f, ".dnz")?;
3411 } else if self.ftz {
3412 write!(f, ".ftz")?;
3413 }
3414 write!(f, " {} {}", self.srcs[0], self.srcs[1])
3415 }
3416 }
3417 impl_display_for_op!(OpHMul2);
3418
3419 #[derive(Clone, Copy, Eq, PartialEq)]
3420 #[allow(dead_code)]
3421 pub enum ImmaSize {
3422 M8N8K16,
3423 M8N8K32,
3424 M16N8K16,
3425 M16N8K32,
3426 M16N8K64,
3427 }
3428
3429 impl fmt::Display for ImmaSize {
3430 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3431 match self {
3432 ImmaSize::M8N8K16 => write!(f, ".m8n8k16"),
3433 ImmaSize::M8N8K32 => write!(f, ".m8n8k32"),
3434 ImmaSize::M16N8K16 => write!(f, ".m16n8k16"),
3435 ImmaSize::M16N8K32 => write!(f, ".m16n8k32"),
3436 ImmaSize::M16N8K64 => write!(f, ".m16n8k64"),
3437 }
3438 }
3439 }
3440
3441 #[repr(C)]
3442 #[derive(SrcsAsSlice, DstsAsSlice)]
3443 pub struct OpImma {
3444 #[dst_type(Vec)]
3445 pub dst: Dst,
3446
3447 pub mat_size: ImmaSize,
3448 pub src_types: [IntType; 2],
3449 pub saturate: bool,
3450
3451 #[src_type(SSA)]
3452 pub srcs: [Src; 3],
3453 }
3454
3455 impl DisplayOp for OpImma {
3456 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3457 let sat = if self.saturate { ".sat" } else { "" };
3458 write!(
3459 f,
3460 "imma{}{}{}{sat} {} {} {}",
3461 self.mat_size,
3462 self.src_types[0],
3463 self.src_types[1],
3464 self.srcs[0],
3465 self.srcs[1],
3466 self.srcs[2],
3467 )
3468 }
3469 }
3470
3471 impl_display_for_op!(OpImma);
3472
3473 #[derive(Clone, Copy, Eq, PartialEq)]
3474 pub enum HmmaSize {
3475 M16N8K16,
3476 M16N8K8,
3477 M16N8K4,
3478 }
3479
3480 impl fmt::Display for HmmaSize {
3481 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3482 match self {
3483 HmmaSize::M16N8K16 => write!(f, ".m16n8k16"),
3484 HmmaSize::M16N8K8 => write!(f, ".m16n8k8"),
3485 HmmaSize::M16N8K4 => write!(f, ".m16n8k4"),
3486 }
3487 }
3488 }
3489
3490 #[repr(C)]
3491 #[derive(SrcsAsSlice, DstsAsSlice)]
3492 pub struct OpHmma {
3493 #[dst_type(Vec)]
3494 pub dst: Dst,
3495
3496 pub mat_size: HmmaSize,
3497 pub src_type: FloatType,
3498 pub dst_type: FloatType,
3499
3500 #[src_type(SSA)]
3501 pub srcs: [Src; 3],
3502 }
3503
3504 impl DisplayOp for OpHmma {
3505 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3506 write!(
3507 f,
3508 "hmma{}{} {} {} {}",
3509 self.mat_size,
3510 self.dst_type,
3511 self.srcs[0],
3512 self.srcs[1],
3513 self.srcs[2],
3514 )
3515 }
3516 }
3517
3518 impl_display_for_op!(OpHmma);
3519
3520 #[repr(C)]
3521 #[derive(SrcsAsSlice, DstsAsSlice)]
3522 pub struct OpHFma2 {
3523 #[dst_type(F16v2)]
3524 pub dst: Dst,
3525
3526 #[src_type(F16v2)]
3527 pub srcs: [Src; 3],
3528
3529 pub saturate: bool,
3530 pub ftz: bool,
3531 pub dnz: bool,
3532 pub f32: bool,
3533 }
3534
3535 impl DisplayOp for OpHFma2 {
3536 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3537 let sat = if self.saturate { ".sat" } else { "" };
3538 let f32 = if self.f32 { ".f32" } else { "" };
3539 write!(f, "hfma2{sat}{f32}")?;
3540 if self.dnz {
3541 write!(f, ".dnz")?;
3542 } else if self.ftz {
3543 write!(f, ".ftz")?;
3544 }
3545 write!(f, " {} {} {}", self.srcs[0], self.srcs[1], self.srcs[2])
3546 }
3547 }
3548 impl_display_for_op!(OpHFma2);
3549
3550 #[repr(C)]
3551 #[derive(SrcsAsSlice, DstsAsSlice)]
3552 pub struct OpHMnMx2 {
3553 #[dst_type(F16v2)]
3554 pub dst: Dst,
3555
3556 #[src_type(F16v2)]
3557 pub srcs: [Src; 2],
3558
3559 #[src_type(Pred)]
3560 pub min: Src,
3561
3562 pub ftz: bool,
3563 }
3564
3565 impl DisplayOp for OpHMnMx2 {
3566 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3567 let ftz = if self.ftz { ".ftz" } else { "" };
3568 write!(
3569 f,
3570 "hmnmx2{ftz} {} {} {}",
3571 self.srcs[0], self.srcs[1], self.min
3572 )
3573 }
3574 }
3575 impl_display_for_op!(OpHMnMx2);
3576
3577 #[repr(C)]
3578 #[derive(SrcsAsSlice, DstsAsSlice)]
3579 pub struct OpBMsk {
3580 #[dst_type(GPR)]
3581 pub dst: Dst,
3582
3583 #[src_type(ALU)]
3584 pub pos: Src,
3585
3586 #[src_type(ALU)]
3587 pub width: Src,
3588
3589 pub wrap: bool,
3590 }
3591
3592 impl DisplayOp for OpBMsk {
3593 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3594 let wrap = if self.wrap { ".wrap" } else { ".clamp" };
3595 write!(f, "bmsk{} {} {}", wrap, self.pos, self.width)
3596 }
3597 }
3598 impl_display_for_op!(OpBMsk);
3599
3600 #[repr(C)]
3601 #[derive(SrcsAsSlice, DstsAsSlice)]
3602 pub struct OpBRev {
3603 #[dst_type(GPR)]
3604 pub dst: Dst,
3605
3606 #[src_type(ALU)]
3607 pub src: Src,
3608 }
3609
3610 impl DisplayOp for OpBRev {
3611 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3612 write!(f, "brev {}", self.src)
3613 }
3614 }
3615 impl_display_for_op!(OpBRev);
3616
3617 /// Bitfield extract. Extracts all bits from `base` starting at `offset` into
3618 /// `dst`.
3619 #[repr(C)]
3620 #[derive(SrcsAsSlice, DstsAsSlice)]
3621 pub struct OpBfe {
3622 /// Where to insert the bits.
3623 #[dst_type(GPR)]
3624 pub dst: Dst,
3625
3626 /// The source of bits to extract.
3627 #[src_type(ALU)]
3628 pub base: Src,
3629
3630 /// The range of bits to extract. This source is interpreted as four
3631 /// separate bytes, [b0, b1, b2, b3].
3632 ///
3633 /// b0 and b1: unused
3634 /// b2: the number of bits to extract.
3635 /// b3: the offset of the first bit to extract.
3636 ///
3637 /// This matches the way the hardware works.
3638 #[src_type(ALU)]
3639 pub range: Src,
3640
3641 /// Whether the output is signed
3642 pub signed: bool,
3643
3644 /// Whether to reverse the bits before inserting them into `dst`.
3645 pub reverse: bool,
3646 }
3647
3648 impl DisplayOp for OpBfe {
3649 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3650 write!(f, "bfe")?;
3651 if self.signed {
3652 write!(f, ".s")?;
3653 }
3654 if self.reverse {
3655 write!(f, ".rev")?;
3656 }
3657 write!(f, " {} {}", self.base, self.range,)
3658 }
3659 }
3660 impl_display_for_op!(OpBfe);
3661
3662 #[repr(C)]
3663 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
3664 pub struct OpFlo {
3665 #[dst_type(GPR)]
3666 pub dst: Dst,
3667
3668 #[src_type(ALU)]
3669 pub src: Src,
3670
3671 pub signed: bool,
3672 pub return_shift_amount: bool,
3673 }
3674
3675 impl Foldable for OpFlo {
3676 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
3677 let src = f.get_u32_src(self, &self.src);
3678 let leading = if self.signed && (src & 0x80000000) != 0 {
3679 (!src).leading_zeros()
3680 } else {
3681 src.leading_zeros()
3682 };
3683 let dst = if self.return_shift_amount {
3684 leading
3685 } else {
3686 31 - leading
3687 };
3688 f.set_u32_dst(self, &self.dst, dst);
3689 }
3690 }
3691
3692 impl DisplayOp for OpFlo {
3693 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3694 write!(f, "flo")?;
3695 if self.return_shift_amount {
3696 write!(f, ".samt")?;
3697 }
3698 write!(f, " {}", self.src)
3699 }
3700 }
3701 impl_display_for_op!(OpFlo);
3702
3703 #[repr(C)]
3704 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
3705 pub struct OpIAbs {
3706 #[dst_type(GPR)]
3707 pub dst: Dst,
3708
3709 #[src_type(ALU)]
3710 pub src: Src,
3711 }
3712
3713 impl Foldable for OpIAbs {
3714 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
3715 let src = f.get_u32_src(self, &self.src);
3716 let dst = (src as i32).unsigned_abs();
3717 f.set_u32_dst(self, &self.dst, dst);
3718 }
3719 }
3720
3721 impl DisplayOp for OpIAbs {
3722 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3723 write!(f, "iabs {}", self.src)
3724 }
3725 }
3726 impl_display_for_op!(OpIAbs);
3727
3728 /// Only used on SM50
3729 #[repr(C)]
3730 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
3731 pub struct OpIAdd2 {
3732 #[dst_type(GPR)]
3733 pub dst: Dst,
3734 #[dst_type(Carry)]
3735 pub carry_out: Dst,
3736
3737 #[src_type(I32)]
3738 pub srcs: [Src; 2],
3739 }
3740
3741 impl Foldable for OpIAdd2 {
3742 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
3743 let srcs = [
3744 f.get_u32_src(self, &self.srcs[0]),
3745 f.get_u32_src(self, &self.srcs[1]),
3746 ];
3747
3748 let mut sum = 0_u64;
3749 for i in 0..2 {
3750 if self.srcs[i].src_mod.is_ineg() {
3751 // This is a very literal interpretation of 2's compliment.
3752 // This is not -u64::from(src) or u64::from(-src).
3753 sum += u64::from(!srcs[i]) + 1;
3754 } else {
3755 sum += u64::from(srcs[i]);
3756 }
3757 }
3758
3759 f.set_u32_dst(self, &self.dst, sum as u32);
3760 f.set_carry_dst(self, &self.carry_out, sum >= (1 << 32));
3761 }
3762 }
3763
3764 impl DisplayOp for OpIAdd2 {
3765 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3766 write!(f, "iadd2 {} {}", self.srcs[0], self.srcs[1])
3767 }
3768 }
3769
3770 /// Only used on SM50
3771 #[repr(C)]
3772 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
3773 pub struct OpIAdd2X {
3774 #[dst_type(GPR)]
3775 pub dst: Dst,
3776 #[dst_type(Carry)]
3777 pub carry_out: Dst,
3778
3779 #[src_type(B32)]
3780 pub srcs: [Src; 2],
3781 #[src_type(Carry)]
3782 pub carry_in: Src,
3783 }
3784
3785 impl Foldable for OpIAdd2X {
3786 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
3787 let srcs = [
3788 f.get_u32_bnot_src(self, &self.srcs[0]),
3789 f.get_u32_bnot_src(self, &self.srcs[1]),
3790 ];
3791 let carry_in = f.get_carry_src(self, &self.carry_in);
3792
3793 let sum = u64::from(srcs[0]) + u64::from(srcs[1]) + u64::from(carry_in);
3794
3795 f.set_u32_dst(self, &self.dst, sum as u32);
3796 f.set_carry_dst(self, &self.carry_out, sum >= (1 << 32));
3797 }
3798 }
3799
3800 impl DisplayOp for OpIAdd2X {
3801 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3802 write!(f, "iadd2.x {} {}", self.srcs[0], self.srcs[1])?;
3803 if !self.carry_in.is_zero() {
3804 write!(f, " {}", self.carry_in)?;
3805 }
3806 Ok(())
3807 }
3808 }
3809
3810 #[repr(C)]
3811 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
3812 pub struct OpIAdd3 {
3813 #[dst_type(GPR)]
3814 pub dst: Dst,
3815
3816 #[dst_type(Pred)]
3817 pub overflow: [Dst; 2],
3818
3819 #[src_type(I32)]
3820 pub srcs: [Src; 3],
3821 }
3822
3823 impl Foldable for OpIAdd3 {
3824 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
3825 let srcs = [
3826 f.get_u32_src(self, &self.srcs[0]),
3827 f.get_u32_src(self, &self.srcs[1]),
3828 f.get_u32_src(self, &self.srcs[2]),
3829 ];
3830
3831 let mut sum = 0_u64;
3832 for i in 0..3 {
3833 if self.srcs[i].src_mod.is_ineg() {
3834 // This is a very literal interpretation of 2's compliment.
3835 // This is not -u64::from(src) or u64::from(-src).
3836 sum += u64::from(!srcs[i]) + 1;
3837 } else {
3838 sum += u64::from(srcs[i]);
3839 }
3840 }
3841
3842 f.set_u32_dst(self, &self.dst, sum as u32);
3843 f.set_pred_dst(self, &self.overflow[0], sum >= 1_u64 << 32);
3844 f.set_pred_dst(self, &self.overflow[1], sum >= 2_u64 << 32);
3845 }
3846 }
3847
3848 impl DisplayOp for OpIAdd3 {
3849 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3850 write!(
3851 f,
3852 "iadd3 {} {} {}",
3853 self.srcs[0], self.srcs[1], self.srcs[2],
3854 )
3855 }
3856 }
3857 impl_display_for_op!(OpIAdd3);
3858
3859 #[repr(C)]
3860 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
3861 pub struct OpIAdd3X {
3862 #[dst_type(GPR)]
3863 pub dst: Dst,
3864
3865 #[dst_type(Pred)]
3866 pub overflow: [Dst; 2],
3867
3868 #[src_type(B32)]
3869 pub srcs: [Src; 3],
3870
3871 #[src_type(Pred)]
3872 pub carry: [Src; 2],
3873 }
3874
3875 impl Foldable for OpIAdd3X {
3876 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
3877 let srcs = [
3878 f.get_u32_bnot_src(self, &self.srcs[0]),
3879 f.get_u32_bnot_src(self, &self.srcs[1]),
3880 f.get_u32_bnot_src(self, &self.srcs[2]),
3881 ];
3882 let carry = [
3883 f.get_pred_src(self, &self.carry[0]),
3884 f.get_pred_src(self, &self.carry[1]),
3885 ];
3886
3887 let mut sum = 0_u64;
3888 for i in 0..3 {
3889 sum += u64::from(srcs[i]);
3890 }
3891
3892 for i in 0..2 {
3893 sum += u64::from(carry[i]);
3894 }
3895
3896 f.set_u32_dst(self, &self.dst, sum as u32);
3897 f.set_pred_dst(self, &self.overflow[0], sum >= 1_u64 << 32);
3898 f.set_pred_dst(self, &self.overflow[1], sum >= 2_u64 << 32);
3899 }
3900 }
3901
3902 impl DisplayOp for OpIAdd3X {
3903 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3904 write!(
3905 f,
3906 "iadd3.x {} {} {} {} {}",
3907 self.srcs[0],
3908 self.srcs[1],
3909 self.srcs[2],
3910 self.carry[0],
3911 self.carry[1]
3912 )
3913 }
3914 }
3915 impl_display_for_op!(OpIAdd3X);
3916
3917 #[repr(C)]
3918 #[derive(SrcsAsSlice, DstsAsSlice)]
3919 pub struct OpIDp4 {
3920 #[dst_type(GPR)]
3921 pub dst: Dst,
3922
3923 pub src_types: [IntType; 2],
3924
3925 #[src_type(I32)]
3926 pub srcs: [Src; 3],
3927 }
3928
3929 impl DisplayOp for OpIDp4 {
3930 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3931 write!(
3932 f,
3933 "idp4{}{} {} {} {}",
3934 self.src_types[0],
3935 self.src_types[1],
3936 self.srcs[0],
3937 self.srcs[1],
3938 self.srcs[2],
3939 )
3940 }
3941 }
3942 impl_display_for_op!(OpIDp4);
3943
3944 #[repr(C)]
3945 #[derive(SrcsAsSlice, DstsAsSlice)]
3946 pub struct OpIMad {
3947 #[dst_type(GPR)]
3948 pub dst: Dst,
3949
3950 #[src_type(ALU)]
3951 pub srcs: [Src; 3],
3952
3953 pub signed: bool,
3954 }
3955
3956 impl DisplayOp for OpIMad {
3957 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3958 write!(f, "imad {} {} {}", self.srcs[0], self.srcs[1], self.srcs[2],)
3959 }
3960 }
3961 impl_display_for_op!(OpIMad);
3962
3963 /// Only used on SM50
3964 #[repr(C)]
3965 #[derive(SrcsAsSlice, DstsAsSlice)]
3966 pub struct OpIMul {
3967 #[dst_type(GPR)]
3968 pub dst: Dst,
3969
3970 #[src_type(ALU)]
3971 pub srcs: [Src; 2],
3972
3973 pub signed: [bool; 2],
3974 pub high: bool,
3975 }
3976
3977 impl DisplayOp for OpIMul {
3978 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3979 write!(f, "imul")?;
3980 if self.high {
3981 write!(f, ".hi")?;
3982 }
3983 let src_type = |signed| if signed { ".s32" } else { ".u32" };
3984 write!(
3985 f,
3986 "{}{}",
3987 src_type(self.signed[0]),
3988 src_type(self.signed[1])
3989 )?;
3990 write!(f, " {} {}", self.srcs[0], self.srcs[1])
3991 }
3992 }
3993
3994 #[repr(C)]
3995 #[derive(SrcsAsSlice, DstsAsSlice)]
3996 pub struct OpIMad64 {
3997 #[dst_type(Vec)]
3998 pub dst: Dst,
3999
4000 #[src_type(ALU)]
4001 pub srcs: [Src; 3],
4002
4003 pub signed: bool,
4004 }
4005
4006 impl DisplayOp for OpIMad64 {
4007 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4008 write!(
4009 f,
4010 "imad64 {} {} {}",
4011 self.srcs[0], self.srcs[1], self.srcs[2],
4012 )
4013 }
4014 }
4015 impl_display_for_op!(OpIMad64);
4016
4017 #[repr(C)]
4018 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
4019 pub struct OpIMnMx {
4020 #[dst_type(GPR)]
4021 pub dst: Dst,
4022
4023 pub cmp_type: IntCmpType,
4024
4025 #[src_type(ALU)]
4026 pub srcs: [Src; 2],
4027
4028 #[src_type(Pred)]
4029 pub min: Src,
4030 }
4031
4032 impl Foldable for OpIMnMx {
4033 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
4034 let (a, b) = (
4035 f.get_u32_bnot_src(self, &self.srcs[0]),
4036 f.get_u32_bnot_src(self, &self.srcs[1]),
4037 );
4038 let min = f.get_pred_src(self, &self.min);
4039
4040 let res = match (min, self.cmp_type) {
4041 (true, IntCmpType::U32) => a.min(b),
4042 (true, IntCmpType::I32) => (a as i32).min(b as i32) as u32,
4043 (false, IntCmpType::U32) => a.max(b),
4044 (false, IntCmpType::I32) => (a as i32).max(b as i32) as u32,
4045 };
4046
4047 f.set_u32_dst(self, &self.dst, res);
4048 }
4049 }
4050
4051 impl DisplayOp for OpIMnMx {
4052 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4053 write!(
4054 f,
4055 "imnmx{} {} {} {}",
4056 self.cmp_type, self.srcs[0], self.srcs[1], self.min
4057 )
4058 }
4059 }
4060 impl_display_for_op!(OpIMnMx);
4061
4062 #[repr(C)]
4063 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
4064 pub struct OpISetP {
4065 #[dst_type(Pred)]
4066 pub dst: Dst,
4067
4068 pub set_op: PredSetOp,
4069 pub cmp_op: IntCmpOp,
4070 pub cmp_type: IntCmpType,
4071 pub ex: bool,
4072
4073 #[src_type(ALU)]
4074 pub srcs: [Src; 2],
4075
4076 #[src_type(Pred)]
4077 pub accum: Src,
4078
4079 #[src_type(Pred)]
4080 pub low_cmp: Src,
4081 }
4082
4083 impl Foldable for OpISetP {
4084 fn fold(&self, sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
4085 let x = f.get_u32_src(self, &self.srcs[0]);
4086 let y = f.get_u32_src(self, &self.srcs[1]);
4087 let accum = f.get_pred_src(self, &self.accum);
4088 let low_cmp = f.get_pred_src(self, &self.low_cmp);
4089
4090 let cmp = if self.cmp_type.is_signed() {
4091 let x = x as i32;
4092 let y = y as i32;
4093 match &self.cmp_op {
4094 IntCmpOp::False => false,
4095 IntCmpOp::True => true,
4096 IntCmpOp::Eq => x == y,
4097 IntCmpOp::Ne => x != y,
4098 IntCmpOp::Lt => x < y,
4099 IntCmpOp::Le => x <= y,
4100 IntCmpOp::Gt => x > y,
4101 IntCmpOp::Ge => x >= y,
4102 }
4103 } else {
4104 match &self.cmp_op {
4105 IntCmpOp::False => false,
4106 IntCmpOp::True => true,
4107 IntCmpOp::Eq => x == y,
4108 IntCmpOp::Ne => x != y,
4109 IntCmpOp::Lt => x < y,
4110 IntCmpOp::Le => x <= y,
4111 IntCmpOp::Gt => x > y,
4112 IntCmpOp::Ge => x >= y,
4113 }
4114 };
4115
4116 let cmp_op_is_const =
4117 matches!(self.cmp_op, IntCmpOp::False | IntCmpOp::True);
4118 let cmp = if self.ex && x == y && !cmp_op_is_const {
4119 // Pre-Volta, isetp.x takes the accumulator into account. If we
4120 // want to support this, we need to take an an accumulator into
4121 // account. Disallow it for now.
4122 assert!(sm.sm() >= 70);
4123 low_cmp
4124 } else {
4125 cmp
4126 };
4127
4128 let dst = self.set_op.eval(cmp, accum);
4129
4130 f.set_pred_dst(self, &self.dst, dst);
4131 }
4132 }
4133
4134 impl DisplayOp for OpISetP {
4135 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4136 write!(f, "isetp{}{}", self.cmp_op, self.cmp_type)?;
4137 if !self.set_op.is_trivial(&self.accum) {
4138 write!(f, "{}", self.set_op)?;
4139 }
4140 if self.ex {
4141 write!(f, ".ex")?;
4142 }
4143 write!(f, " {} {}", self.srcs[0], self.srcs[1])?;
4144 if !self.set_op.is_trivial(&self.accum) {
4145 write!(f, " {}", self.accum)?;
4146 }
4147 if self.ex {
4148 write!(f, " {}", self.low_cmp)?;
4149 }
4150 Ok(())
4151 }
4152 }
4153 impl_display_for_op!(OpISetP);
4154
4155 #[repr(C)]
4156 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
4157 pub struct OpLea {
4158 #[dst_type(GPR)]
4159 pub dst: Dst,
4160
4161 #[dst_type(Pred)]
4162 pub overflow: Dst,
4163
4164 #[src_type(ALU)]
4165 pub a: Src,
4166
4167 #[src_type(I32)]
4168 pub b: Src,
4169
4170 #[src_type(ALU)]
4171 pub a_high: Src, // High 32-bits of a if .dst_high is set
4172
4173 pub shift: u8,
4174 pub dst_high: bool,
4175 pub intermediate_mod: SrcMod, // Modifier for shifted temporary (a << shift)
4176 }
4177
4178 impl Foldable for OpLea {
4179 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
4180 let a = f.get_u32_src(self, &self.a);
4181 let mut b = f.get_u32_src(self, &self.b);
4182 let a_high = f.get_u32_src(self, &self.a_high);
4183
4184 let mut overflow = false;
4185
4186 let mut shift_result = if self.dst_high {
4187 let a = a as u64;
4188 let a_high = a_high as u64;
4189 let a = (a_high << 32) | a;
4190
4191 (a >> (32 - self.shift)) as u32
4192 } else {
4193 a << self.shift
4194 };
4195
4196 if self.intermediate_mod.is_ineg() {
4197 let o;
4198 (shift_result, o) = u32::overflowing_add(!shift_result, 1);
4199 overflow |= o;
4200 }
4201
4202 if self.b.src_mod.is_ineg() {
4203 let o;
4204 (b, o) = u32::overflowing_add(!b, 1);
4205 overflow |= o;
4206 }
4207
4208 let (dst, o) = u32::overflowing_add(shift_result, b);
4209 overflow |= o;
4210
4211 f.set_u32_dst(self, &self.dst, dst);
4212 f.set_pred_dst(self, &self.overflow, overflow);
4213 }
4214 }
4215
4216 impl DisplayOp for OpLea {
4217 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4218 write!(f, "lea")?;
4219 if self.dst_high {
4220 write!(f, ".hi")?;
4221 }
4222 write!(f, " {} {} {}", self.a, self.shift, self.b)?;
4223 if self.dst_high {
4224 write!(f, " {}", self.a_high)?;
4225 }
4226 Ok(())
4227 }
4228 }
4229 impl_display_for_op!(OpLea);
4230
4231 #[repr(C)]
4232 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
4233 pub struct OpLeaX {
4234 #[dst_type(GPR)]
4235 pub dst: Dst,
4236
4237 #[dst_type(Pred)]
4238 pub overflow: Dst,
4239
4240 #[src_type(ALU)]
4241 pub a: Src,
4242
4243 #[src_type(B32)]
4244 pub b: Src,
4245
4246 #[src_type(ALU)]
4247 pub a_high: Src, // High 32-bits of a if .dst_high is set
4248
4249 #[src_type(Pred)]
4250 pub carry: Src,
4251
4252 pub shift: u8,
4253 pub dst_high: bool,
4254 pub intermediate_mod: SrcMod, // Modifier for shifted temporary (a << shift)
4255 }
4256
4257 impl Foldable for OpLeaX {
4258 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
4259 let a = f.get_u32_src(self, &self.a);
4260 let mut b = f.get_u32_src(self, &self.b);
4261 let a_high = f.get_u32_src(self, &self.a_high);
4262 let carry = f.get_pred_src(self, &self.carry);
4263
4264 let mut overflow = false;
4265
4266 let mut shift_result = if self.dst_high {
4267 let a = a as u64;
4268 let a_high = a_high as u64;
4269 let a = (a_high << 32) | a;
4270
4271 (a >> (32 - self.shift)) as u32
4272 } else {
4273 a << self.shift
4274 };
4275
4276 if self.intermediate_mod.is_bnot() {
4277 shift_result = !shift_result;
4278 }
4279
4280 if self.b.src_mod.is_bnot() {
4281 b = !b;
4282 }
4283
4284 let (dst, o) = u32::overflowing_add(shift_result, b);
4285 overflow |= o;
4286
4287 let (dst, o) = u32::overflowing_add(dst, if carry { 1 } else { 0 });
4288 overflow |= o;
4289
4290 f.set_u32_dst(self, &self.dst, dst);
4291 f.set_pred_dst(self, &self.overflow, overflow);
4292 }
4293 }
4294
4295 impl DisplayOp for OpLeaX {
4296 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4297 write!(f, "lea.x")?;
4298 if self.dst_high {
4299 write!(f, ".hi")?;
4300 }
4301 write!(f, " {} {} {}", self.a, self.shift, self.b)?;
4302 if self.dst_high {
4303 write!(f, " {}", self.a_high)?;
4304 }
4305 write!(f, " {}", self.carry)?;
4306 Ok(())
4307 }
4308 }
4309 impl_display_for_op!(OpLeaX);
4310
4311 #[repr(C)]
4312 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
4313 pub struct OpLop2 {
4314 #[dst_type(GPR)]
4315 pub dst: Dst,
4316
4317 #[src_type(B32)]
4318 pub srcs: [Src; 2],
4319
4320 pub op: LogicOp2,
4321 }
4322
4323 impl DisplayOp for OpLop2 {
4324 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4325 write!(f, "lop2.{} {} {}", self.op, self.srcs[0], self.srcs[1],)
4326 }
4327 }
4328
4329 impl Foldable for OpLop2 {
4330 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
4331 let srcs = [
4332 f.get_u32_bnot_src(self, &self.srcs[0]),
4333 f.get_u32_bnot_src(self, &self.srcs[1]),
4334 ];
4335 let dst = match self.op {
4336 LogicOp2::And => srcs[0] & srcs[1],
4337 LogicOp2::Or => srcs[0] | srcs[1],
4338 LogicOp2::Xor => srcs[0] ^ srcs[1],
4339 LogicOp2::PassB => srcs[1],
4340 };
4341 f.set_u32_dst(self, &self.dst, dst);
4342 }
4343 }
4344
4345 #[repr(C)]
4346 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
4347 pub struct OpLop3 {
4348 #[dst_type(GPR)]
4349 pub dst: Dst,
4350
4351 #[src_type(ALU)]
4352 pub srcs: [Src; 3],
4353
4354 pub op: LogicOp3,
4355 }
4356
4357 impl Foldable for OpLop3 {
4358 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
4359 let srcs = [
4360 f.get_u32_bnot_src(self, &self.srcs[0]),
4361 f.get_u32_bnot_src(self, &self.srcs[1]),
4362 f.get_u32_bnot_src(self, &self.srcs[2]),
4363 ];
4364 let dst = self.op.eval(srcs[0], srcs[1], srcs[2]);
4365 f.set_u32_dst(self, &self.dst, dst);
4366 }
4367 }
4368
4369 impl DisplayOp for OpLop3 {
4370 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4371 write!(
4372 f,
4373 "lop3.{} {} {} {}",
4374 self.op, self.srcs[0], self.srcs[1], self.srcs[2],
4375 )
4376 }
4377 }
4378 impl_display_for_op!(OpLop3);
4379
4380 #[derive(Clone, Copy, Eq, PartialEq)]
4381 pub enum ShflOp {
4382 Idx,
4383 Up,
4384 Down,
4385 Bfly,
4386 }
4387
4388 impl fmt::Display for ShflOp {
4389 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4390 match self {
4391 ShflOp::Idx => write!(f, "idx"),
4392 ShflOp::Up => write!(f, "up"),
4393 ShflOp::Down => write!(f, "down"),
4394 ShflOp::Bfly => write!(f, "bfly"),
4395 }
4396 }
4397 }
4398
4399 #[repr(C)]
4400 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
4401 pub struct OpShf {
4402 #[dst_type(GPR)]
4403 pub dst: Dst,
4404
4405 #[src_type(GPR)]
4406 pub low: Src,
4407
4408 #[src_type(ALU)]
4409 pub high: Src,
4410
4411 #[src_type(ALU)]
4412 pub shift: Src,
4413
4414 pub right: bool,
4415 pub wrap: bool,
4416 pub data_type: IntType,
4417 pub dst_high: bool,
4418 }
4419
4420 fn reduce_shift_imm(shift: &mut Src, wrap: bool, bits: u32) {
4421 debug_assert!(shift.src_mod.is_none());
4422 if let SrcRef::Imm32(shift) = &mut shift.src_ref {
4423 if wrap {
4424 *shift &= bits - 1;
4425 } else {
4426 *shift = std::cmp::min(*shift, bits)
4427 }
4428 }
4429 }
4430
4431 impl OpShf {
4432 /// Reduces the shift immediate, if any. Out-of-range shifts are either
4433 /// clamped to the maximum or wrapped as needed.
4434 pub fn reduce_shift_imm(&mut self) {
4435 let bits = self.data_type.bits().try_into().unwrap();
4436 reduce_shift_imm(&mut self.shift, self.wrap, bits);
4437 }
4438 }
4439
4440 impl Foldable for OpShf {
4441 fn fold(&self, sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
4442 let low = f.get_u32_src(self, &self.low);
4443 let high = f.get_u32_src(self, &self.high);
4444 let shift = f.get_u32_src(self, &self.shift);
4445
4446 let bits: u32 = self.data_type.bits().try_into().unwrap();
4447 let shift = if self.wrap {
4448 shift & (bits - 1)
4449 } else {
4450 min(shift, bits)
4451 };
4452
4453 let x = u64::from(low) | (u64::from(high) << 32);
4454 let shifted = if sm.sm() < 70
4455 && self.dst_high
4456 && self.data_type != IntType::I64
4457 {
4458 if self.right {
4459 x.checked_shr(shift).unwrap_or(0)
4460 } else {
4461 x.checked_shl(shift).unwrap_or(0)
4462 }
4463 } else if self.data_type.is_signed() {
4464 if self.right {
4465 let x = x as i64;
4466 x.checked_shr(shift).unwrap_or(x >> 63) as u64
4467 } else {
4468 x.checked_shl(shift).unwrap_or(0)
4469 }
4470 } else {
4471 if self.right {
4472 x.checked_shr(shift).unwrap_or(0)
4473 } else {
4474 x.checked_shl(shift).unwrap_or(0)
4475 }
4476 };
4477
4478 let dst = if (sm.sm() < 70 && !self.right) || self.dst_high {
4479 (shifted >> 32) as u32
4480 } else {
4481 shifted as u32
4482 };
4483
4484 f.set_u32_dst(self, &self.dst, dst);
4485 }
4486 }
4487
4488 impl DisplayOp for OpShf {
4489 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4490 write!(f, "shf")?;
4491 if self.right {
4492 write!(f, ".r")?;
4493 } else {
4494 write!(f, ".l")?;
4495 }
4496 if self.wrap {
4497 write!(f, ".w")?;
4498 }
4499 write!(f, "{}", self.data_type)?;
4500 if self.dst_high {
4501 write!(f, ".hi")?;
4502 }
4503 write!(f, " {} {} {}", self.low, self.high, self.shift)
4504 }
4505 }
4506 impl_display_for_op!(OpShf);
4507
4508 /// Only used on SM50
4509 #[repr(C)]
4510 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
4511 pub struct OpShl {
4512 #[dst_type(GPR)]
4513 pub dst: Dst,
4514
4515 #[src_type(GPR)]
4516 pub src: Src,
4517
4518 #[src_type(ALU)]
4519 pub shift: Src,
4520
4521 pub wrap: bool,
4522 }
4523
4524 impl OpShl {
4525 /// Reduces the shift immediate, if any. Out-of-range shifts are either
4526 /// clamped to the maximum or wrapped as needed.
4527 pub fn reduce_shift_imm(&mut self) {
4528 reduce_shift_imm(&mut self.shift, self.wrap, 32);
4529 }
4530 }
4531
4532 impl DisplayOp for OpShl {
4533 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4534 write!(f, "shl")?;
4535 if self.wrap {
4536 write!(f, ".w")?;
4537 }
4538 write!(f, " {} {}", self.src, self.shift)
4539 }
4540 }
4541
4542 impl Foldable for OpShl {
4543 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
4544 let x = f.get_u32_src(self, &self.src);
4545 let shift = f.get_u32_src(self, &self.shift);
4546
4547 let shift = if self.wrap {
4548 shift & 31
4549 } else {
4550 min(shift, 32)
4551 };
4552 let dst = x.checked_shl(shift).unwrap_or(0);
4553 f.set_u32_dst(self, &self.dst, dst);
4554 }
4555 }
4556
4557 /// Only used on SM50
4558 #[repr(C)]
4559 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
4560 pub struct OpShr {
4561 #[dst_type(GPR)]
4562 pub dst: Dst,
4563
4564 #[src_type(GPR)]
4565 pub src: Src,
4566
4567 #[src_type(ALU)]
4568 pub shift: Src,
4569
4570 pub wrap: bool,
4571 pub signed: bool,
4572 }
4573
4574 impl DisplayOp for OpShr {
4575 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4576 write!(f, "shr")?;
4577 if self.wrap {
4578 write!(f, ".w")?;
4579 }
4580 if !self.signed {
4581 write!(f, ".u32")?;
4582 }
4583 write!(f, " {} {}", self.src, self.shift)
4584 }
4585 }
4586
4587 impl OpShr {
4588 /// Reduces the shift immediate, if any. Out-of-range shifts are either
4589 /// clamped to the maximum or wrapped as needed.
4590 pub fn reduce_shift_imm(&mut self) {
4591 reduce_shift_imm(&mut self.shift, self.wrap, 32);
4592 }
4593 }
4594
4595 impl Foldable for OpShr {
4596 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
4597 let x = f.get_u32_src(self, &self.src);
4598 let shift = f.get_u32_src(self, &self.shift);
4599
4600 let shift = if self.wrap {
4601 shift & 31
4602 } else {
4603 min(shift, 32)
4604 };
4605 let dst = if self.signed {
4606 let x = x as i32;
4607 x.checked_shr(shift).unwrap_or(x >> 31) as u32
4608 } else {
4609 x.checked_shr(shift).unwrap_or(0)
4610 };
4611 f.set_u32_dst(self, &self.dst, dst);
4612 }
4613 }
4614
4615 #[repr(C)]
4616 pub struct OpF2F {
4617 pub dst: Dst,
4618 pub src: Src,
4619
4620 pub src_type: FloatType,
4621 pub dst_type: FloatType,
4622 pub rnd_mode: FRndMode,
4623 pub ftz: bool,
4624 /// For 16-bit up-conversions, take the high 16 bits of the source register.
4625 /// For 16-bit down-conversions, place the result into the upper 16 bits of
4626 /// the destination register
4627 pub high: bool,
4628 /// Round to the nearest integer rather than nearest float
4629 ///
4630 /// Not available on SM70+
4631 pub integer_rnd: bool,
4632 }
4633
4634 impl AsSlice<Src> for OpF2F {
4635 type Attr = SrcType;
4636
4637 fn as_slice(&self) -> &[Src] {
4638 std::slice::from_ref(&self.src)
4639 }
4640
4641 fn as_mut_slice(&mut self) -> &mut [Src] {
4642 std::slice::from_mut(&mut self.src)
4643 }
4644
4645 fn attrs(&self) -> SrcTypeList {
4646 let src_type = match self.src_type {
4647 FloatType::F16 => SrcType::F16,
4648 FloatType::F32 => SrcType::F32,
4649 FloatType::F64 => SrcType::F64,
4650 };
4651 SrcTypeList::Uniform(src_type)
4652 }
4653 }
4654
4655 impl AsSlice<Dst> for OpF2F {
4656 type Attr = DstType;
4657
4658 fn as_slice(&self) -> &[Dst] {
4659 std::slice::from_ref(&self.dst)
4660 }
4661
4662 fn as_mut_slice(&mut self) -> &mut [Dst] {
4663 std::slice::from_mut(&mut self.dst)
4664 }
4665
4666 fn attrs(&self) -> DstTypeList {
4667 let dst_type = match self.dst_type {
4668 FloatType::F16 => DstType::F16,
4669 FloatType::F32 => DstType::F32,
4670 FloatType::F64 => DstType::F64,
4671 };
4672 DstTypeList::Uniform(dst_type)
4673 }
4674 }
4675
4676 impl DisplayOp for OpF2F {
4677 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4678 write!(f, "f2f")?;
4679 if self.ftz {
4680 write!(f, ".ftz")?;
4681 }
4682 if self.integer_rnd {
4683 write!(f, ".int")?;
4684 }
4685 write!(
4686 f,
4687 "{}{}{} {}",
4688 self.dst_type, self.src_type, self.rnd_mode, self.src,
4689 )
4690 }
4691 }
4692 impl_display_for_op!(OpF2F);
4693
4694 #[repr(C)]
4695 #[derive(DstsAsSlice, SrcsAsSlice)]
4696 pub struct OpF2FP {
4697 #[dst_type(GPR)]
4698 pub dst: Dst,
4699
4700 #[src_type(ALU)]
4701 pub srcs: [Src; 2],
4702
4703 pub rnd_mode: FRndMode,
4704 }
4705
4706 impl DisplayOp for OpF2FP {
4707 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4708 write!(f, "f2fp.pack_ab")?;
4709 if self.rnd_mode != FRndMode::NearestEven {
4710 write!(f, "{}", self.rnd_mode)?;
4711 }
4712 write!(f, " {}, {}", self.srcs[0], self.srcs[1],)
4713 }
4714 }
4715 impl_display_for_op!(OpF2FP);
4716
4717 #[repr(C)]
4718 #[derive(DstsAsSlice)]
4719 pub struct OpF2I {
4720 #[dst_type(GPR)]
4721 pub dst: Dst,
4722
4723 pub src: Src,
4724
4725 pub src_type: FloatType,
4726 pub dst_type: IntType,
4727 pub rnd_mode: FRndMode,
4728 pub ftz: bool,
4729 }
4730
4731 impl AsSlice<Src> for OpF2I {
4732 type Attr = SrcType;
4733
4734 fn as_slice(&self) -> &[Src] {
4735 std::slice::from_ref(&self.src)
4736 }
4737
4738 fn as_mut_slice(&mut self) -> &mut [Src] {
4739 std::slice::from_mut(&mut self.src)
4740 }
4741
4742 fn attrs(&self) -> SrcTypeList {
4743 let src_type = match self.src_type {
4744 FloatType::F16 => SrcType::F16,
4745 FloatType::F32 => SrcType::F32,
4746 FloatType::F64 => SrcType::F64,
4747 };
4748 SrcTypeList::Uniform(src_type)
4749 }
4750 }
4751
4752 impl DisplayOp for OpF2I {
4753 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4754 let ftz = if self.ftz { ".ftz" } else { "" };
4755 write!(
4756 f,
4757 "f2i{}{}{}{ftz} {}",
4758 self.dst_type, self.src_type, self.rnd_mode, self.src,
4759 )
4760 }
4761 }
4762 impl_display_for_op!(OpF2I);
4763
4764 #[repr(C)]
4765 pub struct OpI2F {
4766 pub dst: Dst,
4767 pub src: Src,
4768
4769 pub dst_type: FloatType,
4770 pub src_type: IntType,
4771 pub rnd_mode: FRndMode,
4772 }
4773
4774 impl AsSlice<Src> for OpI2F {
4775 type Attr = SrcType;
4776
4777 fn as_slice(&self) -> &[Src] {
4778 std::slice::from_ref(&self.src)
4779 }
4780
4781 fn as_mut_slice(&mut self) -> &mut [Src] {
4782 std::slice::from_mut(&mut self.src)
4783 }
4784
4785 fn attrs(&self) -> SrcTypeList {
4786 if self.src_type.bits() <= 32 {
4787 SrcTypeList::Uniform(SrcType::ALU)
4788 } else {
4789 SrcTypeList::Uniform(SrcType::GPR)
4790 }
4791 }
4792 }
4793
4794 impl AsSlice<Dst> for OpI2F {
4795 type Attr = DstType;
4796
4797 fn as_slice(&self) -> &[Dst] {
4798 std::slice::from_ref(&self.dst)
4799 }
4800
4801 fn as_mut_slice(&mut self) -> &mut [Dst] {
4802 std::slice::from_mut(&mut self.dst)
4803 }
4804
4805 fn attrs(&self) -> DstTypeList {
4806 let dst_type = match self.dst_type {
4807 FloatType::F16 => DstType::F16,
4808 FloatType::F32 => DstType::F32,
4809 FloatType::F64 => DstType::F64,
4810 };
4811 DstTypeList::Uniform(dst_type)
4812 }
4813 }
4814
4815 impl DisplayOp for OpI2F {
4816 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4817 write!(
4818 f,
4819 "i2f{}{}{} {}",
4820 self.dst_type, self.src_type, self.rnd_mode, self.src,
4821 )
4822 }
4823 }
4824 impl_display_for_op!(OpI2F);
4825
4826 /// Not used on SM70+
4827 #[repr(C)]
4828 #[derive(SrcsAsSlice, DstsAsSlice)]
4829 pub struct OpI2I {
4830 #[dst_type(GPR)]
4831 pub dst: Dst,
4832
4833 #[src_type(ALU)]
4834 pub src: Src,
4835
4836 pub src_type: IntType,
4837 pub dst_type: IntType,
4838
4839 pub saturate: bool,
4840 pub abs: bool,
4841 pub neg: bool,
4842 }
4843
4844 impl DisplayOp for OpI2I {
4845 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4846 write!(f, "i2i")?;
4847 if self.saturate {
4848 write!(f, ".sat ")?;
4849 }
4850 write!(f, "{}{} {}", self.dst_type, self.src_type, self.src,)?;
4851 if self.abs {
4852 write!(f, ".abs")?;
4853 }
4854 if self.neg {
4855 write!(f, ".neg")?;
4856 }
4857 Ok(())
4858 }
4859 }
4860 impl_display_for_op!(OpI2I);
4861
4862 #[repr(C)]
4863 #[derive(DstsAsSlice)]
4864 pub struct OpFRnd {
4865 #[dst_type(F32)]
4866 pub dst: Dst,
4867
4868 pub src: Src,
4869
4870 pub dst_type: FloatType,
4871 pub src_type: FloatType,
4872 pub rnd_mode: FRndMode,
4873 pub ftz: bool,
4874 }
4875
4876 impl AsSlice<Src> for OpFRnd {
4877 type Attr = SrcType;
4878
4879 fn as_slice(&self) -> &[Src] {
4880 std::slice::from_ref(&self.src)
4881 }
4882
4883 fn as_mut_slice(&mut self) -> &mut [Src] {
4884 std::slice::from_mut(&mut self.src)
4885 }
4886
4887 fn attrs(&self) -> SrcTypeList {
4888 let src_type = match self.src_type {
4889 FloatType::F16 => SrcType::F16,
4890 FloatType::F32 => SrcType::F32,
4891 FloatType::F64 => SrcType::F64,
4892 };
4893 SrcTypeList::Uniform(src_type)
4894 }
4895 }
4896
4897 impl DisplayOp for OpFRnd {
4898 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4899 let ftz = if self.ftz { ".ftz" } else { "" };
4900 write!(
4901 f,
4902 "frnd{}{}{}{ftz} {}",
4903 self.dst_type, self.src_type, self.rnd_mode, self.src,
4904 )
4905 }
4906 }
4907 impl_display_for_op!(OpFRnd);
4908
4909 #[repr(C)]
4910 #[derive(SrcsAsSlice, DstsAsSlice)]
4911 pub struct OpMov {
4912 #[dst_type(GPR)]
4913 pub dst: Dst,
4914
4915 #[src_type(ALU)]
4916 pub src: Src,
4917
4918 pub quad_lanes: u8,
4919 }
4920
4921 impl DisplayOp for OpMov {
4922 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4923 if self.quad_lanes == 0xf {
4924 write!(f, "mov {}", self.src)
4925 } else {
4926 write!(f, "mov[{:#x}] {}", self.quad_lanes, self.src)
4927 }
4928 }
4929 }
4930 impl_display_for_op!(OpMov);
4931
4932 #[repr(C)]
4933 #[derive(SrcsAsSlice, DstsAsSlice)]
4934 pub struct OpMovm {
4935 pub dst: Dst,
4936
4937 #[src_type(GPR)]
4938 pub src: Src,
4939 }
4940
4941 impl DisplayOp for OpMovm {
4942 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4943 write!(f, "movm.16.m8n8.trans {}", self.src)
4944 }
4945 }
4946
4947 impl_display_for_op!(OpMovm);
4948
4949 #[derive(Copy, Clone)]
4950 pub struct PrmtSelByte(u8);
4951
4952 impl PrmtSelByte {
4953 pub const INVALID: PrmtSelByte = PrmtSelByte(u8::MAX);
4954
4955 pub fn new(src_idx: usize, byte_idx: usize, msb: bool) -> PrmtSelByte {
4956 assert!(src_idx < 2);
4957 assert!(byte_idx < 4);
4958
4959 let mut nib = 0;
4960 nib |= (src_idx as u8) << 2;
4961 nib |= byte_idx as u8;
4962 if msb {
4963 nib |= 0x8;
4964 }
4965 PrmtSelByte(nib)
4966 }
4967
4968 pub fn src(&self) -> usize {
4969 ((self.0 >> 2) & 0x1).into()
4970 }
4971
4972 pub fn byte(&self) -> usize {
4973 (self.0 & 0x3).into()
4974 }
4975
4976 pub fn msb(&self) -> bool {
4977 (self.0 & 0x8) != 0
4978 }
4979
4980 pub fn fold_u32(&self, u: u32) -> u8 {
4981 let mut sb = (u >> (self.byte() * 8)) as u8;
4982 if self.msb() {
4983 sb = ((sb as i8) >> 7) as u8;
4984 }
4985 sb
4986 }
4987 }
4988
4989 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
4990 pub struct PrmtSel(pub u16);
4991
4992 impl PrmtSel {
4993 pub fn new(bytes: [PrmtSelByte; 4]) -> PrmtSel {
4994 let mut sel = 0;
4995 for i in 0..4 {
4996 assert!(bytes[i].0 <= 0xf);
4997 sel |= u16::from(bytes[i].0) << (i * 4);
4998 }
4999 PrmtSel(sel)
5000 }
5001
5002 pub fn get(&self, byte_idx: usize) -> PrmtSelByte {
5003 assert!(byte_idx < 4);
5004 PrmtSelByte(((self.0 >> (byte_idx * 4)) & 0xf) as u8)
5005 }
5006 }
5007
5008 #[allow(dead_code)]
5009 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
5010 pub enum PrmtMode {
5011 Index,
5012 Forward4Extract,
5013 Backward4Extract,
5014 Replicate8,
5015 EdgeClampLeft,
5016 EdgeClampRight,
5017 Replicate16,
5018 }
5019
5020 impl fmt::Display for PrmtMode {
5021 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5022 match self {
5023 PrmtMode::Index => Ok(()),
5024 PrmtMode::Forward4Extract => write!(f, ".f4e"),
5025 PrmtMode::Backward4Extract => write!(f, ".b4e"),
5026 PrmtMode::Replicate8 => write!(f, ".rc8"),
5027 PrmtMode::EdgeClampLeft => write!(f, ".ecl"),
5028 PrmtMode::EdgeClampRight => write!(f, ".ecl"),
5029 PrmtMode::Replicate16 => write!(f, ".rc16"),
5030 }
5031 }
5032 }
5033
5034 #[repr(C)]
5035 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
5036 /// Permutes `srcs` into `dst` using `selection`.
5037 pub struct OpPrmt {
5038 #[dst_type(GPR)]
5039 pub dst: Dst,
5040
5041 #[src_type(ALU)]
5042 pub srcs: [Src; 2],
5043
5044 #[src_type(ALU)]
5045 pub sel: Src,
5046
5047 pub mode: PrmtMode,
5048 }
5049
5050 impl OpPrmt {
5051 pub fn get_sel(&self) -> Option<PrmtSel> {
5052 // TODO: We could construct a PrmtSel for the other modes but we don't
5053 // use them right now because they're kinda pointless.
5054 if self.mode != PrmtMode::Index {
5055 return None;
5056 }
5057
5058 self.sel.as_u32(SrcType::ALU).map(|sel| {
5059 // The top 16 bits are ignored
5060 PrmtSel(sel as u16)
5061 })
5062 }
5063
5064 /// Reduces the sel immediate, if any.
5065 pub fn reduce_sel_imm(&mut self) {
5066 assert!(self.sel.src_mod.is_none());
5067 if let SrcRef::Imm32(sel) = &mut self.sel.src_ref {
5068 // Only the bottom 16 bits matter anyway
5069 *sel &= 0xffff;
5070 }
5071 }
5072
5073 pub fn as_u32(&self) -> Option<u32> {
5074 let sel = self.get_sel()?;
5075
5076 let mut imm = 0_u32;
5077 for b in 0..4 {
5078 let sel_byte = sel.get(b);
5079 let src_u32 = self.srcs[sel_byte.src()].as_u32(SrcType::ALU)?;
5080
5081 let sb = sel_byte.fold_u32(src_u32);
5082 imm |= u32::from(sb) << (b * 8);
5083 }
5084 Some(imm)
5085 }
5086 }
5087
5088 impl Foldable for OpPrmt {
5089 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
5090 let srcs = [
5091 f.get_u32_src(self, &self.srcs[0]),
5092 f.get_u32_src(self, &self.srcs[1]),
5093 ];
5094 let sel = f.get_u32_src(self, &self.sel);
5095
5096 assert!(self.mode == PrmtMode::Index);
5097 let sel = PrmtSel(sel as u16);
5098
5099 let mut dst = 0_u32;
5100 for b in 0..4 {
5101 let sel_byte = sel.get(b);
5102 let src = srcs[sel_byte.src()];
5103 let sb = sel_byte.fold_u32(src);
5104 dst |= u32::from(sb) << (b * 8);
5105 }
5106
5107 f.set_u32_dst(self, &self.dst, dst);
5108 }
5109 }
5110
5111 impl DisplayOp for OpPrmt {
5112 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5113 write!(
5114 f,
5115 "prmt{} {} [{}] {}",
5116 self.mode, self.srcs[0], self.sel, self.srcs[1],
5117 )
5118 }
5119 }
5120 impl_display_for_op!(OpPrmt);
5121
5122 #[repr(C)]
5123 #[derive(SrcsAsSlice, DstsAsSlice)]
5124 pub struct OpSel {
5125 #[dst_type(GPR)]
5126 pub dst: Dst,
5127
5128 #[src_type(Pred)]
5129 pub cond: Src,
5130
5131 #[src_type(ALU)]
5132 pub srcs: [Src; 2],
5133 }
5134
5135 impl DisplayOp for OpSel {
5136 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5137 write!(f, "sel {} {} {}", self.cond, self.srcs[0], self.srcs[1],)
5138 }
5139 }
5140 impl_display_for_op!(OpSel);
5141
5142 #[repr(C)]
5143 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
5144 pub struct OpSgxt {
5145 #[dst_type(GPR)]
5146 pub dst: Dst,
5147
5148 #[src_type(ALU)]
5149 pub a: Src,
5150
5151 #[src_type(ALU)]
5152 pub bits: Src,
5153
5154 pub signed: bool,
5155 }
5156
5157 impl DisplayOp for OpSgxt {
5158 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5159 let modifier = if self.signed { "" } else { ".u32" };
5160 write!(f, "sgxt{} {} {}", modifier, self.a, self.bits)
5161 }
5162 }
5163 impl_display_for_op!(OpSgxt);
5164
5165 impl Foldable for OpSgxt {
5166 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
5167 let a = f.get_u32_src(self, &self.a);
5168 let bits = f.get_u32_src(self, &self.bits);
5169
5170 let dst = if bits >= 32 {
5171 a
5172 } else if bits == 0 {
5173 0
5174 } else {
5175 let shift = 32 - bits;
5176 let a = a << shift;
5177 if self.signed {
5178 let a = a as i32;
5179 (a >> shift) as u32
5180 } else {
5181 a >> shift
5182 }
5183 };
5184 f.set_u32_dst(self, &self.dst, dst);
5185 }
5186 }
5187
5188 #[repr(C)]
5189 #[derive(SrcsAsSlice, DstsAsSlice)]
5190 pub struct OpShfl {
5191 #[dst_type(GPR)]
5192 pub dst: Dst,
5193
5194 #[dst_type(Pred)]
5195 pub in_bounds: Dst,
5196
5197 #[src_type(SSA)]
5198 pub src: Src,
5199
5200 #[src_type(ALU)]
5201 pub lane: Src,
5202
5203 #[src_type(ALU)]
5204 pub c: Src,
5205
5206 pub op: ShflOp,
5207 }
5208
5209 impl OpShfl {
5210 /// Reduces the lane and c immediates, if any. The hardware only uses
5211 /// some of the bits of `lane` and `c` and ignores the rest. This method
5212 /// masks off the unused bits and ensures that any immediate values fit
5213 /// in the limited encoding space in the instruction.
5214 pub fn reduce_lane_c_imm(&mut self) {
5215 debug_assert!(self.lane.src_mod.is_none());
5216 if let SrcRef::Imm32(lane) = &mut self.lane.src_ref {
5217 *lane &= 0x1f;
5218 }
5219
5220 debug_assert!(self.c.src_mod.is_none());
5221 if let SrcRef::Imm32(c) = &mut self.c.src_ref {
5222 *c &= 0x1f1f;
5223 }
5224 }
5225 }
5226
5227 impl DisplayOp for OpShfl {
5228 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5229 write!(f, "shfl.{} {} {} {}", self.op, self.src, self.lane, self.c)
5230 }
5231 }
5232 impl_display_for_op!(OpShfl);
5233
5234 #[repr(C)]
5235 #[derive(SrcsAsSlice, DstsAsSlice)]
5236 pub struct OpPLop3 {
5237 #[dst_type(Pred)]
5238 pub dsts: [Dst; 2],
5239
5240 #[src_type(Pred)]
5241 pub srcs: [Src; 3],
5242
5243 pub ops: [LogicOp3; 2],
5244 }
5245
5246 impl DisplayOp for OpPLop3 {
5247 fn fmt_dsts(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5248 write!(f, "{} {}", self.dsts[0], self.dsts[1])
5249 }
5250
5251 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5252 write!(
5253 f,
5254 "plop3 {} {} {} {} {}",
5255 self.srcs[0], self.srcs[1], self.srcs[2], self.ops[0], self.ops[1],
5256 )
5257 }
5258 }
5259 impl_display_for_op!(OpPLop3);
5260
5261 #[repr(C)]
5262 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
5263 pub struct OpPSetP {
5264 #[dst_type(Pred)]
5265 pub dsts: [Dst; 2],
5266
5267 pub ops: [PredSetOp; 2],
5268
5269 #[src_type(Pred)]
5270 pub srcs: [Src; 3],
5271 }
5272
5273 impl Foldable for OpPSetP {
5274 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
5275 let srcs = [
5276 f.get_pred_src(self, &self.srcs[0]),
5277 f.get_pred_src(self, &self.srcs[1]),
5278 f.get_pred_src(self, &self.srcs[2]),
5279 ];
5280
5281 let tmp = self.ops[0].eval(srcs[0], srcs[1]);
5282 let dst0 = self.ops[1].eval(srcs[2], tmp);
5283
5284 let tmp = self.ops[0].eval(!srcs[0], srcs[1]);
5285 let dst1 = self.ops[1].eval(srcs[2], tmp);
5286
5287 f.set_pred_dst(self, &self.dsts[0], dst0);
5288 f.set_pred_dst(self, &self.dsts[1], dst1);
5289 }
5290 }
5291
5292 impl DisplayOp for OpPSetP {
5293 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5294 write!(
5295 f,
5296 "psetp{}{} {} {} {}",
5297 self.ops[0], self.ops[1], self.srcs[0], self.srcs[1], self.srcs[2],
5298 )
5299 }
5300 }
5301
5302 #[repr(C)]
5303 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
5304 pub struct OpPopC {
5305 #[dst_type(GPR)]
5306 pub dst: Dst,
5307
5308 #[src_type(B32)]
5309 pub src: Src,
5310 }
5311
5312 impl Foldable for OpPopC {
5313 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
5314 let src = f.get_u32_bnot_src(self, &self.src);
5315 let dst = src.count_ones();
5316 f.set_u32_dst(self, &self.dst, dst);
5317 }
5318 }
5319
5320 impl DisplayOp for OpPopC {
5321 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5322 write!(f, "popc {}", self.src,)
5323 }
5324 }
5325 impl_display_for_op!(OpPopC);
5326
5327 #[repr(C)]
5328 #[derive(SrcsAsSlice, DstsAsSlice)]
5329 pub struct OpR2UR {
5330 #[dst_type(GPR)]
5331 pub dst: Dst,
5332
5333 #[src_type(GPR)]
5334 pub src: Src,
5335 }
5336
5337 impl DisplayOp for OpR2UR {
5338 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5339 write!(f, "r2ur {}", self.src)
5340 }
5341 }
5342 impl_display_for_op!(OpR2UR);
5343
5344 #[derive(Copy, Clone, PartialEq, Eq)]
5345 pub enum ReduxOp {
5346 And,
5347 Or,
5348 Xor,
5349 Sum,
5350 Min(IntCmpType),
5351 Max(IntCmpType),
5352 }
5353
5354 impl fmt::Display for ReduxOp {
5355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5356 match self {
5357 ReduxOp::And => write!(f, ".and"),
5358 ReduxOp::Or => write!(f, ".or"),
5359 ReduxOp::Xor => write!(f, ".xor"),
5360 ReduxOp::Sum => write!(f, ".sum"),
5361 ReduxOp::Min(cmp) => write!(f, ".min{cmp}"),
5362 ReduxOp::Max(cmp) => write!(f, ".max{cmp}"),
5363 }
5364 }
5365 }
5366
5367 #[repr(C)]
5368 #[derive(SrcsAsSlice, DstsAsSlice)]
5369 pub struct OpRedux {
5370 #[dst_type(GPR)]
5371 pub dst: Dst,
5372
5373 #[src_type(GPR)]
5374 pub src: Src,
5375
5376 pub op: ReduxOp,
5377 }
5378
5379 impl DisplayOp for OpRedux {
5380 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5381 write!(f, "redux{} {}", self.op, self.src)
5382 }
5383 }
5384 impl_display_for_op!(OpRedux);
5385
5386 #[repr(C)]
5387 #[derive(SrcsAsSlice, DstsAsSlice)]
5388 pub struct OpTex {
5389 pub dsts: [Dst; 2],
5390 pub fault: Dst,
5391
5392 pub tex: TexRef,
5393
5394 #[src_type(SSA)]
5395 pub srcs: [Src; 2],
5396
5397 pub dim: TexDim,
5398 pub lod_mode: TexLodMode,
5399 pub deriv_mode: TexDerivMode,
5400 pub z_cmpr: bool,
5401 pub offset_mode: TexOffsetMode,
5402 pub mem_eviction_priority: MemEvictionPriority,
5403 pub nodep: bool,
5404 pub channel_mask: ChannelMask,
5405 }
5406
5407 impl DisplayOp for OpTex {
5408 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5409 write!(
5410 f,
5411 "tex{}{}{}{}",
5412 self.dim, self.lod_mode, self.offset_mode, self.deriv_mode
5413 )?;
5414 if self.z_cmpr {
5415 write!(f, ".dc")?;
5416 }
5417 write!(f, "{}", self.mem_eviction_priority)?;
5418 if self.nodep {
5419 write!(f, ".nodep")?;
5420 }
5421 write!(f, "{}", self.channel_mask)?;
5422 write!(f, " {} {} {}", self.tex, self.srcs[0], self.srcs[1])
5423 }
5424 }
5425 impl_display_for_op!(OpTex);
5426
5427 #[repr(C)]
5428 #[derive(SrcsAsSlice, DstsAsSlice)]
5429 pub struct OpTld {
5430 pub dsts: [Dst; 2],
5431 pub fault: Dst,
5432
5433 pub tex: TexRef,
5434
5435 #[src_type(SSA)]
5436 pub srcs: [Src; 2],
5437
5438 pub dim: TexDim,
5439 pub is_ms: bool,
5440 pub lod_mode: TexLodMode,
5441 pub offset_mode: TexOffsetMode,
5442 pub mem_eviction_priority: MemEvictionPriority,
5443 pub nodep: bool,
5444 pub channel_mask: ChannelMask,
5445 }
5446
5447 impl DisplayOp for OpTld {
5448 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5449 write!(f, "tld{}{}{}", self.dim, self.lod_mode, self.offset_mode)?;
5450 if self.is_ms {
5451 write!(f, ".ms")?;
5452 }
5453 write!(f, "{}", self.mem_eviction_priority)?;
5454 if self.nodep {
5455 write!(f, ".nodep")?;
5456 }
5457 write!(f, "{}", self.channel_mask)?;
5458 write!(f, " {} {} {}", self.tex, self.srcs[0], self.srcs[1])
5459 }
5460 }
5461 impl_display_for_op!(OpTld);
5462
5463 #[repr(C)]
5464 #[derive(SrcsAsSlice, DstsAsSlice)]
5465 pub struct OpTld4 {
5466 pub dsts: [Dst; 2],
5467 pub fault: Dst,
5468
5469 pub tex: TexRef,
5470
5471 #[src_type(SSA)]
5472 pub srcs: [Src; 2],
5473
5474 pub dim: TexDim,
5475 pub comp: u8,
5476 pub offset_mode: TexOffsetMode,
5477 pub z_cmpr: bool,
5478 pub mem_eviction_priority: MemEvictionPriority,
5479 pub nodep: bool,
5480 pub channel_mask: ChannelMask,
5481 }
5482
5483 impl DisplayOp for OpTld4 {
5484 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5485 write!(f, "tld4.g{}{}", self.dim, self.offset_mode)?;
5486 if self.z_cmpr {
5487 write!(f, ".dc")?;
5488 }
5489 write!(f, "{}", self.mem_eviction_priority)?;
5490 if self.nodep {
5491 write!(f, ".nodep")?;
5492 }
5493 write!(f, "{}", self.channel_mask)?;
5494 write!(f, " {} {} {}", self.tex, self.srcs[0], self.srcs[1])
5495 }
5496 }
5497 impl_display_for_op!(OpTld4);
5498
5499 #[repr(C)]
5500 #[derive(SrcsAsSlice, DstsAsSlice)]
5501 pub struct OpTmml {
5502 pub dsts: [Dst; 2],
5503
5504 pub tex: TexRef,
5505
5506 #[src_type(SSA)]
5507 pub srcs: [Src; 2],
5508
5509 pub dim: TexDim,
5510 pub deriv_mode: TexDerivMode,
5511 pub nodep: bool,
5512 pub channel_mask: ChannelMask,
5513 }
5514
5515 impl DisplayOp for OpTmml {
5516 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5517 write!(f, "tmml.lod{}{}", self.dim, self.deriv_mode)?;
5518 if self.nodep {
5519 write!(f, ".nodep")?;
5520 }
5521 write!(f, "{}", self.channel_mask)?;
5522 write!(f, " {} {} {}", self.tex, self.srcs[0], self.srcs[1])
5523 }
5524 }
5525 impl_display_for_op!(OpTmml);
5526
5527 #[repr(C)]
5528 #[derive(SrcsAsSlice, DstsAsSlice)]
5529 pub struct OpTxd {
5530 pub dsts: [Dst; 2],
5531 pub fault: Dst,
5532
5533 pub tex: TexRef,
5534
5535 #[src_type(SSA)]
5536 pub srcs: [Src; 2],
5537
5538 pub dim: TexDim,
5539 pub offset_mode: TexOffsetMode,
5540 pub mem_eviction_priority: MemEvictionPriority,
5541 pub nodep: bool,
5542 pub channel_mask: ChannelMask,
5543 }
5544
5545 impl DisplayOp for OpTxd {
5546 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5547 write!(
5548 f,
5549 "txd{}{}{}",
5550 self.dim, self.offset_mode, self.mem_eviction_priority
5551 )?;
5552 if self.nodep {
5553 write!(f, ".nodep")?;
5554 }
5555 write!(f, "{}", self.channel_mask)?;
5556 write!(f, " {} {} {}", self.tex, self.srcs[0], self.srcs[1])
5557 }
5558 }
5559 impl_display_for_op!(OpTxd);
5560
5561 #[repr(C)]
5562 #[derive(SrcsAsSlice, DstsAsSlice)]
5563 pub struct OpTxq {
5564 pub dsts: [Dst; 2],
5565
5566 pub tex: TexRef,
5567
5568 #[src_type(SSA)]
5569 pub src: Src,
5570
5571 pub query: TexQuery,
5572 pub nodep: bool,
5573 pub channel_mask: ChannelMask,
5574 }
5575
5576 impl DisplayOp for OpTxq {
5577 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5578 write!(f, "txq")?;
5579 if self.nodep {
5580 write!(f, ".nodep")?;
5581 }
5582 write!(f, "{}", self.channel_mask)?;
5583 write!(f, " {} {} {}", self.tex, self.src, self.query)
5584 }
5585 }
5586 impl_display_for_op!(OpTxq);
5587
5588 #[allow(dead_code)]
5589 #[derive(Clone, Copy, Eq, PartialEq)]
5590 pub enum ImageAccess {
5591 Binary(MemType),
5592 Formatted(ChannelMask),
5593 }
5594
5595 impl fmt::Display for ImageAccess {
5596 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5597 match self {
5598 ImageAccess::Binary(mem_type) => write!(f, ".b{mem_type}"),
5599 ImageAccess::Formatted(mask) => write!(f, ".p{mask}"),
5600 }
5601 }
5602 }
5603
5604 #[repr(C)]
5605 #[derive(SrcsAsSlice, DstsAsSlice)]
5606 pub struct OpSuLd {
5607 pub dst: Dst,
5608 pub fault: Dst,
5609
5610 pub image_access: ImageAccess,
5611 pub image_dim: ImageDim,
5612 pub mem_order: MemOrder,
5613 pub mem_eviction_priority: MemEvictionPriority,
5614
5615 #[src_type(SSA)]
5616 pub handle: Src,
5617
5618 #[src_type(SSA)]
5619 pub coord: Src,
5620 }
5621
5622 impl DisplayOp for OpSuLd {
5623 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5624 write!(
5625 f,
5626 "suld{}{}{}{} [{}] {}",
5627 self.image_access,
5628 self.image_dim,
5629 self.mem_order,
5630 self.mem_eviction_priority,
5631 self.coord,
5632 self.handle,
5633 )
5634 }
5635 }
5636 impl_display_for_op!(OpSuLd);
5637
5638 #[repr(C)]
5639 #[derive(SrcsAsSlice, DstsAsSlice)]
5640 pub struct OpSuSt {
5641 pub image_access: ImageAccess,
5642 pub image_dim: ImageDim,
5643 pub mem_order: MemOrder,
5644 pub mem_eviction_priority: MemEvictionPriority,
5645
5646 #[src_type(SSA)]
5647 pub handle: Src,
5648
5649 #[src_type(SSA)]
5650 pub coord: Src,
5651
5652 #[src_type(SSA)]
5653 pub data: Src,
5654 }
5655
5656 impl DisplayOp for OpSuSt {
5657 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5658 write!(
5659 f,
5660 "sust{}{}{}{} [{}] {} {}",
5661 self.image_access,
5662 self.image_dim,
5663 self.mem_order,
5664 self.mem_eviction_priority,
5665 self.coord,
5666 self.data,
5667 self.handle,
5668 )
5669 }
5670 }
5671 impl_display_for_op!(OpSuSt);
5672
5673 #[repr(C)]
5674 #[derive(SrcsAsSlice, DstsAsSlice)]
5675 pub struct OpSuAtom {
5676 pub dst: Dst,
5677 pub fault: Dst,
5678
5679 pub image_dim: ImageDim,
5680
5681 pub atom_op: AtomOp,
5682 pub atom_type: AtomType,
5683
5684 pub mem_order: MemOrder,
5685 pub mem_eviction_priority: MemEvictionPriority,
5686
5687 #[src_type(SSA)]
5688 pub handle: Src,
5689
5690 #[src_type(SSA)]
5691 pub coord: Src,
5692
5693 #[src_type(SSA)]
5694 pub data: Src,
5695 }
5696
5697 impl DisplayOp for OpSuAtom {
5698 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5699 write!(
5700 f,
5701 "suatom.p{}{}{}{}{} [{}] {} {}",
5702 self.image_dim,
5703 self.atom_op,
5704 self.atom_type,
5705 self.mem_order,
5706 self.mem_eviction_priority,
5707 self.coord,
5708 self.data,
5709 self.handle,
5710 )
5711 }
5712 }
5713 impl_display_for_op!(OpSuAtom);
5714
5715 #[derive(Clone, Copy)]
5716 pub enum SuClampMode {
5717 StoredInDescriptor,
5718 PitchLinear,
5719 BlockLinear,
5720 }
5721
5722 impl fmt::Display for SuClampMode {
5723 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5724 let s = match self {
5725 SuClampMode::StoredInDescriptor => ".sd",
5726 SuClampMode::PitchLinear => ".pl",
5727 SuClampMode::BlockLinear => ".bl",
5728 };
5729 write!(f, "{}", s)
5730 }
5731 }
5732
5733 #[derive(Clone, Copy)]
5734 pub enum SuClampRound {
5735 R1,
5736 R2,
5737 R4,
5738 R8,
5739 R16,
5740 }
5741
5742 impl SuClampRound {
5743 pub fn to_int(&self) -> u8 {
5744 match self {
5745 SuClampRound::R1 => 1,
5746 SuClampRound::R2 => 2,
5747 SuClampRound::R4 => 4,
5748 SuClampRound::R8 => 8,
5749 SuClampRound::R16 => 16,
5750 }
5751 }
5752
5753 #[allow(dead_code)]
5754 pub fn to_mask(&self) -> u32 {
5755 !(self.to_int() as u32 - 1)
5756 }
5757 }
5758
5759 impl fmt::Display for SuClampRound {
5760 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5761 write!(f, ".r{}", self.to_int())
5762 }
5763 }
5764
5765 /// Kepler only
5766 /// Surface Clamp
5767 ///
5768 /// Can clamp coordinates of surface operations in a 0..=clamp inclusive
5769 /// range. It also computes other information useful to compute the
5770 /// real address of an element within an image for both block-lienar and
5771 /// pitch-linear layouts. We can also reduce this operation to a "stupid"
5772 /// inclusive clamp by setting modifier Mode=PitchLinear and is_2d=false
5773 /// this will not compute any extra operations and is useful to clamp array
5774 /// indexes.
5775 ///
5776 /// Since the shader code does not know if an image layout is block-linear
5777 /// or pitch-linear, this opcode must be able to do both, the operation
5778 /// is then selected by the "clamp" bitfield, usually read from a descriptor.
5779 /// In block-linear mode we divide the bits that will compute the higher
5780 /// part and the lower part.
5781 #[repr(C)]
5782 #[derive(SrcsAsSlice, DstsAsSlice, Clone)]
5783 pub struct OpSuClamp {
5784 #[dst_type(GPR)]
5785 pub dst: Dst,
5786 #[dst_type(Pred)]
5787 pub out_of_bounds: Dst,
5788
5789 /// This modifier specifies if we use pitch-linear or block-linear
5790 /// calculations, another option is to support both and read the actual
5791 /// format from the clamp (shader code doesn't always know if an image
5792 /// layout).
5793 /// When mode=pitch_linear and is_2d=false the suclamp op enters a
5794 /// simpler "plain" mode where it only performs clamping and the output
5795 /// register doesn't contain any information bits about pitch-linear or
5796 /// block-linear calculations
5797 pub mode: SuClampMode,
5798 /// Strangely enough, "round" just rounds the clamp, not the source
5799 /// this does not help at all with clamping coordinates.
5800 /// It could be useful when clamping raw addresses of a multi-byte read.
5801 /// ex: if we read 4 bytes at once, and the buffer length is 16,
5802 /// the bounds will be 15 (they are inclusive), but if we read
5803 /// at address 15 we would read bytes 15..19, so we are out of range.
5804 /// if we clamp tthe bounds to R4 the effective bound becomes 12
5805 /// so the read will be performed from 12..16, remaining in bounds.
5806 pub round: SuClampRound,
5807 pub is_s32: bool,
5808 pub is_2d: bool,
5809
5810 #[src_type(GPR)]
5811 pub coords: Src,
5812
5813 /// Packed parameter containing both bounds (inclusive)
5814 /// and other information (explained in more details in Foldable):
5815 /// 0..20: bound (inclusive)
5816 /// 21: pitch_linear (used if mode == StoredInDescriptor)
5817 /// 22..26: coord shl
5818 /// 26..29: coord shr
5819 /// 29..32: n. of tiles
5820 #[src_type(ALU)]
5821 pub params: Src,
5822 /// Added to the coords, it's only an i6
5823 pub imm: i8,
5824 }
5825
5826 impl Foldable for OpSuClamp {
5827 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
5828 let src = f.get_u32_src(self, &self.coords);
5829 let params = f.get_u32_src(self, &self.params);
5830 let imm = self.imm; // i6
5831
5832 let src = if self.is_s32 {
5833 (src as i32) as i64
5834 } else {
5835 src as i64
5836 };
5837 let src = src + (imm as i64);
5838
5839 let params_bv = BitView::new(&params);
5840 let pitch_linear = match self.mode {
5841 SuClampMode::StoredInDescriptor => params_bv.get_bit(21),
5842 SuClampMode::PitchLinear => true,
5843 SuClampMode::BlockLinear => false,
5844 };
5845
5846 let bounds = if pitch_linear && !self.is_2d {
5847 params
5848 } else {
5849 params_bv.get_bit_range_u64(0..20) as u32
5850 };
5851
5852 let bounds = bounds & self.round.to_mask();
5853 let (is_oob, clamped) = if src < 0 {
5854 (true, 0)
5855 } else if src > (bounds as i64) {
5856 (true, bounds)
5857 } else {
5858 (false, src as u32)
5859 };
5860
5861 let mut out = 0u32;
5862 let mut bv = BitMutView::new(&mut out);
5863 if pitch_linear {
5864 if !self.is_2d {
5865 // simple clamp mode, NO BITFIELD
5866 bv.set_field(0..32, clamped);
5867 } else {
5868 // Real, pitch_linear mode
5869 bv.set_field(0..20, clamped & 0xfffff);
5870
5871 // Pass through el_size_log2
5872 bv.set_field(27..30, params_bv.get_bit_range_u64(26..29));
5873 bv.set_bit(30, true); // pitch_linear=true
5874 bv.set_bit(31, is_oob);
5875 }
5876 } else {
5877 // Block linear
5878
5879 // Number of bits to discard for GoB coordinates
5880 let shr_a = params_bv.get_bit_range_u64(22..26) as u8;
5881 // Block coords
5882 bv.set_field(0..16, (clamped >> shr_a) & 0xffff);
5883
5884 // Shift applied to coords, always zero except for x.
5885 // (for coord x=1 and format R32, we want to access byte 4)
5886 // e.g. R8 -> 0, R32 -> 2, 128 -> 4
5887 let el_size_log2 = params_bv.get_bit_range_u64(26..29) as u8;
5888 // Coord inside GoB (element space)
5889 bv.set_field(16..24, (clamped << el_size_log2) & 0xff);
5890
5891 // Useful later to compute gob-space coords.
5892 let n_tiles = params_bv.get_bit_range_u64(29..32) as u8;
5893 bv.set_field(27..30, n_tiles);
5894 bv.set_bit(30, false); // pitch_linear=false
5895 bv.set_bit(31, is_oob);
5896 }
5897 f.set_u32_dst(self, &self.dst, out);
5898 f.set_pred_dst(self, &self.out_of_bounds, is_oob);
5899 }
5900 }
5901
5902 impl DisplayOp for OpSuClamp {
5903 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5904 write!(f, "suclamp{}", self.mode)?;
5905 if !matches!(self.round, SuClampRound::R1) {
5906 write!(f, "{}", self.round)?;
5907 }
5908 if !self.is_s32 {
5909 write!(f, ".u32")?;
5910 }
5911 if !self.is_2d {
5912 write!(f, ".1d")?;
5913 }
5914
5915 write! {f, " {} {} {:x}", self.coords, self.params, self.imm}
5916 }
5917 }
5918 impl_display_for_op!(OpSuClamp);
5919
5920 /// Kepler only
5921 /// BitField Merge
5922 ///
5923 /// The resulting bit-field is composed of a high-part 8..32 that is merged
5924 /// with the address by sueau, and a lower-part 0..8 that is provided
5925 /// directly to suldga/sustga and defines the lower offset of the glonal array.
5926 #[repr(C)]
5927 #[derive(SrcsAsSlice, DstsAsSlice, Clone)]
5928 pub struct OpSuBfm {
5929 #[dst_type(GPR)]
5930 pub dst: Dst,
5931 #[dst_type(Pred)]
5932 pub pdst: Dst,
5933
5934 /// x, y, z
5935 #[src_type(ALU)]
5936 pub srcs: [Src; 3],
5937 /// When is_3d=false the third source is ignored, but still used in
5938 /// pitch-linear computation.
5939 pub is_3d: bool,
5940 }
5941
5942 impl Foldable for OpSuBfm {
5943 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
5944 let x_raw = f.get_u32_src(self, &self.srcs[0]);
5945 let y_raw = f.get_u32_src(self, &self.srcs[1]);
5946 let z_raw = f.get_u32_src(self, &self.srcs[2]);
5947
5948 let x = BitView::new(&x_raw);
5949 let y = BitView::new(&y_raw);
5950 let z = BitView::new(&z_raw);
5951
5952 let mut o_raw = 0u32;
5953 let mut o = BitMutView::new(&mut o_raw);
5954
5955 let is_pitch_linear_2d = x.get_bit(30) || y.get_bit(30);
5956
5957 if !is_pitch_linear_2d {
5958 // Copy coordinates inside of GoB space.
5959 // They are 6 bits from x and 3 from y (GoB is 64x8 bytes).
5960 // Bits from 0..8 are ignored by sueau and are used directly
5961 // by suldga/sustga.
5962 // Bit 9 will become the first bit of the higher part in
5963 // sueau.
5964 o.set_bit_range_u64(0..4, x.get_bit_range_u64(16..20));
5965
5966 // Address calculation inside of GoB should virtually be
5967 // y * 64 + x * element_size (each row is linear).
5968 // So why are those bits swizzled like so?
5969 // I have no idea, but these are correct even for atomics
5970 // that accept real addresses.
5971 o.set_bit(4, y.get_bit(16));
5972 o.set_bit(5, y.get_bit(17));
5973 o.set_bit(6, x.get_bit(20));
5974 o.set_bit(7, y.get_bit(18));
5975
5976 o.set_bit(8, x.get_bit(21));
5977 // 9..11: 0
5978
5979 // -------------- Tiles --------------
5980 // Number of tiles log2
5981 let ntx = x.get_bit_range_u64(27..30) & 0x1;
5982 let nty = y.get_bit_range_u64(27..30);
5983 let ntz = z.get_bit_range_u64(27..30);
5984 let ntz = ntz * (self.is_3d as u64); // z is ignored if is_3d=false
5985
5986 // Computes how many bits to dedicate to GoB coords inside
5987 // a block
5988 o.set_field(12..16, ntx + nty + ntz);
5989
5990 // Coords in gob_space.
5991 // Remove 6 bits from x and 3 bits from y, those are used
5992 // as element coords in GoB space.
5993 let a = x.get_bit_range_u64(22..24); // 1100_0000
5994 let b = y.get_bit_range_u64(19..24); // 1111_1000
5995 let c = z.get_bit_range_u64(16..24); // 1111_1111
5996
5997 // nt* indicates how many bits to consider (max 5)
5998 let a = a & ((1 << ntx) - 1);
5999 let b = b & ((1 << nty.min(5)) - 1);
6000 let c = c & ((1 << ntz.min(5)) - 1);
6001
6002 // Compute gob offset
6003 // We can just or together at certain offsets because
6004 // Tiles are always powers of two in each direction.
6005 // z || y || x (LSB)
6006 let res = c;
6007 let res = (res << nty) | b;
6008 let res = (res << ntx) | a;
6009 let mask = match ntx {
6010 0 => 0x3ff,
6011 _ => 0x7ff,
6012 };
6013
6014 // gob coords will be put before the block coords in
6015 // sueau.
6016 o.set_field(16..27, res & mask);
6017 } else {
6018 let d = z.get_bit_range_u64(0..8);
6019 let el_size_log2 = x.get_bit_range_u64(27..30);
6020 o.set_field(0..8, (d << el_size_log2) & 0xff);
6021 // 9..11: 0
6022 o.set_field(12..15, el_size_log2);
6023 }
6024
6025 o.set_bit(11, is_pitch_linear_2d);
6026
6027 let is_oob =
6028 x.get_bit(31) || y.get_bit(31) || (z.get_bit(31) && self.is_3d);
6029 f.set_u32_dst(self, &self.dst, o_raw);
6030 f.set_pred_dst(self, &self.pdst, is_oob);
6031 }
6032 }
6033
6034 impl DisplayOp for OpSuBfm {
6035 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6036 write!(f, "subfm")?;
6037
6038 if self.is_3d {
6039 write!(f, ".3d")?;
6040 }
6041
6042 write!(f, " {} {} {}", self.srcs[0], self.srcs[1], self.srcs[2])
6043 }
6044 }
6045 impl_display_for_op!(OpSuBfm);
6046
6047 /// Kepler only
6048 /// Used to compute the higher 32 bits of image address using
6049 /// the merged bitfield and the block coordinates (offset).
6050 /// It can switch to a pitch_linear mode (bit 11 of bit-field).
6051 #[repr(C)]
6052 #[derive(SrcsAsSlice, DstsAsSlice, Clone)]
6053 pub struct OpSuEau {
6054 #[dst_type(GPR)]
6055 pub dst: Dst,
6056
6057 /// offset is computed from the block coordinates.
6058 /// it's ok to add it directly to the address since they are both
6059 /// "aligned" to 64 (the first 8 bits are removed from both)
6060 #[src_type(GPR)]
6061 pub off: Src,
6062
6063 /// 8.. 9: offset, last bit
6064 /// 11..12: pitch_linear: when enabled the bf-offset is ignored and
6065 /// the off_shl is subtracted by 8
6066 /// 12..16: off_shl, shifts left the offset by off_shl + 1
6067 /// 16..27: 11-bit offset, when joined with the 1-bit offset completes the
6068 /// 12-bit offset ORed to the src offset after shifting
6069 /// (unless pitch_linear)
6070 #[src_type(ALU)]
6071 pub bit_field: Src,
6072
6073 #[src_type(GPR)]
6074 pub addr: Src,
6075 }
6076
6077 impl Foldable for OpSuEau {
6078 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
6079 let off_raw = f.get_u32_src(self, &self.off);
6080 let bf_raw = f.get_u32_src(self, &self.bit_field);
6081 let addr = f.get_u32_src(self, &self.addr);
6082
6083 let bf = BitView::new(&bf_raw);
6084
6085 let off1 = bf.get_bit_range_u64(8..9) as u32;
6086 let is_pitch_linear = bf.get_bit(11);
6087 let off_shift = bf.get_bit_range_u64(12..16) as u32;
6088 let offs = bf.get_bit_range_u64(16..27) as u32;
6089
6090 let res = if !is_pitch_linear {
6091 // Block linear
6092 // off_raw are the block coordinates
6093 // to those we add gob coordinates from the merged bitfield
6094 // and the MSB of in-gob coordinates.
6095 let omul = off_shift + 1;
6096 let real_off = (off_raw << omul) | (offs << 1) | off1;
6097 addr.wrapping_add(real_off & 0x7ff_ffff)
6098 } else {
6099 // Add the high part of the coordinates to addr
6100 // off << (omul - 8)
6101 // but for negative values do a shr instead.
6102 // In fact, off_shift will always be < 8 because pitch_linear
6103 // subfm only assigns bits 12..15, so this is always a shr
6104 let shl_amount = off_shift as i32 - 8;
6105 let off = if shl_amount < 0 {
6106 off_raw >> (-shl_amount as u32)
6107 } else {
6108 off_raw << (shl_amount as u32)
6109 };
6110 addr.wrapping_add(off & 0xff_ffff)
6111 };
6112 f.set_u32_dst(self, &self.dst, res);
6113 }
6114 }
6115
6116 impl DisplayOp for OpSuEau {
6117 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6118 write! {f, "sueau {} {} {}", self.off, self.bit_field, self.addr}
6119 }
6120 }
6121 impl_display_for_op!(OpSuEau);
6122
6123 #[derive(Copy, Clone, Debug)]
6124 pub enum IMadSpSrcType {
6125 U32,
6126 U24,
6127 U16Hi,
6128 U16Lo,
6129 S32,
6130 S24,
6131 S16Hi,
6132 S16Lo,
6133 }
6134
6135 impl IMadSpSrcType {
6136 pub fn unsigned(self) -> IMadSpSrcType {
6137 use IMadSpSrcType::*;
6138 match self {
6139 S32 => U32,
6140 S24 => U24,
6141 S16Hi => U16Hi,
6142 S16Lo => U16Lo,
6143 x => x,
6144 }
6145 }
6146
6147 #[allow(dead_code)] // Used in hw_tests
6148 pub fn with_sign(self, sign: bool) -> Self {
6149 use IMadSpSrcType::*;
6150 if !sign {
6151 return self.unsigned();
6152 }
6153 match self {
6154 U32 => S32,
6155 U24 => S24,
6156 U16Hi => S16Hi,
6157 U16Lo => S16Lo,
6158 x => x,
6159 }
6160 }
6161
6162 pub fn sign(self) -> bool {
6163 use IMadSpSrcType::*;
6164 match self {
6165 U32 | U24 | U16Hi | U16Lo => false,
6166 S32 | S24 | S16Hi | S16Lo => true,
6167 }
6168 }
6169
6170 #[allow(dead_code)]
6171 fn cast(&self, v: u32) -> i64 {
6172 use IMadSpSrcType::*;
6173 match self {
6174 U32 => v as i64,
6175 U24 => (v & 0x00ff_ffff) as i64,
6176 U16Lo => (v as u16) as i64,
6177 U16Hi => (v >> 16) as i64,
6178 S32 => (v as i32) as i64,
6179 S24 => (((v as i32) << 8) >> 8) as i64, // Sign extend
6180 S16Lo => (v as i16) as i64,
6181 S16Hi => ((v >> 16) as i16) as i64,
6182 }
6183 }
6184 }
6185
6186 impl fmt::Display for IMadSpSrcType {
6187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6188 let sign = if self.sign() { ".s" } else { ".u" };
6189 let width = match self.unsigned() {
6190 IMadSpSrcType::U32 => "32",
6191 IMadSpSrcType::U24 => "24",
6192 IMadSpSrcType::U16Lo => "16h0",
6193 IMadSpSrcType::U16Hi => "16h1",
6194 _ => unreachable!(),
6195 };
6196 write!(f, "{}{}", sign, width)
6197 }
6198 }
6199
6200 #[derive(Clone, Copy, Debug)]
6201 pub enum IMadSpMode {
6202 Explicit([IMadSpSrcType; 3]),
6203 // Parameters are loaded from src1 bits 26..32
6204 FromSrc1,
6205 }
6206
6207 impl fmt::Display for IMadSpMode {
6208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6209 match self {
6210 IMadSpMode::Explicit([a, b, c]) => write!(f, "{a}{b}{c}"),
6211 IMadSpMode::FromSrc1 => write!(f, ".sd"),
6212 }
6213 }
6214 }
6215
6216 /// Kepler only
6217 /// Extracted Integer Multiply and Add.
6218 /// It does the same operation as an imad op, but it can extract the
6219 /// sources from a subset of the register (only 32, 24 or 16 bits).
6220 /// It can also do a "load parameters" mode where the modifiers are
6221 /// loaded from the higher bits in src2 (check Foldable impl for details).
6222 /// Limits: src1 can never be U32 or U16Hi,
6223 /// src2 can never be U16Hi
6224 /// src2 signedness is tied to src1 and src0 signedness,
6225 /// if either is signed, src2 must be signed too.
6226 #[repr(C)]
6227 #[derive(SrcsAsSlice, DstsAsSlice, Clone)]
6228 pub struct OpIMadSp {
6229 #[dst_type(GPR)]
6230 pub dst: Dst,
6231
6232 #[src_type(ALU)]
6233 pub srcs: [Src; 3],
6234
6235 pub mode: IMadSpMode,
6236 }
6237
6238 impl Foldable for OpIMadSp {
6239 fn fold(&self, _sm: &ShaderModelInfo, f: &mut OpFoldData<'_>) {
6240 let src0 = f.get_u32_src(self, &self.srcs[0]);
6241 let src1 = f.get_u32_src(self, &self.srcs[1]);
6242 let src2 = f.get_u32_src(self, &self.srcs[2]);
6243
6244 let (src_type0, src_type1, src_type2) = match self.mode {
6245 IMadSpMode::Explicit([t0, t1, t2]) => (t0, t1, t2),
6246 IMadSpMode::FromSrc1 => {
6247 let params = BitView::new(&src1);
6248
6249 let st2 = params.get_bit_range_u64(26..28) as usize;
6250 let st1 = params.get_bit_range_u64(28..30) as usize;
6251 let st0 = params.get_bit_range_u64(30..32) as usize;
6252
6253 use IMadSpSrcType::*;
6254 let types0 = [U32, U24, U16Lo, U16Hi];
6255 let types1 = [U16Lo, U24, U16Lo, U24];
6256 let types2 = [U32, U24, U16Lo, U32];
6257
6258 (
6259 types0[st0].unsigned(),
6260 types1[st1].unsigned(),
6261 types2[st2].unsigned(),
6262 )
6263 }
6264 };
6265
6266 let src0 = src_type0.cast(src0);
6267 let src1 = src_type1.cast(src1);
6268 let src2 = src_type2.cast(src2);
6269
6270 f.set_u32_dst(self, &self.dst, (src0 * src1 + src2) as u32);
6271 }
6272 }
6273
6274 impl DisplayOp for OpIMadSp {
6275 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6276 write!(
6277 f,
6278 "imadsp{} {} {} {}",
6279 self.mode, self.srcs[0], self.srcs[1], self.srcs[2]
6280 )
6281 }
6282 }
6283 impl_display_for_op!(OpIMadSp);
6284
6285 /// In SuGa ops, the address is always specified in two parts, the higher
6286 /// part contains the base address without the lower 8 bits (base_addr >> 8),
6287 /// while the lower part might contain either the missing 8 bits (U8) or
6288 /// a full 32-bit offset that must not be shifted (U32).
6289 ///
6290 /// In short:
6291 /// U8 : real_address = (addr_hi << 8) + (addr_lo & 0xFF)
6292 /// U32: real_address = (addr_hi << 8) + addr_lo
6293 /// The signed variants do the same but with sign extension probably
6294 #[derive(Clone, Copy)]
6295 pub enum SuGaOffsetMode {
6296 U32,
6297 S32,
6298 U8,
6299 S8,
6300 }
6301
6302 /// Kepler only
6303 /// Load a pixel from an image, takes the pixel address and format as an
6304 /// argument. Since the image coordinates are not present, the instruction
6305 /// also needs an `out_of_bounds` predicate, when true it always load (0, 0, 0, 1)
6306 #[repr(C)]
6307 #[derive(SrcsAsSlice, DstsAsSlice)]
6308 pub struct OpSuLdGa {
6309 pub dst: Dst,
6310
6311 pub mem_type: MemType,
6312 pub offset_mode: SuGaOffsetMode,
6313 pub cache_op: LdCacheOp,
6314
6315 /// Format for the loaded data, passed directly from the descriptor.
6316 #[src_type(GPR)]
6317 pub format: Src,
6318
6319 /// This is not an address, but it's two registers that contain
6320 /// [addr >> 8, addr & 0xff].
6321 /// This works because addr >> 8 is 32-bits (GOB-aligned) and the
6322 /// rest 8-bits are extracted by the bit-field
6323 /// It's useful since in block-linear mode the lower bits and the higher
6324 /// bits are computed in different ways.
6325 #[src_type(SSA)]
6326 pub addr: Src,
6327
6328 #[src_type(Pred)]
6329 pub out_of_bounds: Src,
6330 }
6331
6332 impl DisplayOp for OpSuLdGa {
6333 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6334 write!(
6335 f,
6336 "suldga{}{} [{}] {} {}",
6337 self.mem_type,
6338 self.cache_op,
6339 self.addr,
6340 self.format,
6341 self.out_of_bounds
6342 )
6343 }
6344 }
6345 impl_display_for_op!(OpSuLdGa);
6346
6347 /// Kepler only
6348 /// Store a pixel in an image, takes the pixel address and format as an
6349 /// argument. Since the image coordinates are not present, the instruction
6350 /// also needs an `out_of_bounds` predicate, when true, stores are ingored
6351 #[repr(C)]
6352 #[derive(SrcsAsSlice, DstsAsSlice)]
6353 pub struct OpSuStGa {
6354 pub image_access: ImageAccess,
6355 pub offset_mode: SuGaOffsetMode,
6356 pub cache_op: StCacheOp,
6357
6358 #[src_type(GPR)]
6359 pub format: Src,
6360
6361 #[src_type(SSA)]
6362 pub addr: Src,
6363
6364 #[src_type(SSA)]
6365 pub data: Src,
6366
6367 #[src_type(Pred)]
6368 pub out_of_bounds: Src,
6369 }
6370
6371 impl DisplayOp for OpSuStGa {
6372 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6373 write!(
6374 f,
6375 "sustga{}{} [{}] {} {} {}",
6376 self.image_access,
6377 self.cache_op,
6378 self.addr,
6379 self.format,
6380 self.data,
6381 self.out_of_bounds,
6382 )
6383 }
6384 }
6385 impl_display_for_op!(OpSuStGa);
6386
6387 #[repr(C)]
6388 #[derive(SrcsAsSlice, DstsAsSlice)]
6389 pub struct OpLd {
6390 pub dst: Dst,
6391
6392 #[src_type(GPR)]
6393 pub addr: Src,
6394
6395 pub offset: i32,
6396 pub access: MemAccess,
6397 }
6398
6399 impl DisplayOp for OpLd {
6400 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6401 write!(f, "ld{} [{}", self.access, self.addr)?;
6402 if self.offset > 0 {
6403 write!(f, "+{:#x}", self.offset)?;
6404 }
6405 write!(f, "]")
6406 }
6407 }
6408 impl_display_for_op!(OpLd);
6409
6410 #[allow(dead_code)]
6411 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
6412 pub enum LdcMode {
6413 Indexed,
6414 IndexedLinear,
6415 IndexedSegmented,
6416 IndexedSegmentedLinear,
6417 }
6418
6419 impl fmt::Display for LdcMode {
6420 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6421 match self {
6422 LdcMode::Indexed => Ok(()),
6423 LdcMode::IndexedLinear => write!(f, ".il"),
6424 LdcMode::IndexedSegmented => write!(f, ".is"),
6425 LdcMode::IndexedSegmentedLinear => write!(f, ".isl"),
6426 }
6427 }
6428 }
6429
6430 #[repr(C)]
6431 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
6432 pub struct OpLdc {
6433 pub dst: Dst,
6434
6435 #[src_type(ALU)]
6436 pub cb: Src,
6437
6438 #[src_type(GPR)]
6439 pub offset: Src,
6440
6441 pub mode: LdcMode,
6442 pub mem_type: MemType,
6443 }
6444
6445 impl DisplayOp for OpLdc {
6446 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6447 let SrcRef::CBuf(cb) = &self.cb.src_ref else {
6448 panic!("Not a cbuf");
6449 };
6450 write!(f, "ldc{}{} {}[", self.mode, self.mem_type, cb.buf)?;
6451 if self.offset.is_zero() {
6452 write!(f, "+{:#x}", cb.offset)?;
6453 } else if cb.offset == 0 {
6454 write!(f, "{}", self.offset)?;
6455 } else {
6456 write!(f, "{}+{:#x}", self.offset, cb.offset)?;
6457 }
6458 write!(f, "]")
6459 }
6460 }
6461 impl_display_for_op!(OpLdc);
6462
6463 #[derive(Clone, Copy, Eq, PartialEq)]
6464 pub enum LdsmSize {
6465 M8N8,
6466 MT8N8,
6467 }
6468
6469 impl fmt::Display for LdsmSize {
6470 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6471 match self {
6472 LdsmSize::M8N8 => write!(f, "m8n8"),
6473 LdsmSize::MT8N8 => write!(f, "m8n8.trans"),
6474 }
6475 }
6476 }
6477
6478 #[repr(C)]
6479 #[derive(SrcsAsSlice, DstsAsSlice)]
6480 pub struct OpLdsm {
6481 #[dst_type(Vec)]
6482 pub dst: Dst,
6483
6484 pub mat_size: LdsmSize,
6485 pub mat_count: u8,
6486
6487 #[src_type(SSA)]
6488 pub addr: Src,
6489
6490 pub offset: i32,
6491 }
6492
6493 impl DisplayOp for OpLdsm {
6494 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6495 write!(
6496 f,
6497 "ldsm.16.{}.x{} [{}",
6498 self.mat_size, self.mat_count, self.addr,
6499 )?;
6500 if self.offset > 0 {
6501 write!(f, "+{:#x}", self.offset)?;
6502 }
6503 write!(f, "]")
6504 }
6505 }
6506
6507 impl_display_for_op!(OpLdsm);
6508
6509 /// Used for Kepler to implement shared atomics.
6510 /// In addition to the load, it tries to lock the address,
6511 /// Kepler hardware has (1024?) hardware mutex locks.
6512 #[repr(C)]
6513 #[derive(SrcsAsSlice, DstsAsSlice)]
6514 pub struct OpLdSharedLock {
6515 pub dst: Dst,
6516 #[dst_type(Pred)]
6517 pub locked: Dst,
6518
6519 #[src_type(GPR)]
6520 pub addr: Src,
6521
6522 pub offset: i32,
6523 pub mem_type: MemType,
6524 }
6525
6526 impl DisplayOp for OpLdSharedLock {
6527 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6528 write!(f, "ldslk{} [{}", self.mem_type, self.addr)?;
6529 if self.offset > 0 {
6530 write!(f, "+{:#x}", self.offset)?;
6531 }
6532 write!(f, "]")
6533 }
6534 }
6535 impl_display_for_op!(OpLdSharedLock);
6536
6537 #[repr(C)]
6538 #[derive(SrcsAsSlice, DstsAsSlice)]
6539 pub struct OpSt {
6540 #[src_type(GPR)]
6541 pub addr: Src,
6542
6543 #[src_type(SSA)]
6544 pub data: Src,
6545
6546 pub offset: i32,
6547 pub access: MemAccess,
6548 }
6549
6550 impl DisplayOp for OpSt {
6551 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6552 write!(f, "st{} [{}", self.access, self.addr)?;
6553 if self.offset > 0 {
6554 write!(f, "+{:#x}", self.offset)?;
6555 }
6556 write!(f, "] {}", self.data)
6557 }
6558 }
6559 impl_display_for_op!(OpSt);
6560
6561 /// Used for Kepler to implement shared atomics.
6562 /// It checks that the address is still properly locked, performs the
6563 /// store operation and unlocks the previously unlocked address.
6564 #[repr(C)]
6565 #[derive(SrcsAsSlice, DstsAsSlice)]
6566 pub struct OpStSCheckUnlock {
6567 #[dst_type(Pred)]
6568 pub locked: Dst,
6569
6570 #[src_type(GPR)]
6571 pub addr: Src,
6572 #[src_type(SSA)]
6573 pub data: Src,
6574
6575 pub offset: i32,
6576 pub mem_type: MemType,
6577 }
6578
6579 impl DisplayOp for OpStSCheckUnlock {
6580 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6581 write!(f, "stscul{} [{}", self.mem_type, self.addr)?;
6582 if self.offset > 0 {
6583 write!(f, "+{:#x}", self.offset)?;
6584 }
6585 write!(f, "] {}", self.data)
6586 }
6587 }
6588 impl_display_for_op!(OpStSCheckUnlock);
6589
6590 #[repr(C)]
6591 #[derive(SrcsAsSlice, DstsAsSlice)]
6592 pub struct OpAtom {
6593 pub dst: Dst,
6594
6595 #[src_type(GPR)]
6596 pub addr: Src,
6597
6598 #[src_type(GPR)]
6599 pub cmpr: Src,
6600
6601 #[src_type(SSA)]
6602 pub data: Src,
6603
6604 pub atom_op: AtomOp,
6605 pub atom_type: AtomType,
6606
6607 pub addr_offset: i32,
6608
6609 pub mem_space: MemSpace,
6610 pub mem_order: MemOrder,
6611 pub mem_eviction_priority: MemEvictionPriority,
6612 }
6613
6614 impl DisplayOp for OpAtom {
6615 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6616 write!(
6617 f,
6618 "atom{}{}{}{}{}",
6619 self.atom_op,
6620 self.atom_type,
6621 self.mem_space,
6622 self.mem_order,
6623 self.mem_eviction_priority,
6624 )?;
6625 write!(f, " [")?;
6626 if !self.addr.is_zero() {
6627 write!(f, "{}", self.addr)?;
6628 }
6629 if self.addr_offset > 0 {
6630 if !self.addr.is_zero() {
6631 write!(f, "+")?;
6632 }
6633 write!(f, "{:#x}", self.addr_offset)?;
6634 }
6635 write!(f, "]")?;
6636 if self.atom_op == AtomOp::CmpExch(AtomCmpSrc::Separate) {
6637 write!(f, " {}", self.cmpr)?;
6638 }
6639 write!(f, " {}", self.data)
6640 }
6641 }
6642 impl_display_for_op!(OpAtom);
6643
6644 #[repr(C)]
6645 #[derive(SrcsAsSlice, DstsAsSlice)]
6646 pub struct OpAL2P {
6647 pub dst: Dst,
6648
6649 #[src_type(GPR)]
6650 pub offset: Src,
6651
6652 pub addr: u16,
6653 pub comps: u8,
6654 pub output: bool,
6655 }
6656
6657 impl DisplayOp for OpAL2P {
6658 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6659 write!(f, "al2p")?;
6660 if self.output {
6661 write!(f, ".o")?;
6662 }
6663 write!(f, " a[{:#x}", self.addr)?;
6664 if !self.offset.is_zero() {
6665 write!(f, "+{}", self.offset)?;
6666 }
6667 write!(f, "]")
6668 }
6669 }
6670 impl_display_for_op!(OpAL2P);
6671
6672 #[repr(C)]
6673 #[derive(SrcsAsSlice, DstsAsSlice)]
6674 pub struct OpALd {
6675 pub dst: Dst,
6676
6677 #[src_type(GPR)]
6678 pub vtx: Src,
6679
6680 #[src_type(GPR)]
6681 pub offset: Src,
6682
6683 pub addr: u16,
6684 pub comps: u8,
6685 pub patch: bool,
6686 pub output: bool,
6687 pub phys: bool,
6688 }
6689
6690 impl DisplayOp for OpALd {
6691 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6692 write!(f, "ald")?;
6693 if self.output {
6694 write!(f, ".o")?;
6695 }
6696 if self.patch {
6697 write!(f, ".p")?;
6698 }
6699 if self.phys {
6700 write!(f, ".phys")?;
6701 }
6702 write!(f, " a")?;
6703 if !self.vtx.is_zero() {
6704 write!(f, "[{}]", self.vtx)?;
6705 }
6706 write!(f, "[{:#x}", self.addr)?;
6707 if !self.offset.is_zero() {
6708 write!(f, "+{}", self.offset)?;
6709 }
6710 write!(f, "]")
6711 }
6712 }
6713 impl_display_for_op!(OpALd);
6714
6715 #[repr(C)]
6716 #[derive(SrcsAsSlice, DstsAsSlice)]
6717 pub struct OpASt {
6718 #[src_type(GPR)]
6719 pub vtx: Src,
6720
6721 #[src_type(GPR)]
6722 pub offset: Src,
6723
6724 #[src_type(SSA)]
6725 pub data: Src,
6726
6727 pub addr: u16,
6728 pub comps: u8,
6729 pub patch: bool,
6730 pub phys: bool,
6731 }
6732
6733 impl DisplayOp for OpASt {
6734 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6735 write!(f, "ast")?;
6736 if self.patch {
6737 write!(f, ".p")?;
6738 }
6739 if self.phys {
6740 write!(f, ".phys")?;
6741 }
6742 write!(f, " a")?;
6743 if !self.vtx.is_zero() {
6744 write!(f, "[{}]", self.vtx)?;
6745 }
6746 write!(f, "[{:#x}", self.addr)?;
6747 if !self.offset.is_zero() {
6748 write!(f, "+{}", self.offset)?;
6749 }
6750 write!(f, "] {}", self.data)
6751 }
6752 }
6753 impl_display_for_op!(OpASt);
6754
6755 #[repr(C)]
6756 #[derive(SrcsAsSlice, DstsAsSlice)]
6757 pub struct OpIpa {
6758 pub dst: Dst,
6759 pub addr: u16,
6760 pub freq: InterpFreq,
6761 pub loc: InterpLoc,
6762 pub inv_w: Src,
6763 pub offset: Src,
6764 }
6765
6766 impl DisplayOp for OpIpa {
6767 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6768 write!(
6769 f,
6770 "ipa{}{} a[{:#x}] {}",
6771 self.freq, self.loc, self.addr, self.inv_w
6772 )?;
6773 if self.loc == InterpLoc::Offset {
6774 write!(f, " {}", self.offset)?;
6775 }
6776 Ok(())
6777 }
6778 }
6779 impl_display_for_op!(OpIpa);
6780
6781 #[repr(C)]
6782 #[derive(SrcsAsSlice, DstsAsSlice)]
6783 pub struct OpLdTram {
6784 pub dst: Dst,
6785 pub addr: u16,
6786 pub use_c: bool,
6787 }
6788
6789 impl DisplayOp for OpLdTram {
6790 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6791 write!(f, "ldtram")?;
6792 if self.use_c {
6793 write!(f, ".c")?;
6794 } else {
6795 write!(f, ".ab")?;
6796 }
6797 write!(f, " a[{:#x}]", self.addr)?;
6798 Ok(())
6799 }
6800 }
6801 impl_display_for_op!(OpLdTram);
6802
6803 #[allow(dead_code)]
6804 #[derive(Copy, Clone, Debug)]
6805 pub enum CCtlOp {
6806 Qry1, // Only available pre-Volta
6807 PF1,
6808 PF1_5, // Only available pre-Volta
6809 PF2,
6810 WB,
6811 IV,
6812 IVAll,
6813 RS,
6814 RSLB, // Only available pre-Volta
6815 IVAllP, // Only available on Volta+
6816 WBAll, // Only available on Volta+
6817 WBAllP, // Only available on Volta+
6818 }
6819
6820 impl CCtlOp {
6821 pub fn is_all(&self) -> bool {
6822 match self {
6823 CCtlOp::Qry1
6824 | CCtlOp::PF1
6825 | CCtlOp::PF1_5
6826 | CCtlOp::PF2
6827 | CCtlOp::WB
6828 | CCtlOp::IV
6829 | CCtlOp::RS
6830 | CCtlOp::RSLB => false,
6831 CCtlOp::IVAll | CCtlOp::IVAllP | CCtlOp::WBAll | CCtlOp::WBAllP => {
6832 true
6833 }
6834 }
6835 }
6836 }
6837
6838 impl fmt::Display for CCtlOp {
6839 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6840 match self {
6841 CCtlOp::Qry1 => write!(f, "qry1"),
6842 CCtlOp::PF1 => write!(f, "pf1"),
6843 CCtlOp::PF1_5 => write!(f, "pf1.5"),
6844 CCtlOp::PF2 => write!(f, "pf2"),
6845 CCtlOp::WB => write!(f, "wb"),
6846 CCtlOp::IV => write!(f, "iv"),
6847 CCtlOp::IVAll => write!(f, "ivall"),
6848 CCtlOp::RS => write!(f, "rs"),
6849 CCtlOp::RSLB => write!(f, "rslb"),
6850 CCtlOp::IVAllP => write!(f, "ivallp"),
6851 CCtlOp::WBAll => write!(f, "wball"),
6852 CCtlOp::WBAllP => write!(f, "wballp"),
6853 }
6854 }
6855 }
6856
6857 #[repr(C)]
6858 #[derive(SrcsAsSlice, DstsAsSlice)]
6859 pub struct OpCCtl {
6860 pub op: CCtlOp,
6861
6862 pub mem_space: MemSpace,
6863
6864 #[src_type(GPR)]
6865 pub addr: Src,
6866
6867 pub addr_offset: i32,
6868 }
6869
6870 impl DisplayOp for OpCCtl {
6871 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6872 write!(f, "cctl{}", self.mem_space)?;
6873 if !self.op.is_all() {
6874 write!(f, " [{}", self.addr)?;
6875 if self.addr_offset > 0 {
6876 write!(f, "+{:#x}", self.addr_offset)?;
6877 }
6878 write!(f, "]")?;
6879 }
6880 Ok(())
6881 }
6882 }
6883 impl_display_for_op!(OpCCtl);
6884
6885 #[repr(C)]
6886 #[derive(SrcsAsSlice, DstsAsSlice)]
6887 pub struct OpMemBar {
6888 pub scope: MemScope,
6889 }
6890
6891 impl DisplayOp for OpMemBar {
6892 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6893 write!(f, "membar.sc.{}", self.scope)
6894 }
6895 }
6896 impl_display_for_op!(OpMemBar);
6897
6898 #[repr(C)]
6899 #[derive(SrcsAsSlice, DstsAsSlice)]
6900 pub struct OpBClear {
6901 pub dst: Dst,
6902 }
6903
6904 impl DisplayOp for OpBClear {
6905 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6906 write!(f, "bclear")
6907 }
6908 }
6909 impl_display_for_op!(OpBClear);
6910
6911 #[repr(C)]
6912 #[derive(SrcsAsSlice, DstsAsSlice)]
6913 pub struct OpBMov {
6914 pub dst: Dst,
6915 pub src: Src,
6916 pub clear: bool,
6917 }
6918
6919 impl DisplayOp for OpBMov {
6920 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6921 write!(f, "bmov.32")?;
6922 if self.clear {
6923 write!(f, ".clear")?;
6924 }
6925 write!(f, " {}", self.src)
6926 }
6927 }
6928 impl_display_for_op!(OpBMov);
6929
6930 #[repr(C)]
6931 #[derive(SrcsAsSlice, DstsAsSlice)]
6932 pub struct OpBreak {
6933 #[dst_type(Bar)]
6934 pub bar_out: Dst,
6935
6936 #[src_type(Bar)]
6937 pub bar_in: Src,
6938
6939 #[src_type(Pred)]
6940 pub cond: Src,
6941 }
6942
6943 impl DisplayOp for OpBreak {
6944 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6945 write!(f, "break {} {}", self.bar_in, self.cond)
6946 }
6947 }
6948 impl_display_for_op!(OpBreak);
6949
6950 #[repr(C)]
6951 #[derive(SrcsAsSlice, DstsAsSlice)]
6952 pub struct OpBSSy {
6953 #[dst_type(Bar)]
6954 pub bar_out: Dst,
6955
6956 #[src_type(Pred)]
6957 pub bar_in: Src,
6958
6959 #[src_type(Pred)]
6960 pub cond: Src,
6961
6962 pub target: Label,
6963 }
6964
6965 impl DisplayOp for OpBSSy {
6966 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6967 write!(f, "bssy {} {} {}", self.bar_in, self.cond, self.target)
6968 }
6969 }
6970 impl_display_for_op!(OpBSSy);
6971
6972 #[repr(C)]
6973 #[derive(SrcsAsSlice, DstsAsSlice)]
6974 pub struct OpBSync {
6975 #[src_type(Bar)]
6976 pub bar: Src,
6977
6978 #[src_type(Pred)]
6979 pub cond: Src,
6980 }
6981
6982 impl DisplayOp for OpBSync {
6983 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6984 write!(f, "bsync {} {}", self.bar, self.cond)
6985 }
6986 }
6987 impl_display_for_op!(OpBSync);
6988
6989 /// Takes the branch when the guard predicate and all sources evaluate to true.
6990 #[repr(C)]
6991 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
6992 pub struct OpBra {
6993 pub target: Label,
6994
6995 /// Can be a UPred if uniform
6996 // TODO: actually .u has another form with an additional UPred input.
6997 #[src_type(Pred)]
6998 pub cond: Src,
6999 }
7000
7001 impl DisplayOp for OpBra {
7002 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7003 write!(f, "bra {} {}", self.cond, self.target)
7004 }
7005 }
7006 impl_display_for_op!(OpBra);
7007
7008 #[repr(C)]
7009 #[derive(SrcsAsSlice, DstsAsSlice)]
7010 pub struct OpSSy {
7011 pub target: Label,
7012 }
7013
7014 impl DisplayOp for OpSSy {
7015 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7016 write!(f, "ssy {}", self.target)
7017 }
7018 }
7019 impl_display_for_op!(OpSSy);
7020
7021 #[repr(C)]
7022 #[derive(SrcsAsSlice, DstsAsSlice)]
7023 pub struct OpSync {
7024 pub target: Label,
7025 }
7026
7027 impl DisplayOp for OpSync {
7028 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7029 write!(f, "sync {}", self.target)
7030 }
7031 }
7032 impl_display_for_op!(OpSync);
7033
7034 #[repr(C)]
7035 #[derive(SrcsAsSlice, DstsAsSlice)]
7036 pub struct OpBrk {
7037 pub target: Label,
7038 }
7039
7040 impl DisplayOp for OpBrk {
7041 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7042 write!(f, "brk {}", self.target)
7043 }
7044 }
7045 impl_display_for_op!(OpBrk);
7046
7047 #[repr(C)]
7048 #[derive(SrcsAsSlice, DstsAsSlice)]
7049 pub struct OpPBk {
7050 pub target: Label,
7051 }
7052
7053 impl DisplayOp for OpPBk {
7054 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7055 write!(f, "pbk {}", self.target)
7056 }
7057 }
7058 impl_display_for_op!(OpPBk);
7059
7060 #[repr(C)]
7061 #[derive(SrcsAsSlice, DstsAsSlice)]
7062 pub struct OpCont {
7063 pub target: Label,
7064 }
7065
7066 impl DisplayOp for OpCont {
7067 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7068 write!(f, "cont {}", self.target)
7069 }
7070 }
7071 impl_display_for_op!(OpCont);
7072
7073 #[repr(C)]
7074 #[derive(SrcsAsSlice, DstsAsSlice)]
7075 pub struct OpPCnt {
7076 pub target: Label,
7077 }
7078
7079 impl DisplayOp for OpPCnt {
7080 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7081 write!(f, "pcnt {}", self.target)
7082 }
7083 }
7084 impl_display_for_op!(OpPCnt);
7085
7086 #[repr(C)]
7087 #[derive(Clone, SrcsAsSlice, DstsAsSlice)]
7088 pub struct OpExit {}
7089
7090 impl DisplayOp for OpExit {
7091 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7092 write!(f, "exit")
7093 }
7094 }
7095 impl_display_for_op!(OpExit);
7096
7097 #[repr(C)]
7098 #[derive(SrcsAsSlice, DstsAsSlice)]
7099 pub struct OpWarpSync {
7100 pub mask: u32,
7101 }
7102
7103 impl DisplayOp for OpWarpSync {
7104 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7105 write!(f, "warpsync 0x{:x}", self.mask)
7106 }
7107 }
7108 impl_display_for_op!(OpWarpSync);
7109
7110 #[repr(C)]
7111 #[derive(SrcsAsSlice, DstsAsSlice)]
7112 pub struct OpBar {}
7113
7114 impl DisplayOp for OpBar {
7115 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7116 write!(f, "bar.sync")
7117 }
7118 }
7119 impl_display_for_op!(OpBar);
7120
7121 /// Instruction only used on Kepler(A|B).
7122 /// Kepler has explicit dependency tracking for texture loads.
7123 /// When a texture load is executed, it is put on some kind of FIFO queue
7124 /// for later execution.
7125 /// Before the results of a texture are used we need to wait on the queue,
7126 /// texdepbar waits until the queue has at most `textures_left` elements.
7127 #[repr(C)]
7128 #[derive(SrcsAsSlice, DstsAsSlice)]
7129 pub struct OpTexDepBar {
7130 pub textures_left: u8,
7131 }
7132
7133 impl OpTexDepBar {
7134 /// Maximum value of textures_left
7135 ///
7136 /// The maximum encodable value is 63. However, nvcc starts emitting
7137 /// TEXDEPBAR 0x3e as soon as it hits 62 texture instructions.
7138 pub const MAX_TEXTURES_LEFT: u8 = 62;
7139 }
7140
7141 impl DisplayOp for OpTexDepBar {
7142 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7143 write!(f, "texdepbar {}", self.textures_left)
7144 }
7145 }
7146 impl_display_for_op!(OpTexDepBar);
7147
7148 #[repr(C)]
7149 #[derive(SrcsAsSlice, DstsAsSlice)]
7150 pub struct OpCS2R {
7151 pub dst: Dst,
7152 pub idx: u8,
7153 }
7154
7155 impl DisplayOp for OpCS2R {
7156 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7157 write!(f, "cs2r sr[{:#x}]", self.idx)
7158 }
7159 }
7160 impl_display_for_op!(OpCS2R);
7161
7162 #[repr(C)]
7163 #[derive(SrcsAsSlice, DstsAsSlice)]
7164 pub struct OpIsberd {
7165 #[dst_type(GPR)]
7166 pub dst: Dst,
7167
7168 #[src_type(SSA)]
7169 pub idx: Src,
7170 }
7171
7172 impl DisplayOp for OpIsberd {
7173 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7174 write!(f, "isberd [{}]", self.idx)
7175 }
7176 }
7177 impl_display_for_op!(OpIsberd);
7178
7179 /// Vertex Index Load
7180 /// (Only available in Kepler)
7181 ///
7182 /// Takes as input the vertex index and loads the vertex address in
7183 /// attribute space.
7184 #[repr(C)]
7185 #[derive(SrcsAsSlice, DstsAsSlice)]
7186 pub struct OpViLd {
7187 #[dst_type(GPR)]
7188 pub dst: Dst,
7189
7190 #[src_type(SSA)]
7191 pub idx: Src,
7192
7193 pub off: i8,
7194 }
7195
7196 impl DisplayOp for OpViLd {
7197 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7198 write!(f, "vild v[")?;
7199
7200 if !self.idx.is_zero() {
7201 write!(f, "{}", self.idx)?;
7202 if self.off != 0 {
7203 write!(f, "{:+}", self.off)?;
7204 }
7205 } else {
7206 write!(f, "{}", self.off)?;
7207 }
7208
7209 write!(f, "]")
7210 }
7211 }
7212 impl_display_for_op!(OpViLd);
7213
7214 #[repr(C)]
7215 #[derive(SrcsAsSlice, DstsAsSlice)]
7216 pub struct OpKill {}
7217
7218 impl DisplayOp for OpKill {
7219 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7220 write!(f, "kill")
7221 }
7222 }
7223 impl_display_for_op!(OpKill);
7224
7225 #[repr(C)]
7226 #[derive(SrcsAsSlice, DstsAsSlice)]
7227 pub struct OpNop {
7228 pub label: Option<Label>,
7229 }
7230
7231 impl DisplayOp for OpNop {
7232 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7233 write!(f, "nop")?;
7234 if let Some(label) = &self.label {
7235 write!(f, " {}", label)?;
7236 }
7237 Ok(())
7238 }
7239 }
7240 impl_display_for_op!(OpNop);
7241
7242 #[allow(dead_code)]
7243 pub enum PixVal {
7244 MsCount,
7245 CovMask,
7246 Covered,
7247 Offset,
7248 CentroidOffset,
7249 MyIndex,
7250 InnerCoverage,
7251 }
7252
7253 impl fmt::Display for PixVal {
7254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7255 match self {
7256 PixVal::MsCount => write!(f, ".mscount"),
7257 PixVal::CovMask => write!(f, ".covmask"),
7258 PixVal::Covered => write!(f, ".covered"),
7259 PixVal::Offset => write!(f, ".offset"),
7260 PixVal::CentroidOffset => write!(f, ".centroid_offset"),
7261 PixVal::MyIndex => write!(f, ".my_index"),
7262 PixVal::InnerCoverage => write!(f, ".inner_coverage"),
7263 }
7264 }
7265 }
7266
7267 #[repr(C)]
7268 #[derive(SrcsAsSlice, DstsAsSlice)]
7269 pub struct OpPixLd {
7270 pub dst: Dst,
7271 pub val: PixVal,
7272 }
7273
7274 impl DisplayOp for OpPixLd {
7275 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7276 write!(f, "pixld{}", self.val)
7277 }
7278 }
7279 impl_display_for_op!(OpPixLd);
7280
7281 #[repr(C)]
7282 #[derive(SrcsAsSlice, DstsAsSlice)]
7283 pub struct OpS2R {
7284 pub dst: Dst,
7285 pub idx: u8,
7286 }
7287
7288 impl DisplayOp for OpS2R {
7289 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7290 write!(f, "s2r sr[{:#x}]", self.idx)
7291 }
7292 }
7293 impl_display_for_op!(OpS2R);
7294
7295 pub enum VoteOp {
7296 Any,
7297 All,
7298 Eq,
7299 }
7300
7301 impl fmt::Display for VoteOp {
7302 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7303 match self {
7304 VoteOp::Any => write!(f, "any"),
7305 VoteOp::All => write!(f, "all"),
7306 VoteOp::Eq => write!(f, "eq"),
7307 }
7308 }
7309 }
7310
7311 #[repr(C)]
7312 #[derive(SrcsAsSlice, DstsAsSlice)]
7313 pub struct OpVote {
7314 pub op: VoteOp,
7315
7316 #[dst_type(GPR)]
7317 pub ballot: Dst,
7318
7319 #[dst_type(Pred)]
7320 pub vote: Dst,
7321
7322 #[src_type(Pred)]
7323 pub pred: Src,
7324 }
7325
7326 impl DisplayOp for OpVote {
7327 fn fmt_dsts(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7328 if self.ballot.is_none() && self.vote.is_none() {
7329 write!(f, "none")
7330 } else {
7331 if !self.ballot.is_none() {
7332 write!(f, "{}", self.ballot)?;
7333 }
7334 if !self.vote.is_none() {
7335 write!(f, "{}", self.vote)?;
7336 }
7337 Ok(())
7338 }
7339 }
7340
7341 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7342 write!(f, "vote.{} {}", self.op, self.pred)
7343 }
7344 }
7345 impl_display_for_op!(OpVote);
7346
7347 #[allow(dead_code)]
7348 #[derive(Copy, Clone)]
7349 pub enum MatchOp {
7350 All,
7351 Any,
7352 }
7353
7354 impl fmt::Display for MatchOp {
7355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7356 match self {
7357 MatchOp::All => write!(f, ".all"),
7358 MatchOp::Any => write!(f, ".any"),
7359 }
7360 }
7361 }
7362
7363 #[repr(C)]
7364 #[derive(SrcsAsSlice, DstsAsSlice)]
7365 pub struct OpMatch {
7366 #[dst_type(Pred)]
7367 pub pred: Dst,
7368
7369 #[dst_type(GPR)]
7370 pub mask: Dst,
7371
7372 #[src_type(GPR)]
7373 pub src: Src,
7374
7375 pub op: MatchOp,
7376 pub u64: bool,
7377 }
7378
7379 impl DisplayOp for OpMatch {
7380 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7381 let u64_str = if self.u64 { ".u64" } else { "" };
7382 write!(f, "match{}{} {}", self.op, u64_str, self.src)
7383 }
7384 }
7385 impl_display_for_op!(OpMatch);
7386
7387 #[repr(C)]
7388 #[derive(SrcsAsSlice, DstsAsSlice)]
7389 pub struct OpUndef {
7390 pub dst: Dst,
7391 }
7392
7393 impl DisplayOp for OpUndef {
7394 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7395 write!(f, "undef {}", self.dst)
7396 }
7397 }
7398 impl_display_for_op!(OpUndef);
7399
7400 #[repr(C)]
7401 #[derive(SrcsAsSlice, DstsAsSlice)]
7402 pub struct OpSrcBar {
7403 pub src: Src,
7404 }
7405
7406 impl DisplayOp for OpSrcBar {
7407 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7408 write!(f, "src_bar {}", self.src)
7409 }
7410 }
7411 impl_display_for_op!(OpSrcBar);
7412
7413 pub struct VecPair<A, B> {
7414 a: Vec<A>,
7415 b: Vec<B>,
7416 }
7417
7418 impl<A, B> VecPair<A, B> {
7419 pub fn append(&mut self, other: &mut VecPair<A, B>) {
7420 self.a.append(&mut other.a);
7421 self.b.append(&mut other.b);
7422 }
7423
7424 pub fn is_empty(&self) -> bool {
7425 debug_assert!(self.a.len() == self.b.len());
7426 self.a.is_empty()
7427 }
7428
7429 pub fn iter(&self) -> Zip<slice::Iter<'_, A>, slice::Iter<'_, B>> {
7430 debug_assert!(self.a.len() == self.b.len());
7431 self.a.iter().zip(self.b.iter())
7432 }
7433
7434 pub fn iter_mut(
7435 &mut self,
7436 ) -> Zip<slice::IterMut<'_, A>, slice::IterMut<'_, B>> {
7437 debug_assert!(self.a.len() == self.b.len());
7438 self.a.iter_mut().zip(self.b.iter_mut())
7439 }
7440
7441 pub fn len(&self) -> usize {
7442 debug_assert!(self.a.len() == self.b.len());
7443 self.a.len()
7444 }
7445
7446 pub fn new() -> Self {
7447 Self {
7448 a: Vec::new(),
7449 b: Vec::new(),
7450 }
7451 }
7452
7453 pub fn push(&mut self, a: A, b: B) {
7454 debug_assert!(self.a.len() == self.b.len());
7455 self.a.push(a);
7456 self.b.push(b);
7457 }
7458 }
7459
7460 impl<A: Clone, B: Clone> VecPair<A, B> {
7461 pub fn retain(&mut self, mut f: impl FnMut(&A, &B) -> bool) {
7462 debug_assert!(self.a.len() == self.b.len());
7463 let len = self.a.len();
7464 let mut i = 0_usize;
7465 while i < len {
7466 if !f(&self.a[i], &self.b[i]) {
7467 break;
7468 }
7469 i += 1;
7470 }
7471
7472 let mut new_len = i;
7473
7474 // Don't check this one twice.
7475 i += 1;
7476
7477 while i < len {
7478 // This could be more efficient but it's good enough for our
7479 // purposes since everything we're storing is small and has a
7480 // trivial Drop.
7481 if f(&self.a[i], &self.b[i]) {
7482 self.a[new_len] = self.a[i].clone();
7483 self.b[new_len] = self.b[i].clone();
7484 new_len += 1;
7485 }
7486 i += 1;
7487 }
7488
7489 if new_len < len {
7490 self.a.truncate(new_len);
7491 self.b.truncate(new_len);
7492 }
7493 }
7494 }
7495
7496 mod phi {
7497 #[allow(unused_imports)]
7498 use crate::ir::{OpPhiDsts, OpPhiSrcs};
7499 use compiler::bitset::IntoBitIndex;
7500 use std::fmt;
7501
7502 /// A phi node
7503 ///
7504 /// Phis in NAK are implemented differently from NIR and similar IRs.
7505 /// Instead of having a single phi instruction which lives in the successor
7506 /// block, each `Phi` represents a single merged 32-bit (or 1-bit for
7507 /// predicates) value and we have separate [`OpPhiSrcs`] and [`OpPhiDsts`]
7508 /// instructions which map phis to sources and destinations.
7509 ///
7510 /// One of the problems fundamental to phis is that they really live on the
7511 /// edges between blocks. Regardless of where the phi instruction lives in
7512 /// the IR data structures, its sources are consumed at the end of the
7513 /// predecessor block and its destinations are defined at the start of the
7514 /// successor block and all phi sources and destinations get consumed and go
7515 /// live simultaneously for any given CFG edge. For a phi that participates
7516 /// in a back-edge, this means that the source of the phi may be consumed
7517 /// after (in block order) the destination goes live.
7518 ///
7519 /// In NIR, this has caused no end of headaches. Most passes which need to
7520 /// process phis ignore phis when first processing a block and then have a
7521 /// special case at the end of each block which walks the successors and
7522 /// processes the successor's phis, looking only at the phi sources whose
7523 /// predecessor matches the block. This is clunky and often forgotten by
7524 /// optimization and lowering pass authors. It's also easy to get missed by
7525 /// testing since it only really breaks if you have a phi which participates
7526 /// in a back-edge so it often gets found later when something breaks in the
7527 /// wild.
7528 ///
7529 /// To work around this (and also make things a little more Rust-friendly),
7530 /// NAK places the instruction which consumes phi sources at the end of the
7531 /// predecessor block and the instruction which defines phi destinations at
7532 /// the start of the successor block. This structurally eliminates the
7533 /// problem that has plagued NIR for years. The cost to this solution is
7534 /// that we have to create maps from phis to/from SSA values whenever we
7535 /// want to optimize the phis themselves. However, this affects few enough
7536 /// passes that the benefits to the rest of the IR are worth the trade-off,
7537 /// at least for a back-end compiler.
7538 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
7539 pub struct Phi {
7540 idx: u32,
7541 }
7542
7543 impl IntoBitIndex for Phi {
7544 fn into_bit_index(self) -> usize {
7545 self.idx.try_into().unwrap()
7546 }
7547 }
7548
7549 impl fmt::Display for Phi {
7550 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7551 write!(f, "φ{}", self.idx)
7552 }
7553 }
7554
7555 pub struct PhiAllocator {
7556 count: u32,
7557 }
7558
7559 impl PhiAllocator {
7560 pub fn new() -> PhiAllocator {
7561 PhiAllocator { count: 0 }
7562 }
7563
7564 pub fn alloc(&mut self) -> Phi {
7565 let idx = self.count;
7566 self.count = idx + 1;
7567 Phi { idx }
7568 }
7569 }
7570 }
7571 pub use phi::{Phi, PhiAllocator};
7572
7573 /// An instruction which maps [Phi]s to sources in the predecessor block
7574 #[repr(C)]
7575 #[derive(DstsAsSlice)]
7576 pub struct OpPhiSrcs {
7577 pub srcs: VecPair<Phi, Src>,
7578 }
7579
7580 impl OpPhiSrcs {
7581 pub fn new() -> OpPhiSrcs {
7582 OpPhiSrcs {
7583 srcs: VecPair::new(),
7584 }
7585 }
7586 }
7587
7588 impl AsSlice<Src> for OpPhiSrcs {
7589 type Attr = SrcType;
7590
7591 fn as_slice(&self) -> &[Src] {
7592 &self.srcs.b
7593 }
7594
7595 fn as_mut_slice(&mut self) -> &mut [Src] {
7596 &mut self.srcs.b
7597 }
7598
7599 fn attrs(&self) -> SrcTypeList {
7600 SrcTypeList::Uniform(SrcType::GPR)
7601 }
7602 }
7603
7604 impl DisplayOp for OpPhiSrcs {
7605 fn fmt_dsts(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
7606 Ok(())
7607 }
7608
7609 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7610 write!(f, "phi_src ")?;
7611 for (i, (phi, src)) in self.srcs.iter().enumerate() {
7612 if i > 0 {
7613 write!(f, ", ")?;
7614 }
7615 write!(f, "{phi} = {src}")?;
7616 }
7617 Ok(())
7618 }
7619 }
7620 impl_display_for_op!(OpPhiSrcs);
7621
7622 /// An instruction which maps [Phi]s to destinations in the succeessor block
7623 #[repr(C)]
7624 #[derive(SrcsAsSlice)]
7625 pub struct OpPhiDsts {
7626 pub dsts: VecPair<Phi, Dst>,
7627 }
7628
7629 impl OpPhiDsts {
7630 pub fn new() -> OpPhiDsts {
7631 OpPhiDsts {
7632 dsts: VecPair::new(),
7633 }
7634 }
7635 }
7636
7637 impl AsSlice<Dst> for OpPhiDsts {
7638 type Attr = DstType;
7639
7640 fn as_slice(&self) -> &[Dst] {
7641 &self.dsts.b
7642 }
7643
7644 fn as_mut_slice(&mut self) -> &mut [Dst] {
7645 &mut self.dsts.b
7646 }
7647
7648 fn attrs(&self) -> DstTypeList {
7649 DstTypeList::Uniform(DstType::Vec)
7650 }
7651 }
7652
7653 impl DisplayOp for OpPhiDsts {
7654 fn fmt_dsts(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
7655 Ok(())
7656 }
7657
7658 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7659 write!(f, "phi_dst ")?;
7660 for (i, (phi, dst)) in self.dsts.iter().enumerate() {
7661 if i > 0 {
7662 write!(f, ", ")?;
7663 }
7664 write!(f, "{dst} = {phi}")?;
7665 }
7666 Ok(())
7667 }
7668 }
7669 impl_display_for_op!(OpPhiDsts);
7670
7671 #[repr(C)]
7672 #[derive(SrcsAsSlice, DstsAsSlice)]
7673 pub struct OpCopy {
7674 pub dst: Dst,
7675 pub src: Src,
7676 }
7677
7678 impl DisplayOp for OpCopy {
7679 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7680 write!(f, "copy {}", self.src)
7681 }
7682 }
7683 impl_display_for_op!(OpCopy);
7684
7685 #[repr(C)]
7686 #[derive(SrcsAsSlice, DstsAsSlice)]
7687 /// Copies a value and pins its destination in the register file
7688 pub struct OpPin {
7689 pub dst: Dst,
7690 #[src_type(SSA)]
7691 pub src: Src,
7692 }
7693
7694 impl DisplayOp for OpPin {
7695 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7696 write!(f, "pin {}", self.src)
7697 }
7698 }
7699 impl_display_for_op!(OpPin);
7700
7701 #[repr(C)]
7702 #[derive(SrcsAsSlice, DstsAsSlice)]
7703 /// Copies a pinned value to an unpinned value
7704 pub struct OpUnpin {
7705 pub dst: Dst,
7706 #[src_type(SSA)]
7707 pub src: Src,
7708 }
7709
7710 impl DisplayOp for OpUnpin {
7711 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7712 write!(f, "unpin {}", self.src)
7713 }
7714 }
7715 impl_display_for_op!(OpUnpin);
7716
7717 #[repr(C)]
7718 #[derive(SrcsAsSlice, DstsAsSlice)]
7719 pub struct OpSwap {
7720 pub dsts: [Dst; 2],
7721 pub srcs: [Src; 2],
7722 }
7723
7724 impl DisplayOp for OpSwap {
7725 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7726 write!(f, "swap {} {}", self.srcs[0], self.srcs[1])
7727 }
7728 }
7729 impl_display_for_op!(OpSwap);
7730
7731 #[repr(C)]
7732 pub struct OpParCopy {
7733 pub dsts_srcs: VecPair<Dst, Src>,
7734 pub tmp: Option<RegRef>,
7735 }
7736
7737 impl OpParCopy {
7738 pub fn new() -> OpParCopy {
7739 OpParCopy {
7740 dsts_srcs: VecPair::new(),
7741 tmp: None,
7742 }
7743 }
7744
7745 pub fn is_empty(&self) -> bool {
7746 self.dsts_srcs.is_empty()
7747 }
7748
7749 pub fn push(&mut self, dst: Dst, src: Src) {
7750 self.dsts_srcs.push(dst, src);
7751 }
7752 }
7753
7754 impl AsSlice<Src> for OpParCopy {
7755 type Attr = SrcType;
7756
7757 fn as_slice(&self) -> &[Src] {
7758 &self.dsts_srcs.b
7759 }
7760
7761 fn as_mut_slice(&mut self) -> &mut [Src] {
7762 &mut self.dsts_srcs.b
7763 }
7764
7765 fn attrs(&self) -> SrcTypeList {
7766 SrcTypeList::Uniform(SrcType::GPR)
7767 }
7768 }
7769
7770 impl AsSlice<Dst> for OpParCopy {
7771 type Attr = DstType;
7772
7773 fn as_slice(&self) -> &[Dst] {
7774 &self.dsts_srcs.a
7775 }
7776
7777 fn as_mut_slice(&mut self) -> &mut [Dst] {
7778 &mut self.dsts_srcs.a
7779 }
7780
7781 fn attrs(&self) -> DstTypeList {
7782 DstTypeList::Uniform(DstType::Vec)
7783 }
7784 }
7785
7786 impl DisplayOp for OpParCopy {
7787 fn fmt_dsts(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
7788 Ok(())
7789 }
7790
7791 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7792 write!(f, "par_copy")?;
7793 for (i, (dst, src)) in self.dsts_srcs.iter().enumerate() {
7794 if i > 0 {
7795 write!(f, ",")?;
7796 }
7797 write!(f, " {} = {}", dst, src)?;
7798 }
7799 Ok(())
7800 }
7801 }
7802 impl_display_for_op!(OpParCopy);
7803
7804 #[repr(C)]
7805 #[derive(DstsAsSlice)]
7806 pub struct OpRegOut {
7807 pub srcs: Vec<Src>,
7808 }
7809
7810 impl AsSlice<Src> for OpRegOut {
7811 type Attr = SrcType;
7812
7813 fn as_slice(&self) -> &[Src] {
7814 &self.srcs
7815 }
7816
7817 fn as_mut_slice(&mut self) -> &mut [Src] {
7818 &mut self.srcs
7819 }
7820
7821 fn attrs(&self) -> SrcTypeList {
7822 SrcTypeList::Uniform(SrcType::GPR)
7823 }
7824 }
7825
7826 impl DisplayOp for OpRegOut {
7827 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7828 write!(f, "reg_out {{")?;
7829 for (i, src) in self.srcs.iter().enumerate() {
7830 if i > 0 {
7831 write!(f, ",")?;
7832 }
7833 write!(f, " {}", src)?;
7834 }
7835 write!(f, " }}")
7836 }
7837 }
7838 impl_display_for_op!(OpRegOut);
7839
7840 #[derive(Copy, Clone, Debug, PartialEq)]
7841 pub enum OutType {
7842 Emit,
7843 Cut,
7844 EmitThenCut,
7845 }
7846
7847 impl fmt::Display for OutType {
7848 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7849 match self {
7850 OutType::Emit => write!(f, "emit"),
7851 OutType::Cut => write!(f, "cut"),
7852 OutType::EmitThenCut => write!(f, "emit_then_cut"),
7853 }
7854 }
7855 }
7856
7857 #[repr(C)]
7858 #[derive(SrcsAsSlice, DstsAsSlice)]
7859 pub struct OpOut {
7860 pub dst: Dst,
7861
7862 #[src_type(SSA)]
7863 pub handle: Src,
7864
7865 #[src_type(ALU)]
7866 pub stream: Src,
7867
7868 pub out_type: OutType,
7869 }
7870
7871 impl DisplayOp for OpOut {
7872 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7873 write!(f, "out.{} {} {}", self.out_type, self.handle, self.stream)
7874 }
7875 }
7876 impl_display_for_op!(OpOut);
7877
7878 #[repr(C)]
7879 #[derive(SrcsAsSlice, DstsAsSlice)]
7880 pub struct OpOutFinal {
7881 #[src_type(SSA)]
7882 pub handle: Src,
7883 }
7884
7885 impl DisplayOp for OpOutFinal {
7886 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7887 write!(f, "out.final {{ {} }}", self.handle)
7888 }
7889 }
7890 impl_display_for_op!(OpOutFinal);
7891
7892 /// Describes an annotation on an instruction.
7893 #[repr(C)]
7894 #[derive(SrcsAsSlice, DstsAsSlice)]
7895 pub struct OpAnnotate {
7896 /// The annotation
7897 pub annotation: String,
7898 }
7899
7900 impl DisplayOp for OpAnnotate {
7901 fn fmt_op(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7902 write!(f, "// {}", self.annotation)
7903 }
7904 }
7905
7906 impl fmt::Display for OpAnnotate {
7907 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7908 self.fmt_op(f)
7909 }
7910 }
7911
7912 #[derive(DisplayOp, DstsAsSlice, SrcsAsSlice, FromVariants)]
7913 pub enum Op {
7914 FAdd(Box<OpFAdd>),
7915 FFma(Box<OpFFma>),
7916 FMnMx(Box<OpFMnMx>),
7917 FMul(Box<OpFMul>),
7918 Rro(Box<OpRro>),
7919 MuFu(Box<OpMuFu>),
7920 FSet(Box<OpFSet>),
7921 FSetP(Box<OpFSetP>),
7922 FSwzAdd(Box<OpFSwzAdd>),
7923 FSwz(Box<OpFSwz>),
7924 DAdd(Box<OpDAdd>),
7925 DFma(Box<OpDFma>),
7926 DMnMx(Box<OpDMnMx>),
7927 DMul(Box<OpDMul>),
7928 DSetP(Box<OpDSetP>),
7929 HAdd2(Box<OpHAdd2>),
7930 HFma2(Box<OpHFma2>),
7931 HMul2(Box<OpHMul2>),
7932 HSet2(Box<OpHSet2>),
7933 HSetP2(Box<OpHSetP2>),
7934 Imma(Box<OpImma>),
7935 Hmma(Box<OpHmma>),
7936 Ldsm(Box<OpLdsm>),
7937 HMnMx2(Box<OpHMnMx2>),
7938 BMsk(Box<OpBMsk>),
7939 BRev(Box<OpBRev>),
7940 Bfe(Box<OpBfe>),
7941 Flo(Box<OpFlo>),
7942 IAbs(Box<OpIAbs>),
7943 IAdd2(Box<OpIAdd2>),
7944 IAdd2X(Box<OpIAdd2X>),
7945 IAdd3(Box<OpIAdd3>),
7946 IAdd3X(Box<OpIAdd3X>),
7947 IDp4(Box<OpIDp4>),
7948 IMad(Box<OpIMad>),
7949 IMad64(Box<OpIMad64>),
7950 IMul(Box<OpIMul>),
7951 IMnMx(Box<OpIMnMx>),
7952 ISetP(Box<OpISetP>),
7953 Lea(Box<OpLea>),
7954 LeaX(Box<OpLeaX>),
7955 Lop2(Box<OpLop2>),
7956 Lop3(Box<OpLop3>),
7957 PopC(Box<OpPopC>),
7958 Shf(Box<OpShf>),
7959 Shl(Box<OpShl>),
7960 Shr(Box<OpShr>),
7961 F2F(Box<OpF2F>),
7962 F2FP(Box<OpF2FP>),
7963 F2I(Box<OpF2I>),
7964 I2F(Box<OpI2F>),
7965 I2I(Box<OpI2I>),
7966 FRnd(Box<OpFRnd>),
7967 Mov(Box<OpMov>),
7968 Movm(Box<OpMovm>),
7969 Prmt(Box<OpPrmt>),
7970 Sel(Box<OpSel>),
7971 Sgxt(Box<OpSgxt>),
7972 Shfl(Box<OpShfl>),
7973 PLop3(Box<OpPLop3>),
7974 PSetP(Box<OpPSetP>),
7975 R2UR(Box<OpR2UR>),
7976 Redux(Box<OpRedux>),
7977 Tex(Box<OpTex>),
7978 Tld(Box<OpTld>),
7979 Tld4(Box<OpTld4>),
7980 Tmml(Box<OpTmml>),
7981 Txd(Box<OpTxd>),
7982 Txq(Box<OpTxq>),
7983 SuLd(Box<OpSuLd>),
7984 SuSt(Box<OpSuSt>),
7985 SuAtom(Box<OpSuAtom>),
7986 SuClamp(Box<OpSuClamp>),
7987 SuBfm(Box<OpSuBfm>),
7988 SuEau(Box<OpSuEau>),
7989 IMadSp(Box<OpIMadSp>),
7990 SuLdGa(Box<OpSuLdGa>),
7991 SuStGa(Box<OpSuStGa>),
7992 Ld(Box<OpLd>),
7993 Ldc(Box<OpLdc>),
7994 LdSharedLock(Box<OpLdSharedLock>),
7995 St(Box<OpSt>),
7996 StSCheckUnlock(Box<OpStSCheckUnlock>),
7997 Atom(Box<OpAtom>),
7998 AL2P(Box<OpAL2P>),
7999 ALd(Box<OpALd>),
8000 ASt(Box<OpASt>),
8001 Ipa(Box<OpIpa>),
8002 LdTram(Box<OpLdTram>),
8003 CCtl(Box<OpCCtl>),
8004 MemBar(Box<OpMemBar>),
8005 BClear(Box<OpBClear>),
8006 BMov(Box<OpBMov>),
8007 Break(Box<OpBreak>),
8008 BSSy(Box<OpBSSy>),
8009 BSync(Box<OpBSync>),
8010 Bra(Box<OpBra>),
8011 SSy(OpSSy),
8012 Sync(OpSync),
8013 Brk(OpBrk),
8014 PBk(OpPBk),
8015 Cont(OpCont),
8016 PCnt(OpPCnt),
8017 Exit(OpExit),
8018 WarpSync(Box<OpWarpSync>),
8019 Bar(Box<OpBar>),
8020 TexDepBar(Box<OpTexDepBar>),
8021 CS2R(Box<OpCS2R>),
8022 Isberd(Box<OpIsberd>),
8023 ViLd(Box<OpViLd>),
8024 Kill(Box<OpKill>),
8025 Nop(OpNop),
8026 PixLd(Box<OpPixLd>),
8027 S2R(Box<OpS2R>),
8028 Vote(Box<OpVote>),
8029 Match(Box<OpMatch>),
8030 Undef(Box<OpUndef>),
8031 SrcBar(Box<OpSrcBar>),
8032 PhiSrcs(Box<OpPhiSrcs>),
8033 PhiDsts(Box<OpPhiDsts>),
8034 Copy(Box<OpCopy>),
8035 Pin(Box<OpPin>),
8036 Unpin(Box<OpUnpin>),
8037 Swap(Box<OpSwap>),
8038 ParCopy(Box<OpParCopy>),
8039 RegOut(Box<OpRegOut>),
8040 Out(Box<OpOut>),
8041 OutFinal(Box<OpOutFinal>),
8042 Annotate(Box<OpAnnotate>),
8043 }
8044 impl_display_for_op!(Op);
8045
8046 #[cfg(target_arch = "x86_64")]
8047 const _: () = {
8048 debug_assert!(size_of::<Op>() == 16);
8049 };
8050
8051 impl Op {
8052 pub fn is_branch(&self) -> bool {
8053 matches!(
8054 self,
8055 Op::Bra(_) | Op::Sync(_) | Op::Brk(_) | Op::Cont(_) | Op::Exit(_)
8056 )
8057 }
8058
8059 pub fn is_fp64(&self) -> bool {
8060 match self {
8061 Op::MuFu(op) => matches!(op.op, MuFuOp::Rcp64H | MuFuOp::Rsq64H),
8062 Op::DAdd(_)
8063 | Op::DFma(_)
8064 | Op::DMnMx(_)
8065 | Op::DMul(_)
8066 | Op::DSetP(_) => true,
8067 Op::F2F(op) => op.src_type.bits() == 64 || op.dst_type.bits() == 64,
8068 Op::F2I(op) => op.src_type.bits() == 64 || op.dst_type.bits() == 64,
8069 Op::I2F(op) => op.src_type.bits() == 64 || op.dst_type.bits() == 64,
8070 Op::FRnd(op) => {
8071 op.src_type.bits() == 64 || op.dst_type.bits() == 64
8072 }
8073 _ => false,
8074 }
8075 }
8076
8077 pub fn has_fixed_latency(&self, sm: u8) -> bool {
8078 match self {
8079 // Float ALU
8080 Op::F2FP(_)
8081 | Op::FAdd(_)
8082 | Op::FFma(_)
8083 | Op::FMnMx(_)
8084 | Op::FMul(_)
8085 | Op::FSet(_)
8086 | Op::FSetP(_)
8087 | Op::HAdd2(_)
8088 | Op::HFma2(_)
8089 | Op::HMul2(_)
8090 | Op::HSet2(_)
8091 | Op::HSetP2(_)
8092 | Op::HMnMx2(_)
8093 | Op::FSwz(_)
8094 | Op::FSwzAdd(_) => true,
8095
8096 // Multi-function unit is variable latency
8097 Op::Rro(_) | Op::MuFu(_) => false,
8098
8099 // Double-precision float ALU
8100 Op::DAdd(_)
8101 | Op::DFma(_)
8102 | Op::DMnMx(_)
8103 | Op::DMul(_)
8104 | Op::DSetP(_) => false,
8105
8106 // Matrix Multiply Add
8107 Op::Imma(_) | Op::Hmma(_) | Op::Ldsm(_) | Op::Movm(_) => false,
8108
8109 // Integer ALU
8110 Op::BRev(_) | Op::Flo(_) | Op::PopC(_) => false,
8111 Op::IMad(_) | Op::IMul(_) => sm >= 70,
8112 Op::BMsk(_)
8113 | Op::IAbs(_)
8114 | Op::IAdd2(_)
8115 | Op::IAdd2X(_)
8116 | Op::IAdd3(_)
8117 | Op::IAdd3X(_)
8118 | Op::IDp4(_)
8119 | Op::IMad64(_)
8120 | Op::IMnMx(_)
8121 | Op::ISetP(_)
8122 | Op::Lea(_)
8123 | Op::LeaX(_)
8124 | Op::Lop2(_)
8125 | Op::Lop3(_)
8126 | Op::SuClamp(_)
8127 | Op::SuBfm(_)
8128 | Op::SuEau(_)
8129 | Op::IMadSp(_)
8130 | Op::Shf(_)
8131 | Op::Shl(_)
8132 | Op::Shr(_)
8133 | Op::Bfe(_) => true,
8134
8135 // Conversions are variable latency?!?
8136 Op::F2F(_) | Op::F2I(_) | Op::I2F(_) | Op::I2I(_) | Op::FRnd(_) => {
8137 false
8138 }
8139
8140 // Move ops
8141 Op::Mov(_) | Op::Prmt(_) | Op::Sel(_) | Op::Sgxt(_) => true,
8142 Op::Shfl(_) => false,
8143
8144 // Predicate ops
8145 Op::PLop3(_) | Op::PSetP(_) => true,
8146
8147 // Uniform ops
8148 Op::R2UR(_) | Op::Redux(_) => false,
8149
8150 // Texture ops
8151 Op::Tex(_)
8152 | Op::Tld(_)
8153 | Op::Tld4(_)
8154 | Op::Tmml(_)
8155 | Op::Txd(_)
8156 | Op::Txq(_) => false,
8157
8158 // Surface ops
8159 Op::SuLd(_)
8160 | Op::SuSt(_)
8161 | Op::SuAtom(_)
8162 | Op::SuLdGa(_)
8163 | Op::SuStGa(_) => false,
8164
8165 // Memory ops
8166 Op::Ld(_)
8167 | Op::Ldc(_)
8168 | Op::LdSharedLock(_)
8169 | Op::St(_)
8170 | Op::StSCheckUnlock(_)
8171 | Op::Atom(_)
8172 | Op::AL2P(_)
8173 | Op::ALd(_)
8174 | Op::ASt(_)
8175 | Op::Ipa(_)
8176 | Op::CCtl(_)
8177 | Op::LdTram(_)
8178 | Op::MemBar(_) => false,
8179
8180 // Control-flow ops
8181 Op::BClear(_)
8182 | Op::Break(_)
8183 | Op::BSSy(_)
8184 | Op::BSync(_)
8185 | Op::SSy(_)
8186 | Op::Sync(_)
8187 | Op::Brk(_)
8188 | Op::PBk(_)
8189 | Op::Cont(_)
8190 | Op::PCnt(_)
8191 | Op::Bra(_)
8192 | Op::Exit(_)
8193 | Op::WarpSync(_) => false,
8194
8195 // The barrier half is HW scoreboarded by the GPR isn't. When
8196 // moving from a GPR to a barrier, we still need a token for WaR
8197 // hazards.
8198 Op::BMov(_) => false,
8199
8200 // Geometry ops
8201 Op::Out(_) | Op::OutFinal(_) => false,
8202
8203 // Miscellaneous ops
8204 Op::Bar(_)
8205 | Op::TexDepBar(_)
8206 | Op::CS2R(_)
8207 | Op::Isberd(_)
8208 | Op::ViLd(_)
8209 | Op::Kill(_)
8210 | Op::PixLd(_)
8211 | Op::S2R(_)
8212 | Op::Match(_) => false,
8213 Op::Nop(_) | Op::Vote(_) => true,
8214
8215 // Virtual ops
8216 Op::Undef(_)
8217 | Op::SrcBar(_)
8218 | Op::PhiSrcs(_)
8219 | Op::PhiDsts(_)
8220 | Op::Copy(_)
8221 | Op::Pin(_)
8222 | Op::Unpin(_)
8223 | Op::Swap(_)
8224 | Op::ParCopy(_)
8225 | Op::RegOut(_)
8226 | Op::Annotate(_) => {
8227 panic!("Not a hardware opcode")
8228 }
8229 }
8230 }
8231
8232 /// Some decoupled instructions don't need
8233 /// scoreboards, due to our usage.
8234 pub fn no_scoreboard(&self) -> bool {
8235 matches!(
8236 self,
8237 Op::BClear(_)
8238 | Op::Break(_)
8239 | Op::BSSy(_)
8240 | Op::BSync(_)
8241 | Op::SSy(_)
8242 | Op::Sync(_)
8243 | Op::Brk(_)
8244 | Op::PBk(_)
8245 | Op::Cont(_)
8246 | Op::PCnt(_)
8247 | Op::Bra(_)
8248 | Op::Exit(_)
8249 )
8250 }
8251
8252 pub fn is_virtual(&self) -> bool {
8253 match self {
8254 // Float ALU
8255 Op::F2FP(_)
8256 | Op::FAdd(_)
8257 | Op::FFma(_)
8258 | Op::FMnMx(_)
8259 | Op::FMul(_)
8260 | Op::FSet(_)
8261 | Op::FSetP(_)
8262 | Op::HAdd2(_)
8263 | Op::HFma2(_)
8264 | Op::HMul2(_)
8265 | Op::HSet2(_)
8266 | Op::HSetP2(_)
8267 | Op::HMnMx2(_)
8268 | Op::FSwz(_)
8269 | Op::FSwzAdd(_) => false,
8270
8271 // Multi-function unit
8272 Op::Rro(_) | Op::MuFu(_) => false,
8273
8274 // Double-precision float ALU
8275 Op::DAdd(_)
8276 | Op::DFma(_)
8277 | Op::DMnMx(_)
8278 | Op::DMul(_)
8279 | Op::DSetP(_) => false,
8280
8281 // Matrix Multiply Add
8282 Op::Imma(_) | Op::Hmma(_) | Op::Ldsm(_) | Op::Movm(_) => false,
8283
8284 // Integer ALU
8285 Op::BRev(_)
8286 | Op::Flo(_)
8287 | Op::PopC(_)
8288 | Op::IMad(_)
8289 | Op::IMul(_)
8290 | Op::BMsk(_)
8291 | Op::IAbs(_)
8292 | Op::IAdd2(_)
8293 | Op::IAdd2X(_)
8294 | Op::IAdd3(_)
8295 | Op::IAdd3X(_)
8296 | Op::IDp4(_)
8297 | Op::IMad64(_)
8298 | Op::IMnMx(_)
8299 | Op::ISetP(_)
8300 | Op::Lea(_)
8301 | Op::LeaX(_)
8302 | Op::Lop2(_)
8303 | Op::Lop3(_)
8304 | Op::SuClamp(_)
8305 | Op::SuBfm(_)
8306 | Op::SuEau(_)
8307 | Op::IMadSp(_)
8308 | Op::Shf(_)
8309 | Op::Shl(_)
8310 | Op::Shr(_)
8311 | Op::Bfe(_) => false,
8312
8313 // Conversions
8314 Op::F2F(_) | Op::F2I(_) | Op::I2F(_) | Op::I2I(_) | Op::FRnd(_) => {
8315 false
8316 }
8317
8318 // Move ops
8319 Op::Mov(_)
8320 | Op::Prmt(_)
8321 | Op::Sel(_)
8322 | Op::Sgxt(_)
8323 | Op::Shfl(_) => false,
8324
8325 // Predicate ops
8326 Op::PLop3(_) | Op::PSetP(_) => false,
8327
8328 // Uniform ops
8329 Op::R2UR(op) => {
8330 op.src.is_uniform() || op.dst.file() == Some(RegFile::UPred)
8331 }
8332 Op::Redux(_) => false,
8333
8334 // Texture ops
8335 Op::Tex(_)
8336 | Op::Tld(_)
8337 | Op::Tld4(_)
8338 | Op::Tmml(_)
8339 | Op::Txd(_)
8340 | Op::Txq(_) => false,
8341
8342 // Surface ops
8343 Op::SuLd(_)
8344 | Op::SuSt(_)
8345 | Op::SuAtom(_)
8346 | Op::SuLdGa(_)
8347 | Op::SuStGa(_) => false,
8348
8349 // Memory ops
8350 Op::Ld(_)
8351 | Op::Ldc(_)
8352 | Op::LdSharedLock(_)
8353 | Op::St(_)
8354 | Op::StSCheckUnlock(_)
8355 | Op::Atom(_)
8356 | Op::AL2P(_)
8357 | Op::ALd(_)
8358 | Op::ASt(_)
8359 | Op::Ipa(_)
8360 | Op::CCtl(_)
8361 | Op::LdTram(_)
8362 | Op::MemBar(_) => false,
8363
8364 // Control-flow ops
8365 Op::BClear(_)
8366 | Op::Break(_)
8367 | Op::BSSy(_)
8368 | Op::BSync(_)
8369 | Op::SSy(_)
8370 | Op::Sync(_)
8371 | Op::Brk(_)
8372 | Op::PBk(_)
8373 | Op::Cont(_)
8374 | Op::PCnt(_)
8375 | Op::Bra(_)
8376 | Op::Exit(_)
8377 | Op::WarpSync(_) => false,
8378
8379 // Barrier
8380 Op::BMov(_) => false,
8381
8382 // Geometry ops
8383 Op::Out(_) | Op::OutFinal(_) => false,
8384
8385 // Miscellaneous ops
8386 Op::Bar(_)
8387 | Op::TexDepBar(_)
8388 | Op::CS2R(_)
8389 | Op::Isberd(_)
8390 | Op::ViLd(_)
8391 | Op::Kill(_)
8392 | Op::PixLd(_)
8393 | Op::S2R(_)
8394 | Op::Match(_)
8395 | Op::Nop(_)
8396 | Op::Vote(_) => false,
8397
8398 // Virtual ops
8399 Op::Undef(_)
8400 | Op::SrcBar(_)
8401 | Op::PhiSrcs(_)
8402 | Op::PhiDsts(_)
8403 | Op::Copy(_)
8404 | Op::Pin(_)
8405 | Op::Unpin(_)
8406 | Op::Swap(_)
8407 | Op::ParCopy(_)
8408 | Op::RegOut(_)
8409 | Op::Annotate(_) => true,
8410 }
8411 }
8412 }
8413
8414 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
8415 pub enum PredRef {
8416 None,
8417 SSA(SSAValue),
8418 Reg(RegRef),
8419 }
8420
8421 impl PredRef {
8422 #[allow(dead_code)]
8423 pub fn as_reg(&self) -> Option<&RegRef> {
8424 match self {
8425 PredRef::Reg(r) => Some(r),
8426 _ => None,
8427 }
8428 }
8429
8430 #[allow(dead_code)]
8431 pub fn as_ssa(&self) -> Option<&SSAValue> {
8432 match self {
8433 PredRef::SSA(r) => Some(r),
8434 _ => None,
8435 }
8436 }
8437
8438 pub fn is_none(&self) -> bool {
8439 matches!(self, PredRef::None)
8440 }
8441
8442 pub fn iter_ssa(&self) -> slice::Iter<'_, SSAValue> {
8443 match self {
8444 PredRef::None | PredRef::Reg(_) => &[],
8445 PredRef::SSA(ssa) => slice::from_ref(ssa),
8446 }
8447 .iter()
8448 }
8449
8450 pub fn iter_ssa_mut(&mut self) -> slice::IterMut<'_, SSAValue> {
8451 match self {
8452 PredRef::None | PredRef::Reg(_) => &mut [],
8453 PredRef::SSA(ssa) => slice::from_mut(ssa),
8454 }
8455 .iter_mut()
8456 }
8457 }
8458
8459 impl From<RegRef> for PredRef {
8460 fn from(reg: RegRef) -> PredRef {
8461 PredRef::Reg(reg)
8462 }
8463 }
8464
8465 impl From<SSAValue> for PredRef {
8466 fn from(ssa: SSAValue) -> PredRef {
8467 PredRef::SSA(ssa)
8468 }
8469 }
8470
8471 impl fmt::Display for PredRef {
8472 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8473 match self {
8474 PredRef::None => write!(f, "pT"),
8475 PredRef::SSA(ssa) => ssa.fmt(f),
8476 PredRef::Reg(reg) => reg.fmt(f),
8477 }
8478 }
8479 }
8480
8481 #[derive(Clone, Copy)]
8482 pub struct Pred {
8483 pub pred_ref: PredRef,
8484 pub pred_inv: bool,
8485 }
8486
8487 impl Pred {
8488 pub fn is_true(&self) -> bool {
8489 self.pred_ref.is_none() && !self.pred_inv
8490 }
8491
8492 pub fn is_false(&self) -> bool {
8493 self.pred_ref.is_none() && self.pred_inv
8494 }
8495
8496 pub fn iter_ssa(&self) -> slice::Iter<'_, SSAValue> {
8497 self.pred_ref.iter_ssa()
8498 }
8499
8500 pub fn iter_ssa_mut(&mut self) -> slice::IterMut<'_, SSAValue> {
8501 self.pred_ref.iter_ssa_mut()
8502 }
8503
8504 pub fn bnot(self) -> Self {
8505 Pred {
8506 pred_ref: self.pred_ref,
8507 pred_inv: !self.pred_inv,
8508 }
8509 }
8510 }
8511
8512 impl From<bool> for Pred {
8513 fn from(b: bool) -> Self {
8514 Pred {
8515 pred_ref: PredRef::None,
8516 pred_inv: !b,
8517 }
8518 }
8519 }
8520
8521 impl<T: Into<PredRef>> From<T> for Pred {
8522 fn from(p: T) -> Self {
8523 Pred {
8524 pred_ref: p.into(),
8525 pred_inv: false,
8526 }
8527 }
8528 }
8529
8530 impl fmt::Display for Pred {
8531 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8532 if self.pred_inv {
8533 write!(f, "!")?;
8534 }
8535 self.pred_ref.fmt(f)
8536 }
8537 }
8538
8539 pub const MIN_INSTR_DELAY: u8 = 1;
8540
8541 pub struct InstrDeps {
8542 pub delay: u8,
8543 pub yld: bool,
8544 wr_bar: i8,
8545 rd_bar: i8,
8546 pub wt_bar_mask: u8,
8547 pub reuse_mask: u8,
8548 }
8549
8550 impl InstrDeps {
8551 pub fn new() -> InstrDeps {
8552 InstrDeps {
8553 delay: 0,
8554 yld: false,
8555 wr_bar: -1,
8556 rd_bar: -1,
8557 wt_bar_mask: 0,
8558 reuse_mask: 0,
8559 }
8560 }
8561
8562 pub fn rd_bar(&self) -> Option<u8> {
8563 if self.rd_bar < 0 {
8564 None
8565 } else {
8566 Some(self.rd_bar.try_into().unwrap())
8567 }
8568 }
8569
8570 pub fn wr_bar(&self) -> Option<u8> {
8571 if self.wr_bar < 0 {
8572 None
8573 } else {
8574 Some(self.wr_bar.try_into().unwrap())
8575 }
8576 }
8577
8578 pub fn set_delay(&mut self, delay: u8) {
8579 self.delay = delay;
8580 }
8581
8582 pub fn set_yield(&mut self, yld: bool) {
8583 self.yld = yld;
8584 }
8585
8586 pub fn set_rd_bar(&mut self, idx: u8) {
8587 assert!(idx < 6);
8588 self.rd_bar = idx.try_into().unwrap();
8589 }
8590
8591 pub fn set_wr_bar(&mut self, idx: u8) {
8592 assert!(idx < 6);
8593 self.wr_bar = idx.try_into().unwrap();
8594 }
8595
8596 pub fn add_wt_bar(&mut self, idx: u8) {
8597 self.add_wt_bar_mask(1 << idx);
8598 }
8599
8600 pub fn add_wt_bar_mask(&mut self, bar_mask: u8) {
8601 assert!(bar_mask < 1 << 6);
8602 self.wt_bar_mask |= bar_mask;
8603 }
8604
8605 #[allow(dead_code)]
8606 pub fn add_reuse(&mut self, idx: u8) {
8607 assert!(idx < 6);
8608 self.reuse_mask |= 1_u8 << idx;
8609 }
8610 }
8611
8612 impl fmt::Display for InstrDeps {
8613 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8614 if self.delay > 0 {
8615 write!(f, " delay={}", self.delay)?;
8616 }
8617 if self.wt_bar_mask != 0 {
8618 write!(f, " wt={:06b}", self.wt_bar_mask)?;
8619 }
8620 if self.rd_bar >= 0 {
8621 write!(f, " rd:{}", self.rd_bar)?;
8622 }
8623 if self.wr_bar >= 0 {
8624 write!(f, " wr:{}", self.wr_bar)?;
8625 }
8626 if self.reuse_mask != 0 {
8627 write!(f, " reuse={:06b}", self.reuse_mask)?;
8628 }
8629 if self.yld {
8630 write!(f, " yld")?;
8631 }
8632 Ok(())
8633 }
8634 }
8635
8636 pub struct Instr {
8637 pub pred: Pred,
8638 pub op: Op,
8639 pub deps: InstrDeps,
8640 }
8641
8642 impl Instr {
8643 pub fn new(op: impl Into<Op>) -> Self {
8644 Self {
8645 op: op.into(),
8646 pred: true.into(),
8647 deps: InstrDeps::new(),
8648 }
8649 }
8650
8651 pub fn dsts(&self) -> &[Dst] {
8652 self.op.dsts_as_slice()
8653 }
8654
8655 pub fn dsts_mut(&mut self) -> &mut [Dst] {
8656 self.op.dsts_as_mut_slice()
8657 }
8658
8659 pub fn srcs(&self) -> &[Src] {
8660 self.op.srcs_as_slice()
8661 }
8662
8663 pub fn srcs_mut(&mut self) -> &mut [Src] {
8664 self.op.srcs_as_mut_slice()
8665 }
8666
8667 pub fn src_types(&self) -> SrcTypeList {
8668 self.op.src_types()
8669 }
8670
8671 pub fn ssa_uses(&self) -> impl Iterator<Item = &SSAValue> {
8672 self.srcs()
8673 .iter()
8674 .flat_map(|src| src.iter_ssa())
8675 .chain(self.pred.pred_ref.iter_ssa())
8676 }
8677
8678 pub fn for_each_ssa_use(&self, mut f: impl FnMut(&SSAValue)) {
8679 for ssa in self.pred.iter_ssa() {
8680 f(ssa);
8681 }
8682 for src in self.srcs() {
8683 for ssa in src.iter_ssa() {
8684 f(ssa);
8685 }
8686 }
8687 }
8688
8689 pub fn for_each_ssa_use_mut(&mut self, mut f: impl FnMut(&mut SSAValue)) {
8690 for ssa in self.pred.iter_ssa_mut() {
8691 f(ssa);
8692 }
8693 for src in self.srcs_mut() {
8694 for ssa in src.iter_ssa_mut() {
8695 f(ssa);
8696 }
8697 }
8698 }
8699
8700 pub fn for_each_ssa_def(&self, mut f: impl FnMut(&SSAValue)) {
8701 for dst in self.dsts() {
8702 for ssa in dst.iter_ssa() {
8703 f(ssa);
8704 }
8705 }
8706 }
8707
8708 pub fn for_each_ssa_def_mut(&mut self, mut f: impl FnMut(&mut SSAValue)) {
8709 for dst in self.dsts_mut() {
8710 for ssa in dst.iter_ssa_mut() {
8711 f(ssa);
8712 }
8713 }
8714 }
8715
8716 pub fn is_branch(&self) -> bool {
8717 self.op.is_branch()
8718 }
8719
8720 /// Returns true if `self`` is a branch instruction that is always taken.
8721 /// It returns false for non branch instructions.
8722 pub fn is_branch_always_taken(&self) -> bool {
8723 if self.pred.is_true() {
8724 match &self.op {
8725 Op::Bra(bra) => bra.cond.is_true(),
8726 _ => self.is_branch(),
8727 }
8728 } else {
8729 false
8730 }
8731 }
8732
8733 pub fn uses_global_mem(&self) -> bool {
8734 match &self.op {
8735 Op::Atom(op) => op.mem_space != MemSpace::Local,
8736 Op::Ld(op) => op.access.space != MemSpace::Local,
8737 Op::St(op) => op.access.space != MemSpace::Local,
8738 Op::SuAtom(_)
8739 | Op::SuLd(_)
8740 | Op::SuSt(_)
8741 | Op::SuLdGa(_)
8742 | Op::SuStGa(_) => true,
8743 _ => false,
8744 }
8745 }
8746
8747 pub fn writes_global_mem(&self) -> bool {
8748 match &self.op {
8749 Op::Atom(op) => matches!(op.mem_space, MemSpace::Global(_)),
8750 Op::St(op) => matches!(op.access.space, MemSpace::Global(_)),
8751 Op::SuAtom(_) | Op::SuSt(_) | Op::SuStGa(_) => true,
8752 _ => false,
8753 }
8754 }
8755
8756 pub fn can_eliminate(&self) -> bool {
8757 match &self.op {
8758 Op::ASt(_)
8759 | Op::SuSt(_)
8760 | Op::SuStGa(_)
8761 | Op::SuAtom(_)
8762 | Op::LdSharedLock(_)
8763 | Op::St(_)
8764 | Op::StSCheckUnlock(_)
8765 | Op::Atom(_)
8766 | Op::CCtl(_)
8767 | Op::MemBar(_)
8768 | Op::Kill(_)
8769 | Op::Nop(_)
8770 | Op::BSync(_)
8771 | Op::Bra(_)
8772 | Op::SSy(_)
8773 | Op::Sync(_)
8774 | Op::Brk(_)
8775 | Op::PBk(_)
8776 | Op::Cont(_)
8777 | Op::PCnt(_)
8778 | Op::Exit(_)
8779 | Op::WarpSync(_)
8780 | Op::Bar(_)
8781 | Op::TexDepBar(_)
8782 | Op::RegOut(_)
8783 | Op::Out(_)
8784 | Op::OutFinal(_)
8785 | Op::Annotate(_) => false,
8786 Op::BMov(op) => !op.clear,
8787 _ => true,
8788 }
8789 }
8790
8791 pub fn is_uniform(&self) -> bool {
8792 match &self.op {
8793 Op::PhiDsts(_) => false,
8794 op => op.is_uniform(),
8795 }
8796 }
8797
8798 pub fn needs_yield(&self) -> bool {
8799 matches!(&self.op, Op::Bar(_) | Op::BSync(_))
8800 }
8801
8802 fn fmt_pred(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8803 if !self.pred.is_true() {
8804 write!(f, "@{} ", self.pred)?;
8805 }
8806 Ok(())
8807 }
8808 }
8809
8810 impl fmt::Display for Instr {
8811 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8812 write!(f, "{} {}{}", Fmt(|f| self.fmt_pred(f)), self.op, self.deps)
8813 }
8814 }
8815
8816 impl<T: Into<Op>> From<T> for Instr {
8817 fn from(value: T) -> Self {
8818 Self::new(value)
8819 }
8820 }
8821
8822 pub type MappedInstrs = SmallVec<Instr>;
8823
8824 pub struct BasicBlock {
8825 pub label: Label,
8826
8827 /// Whether or not this block is uniform
8828 ///
8829 /// If true, then all non-exited lanes in a warp which execute this block
8830 /// are guaranteed to execute it together
8831 pub uniform: bool,
8832
8833 pub instrs: Vec<Instr>,
8834 }
8835
8836 impl BasicBlock {
8837 pub fn map_instrs(&mut self, mut map: impl FnMut(Instr) -> MappedInstrs) {
8838 let mut instrs = Vec::new();
8839 for i in self.instrs.drain(..) {
8840 match map(i) {
8841 MappedInstrs::None => (),
8842 MappedInstrs::One(i) => {
8843 instrs.push(i);
8844 }
8845 MappedInstrs::Many(mut v) => {
8846 instrs.append(&mut v);
8847 }
8848 }
8849 }
8850 self.instrs = instrs;
8851 }
8852
8853 pub fn phi_dsts_ip(&self) -> Option<usize> {
8854 for (ip, instr) in self.instrs.iter().enumerate() {
8855 match &instr.op {
8856 Op::Annotate(_) => (),
8857 Op::PhiDsts(_) => return Some(ip),
8858 _ => break,
8859 }
8860 }
8861 None
8862 }
8863
8864 pub fn phi_dsts(&self) -> Option<&OpPhiDsts> {
8865 self.phi_dsts_ip().map(|ip| match &self.instrs[ip].op {
8866 Op::PhiDsts(phi) => phi.deref(),
8867 _ => panic!("Expected to find the phi"),
8868 })
8869 }
8870
8871 #[allow(dead_code)]
8872 pub fn phi_dsts_mut(&mut self) -> Option<&mut OpPhiDsts> {
8873 self.phi_dsts_ip().map(|ip| match &mut self.instrs[ip].op {
8874 Op::PhiDsts(phi) => phi.deref_mut(),
8875 _ => panic!("Expected to find the phi"),
8876 })
8877 }
8878
8879 pub fn phi_srcs_ip(&self) -> Option<usize> {
8880 for (ip, instr) in self.instrs.iter().enumerate().rev() {
8881 match &instr.op {
8882 Op::Annotate(_) => (),
8883 Op::PhiSrcs(_) => return Some(ip),
8884 _ if instr.is_branch() => (),
8885 _ => break,
8886 }
8887 }
8888 None
8889 }
8890 pub fn phi_srcs(&self) -> Option<&OpPhiSrcs> {
8891 self.phi_srcs_ip().map(|ip| match &self.instrs[ip].op {
8892 Op::PhiSrcs(phi) => phi.deref(),
8893 _ => panic!("Expected to find the phi"),
8894 })
8895 }
8896
8897 pub fn phi_srcs_mut(&mut self) -> Option<&mut OpPhiSrcs> {
8898 self.phi_srcs_ip().map(|ip| match &mut self.instrs[ip].op {
8899 Op::PhiSrcs(phi) => phi.deref_mut(),
8900 _ => panic!("Expected to find the phi"),
8901 })
8902 }
8903
8904 pub fn branch(&self) -> Option<&Instr> {
8905 self.instrs.last().filter(|&i| i.is_branch())
8906 }
8907
8908 pub fn branch_ip(&self) -> Option<usize> {
8909 if let Some(i) = self.instrs.last() {
8910 if i.is_branch() {
8911 Some(self.instrs.len() - 1)
8912 } else {
8913 None
8914 }
8915 } else {
8916 None
8917 }
8918 }
8919
8920 #[allow(dead_code)]
8921 pub fn branch_mut(&mut self) -> Option<&mut Instr> {
8922 self.instrs.last_mut().filter(|i| i.is_branch())
8923 }
8924
8925 pub fn falls_through(&self) -> bool {
8926 if let Some(i) = self.branch() {
8927 !i.is_branch_always_taken()
8928 } else {
8929 true
8930 }
8931 }
8932 }
8933
8934 /// Stores the index of an instruction in a given Function
8935 ///
8936 /// The block and instruction indices are stored in a memory-efficient way.
8937 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8938 pub struct InstrIdx {
8939 pub block_idx: u32,
8940 pub instr_idx: u32,
8941 }
8942
8943 impl InstrIdx {
8944 pub fn new(bi: usize, ii: usize) -> Self {
8945 Self {
8946 block_idx: bi.try_into().expect("Block index overflow"),
8947 instr_idx: ii.try_into().expect("Instruction index overflow"),
8948 }
8949 }
8950 }
8951
8952 pub struct Function {
8953 pub ssa_alloc: SSAValueAllocator,
8954 pub phi_alloc: PhiAllocator,
8955 pub blocks: CFG<BasicBlock>,
8956 }
8957
8958 impl Function {
8959 pub fn map_instrs(
8960 &mut self,
8961 mut map: impl FnMut(Instr, &mut SSAValueAllocator) -> MappedInstrs,
8962 ) {
8963 let alloc = &mut self.ssa_alloc;
8964 for b in &mut self.blocks {
8965 b.map_instrs(|i| map(i, alloc));
8966 }
8967 }
8968 }
8969
8970 impl fmt::Display for Function {
8971 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8972 let mut pred_width = 0;
8973 let mut dsts_width = 0;
8974 let mut op_width = 0;
8975
8976 let mut blocks = Vec::new();
8977 for b in &self.blocks {
8978 let mut instrs = Vec::new();
8979 for i in &b.instrs {
8980 let mut pred = String::new();
8981 write!(pred, "{}", Fmt(|f| i.fmt_pred(f)))?;
8982 let mut dsts = String::new();
8983 write!(dsts, "{}", Fmt(|f| i.op.fmt_dsts(f)))?;
8984 let mut op = String::new();
8985 write!(op, "{}", Fmt(|f| i.op.fmt_op(f)))?;
8986 let mut deps = String::new();
8987 write!(deps, "{}", i.deps)?;
8988
8989 pred_width = max(pred_width, pred.len());
8990 dsts_width = max(dsts_width, dsts.len());
8991 op_width = max(op_width, op.len());
8992 let is_annotation = matches!(i.op, Op::Annotate(_));
8993
8994 instrs.push((pred, dsts, op, deps, is_annotation));
8995 }
8996 blocks.push(instrs);
8997 }
8998
8999 for (i, mut b) in blocks.drain(..).enumerate() {
9000 let u = if self.blocks[i].uniform { ".u" } else { "" };
9001 write!(f, "block{u} {} {} [", i, self.blocks[i].label)?;
9002 for (pi, p) in self.blocks.pred_indices(i).iter().enumerate() {
9003 if pi > 0 {
9004 write!(f, ", ")?;
9005 }
9006 write!(f, "{}", p)?;
9007 }
9008 write!(f, "] -> {{\n")?;
9009
9010 for (pred, dsts, op, deps, is_annotation) in b.drain(..) {
9011 let eq_sym = if dsts.is_empty() { " " } else { "=" };
9012 if is_annotation {
9013 write!(f, "\n{}\n", op)?;
9014 } else if deps.is_empty() {
9015 write!(
9016 f,
9017 "{:<pred_width$} {:<dsts_width$} {} {}\n",
9018 pred, dsts, eq_sym, op,
9019 )?;
9020 } else {
9021 write!(
9022 f,
9023 "{:<pred_width$} {:<dsts_width$} {} \
9024 {:<op_width$} //{}\n",
9025 pred, dsts, eq_sym, op, deps,
9026 )?;
9027 }
9028 }
9029
9030 write!(f, "}} -> [")?;
9031 for (si, s) in self.blocks.succ_indices(i).iter().enumerate() {
9032 if si > 0 {
9033 write!(f, ", ")?;
9034 }
9035 write!(f, "{}", s)?;
9036 }
9037 write!(f, "]\n")?;
9038 }
9039 Ok(())
9040 }
9041 }
9042
9043 impl Index<InstrIdx> for Function {
9044 type Output = Instr;
9045
9046 fn index(&self, index: InstrIdx) -> &Self::Output {
9047 // Removed at compile time (except for 16-bit targets)
9048 let block_idx: usize = index.block_idx.try_into().unwrap();
9049 let instr_idx: usize = index.instr_idx.try_into().unwrap();
9050 &self.blocks[block_idx].instrs[instr_idx]
9051 }
9052 }
9053
9054 #[derive(Debug)]
9055 pub struct ComputeShaderInfo {
9056 pub local_size: [u16; 3],
9057 pub smem_size: u16,
9058 }
9059
9060 #[derive(Debug)]
9061 pub struct VertexShaderInfo {
9062 pub isbe_space_sharing_enable: bool,
9063 }
9064
9065 #[derive(Debug)]
9066 pub struct FragmentShaderInfo {
9067 pub uses_kill: bool,
9068 pub does_interlock: bool,
9069 pub post_depth_coverage: bool,
9070 pub early_fragment_tests: bool,
9071 pub uses_sample_shading: bool,
9072 }
9073
9074 #[derive(Debug)]
9075 pub struct GeometryShaderInfo {
9076 pub passthrough_enable: bool,
9077 pub stream_out_mask: u8,
9078 pub threads_per_input_primitive: u8,
9079 pub output_topology: OutputTopology,
9080 pub max_output_vertex_count: u16,
9081 }
9082
9083 impl Default for GeometryShaderInfo {
9084 fn default() -> Self {
9085 Self {
9086 passthrough_enable: false,
9087 stream_out_mask: 0,
9088 threads_per_input_primitive: 0,
9089 output_topology: OutputTopology::LineStrip,
9090 max_output_vertex_count: 0,
9091 }
9092 }
9093 }
9094
9095 #[derive(Debug)]
9096 pub struct TessellationInitShaderInfo {
9097 pub per_patch_attribute_count: u8,
9098 pub threads_per_patch: u8,
9099 }
9100
9101 #[repr(u8)]
9102 #[derive(Clone, Copy, Debug)]
9103 pub enum TessellationDomain {
9104 Isoline = NAK_TS_DOMAIN_ISOLINE,
9105 Triangle = NAK_TS_DOMAIN_TRIANGLE,
9106 Quad = NAK_TS_DOMAIN_QUAD,
9107 }
9108
9109 #[repr(u8)]
9110 #[derive(Clone, Copy, Debug)]
9111 pub enum TessellationSpacing {
9112 Integer = NAK_TS_SPACING_INTEGER,
9113 FractionalOdd = NAK_TS_SPACING_FRACT_ODD,
9114 FractionalEven = NAK_TS_SPACING_FRACT_EVEN,
9115 }
9116
9117 #[repr(u8)]
9118 #[derive(Clone, Copy, Debug)]
9119 pub enum TessellationPrimitives {
9120 Points = NAK_TS_PRIMS_POINTS,
9121 Lines = NAK_TS_PRIMS_LINES,
9122 TrianglesCW = NAK_TS_PRIMS_TRIANGLES_CW,
9123 TrianglesCCW = NAK_TS_PRIMS_TRIANGLES_CCW,
9124 }
9125
9126 #[derive(Debug)]
9127 pub struct TessellationShaderInfo {
9128 pub domain: TessellationDomain,
9129 pub spacing: TessellationSpacing,
9130 pub primitives: TessellationPrimitives,
9131 }
9132
9133 #[derive(Debug)]
9134 pub enum ShaderStageInfo {
9135 Compute(ComputeShaderInfo),
9136 Vertex(VertexShaderInfo),
9137 Fragment(FragmentShaderInfo),
9138 Geometry(GeometryShaderInfo),
9139 TessellationInit(TessellationInitShaderInfo),
9140 Tessellation(TessellationShaderInfo),
9141 }
9142
9143 #[derive(Debug, Default)]
9144 pub struct SysValInfo {
9145 pub ab: u32,
9146 pub c: u16,
9147 }
9148
9149 #[derive(Debug)]
9150 pub struct VtgIoInfo {
9151 pub sysvals_in: SysValInfo,
9152 pub sysvals_in_d: u8,
9153 pub sysvals_out: SysValInfo,
9154 pub sysvals_out_d: u8,
9155 pub attr_in: [u32; 4],
9156 pub attr_out: [u32; 4],
9157 pub store_req_start: u8,
9158 pub store_req_end: u8,
9159 pub clip_enable: u8,
9160 pub cull_enable: u8,
9161 pub xfb: Option<Box<nak_xfb_info>>,
9162 }
9163
9164 impl VtgIoInfo {
9165 fn mark_attrs(&mut self, addrs: Range<u16>, written: bool) {
9166 let sysvals = if written {
9167 &mut self.sysvals_out
9168 } else {
9169 &mut self.sysvals_in
9170 };
9171
9172 let sysvals_d = if written {
9173 &mut self.sysvals_out_d
9174 } else {
9175 &mut self.sysvals_in_d
9176 };
9177
9178 let mut attr = BitMutView::new(if written {
9179 &mut self.attr_out
9180 } else {
9181 &mut self.attr_in
9182 });
9183
9184 let mut addrs = addrs;
9185 addrs.start &= !3;
9186 for addr in addrs.step_by(4) {
9187 if addr < 0x080 {
9188 sysvals.ab |= 1 << (addr / 4);
9189 } else if addr < 0x280 {
9190 let attr_idx = (addr - 0x080) as usize / 4;
9191 attr.set_bit(attr_idx, true);
9192 } else if addr < 0x2c0 {
9193 panic!("FF color I/O not supported");
9194 } else if addr < 0x300 {
9195 sysvals.c |= 1 << ((addr - 0x2c0) / 4);
9196 } else if addr >= 0x3a0 && addr < 0x3c0 {
9197 *sysvals_d |= 1 << ((addr - 0x3a0) / 4);
9198 }
9199 }
9200 }
9201
9202 pub fn mark_attrs_read(&mut self, addrs: Range<u16>) {
9203 self.mark_attrs(addrs, false);
9204 }
9205
9206 pub fn mark_attrs_written(&mut self, addrs: Range<u16>) {
9207 self.mark_attrs(addrs, true);
9208 }
9209
9210 pub fn attr_written(&self, addr: u16) -> bool {
9211 if addr < 0x080 {
9212 self.sysvals_out.ab & (1 << (addr / 4)) != 0
9213 } else if addr < 0x280 {
9214 let attr_idx = (addr - 0x080) as usize / 4;
9215 BitView::new(&self.attr_out).get_bit(attr_idx)
9216 } else if addr < 0x2c0 {
9217 panic!("FF color I/O not supported");
9218 } else if addr < 0x300 {
9219 self.sysvals_out.c & (1 << ((addr - 0x2c0) / 4)) != 0
9220 } else if addr >= 0x3a0 && addr < 0x3c0 {
9221 self.sysvals_out_d & (1 << ((addr - 0x3a0) / 4)) != 0
9222 } else {
9223 panic!("Unknown I/O address");
9224 }
9225 }
9226
9227 pub fn mark_store_req(&mut self, addrs: Range<u16>) {
9228 let start = (addrs.start / 4).try_into().unwrap();
9229 let end = ((addrs.end - 1) / 4).try_into().unwrap();
9230 self.store_req_start = min(self.store_req_start, start);
9231 self.store_req_end = max(self.store_req_end, end);
9232 }
9233 }
9234
9235 #[derive(Debug)]
9236 pub struct FragmentIoInfo {
9237 pub sysvals_in: SysValInfo,
9238 pub sysvals_in_d: [PixelImap; 8],
9239 pub attr_in: [PixelImap; 128],
9240 pub barycentric_attr_in: [u32; 4],
9241
9242 pub reads_sample_mask: bool,
9243 pub writes_color: u32,
9244 pub writes_sample_mask: bool,
9245 pub writes_depth: bool,
9246 }
9247
9248 impl FragmentIoInfo {
9249 pub fn mark_attr_read(&mut self, addr: u16, interp: PixelImap) {
9250 if addr < 0x080 {
9251 self.sysvals_in.ab |= 1 << (addr / 4);
9252 } else if addr < 0x280 {
9253 let attr_idx = (addr - 0x080) as usize / 4;
9254 self.attr_in[attr_idx] = interp;
9255 } else if addr < 0x2c0 {
9256 panic!("FF color I/O not supported");
9257 } else if addr < 0x300 {
9258 self.sysvals_in.c |= 1 << ((addr - 0x2c0) / 4);
9259 } else if addr >= 0x3a0 && addr < 0x3c0 {
9260 let attr_idx = (addr - 0x3a0) as usize / 4;
9261 self.sysvals_in_d[attr_idx] = interp;
9262 }
9263 }
9264
9265 pub fn mark_barycentric_attr_in(&mut self, addr: u16) {
9266 assert!(addr >= 0x80 && addr < 0x280);
9267
9268 let mut attr = BitMutView::new(&mut self.barycentric_attr_in);
9269
9270 let attr_idx = (addr - 0x080) as usize / 4;
9271 attr.set_bit(attr_idx, true);
9272 }
9273 }
9274
9275 #[derive(Debug)]
9276 pub enum ShaderIoInfo {
9277 None,
9278 Vtg(VtgIoInfo),
9279 Fragment(FragmentIoInfo),
9280 }
9281
9282 #[derive(Debug)]
9283 pub struct ShaderInfo {
9284 pub max_warps_per_sm: u32,
9285 pub num_gprs: u8,
9286 pub num_control_barriers: u8,
9287 pub num_instrs: u32,
9288 pub num_static_cycles: u64,
9289 pub num_spills_to_mem: u32,
9290 pub num_fills_from_mem: u32,
9291 pub num_spills_to_reg: u32,
9292 pub num_fills_from_reg: u32,
9293 pub slm_size: u32,
9294 pub max_crs_depth: u32,
9295 pub uses_global_mem: bool,
9296 pub writes_global_mem: bool,
9297 pub uses_fp64: bool,
9298 pub stage: ShaderStageInfo,
9299 pub io: ShaderIoInfo,
9300 }
9301
9302 pub trait ShaderModel {
9303 fn sm(&self) -> u8;
9304
9305 #[allow(dead_code)]
9306 fn is_fermi(&self) -> bool {
9307 self.sm() >= 20 && self.sm() < 30
9308 }
9309
9310 fn is_kepler_a(&self) -> bool {
9311 self.sm() >= 30 && self.sm() < 32
9312 }
9313
9314 fn is_kepler_b(&self) -> bool {
9315 // TK1 is SM 3.2 and desktop Kepler B is SM 3.3+
9316 self.sm() >= 32 && self.sm() < 40
9317 }
9318
9319 fn is_kepler(&self) -> bool {
9320 self.is_kepler_a() || self.is_kepler_b()
9321 }
9322
9323 // The following helpers are pulled from GetSpaVersion in the open-source
9324 // NVIDIA kernel driver sources
9325
9326 #[allow(dead_code)]
9327 fn is_maxwell(&self) -> bool {
9328 self.sm() >= 50 && self.sm() < 60
9329 }
9330
9331 #[allow(dead_code)]
9332 fn is_pascal(&self) -> bool {
9333 self.sm() >= 60 && self.sm() < 70
9334 }
9335
9336 fn is_volta(&self) -> bool {
9337 self.sm() >= 70 && self.sm() < 73
9338 }
9339
9340 fn is_turing(&self) -> bool {
9341 self.sm() >= 73 && self.sm() < 80
9342 }
9343
9344 fn is_ampere(&self) -> bool {
9345 self.sm() >= 80 && self.sm() < 89
9346 }
9347
9348 fn is_ada(&self) -> bool {
9349 self.sm() == 89
9350 }
9351
9352 #[allow(dead_code)]
9353 fn is_hopper(&self) -> bool {
9354 self.sm() >= 90 && self.sm() < 100
9355 }
9356
9357 fn is_blackwell_a(&self) -> bool {
9358 self.sm() >= 100 && self.sm() < 110
9359 }
9360
9361 fn is_blackwell_b(&self) -> bool {
9362 self.sm() >= 120 && self.sm() < 130
9363 }
9364
9365 fn is_blackwell(&self) -> bool {
9366 self.is_blackwell_a() || self.is_blackwell_b()
9367 }
9368
9369 fn num_regs(&self, file: RegFile) -> u32;
9370 fn hw_reserved_gprs(&self) -> u32;
9371 fn crs_size(&self, max_crs_depth: u32) -> u32;
9372
9373 fn op_can_be_uniform(&self, op: &Op) -> bool;
9374
9375 // Scheduling information
9376 fn op_needs_scoreboard(&self, op: &Op) -> bool {
9377 !op.no_scoreboard() && !op.has_fixed_latency(self.sm())
9378 }
9379
9380 /// Latency before another non-NOP can execute
9381 fn exec_latency(&self, op: &Op) -> u32;
9382
9383 /// Read-after-read latency
9384 fn raw_latency(
9385 &self,
9386 write: &Op,
9387 dst_idx: usize,
9388 read: &Op,
9389 src_idx: usize,
9390 ) -> u32;
9391
9392 /// Write-after-read latency
9393 fn war_latency(
9394 &self,
9395 read: &Op,
9396 src_idx: usize,
9397 write: &Op,
9398 dst_idx: usize,
9399 ) -> u32;
9400
9401 /// Write-after-write latency
9402 fn waw_latency(
9403 &self,
9404 a: &Op,
9405 a_dst_idx: usize,
9406 a_has_pred: bool,
9407 b: &Op,
9408 b_dst_idx: usize,
9409 ) -> u32;
9410
9411 /// Predicate read-after-write latency
9412 fn paw_latency(&self, write: &Op, dst_idx: usize) -> u32;
9413
9414 /// Worst-case access-after-write latency
9415 fn worst_latency(&self, write: &Op, dst_idx: usize) -> u32;
9416
9417 /// Upper bound on latency
9418 ///
9419 /// Every '*_latency' function must return latencies that are
9420 /// bounded. Ex: self.war_latency() <= self.latency_upper_bound().
9421 /// This is only used for compile-time optimization. If unsure, be
9422 /// conservative.
9423 fn latency_upper_bound(&self) -> u32;
9424
9425 /// Maximum encodable instruction delay
9426 fn max_instr_delay(&self) -> u8;
9427
9428 fn legalize_op(&self, b: &mut LegalizeBuilder, op: &mut Op);
9429 fn encode_shader(&self, s: &Shader<'_>) -> Vec<u32>;
9430 }
9431
9432 pub struct ShaderModelInfo {
9433 sm: u8,
9434 warps_per_sm: u8,
9435 }
9436
9437 impl ShaderModelInfo {
9438 pub fn new(sm: u8, warps_per_sm: u8) -> Self {
9439 ShaderModelInfo { sm, warps_per_sm }
9440 }
9441 }
9442
9443 macro_rules! sm_match {
9444 ($self: expr, |$x: ident| $y: expr) => {
9445 if $self.sm >= 70 {
9446 let $x = ShaderModel70::new($self.sm);
9447 $y
9448 } else if $self.sm >= 50 {
9449 let $x = ShaderModel50::new($self.sm);
9450 $y
9451 } else if $self.sm >= 32 {
9452 let $x = ShaderModel32::new($self.sm);
9453 $y
9454 } else if $self.sm >= 20 {
9455 let $x = ShaderModel20::new($self.sm);
9456 $y
9457 } else {
9458 panic!("Unsupported shader model");
9459 }
9460 };
9461 }
9462
9463 impl ShaderModel for ShaderModelInfo {
9464 fn sm(&self) -> u8 {
9465 self.sm
9466 }
9467
9468 fn num_regs(&self, file: RegFile) -> u32 {
9469 sm_match!(self, |sm| sm.num_regs(file))
9470 }
9471 fn hw_reserved_gprs(&self) -> u32 {
9472 sm_match!(self, |sm| sm.hw_reserved_gprs())
9473 }
9474 fn crs_size(&self, max_crs_depth: u32) -> u32 {
9475 sm_match!(self, |sm| sm.crs_size(max_crs_depth))
9476 }
9477 fn op_can_be_uniform(&self, op: &Op) -> bool {
9478 sm_match!(self, |sm| sm.op_can_be_uniform(op))
9479 }
9480
9481 /// Latency before another non-NOP can execute
9482 fn exec_latency(&self, op: &Op) -> u32 {
9483 sm_match!(self, |sm| sm.exec_latency(op))
9484 }
9485
9486 /// Read-after-read latency
9487 fn raw_latency(
9488 &self,
9489 write: &Op,
9490 dst_idx: usize,
9491 read: &Op,
9492 src_idx: usize,
9493 ) -> u32 {
9494 sm_match!(self, |sm| sm.raw_latency(write, dst_idx, read, src_idx))
9495 }
9496
9497 /// Write-after-read latency
9498 fn war_latency(
9499 &self,
9500 read: &Op,
9501 src_idx: usize,
9502 write: &Op,
9503 dst_idx: usize,
9504 ) -> u32 {
9505 sm_match!(self, |sm| sm.war_latency(read, src_idx, write, dst_idx))
9506 }
9507
9508 /// Write-after-write latency
9509 fn waw_latency(
9510 &self,
9511 a: &Op,
9512 a_dst_idx: usize,
9513 a_has_pred: bool,
9514 b: &Op,
9515 b_dst_idx: usize,
9516 ) -> u32 {
9517 sm_match!(self, |sm| sm
9518 .waw_latency(a, a_dst_idx, a_has_pred, b, b_dst_idx))
9519 }
9520
9521 fn paw_latency(&self, write: &Op, dst_idx: usize) -> u32 {
9522 sm_match!(self, |sm| sm.paw_latency(write, dst_idx))
9523 }
9524 fn worst_latency(&self, write: &Op, dst_idx: usize) -> u32 {
9525 sm_match!(self, |sm| sm.worst_latency(write, dst_idx))
9526 }
9527 fn latency_upper_bound(&self) -> u32 {
9528 sm_match!(self, |sm| sm.latency_upper_bound())
9529 }
9530 fn max_instr_delay(&self) -> u8 {
9531 sm_match!(self, |sm| sm.max_instr_delay())
9532 }
9533 fn legalize_op(&self, b: &mut LegalizeBuilder, op: &mut Op) {
9534 sm_match!(self, |sm| sm.legalize_op(b, op))
9535 }
9536 fn encode_shader(&self, s: &Shader<'_>) -> Vec<u32> {
9537 sm_match!(self, |sm| sm.encode_shader(s))
9538 }
9539 }
9540
9541 pub const fn prev_multiple_of(x: u32, y: u32) -> u32 {
9542 (x / y) * y
9543 }
9544
9545 /// For compute shaders, large values of local_size impose an additional limit
9546 /// on the number of GPRs per thread
9547 pub fn gpr_limit_from_local_size(local_size: &[u16; 3]) -> u32 {
9548 let local_size = local_size[0] * local_size[1] * local_size[2];
9549 // Warps are allocated in multiples of 4
9550 // Multiply that by 32 threads/warp
9551 let local_size = local_size.next_multiple_of(4 * 32) as u32;
9552 let total_regs: u32 = 65536;
9553
9554 let out = total_regs / local_size;
9555 // GPRs are allocated in multiples of 8
9556 let out = prev_multiple_of(out, 8);
9557 min(out, 255)
9558 }
9559
9560 pub fn max_warps_per_sm(sm: &ShaderModelInfo, gprs: u32) -> u32 {
9561 // TODO: Take local_size and shared mem limit into account for compute
9562 let total_regs: u32 = 65536;
9563 // GPRs are allocated in multiples of 8
9564 let gprs = max(gprs, 1);
9565 let gprs = gprs.next_multiple_of(8);
9566 let max_warps = prev_multiple_of((total_regs / 32) / gprs, 4);
9567 min(max_warps, sm.warps_per_sm.into())
9568 }
9569
9570 pub struct Shader<'a> {
9571 pub sm: &'a ShaderModelInfo,
9572 pub info: ShaderInfo,
9573 pub functions: Vec<Function>,
9574 }
9575
9576 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
9577 struct IsbeSpaceSharingStateTracker {
9578 has_attribute_store: bool,
9579 has_attribute_load: bool,
9580 can_overlap_io: bool,
9581 }
9582
9583 impl IsbeSpaceSharingStateTracker {
9584 pub const fn new() -> Self {
9585 Self {
9586 has_attribute_store: false,
9587 has_attribute_load: false,
9588 can_overlap_io: true,
9589 }
9590 }
9591
9592 pub fn visit_instr(&mut self, instr: &Instr) {
9593 // Track attribute store. (XXX: ISBEWR)
9594 self.has_attribute_store |= matches!(instr.op, Op::ASt(_));
9595
9596 // Track attribute load.
9597 if matches!(instr.op, Op::ALd(_) | Op::Isberd(_)) {
9598 self.has_attribute_load = true;
9599
9600 // If we have any attribute load after an attribute store,
9601 // we cannot overlap IO.
9602 if self.has_attribute_store {
9603 self.can_overlap_io = false;
9604 }
9605 }
9606 }
9607
9608 fn merge(&mut self, other: &Self) {
9609 // Propagate details on attribute store and overlap IO.
9610 self.has_attribute_store |= other.has_attribute_store;
9611 self.can_overlap_io &= other.can_overlap_io;
9612
9613 // If a previous block has any attribute store and we found an attribute load,
9614 // we cannot overlap IO.
9615 if other.has_attribute_store && self.has_attribute_load {
9616 self.can_overlap_io = false;
9617 }
9618 }
9619 }
9620
9621 fn can_isbe_space_sharing_be_enabled(f: &Function) -> bool {
9622 let mut state_in = Vec::new();
9623 for block in &f.blocks {
9624 let mut sim = IsbeSpaceSharingStateTracker::new();
9625
9626 for instr in block.instrs.iter() {
9627 sim.visit_instr(instr);
9628 }
9629
9630 if !sim.can_overlap_io {
9631 return false;
9632 }
9633
9634 state_in.push(sim);
9635 }
9636
9637 let mut state_out: Vec<_> = (0..f.blocks.len())
9638 .map(|_| IsbeSpaceSharingStateTracker::new())
9639 .collect();
9640
9641 ForwardDataflow {
9642 cfg: &f.blocks,
9643 block_in: &mut state_in[..],
9644 block_out: &mut state_out[..],
9645 transfer: |_block_idx, _block, sim_out, sim_in| {
9646 if sim_out == sim_in {
9647 false
9648 } else {
9649 *sim_out = *sim_in;
9650 true
9651 }
9652 },
9653 join: |sim_in, pred_sim_out| {
9654 sim_in.merge(pred_sim_out);
9655 },
9656 }
9657 .solve();
9658
9659 for state in state_in {
9660 if !state.can_overlap_io {
9661 return false;
9662 }
9663 }
9664
9665 true
9666 }
9667
9668 impl Shader<'_> {
9669 pub fn for_each_instr(&self, f: &mut impl FnMut(&Instr)) {
9670 for func in &self.functions {
9671 for b in &func.blocks {
9672 for i in &b.instrs {
9673 f(i);
9674 }
9675 }
9676 }
9677 }
9678
9679 pub fn map_instrs(
9680 &mut self,
9681 mut map: impl FnMut(Instr, &mut SSAValueAllocator) -> MappedInstrs,
9682 ) {
9683 for f in &mut self.functions {
9684 f.map_instrs(&mut map);
9685 }
9686 }
9687
9688 /// Remove all annotations, presumably before encoding the shader.
9689 pub fn remove_annotations(&mut self) {
9690 self.map_instrs(|instr: Instr, _| -> MappedInstrs {
9691 if matches!(instr.op, Op::Annotate(_)) {
9692 MappedInstrs::None
9693 } else {
9694 MappedInstrs::One(instr)
9695 }
9696 })
9697 }
9698
9699 pub fn gather_info(&mut self) {
9700 let mut num_instrs = 0;
9701 let mut uses_global_mem = false;
9702 let mut writes_global_mem = false;
9703 let mut uses_fp64 = false;
9704
9705 self.for_each_instr(&mut |instr| {
9706 num_instrs += 1;
9707
9708 if !uses_global_mem {
9709 uses_global_mem = instr.uses_global_mem();
9710 }
9711
9712 if !writes_global_mem {
9713 writes_global_mem = instr.writes_global_mem();
9714 }
9715
9716 if !uses_fp64 {
9717 uses_fp64 = instr.op.is_fp64();
9718 }
9719 });
9720
9721 self.info.num_instrs = num_instrs;
9722 self.info.uses_global_mem = uses_global_mem;
9723 self.info.writes_global_mem = writes_global_mem;
9724 self.info.uses_fp64 = uses_fp64;
9725
9726 self.info.max_warps_per_sm = max_warps_per_sm(
9727 self.sm,
9728 self.info.num_gprs as u32 + self.sm.hw_reserved_gprs(),
9729 );
9730
9731 if self.sm.sm() >= 50 {
9732 if let ShaderStageInfo::Vertex(vertex_info) = &mut self.info.stage {
9733 assert!(self.functions.len() == 1);
9734 vertex_info.isbe_space_sharing_enable =
9735 can_isbe_space_sharing_be_enabled(
9736 self.functions.first().unwrap(),
9737 );
9738 }
9739 }
9740 }
9741 }
9742
9743 impl fmt::Display for Shader<'_> {
9744 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9745 for func in &self.functions {
9746 write!(f, "{}", func)?;
9747 }
9748 Ok(())
9749 }
9750 }