Debian Codegraph @

src/nouveau/compiler/nak/assign_regs.rs

raw
1 // Copyright © 2022 Collabora, Ltd.
2 // SPDX-License-Identifier: MIT
3
4 use crate::api::{GetDebugFlags, DEBUG};
5 use crate::ir::*;
6 use crate::liveness::{BlockLiveness, Liveness, SimpleLiveness};
7 use crate::union_find::UnionFind;
8
9 use compiler::bitset::BitSet;
10 use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
11 use std::cmp::{max, min, Ordering};
12
13 struct KillSet {
14 set: FxHashSet<SSAValue>,
15 vec: Vec<SSAValue>,
16 }
17
18 impl KillSet {
19 pub fn new() -> KillSet {
20 KillSet {
21 set: Default::default(),
22 vec: Vec::new(),
23 }
24 }
25
26 pub fn len(&self) -> usize {
27 self.vec.len()
28 }
29
30 pub fn clear(&mut self) {
31 self.set.clear();
32 self.vec.clear();
33 }
34
35 pub fn insert(&mut self, ssa: SSAValue) {
36 if self.set.insert(ssa) {
37 self.vec.push(ssa);
38 }
39 }
40
41 pub fn iter(&self) -> std::slice::Iter<'_, SSAValue> {
42 self.vec.iter()
43 }
44
45 pub fn is_empty(&self) -> bool {
46 self.vec.is_empty()
47 }
48 }
49
50 // These two helpers are carefully paired for the purposes of RA.
51 // src_ssa_ref() returns whatever SSARef is present in the source, if any.
52 // src_set_reg() overwrites that SSARef with a RegRef.
53 #[inline]
54 fn src_ssa_ref(src: &Src) -> Option<&[SSAValue]> {
55 match &src.src_ref {
56 SrcRef::SSA(ssa) => Some(&ssa[..]),
57 SrcRef::CBuf(CBufRef {
58 buf: CBuf::BindlessSSA(ssa),
59 ..
60 }) => Some(&ssa[..]),
61 _ => None,
62 }
63 }
64
65 #[inline]
66 fn src_set_reg(src: &mut Src, reg: RegRef) {
67 match &mut src.src_ref {
68 SrcRef::SSA(_) => {
69 src.src_ref = reg.into();
70 }
71 SrcRef::CBuf(cb) => {
72 debug_assert!(matches!(&cb.buf, CBuf::BindlessSSA(_)));
73 debug_assert!(reg.file() == RegFile::UGPR && reg.comps() == 2);
74 cb.buf = CBuf::BindlessUGPR(reg);
75 }
76 _ => (),
77 }
78 }
79
80 enum SSAUse {
81 FixedReg(u32),
82 Vec(SSARef),
83 }
84
85 struct SSAUseMap {
86 ssa_map: FxHashMap<SSAValue, Vec<(usize, SSAUse)>>,
87 }
88
89 impl SSAUseMap {
90 fn add_fixed_reg_use(&mut self, ip: usize, ssa: SSAValue, reg: u32) {
91 let v = self.ssa_map.entry(ssa).or_default();
92 v.push((ip, SSAUse::FixedReg(reg)));
93 }
94
95 fn add_vec_use(&mut self, ip: usize, vec: &[SSAValue]) {
96 if vec.len() == 1 {
97 return;
98 }
99
100 for ssa in vec.iter() {
101 let v = self.ssa_map.entry(*ssa).or_default();
102 v.push((ip, SSAUse::Vec(SSARef::new(vec))));
103 }
104 }
105
106 fn find_vec_use_after(&self, ssa: SSAValue, ip: usize) -> Option<&SSAUse> {
107 if let Some(v) = self.ssa_map.get(&ssa) {
108 let p = v.partition_point(|(uip, _)| *uip <= ip);
109 if p == v.len() {
110 None
111 } else {
112 let (_, u) = &v[p];
113 Some(u)
114 }
115 } else {
116 None
117 }
118 }
119
120 pub fn add_block(&mut self, b: &BasicBlock) {
121 for (ip, instr) in b.instrs.iter().enumerate() {
122 match &instr.op {
123 Op::RegOut(op) => {
124 for (i, src) in op.srcs.iter().enumerate() {
125 let out_reg = u32::try_from(i).unwrap();
126 if let Some(ssa) = src_ssa_ref(src) {
127 assert!(ssa.len() == 1);
128 self.add_fixed_reg_use(ip, ssa[0], out_reg);
129 }
130 }
131 }
132 _ => {
133 // We don't care about predicates because they're scalar
134 for src in instr.srcs() {
135 if let Some(ssa) = src_ssa_ref(src) {
136 self.add_vec_use(ip, ssa);
137 }
138 }
139 }
140 }
141 }
142 }
143
144 pub fn for_block(b: &BasicBlock) -> SSAUseMap {
145 let mut am = SSAUseMap {
146 ssa_map: Default::default(),
147 };
148 am.add_block(b);
149 am
150 }
151 }
152
153 /// Tracks the most recent register assigned to a given phi web
154 ///
155 /// During register assignment, we then try to assign this register
156 /// to the next SSAValue in the same web.
157 ///
158 /// This heuristic is inspired by the "Aggressive pre-coalescing" described in
159 /// section 4 of Colombet et al 2011.
160 ///
161 /// Q. Colombet, B. Boissinot, P. Brisk, S. Hack and F. Rastello,
162 /// "Graph-coloring and treescan register allocation using repairing," 2011
163 /// Proceedings of the 14th International Conference on Compilers,
164 /// Architectures and Synthesis for Embedded Systems (CASES), Taipei,
165 /// Taiwan, 2011, pp. 45-54, doi: 10.1145/2038698.2038708.
166 struct PhiWebs {
167 uf: UnionFind<SSAValue, FxBuildHasher>,
168 assignments: FxHashMap<SSAValue, u32>,
169 }
170
171 impl PhiWebs {
172 pub fn new(f: &Function) -> Self {
173 let mut uf = UnionFind::new();
174
175 // Populate uf with phi equivalence classes
176 //
177 // Note that we intentionally don't pay attention to move instructions
178 // below - the assumption is that any move instructions at this point
179 // were inserted by cssa-conversion and will hurt the coalescing
180 for b_idx in 0..f.blocks.len() {
181 let Some(phi_dsts) = f.blocks[b_idx].phi_dsts() else {
182 continue;
183 };
184 let dsts: FxHashMap<Phi, &SSARef> = phi_dsts
185 .dsts
186 .iter()
187 .map(|(idx, dst)| {
188 let ssa_ref = dst.as_ssa().expect("Expected ssa form");
189 (*idx, ssa_ref)
190 })
191 .collect();
192
193 for pred_idx in f.blocks.pred_indices(b_idx) {
194 let phi_srcs =
195 f.blocks[*pred_idx].phi_srcs().expect("Missing phi_srcs");
196 for (src_idx, src) in phi_srcs.srcs.iter() {
197 let a = src.as_ssa().expect("Expected ssa form");
198 let b = dsts[src_idx];
199
200 assert_eq!(a.comps(), 1);
201 assert_eq!(b.comps(), 1);
202
203 uf.union(a[0], b[0]);
204 }
205 }
206 }
207
208 PhiWebs {
209 uf,
210 assignments: Default::default(),
211 }
212 }
213
214 pub fn get(&mut self, ssa: SSAValue) -> Option<u32> {
215 let phi_web_id = self.uf.find(ssa);
216 self.assignments.get(&phi_web_id).copied()
217 }
218
219 pub fn set(&mut self, ssa: SSAValue, reg: u32) {
220 let phi_web_id = self.uf.find(ssa);
221 self.assignments.insert(phi_web_id, reg);
222 }
223 }
224
225 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
226 enum LiveRef {
227 SSA(SSAValue),
228 Phi(Phi),
229 }
230
231 #[derive(Clone, Copy, Eq, Hash, PartialEq)]
232 struct LiveValue {
233 pub live_ref: LiveRef,
234 pub reg_ref: RegRef,
235 }
236
237 // We need a stable ordering of live values so that RA is deterministic
238 impl Ord for LiveValue {
239 fn cmp(&self, other: &Self) -> Ordering {
240 let s_file = u8::from(self.reg_ref.file());
241 let o_file = u8::from(other.reg_ref.file());
242 match s_file.cmp(&o_file) {
243 Ordering::Equal => {
244 let s_idx = self.reg_ref.base_idx();
245 let o_idx = other.reg_ref.base_idx();
246 s_idx.cmp(&o_idx)
247 }
248 ord => ord,
249 }
250 }
251 }
252
253 impl PartialOrd for LiveValue {
254 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
255 Some(self.cmp(other))
256 }
257 }
258
259 #[derive(Clone)]
260 struct RegAllocator {
261 file: RegFile,
262 num_regs: u32,
263 used: BitSet,
264 pinned: BitSet,
265 reg_ssa: Vec<Option<SSAValue>>,
266 ssa_reg: FxHashMap<SSAValue, u32>,
267 }
268
269 impl RegAllocator {
270 pub fn new(file: RegFile, num_regs: u32) -> Self {
271 Self {
272 file: file,
273 num_regs: num_regs,
274 used: Default::default(),
275 pinned: Default::default(),
276 reg_ssa: Vec::new(),
277 ssa_reg: Default::default(),
278 }
279 }
280
281 fn file(&self) -> RegFile {
282 self.file
283 }
284
285 pub fn num_regs_used(&self) -> u32 {
286 self.ssa_reg.len().try_into().unwrap()
287 }
288
289 pub fn reg_is_used(&self, reg: u32) -> bool {
290 self.used.contains(reg.try_into().unwrap())
291 }
292
293 pub fn reg_is_pinned(&self, reg: u32) -> bool {
294 self.pinned.contains(reg.try_into().unwrap())
295 }
296
297 pub fn try_get_reg(&self, ssa: SSAValue) -> Option<u32> {
298 self.ssa_reg.get(&ssa).cloned()
299 }
300
301 pub fn try_get_ssa(&self, reg: u32) -> Option<SSAValue> {
302 if self.reg_is_used(reg) {
303 Some(self.reg_ssa[usize::try_from(reg).unwrap()].unwrap())
304 } else {
305 None
306 }
307 }
308
309 pub fn try_get_vec_reg(&self, vec: &[SSAValue]) -> Option<u32> {
310 let reg = self.try_get_reg(vec[0])?;
311 let comps = u8::try_from(vec.len()).unwrap();
312
313 let align = u32::from(comps).next_power_of_two();
314 if reg % align != 0 {
315 return None;
316 }
317
318 for c in 1..comps {
319 let ssa = vec[usize::from(c)];
320 if self.try_get_reg(ssa) != Some(reg + u32::from(c)) {
321 return None;
322 }
323 }
324 Some(reg)
325 }
326
327 pub fn free_ssa(&mut self, ssa: SSAValue) -> u32 {
328 assert!(ssa.file() == self.file);
329 let reg = self.ssa_reg.remove(&ssa).unwrap();
330 assert!(self.reg_is_used(reg));
331 let reg_usize = usize::try_from(reg).unwrap();
332 assert!(self.reg_ssa[reg_usize] == Some(ssa));
333 self.used.remove(reg_usize);
334 self.pinned.remove(reg_usize);
335 reg
336 }
337
338 pub fn assign_reg(&mut self, ssa: SSAValue, reg: u32) {
339 assert!(ssa.file() == self.file);
340 assert!(reg < self.num_regs);
341 assert!(!self.reg_is_used(reg));
342
343 let reg_usize = usize::try_from(reg).unwrap();
344 if reg_usize >= self.reg_ssa.len() {
345 self.reg_ssa.resize(reg_usize + 1, None);
346 }
347 self.reg_ssa[reg_usize] = Some(ssa);
348 let old = self.ssa_reg.insert(ssa, reg);
349 assert!(old.is_none());
350 self.used.insert(reg_usize);
351 }
352
353 pub fn pin_reg(&mut self, reg: u32) {
354 assert!(self.reg_is_used(reg));
355 self.pinned.insert(reg.try_into().unwrap());
356 }
357
358 fn reg_range_is_unset(set: &BitSet, reg: u32, comps: u8) -> bool {
359 for c in 0..u32::from(comps) {
360 if set.contains((reg + c).try_into().unwrap()) {
361 return false;
362 }
363 }
364 true
365 }
366
367 fn try_find_unset_reg_range(
368 &self,
369 set: &BitSet,
370 start_reg: u32,
371 comps: u8,
372 align_mul: u8,
373 align_offset: u8,
374 ) -> Option<u32> {
375 let res = set.find_aligned_unset_range(
376 start_reg.try_into().unwrap(),
377 comps.into(),
378 align_mul.into(),
379 align_offset.into(),
380 );
381 let res = u32::try_from(res).unwrap();
382 if res + u32::from(comps) <= self.num_regs {
383 Some(res)
384 } else {
385 None
386 }
387 }
388
389 pub fn try_find_unused_reg_range(
390 &self,
391 start_reg: u32,
392 comps: u8,
393 align_mul: u8,
394 align_offset: u8,
395 ) -> Option<u32> {
396 self.try_find_unset_reg_range(
397 &self.used,
398 start_reg,
399 comps,
400 align_mul,
401 align_offset,
402 )
403 }
404
405 pub fn alloc_scalar(
406 &mut self,
407 ip: usize,
408 sum: &SSAUseMap,
409 phi_webs: &mut PhiWebs,
410 ssa: SSAValue,
411 ) -> u32 {
412 // Bias register assignment using the phi coalescing
413 if let Some(reg) = phi_webs.get(ssa) {
414 if !self.reg_is_used(reg) {
415 self.assign_reg(ssa, reg);
416 return reg;
417 }
418 }
419
420 // Otherwise, use SSAUseMap heuristics
421 if let Some(u) = sum.find_vec_use_after(ssa, ip) {
422 match u {
423 SSAUse::FixedReg(reg) => {
424 if !self.reg_is_used(*reg) {
425 self.assign_reg(ssa, *reg);
426 return *reg;
427 }
428 }
429 SSAUse::Vec(vec) => {
430 let mut comp = u8::MAX;
431 for c in 0..vec.comps() {
432 if vec[usize::from(c)] == ssa {
433 comp = c;
434 break;
435 }
436 }
437 assert!(comp < vec.comps());
438
439 let align = vec.comps().next_power_of_two();
440 for c in 0..vec.comps() {
441 if c == comp {
442 continue;
443 }
444
445 let other = vec[usize::from(c)];
446 let Some(other_reg) = self.try_get_reg(other) else {
447 continue;
448 };
449
450 let vec_reg = other_reg & !u32::from(align - 1);
451 if other_reg != vec_reg + u32::from(c) {
452 continue;
453 }
454
455 let reg = vec_reg + u32::from(comp);
456 if reg < self.num_regs && !self.reg_is_used(reg) {
457 self.assign_reg(ssa, reg);
458 return reg;
459 }
460 }
461
462 // We weren't able to pair it with an already allocated
463 // register but maybe we can at least find a place the vec
464 // would fit
465 if let Some(base_reg) =
466 self.try_find_unused_reg_range(0, vec.comps(), align, 0)
467 {
468 let reg = base_reg + u32::from(comp);
469 self.assign_reg(ssa, reg);
470 return reg;
471 }
472 }
473 }
474 }
475
476 let reg = self
477 .try_find_unused_reg_range(0, 1, 1, 0)
478 .expect("Failed to find free register");
479 self.assign_reg(ssa, reg);
480 reg
481 }
482 }
483
484 struct VecRegAllocator<'a> {
485 ra: &'a mut RegAllocator,
486 pcopy: OpParCopy,
487 pinned: BitSet,
488 evicted: FxHashMap<SSAValue, u32>,
489 }
490
491 impl<'a> VecRegAllocator<'a> {
492 fn new(ra: &'a mut RegAllocator) -> Self {
493 let pinned = ra.pinned.clone();
494 VecRegAllocator {
495 ra,
496 pcopy: OpParCopy::new(),
497 pinned,
498 evicted: Default::default(),
499 }
500 }
501
502 fn file(&self) -> RegFile {
503 self.ra.file()
504 }
505
506 fn pin_reg(&mut self, reg: u32) {
507 self.pinned.insert(reg.try_into().unwrap());
508 }
509
510 fn pin_reg_range(&mut self, reg: u32, comps: u8) {
511 for c in 0..u32::from(comps) {
512 self.pin_reg(reg + c);
513 }
514 }
515
516 fn reg_is_pinned(&self, reg: u32) -> bool {
517 self.pinned.contains(reg.try_into().unwrap())
518 }
519
520 fn reg_range_is_unpinned(&self, reg: u32, comps: u8) -> bool {
521 RegAllocator::reg_range_is_unset(&self.pinned, reg, comps)
522 }
523
524 fn assign_pin_reg(&mut self, ssa: SSAValue, reg: u32) -> RegRef {
525 self.pin_reg(reg);
526 self.ra.assign_reg(ssa, reg);
527 RegRef::new(self.file(), reg, 1)
528 }
529
530 pub fn assign_pin_vec_reg(&mut self, vec: &SSARef, reg: u32) -> RegRef {
531 for c in 0..vec.comps() {
532 let ssa = vec[usize::from(c)];
533 self.assign_pin_reg(ssa, reg + u32::from(c));
534 }
535 RegRef::new(self.file(), reg, vec.comps())
536 }
537
538 fn try_find_unpinned_reg_range(
539 &self,
540 start_reg: u32,
541 comps: u8,
542 align_mul: u8,
543 align_offset: u8,
544 ) -> Option<u32> {
545 self.ra.try_find_unset_reg_range(
546 &self.pinned,
547 start_reg,
548 comps,
549 align_mul,
550 align_offset,
551 )
552 }
553
554 pub fn evict_ssa(&mut self, ssa: SSAValue, old_reg: u32) {
555 assert!(ssa.file() == self.file());
556 assert!(!self.reg_is_pinned(old_reg));
557 self.evicted.insert(ssa, old_reg);
558 }
559
560 pub fn evict_reg_if_used(&mut self, reg: u32) {
561 assert!(!self.reg_is_pinned(reg));
562
563 if let Some(ssa) = self.ra.try_get_ssa(reg) {
564 self.ra.free_ssa(ssa);
565 self.evict_ssa(ssa, reg);
566 }
567 }
568
569 fn move_ssa_to_reg(&mut self, ssa: SSAValue, new_reg: u32) {
570 if let Some(old_reg) = self.ra.try_get_reg(ssa) {
571 assert!(!self.evicted.contains_key(&ssa));
572 assert!(!self.reg_is_pinned(old_reg));
573
574 if new_reg == old_reg {
575 self.pin_reg(new_reg);
576 } else {
577 self.ra.free_ssa(ssa);
578 self.evict_reg_if_used(new_reg);
579
580 self.pcopy.push(
581 RegRef::new(self.file(), new_reg, 1).into(),
582 RegRef::new(self.file(), old_reg, 1).into(),
583 );
584
585 self.assign_pin_reg(ssa, new_reg);
586 }
587 } else if let Some(old_reg) = self.evicted.remove(&ssa) {
588 self.evict_reg_if_used(new_reg);
589
590 self.pcopy.push(
591 RegRef::new(self.file(), new_reg, 1).into(),
592 RegRef::new(self.file(), old_reg, 1).into(),
593 );
594
595 self.assign_pin_reg(ssa, new_reg);
596 } else {
597 panic!("Unknown SSA value");
598 }
599 }
600
601 fn finish(mut self, pcopy: &mut OpParCopy) {
602 pcopy.dsts_srcs.append(&mut self.pcopy.dsts_srcs);
603
604 if !self.evicted.is_empty() {
605 // Sort so we get determinism, even if the hash map order changes
606 // from one run to another or due to rust compiler updates.
607 let mut evicted: Vec<_> = self.evicted.drain().collect();
608 evicted.sort_by_key(|(_, reg)| *reg);
609
610 for (ssa, old_reg) in evicted {
611 let mut next_reg = 0;
612 let new_reg = loop {
613 let reg = self
614 .ra
615 .try_find_unused_reg_range(next_reg, 1, 1, 0)
616 .expect("Failed to find free register");
617 if !self.reg_is_pinned(reg) {
618 break reg;
619 }
620 next_reg = reg + 1;
621 };
622
623 pcopy.push(
624 RegRef::new(self.file(), new_reg, 1).into(),
625 RegRef::new(self.file(), old_reg, 1).into(),
626 );
627 self.assign_pin_reg(ssa, new_reg);
628 }
629 }
630 }
631
632 pub fn try_get_vec_reg(&self, vec: &[SSAValue]) -> Option<u32> {
633 self.ra.try_get_vec_reg(vec)
634 }
635
636 pub fn collect_vector(&mut self, vec: &[SSAValue]) -> RegRef {
637 if let Some(reg) = self.try_get_vec_reg(vec) {
638 let comps = u8::try_from(vec.len()).unwrap();
639 self.pin_reg_range(reg, comps);
640 return RegRef::new(self.file(), reg, comps);
641 }
642
643 let comps = u8::try_from(vec.len()).unwrap();
644 let align = comps.next_power_of_two();
645
646 let reg = self
647 .ra
648 .try_find_unused_reg_range(0, comps, align, 0)
649 .or_else(|| {
650 for c in 0..comps {
651 let ssa = vec[usize::from(c)];
652 let Some(comp_reg) = self.ra.try_get_reg(ssa) else {
653 continue;
654 };
655
656 let vec_reg = comp_reg & !u32::from(align - 1);
657 if comp_reg != vec_reg + u32::from(c) {
658 continue;
659 }
660
661 if vec_reg + u32::from(comps) > self.ra.num_regs {
662 continue;
663 }
664
665 if self.reg_range_is_unpinned(vec_reg, comps) {
666 return Some(vec_reg);
667 }
668 }
669 None
670 })
671 .or_else(|| self.try_find_unpinned_reg_range(0, comps, align, 0))
672 .expect("Failed to find an unpinned register range");
673
674 for c in 0..comps {
675 let ssa = vec[usize::from(c)];
676 self.move_ssa_to_reg(ssa, reg + u32::from(c));
677 }
678
679 RegRef::new(self.file(), reg, comps)
680 }
681
682 pub fn alloc_vector(&mut self, vec: &SSARef) -> RegRef {
683 let comps = vec.comps();
684 let align = comps.next_power_of_two();
685
686 if let Some(reg) = self.ra.try_find_unused_reg_range(0, comps, align, 0)
687 {
688 return self.assign_pin_vec_reg(vec, reg);
689 }
690
691 let reg = self
692 .try_find_unpinned_reg_range(0, comps, align, 0)
693 .expect("Failed to find an unpinned register range");
694
695 for c in 0..comps {
696 self.evict_reg_if_used(reg + u32::from(c));
697 }
698 self.assign_pin_vec_reg(vec, reg)
699 }
700
701 pub fn free_killed(&mut self, killed: &KillSet) {
702 for ssa in killed.iter() {
703 if ssa.file() == self.file() {
704 self.ra.free_ssa(*ssa);
705 }
706 }
707 }
708 }
709
710 impl Drop for VecRegAllocator<'_> {
711 fn drop(&mut self) {
712 assert!(self.evicted.is_empty());
713 }
714 }
715
716 fn instr_remap_srcs_file(instr: &mut Instr, ra: &mut VecRegAllocator) {
717 // Collect vector sources first since those may silently pin some of our
718 // scalar sources.
719 for src in instr.srcs_mut() {
720 if let Some(ssa) = src_ssa_ref(src) {
721 if ssa.file() == ra.file() && ssa.len() > 1 {
722 let reg = ra.collect_vector(ssa);
723 src_set_reg(src, reg);
724 }
725 }
726 }
727
728 if let PredRef::SSA(pred) = instr.pred.pred_ref {
729 if pred.file() == ra.file() {
730 instr.pred.pred_ref = ra.collect_vector(&[pred]).into();
731 }
732 }
733
734 for src in instr.srcs_mut() {
735 if let Some(ssa) = src_ssa_ref(src) {
736 if ssa.file() == ra.file() && ssa.len() == 1 {
737 let reg = ra.collect_vector(ssa);
738 src_set_reg(src, reg);
739 }
740 }
741 }
742 }
743
744 fn instr_alloc_scalar_dsts_file(
745 instr: &mut Instr,
746 ip: usize,
747 sum: &SSAUseMap,
748 phi_webs: &mut PhiWebs,
749 ra: &mut RegAllocator,
750 ) {
751 for dst in instr.dsts_mut() {
752 if let Dst::SSA(ssa) = dst {
753 if ssa.file() == ra.file() {
754 assert!(ssa.comps() == 1);
755 let reg = ra.alloc_scalar(ip, sum, phi_webs, ssa[0]);
756 *dst = RegRef::new(ra.file(), reg, 1).into();
757 }
758 }
759 }
760 }
761
762 fn instr_assign_regs_file(
763 instr: &mut Instr,
764 ip: usize,
765 sum: &SSAUseMap,
766 phi_webs: &mut PhiWebs,
767 killed: &KillSet,
768 pcopy: &mut OpParCopy,
769 ra: &mut RegAllocator,
770 ) {
771 struct VecDst {
772 dst_idx: usize,
773 comps: u8,
774 killed: Option<SSARef>,
775 reg: u32,
776 }
777
778 let mut vec_dsts = Vec::new();
779 let mut vec_dst_comps = 0;
780 for (i, dst) in instr.dsts().iter().enumerate() {
781 if let Dst::SSA(ssa) = dst {
782 if ssa.file() == ra.file() && ssa.comps() > 1 {
783 vec_dsts.push(VecDst {
784 dst_idx: i,
785 comps: ssa.comps(),
786 killed: None,
787 reg: u32::MAX,
788 });
789 vec_dst_comps += ssa.comps();
790 }
791 }
792 }
793
794 // No vector destinations is the easy case
795 if vec_dst_comps == 0 {
796 let mut vra = VecRegAllocator::new(ra);
797 instr_remap_srcs_file(instr, &mut vra);
798 vra.free_killed(killed);
799 vra.finish(pcopy);
800 instr_alloc_scalar_dsts_file(instr, ip, sum, phi_webs, ra);
801 return;
802 }
803
804 // Predicates can't be vectors. This lets us ignore instr.pred in our
805 // analysis for the cases below. Only the easy case above needs to care
806 // about them.
807 assert!(!ra.file().is_predicate());
808
809 let mut avail = killed.set.clone();
810 let mut killed_vecs = Vec::new();
811 for src in instr.srcs() {
812 if let Some(vec) = src_ssa_ref(src) {
813 if vec.len() > 1 {
814 let mut vec_killed = true;
815 for ssa in vec.iter() {
816 if ssa.file() != ra.file() || !avail.contains(ssa) {
817 vec_killed = false;
818 break;
819 }
820 }
821 if vec_killed {
822 for ssa in vec.iter() {
823 avail.remove(ssa);
824 }
825 killed_vecs.push(SSARef::new(vec));
826 }
827 }
828 }
829 }
830
831 vec_dsts.sort_by_key(|v| v.comps);
832 killed_vecs.sort_by_key(|v| v.comps());
833
834 let mut next_dst_reg = 0;
835 let mut vec_dsts_map_to_killed_srcs = true;
836 let mut could_trivially_allocate = true;
837 for vec_dst in vec_dsts.iter_mut().rev() {
838 while let Some(src) = killed_vecs.pop() {
839 if src.comps() >= vec_dst.comps {
840 vec_dst.killed = Some(src);
841 break;
842 }
843 }
844 if vec_dst.killed.is_none() {
845 vec_dsts_map_to_killed_srcs = false;
846 }
847
848 let align = vec_dst.comps.next_power_of_two();
849 if let Some(reg) =
850 ra.try_find_unused_reg_range(next_dst_reg, vec_dst.comps, align, 0)
851 {
852 vec_dst.reg = reg;
853 next_dst_reg = reg + u32::from(vec_dst.comps);
854 } else {
855 could_trivially_allocate = false;
856 }
857 }
858
859 if vec_dsts_map_to_killed_srcs {
860 let mut vra = VecRegAllocator::new(ra);
861 instr_remap_srcs_file(instr, &mut vra);
862
863 for vec_dst in &mut vec_dsts {
864 let src_vec = vec_dst.killed.as_ref().unwrap();
865 vec_dst.reg = vra.try_get_vec_reg(src_vec).unwrap();
866 }
867
868 vra.free_killed(killed);
869
870 for vec_dst in vec_dsts {
871 let dst = &mut instr.dsts_mut()[vec_dst.dst_idx];
872 *dst = vra
873 .assign_pin_vec_reg(dst.as_ssa().unwrap(), vec_dst.reg)
874 .into();
875 }
876
877 vra.finish(pcopy);
878
879 instr_alloc_scalar_dsts_file(instr, ip, sum, phi_webs, ra);
880 } else if could_trivially_allocate {
881 let mut vra = VecRegAllocator::new(ra);
882 for vec_dst in vec_dsts {
883 let dst = &mut instr.dsts_mut()[vec_dst.dst_idx];
884 *dst = vra
885 .assign_pin_vec_reg(dst.as_ssa().unwrap(), vec_dst.reg)
886 .into();
887 }
888
889 instr_remap_srcs_file(instr, &mut vra);
890 vra.free_killed(killed);
891 vra.finish(pcopy);
892 instr_alloc_scalar_dsts_file(instr, ip, sum, phi_webs, ra);
893 } else {
894 let mut vra = VecRegAllocator::new(ra);
895 instr_remap_srcs_file(instr, &mut vra);
896
897 // Allocate vector destinations first so we have the most freedom.
898 // Scalar destinations can fill in holes.
899 for dst in instr.dsts_mut() {
900 if let Dst::SSA(ssa) = dst {
901 if ssa.file() == vra.file() && ssa.comps() > 1 {
902 *dst = vra.alloc_vector(ssa).into();
903 }
904 }
905 }
906
907 vra.free_killed(killed);
908 vra.finish(pcopy);
909
910 instr_alloc_scalar_dsts_file(instr, ip, sum, phi_webs, ra);
911 }
912 }
913
914 impl PerRegFile<RegAllocator> {
915 pub fn assign_reg(&mut self, ssa: SSAValue, reg: RegRef) {
916 assert!(reg.file() == ssa.file());
917 assert!(reg.comps() == 1);
918 self[ssa.file()].assign_reg(ssa, reg.base_idx());
919 }
920
921 pub fn free_killed(&mut self, killed: &KillSet) {
922 for ssa in killed.iter() {
923 self[ssa.file()].free_ssa(*ssa);
924 }
925 }
926 }
927
928 struct AssignRegsBlock {
929 ra: PerRegFile<RegAllocator>,
930 pcopy_tmp_gprs: u8,
931 live_in: Vec<LiveValue>,
932 phi_out: FxHashMap<Phi, SrcRef>,
933 }
934
935 impl AssignRegsBlock {
936 fn new(num_regs: &PerRegFile<u32>, pcopy_tmp_gprs: u8) -> AssignRegsBlock {
937 AssignRegsBlock {
938 ra: PerRegFile::new_with(|file| {
939 RegAllocator::new(file, num_regs[file])
940 }),
941 pcopy_tmp_gprs: pcopy_tmp_gprs,
942 live_in: Vec::new(),
943 phi_out: Default::default(),
944 }
945 }
946
947 fn get_scalar(&self, ssa: SSAValue) -> RegRef {
948 let ra = &self.ra[ssa.file()];
949 let reg = ra.try_get_reg(ssa).expect("Unknown SSA value");
950 RegRef::new(ssa.file(), reg, 1)
951 }
952
953 fn alloc_scalar(
954 &mut self,
955 ip: usize,
956 sum: &SSAUseMap,
957 phi_webs: &mut PhiWebs,
958 ssa: SSAValue,
959 ) -> RegRef {
960 let ra = &mut self.ra[ssa.file()];
961 let reg = ra.alloc_scalar(ip, sum, phi_webs, ssa);
962 RegRef::new(ssa.file(), reg, 1)
963 }
964
965 fn pin_vector(&mut self, reg: RegRef) {
966 let ra = &mut self.ra[reg.file()];
967 for c in 0..reg.comps() {
968 ra.pin_reg(reg.comp(c).base_idx());
969 }
970 }
971
972 fn try_coalesce(&mut self, ssa: SSAValue, src: &Src) -> bool {
973 debug_assert!(src.is_unmodified());
974 let SrcRef::Reg(src_reg) = src.src_ref else {
975 return false;
976 };
977 debug_assert!(src_reg.comps() == 1);
978
979 if src_reg.file() != ssa.file() {
980 return false;
981 }
982
983 let ra = &mut self.ra[src_reg.file()];
984 if ra.reg_is_used(src_reg.base_idx()) {
985 return false;
986 }
987
988 ra.assign_reg(ssa, src_reg.base_idx());
989 true
990 }
991
992 fn pcopy_tmp(&self) -> Option<RegRef> {
993 if self.pcopy_tmp_gprs > 0 {
994 Some(RegRef::new(
995 RegFile::GPR,
996 self.ra[RegFile::GPR].num_regs,
997 self.pcopy_tmp_gprs,
998 ))
999 } else {
1000 None
1001 }
1002 }
1003
1004 fn assign_regs_instr(
1005 &mut self,
1006 mut instr: Instr,
1007 ip: usize,
1008 sum: &SSAUseMap,
1009 phi_webs: &mut PhiWebs,
1010 srcs_killed: &KillSet,
1011 dsts_killed: &KillSet,
1012 pcopy: &mut OpParCopy,
1013 ) -> Option<Instr> {
1014 match &mut instr.op {
1015 Op::Undef(undef) => {
1016 if let Dst::SSA(ssa) = &undef.dst {
1017 assert!(ssa.comps() == 1);
1018 self.alloc_scalar(ip, sum, phi_webs, ssa[0]);
1019 }
1020 assert!(srcs_killed.is_empty());
1021 self.ra.free_killed(dsts_killed);
1022 None
1023 }
1024 Op::PhiSrcs(op) => {
1025 for (id, src) in op.srcs.iter() {
1026 assert!(src.is_unmodified());
1027 if let Some(ssa) = src_ssa_ref(src) {
1028 assert!(ssa.len() == 1);
1029 let reg = self.get_scalar(ssa[0]);
1030 self.phi_out.insert(*id, reg.into());
1031 } else {
1032 self.phi_out.insert(*id, src.src_ref.clone());
1033 }
1034 }
1035 assert!(dsts_killed.is_empty());
1036 None
1037 }
1038 Op::PhiDsts(op) => {
1039 assert!(instr.pred.is_true());
1040
1041 for (phi, dst) in op.dsts.iter() {
1042 if let Dst::SSA(ssa) = dst {
1043 assert!(ssa.comps() == 1);
1044 let reg = self.alloc_scalar(ip, sum, phi_webs, ssa[0]);
1045 self.live_in.push(LiveValue {
1046 live_ref: LiveRef::Phi(*phi),
1047 reg_ref: reg,
1048 });
1049 }
1050 }
1051 assert!(srcs_killed.is_empty());
1052 self.ra.free_killed(dsts_killed);
1053
1054 None
1055 }
1056 Op::Break(op) => {
1057 for src in op.srcs_as_mut_slice() {
1058 if let Some(ssa) = src_ssa_ref(src) {
1059 assert!(ssa.len() == 1);
1060 let reg = self.get_scalar(ssa[0]);
1061 src_set_reg(src, reg);
1062 }
1063 }
1064
1065 self.ra.free_killed(srcs_killed);
1066
1067 if let Dst::SSA(ssa) = &op.bar_out {
1068 let reg = *op.bar_in.src_ref.as_reg().unwrap();
1069 self.ra.assign_reg(ssa[0], reg);
1070 op.bar_out = reg.into();
1071 }
1072
1073 self.ra.free_killed(dsts_killed);
1074
1075 Some(instr)
1076 }
1077 Op::BSSy(op) => {
1078 for src in op.srcs_as_mut_slice() {
1079 if let Some(ssa) = src_ssa_ref(src) {
1080 assert!(ssa.len() == 1);
1081 let reg = self.get_scalar(ssa[0]);
1082 src_set_reg(src, reg);
1083 }
1084 }
1085
1086 self.ra.free_killed(srcs_killed);
1087
1088 if let Dst::SSA(ssa) = &op.bar_out {
1089 let reg = *op.bar_in.src_ref.as_reg().unwrap();
1090 self.ra.assign_reg(ssa[0], reg);
1091 op.bar_out = reg.into();
1092 }
1093
1094 self.ra.free_killed(dsts_killed);
1095
1096 Some(instr)
1097 }
1098 Op::Copy(copy) => {
1099 if let Some(ssa) = src_ssa_ref(&copy.src) {
1100 // This may be a Cbuf::BindlessSSA source so we need to
1101 // support vectors because cbuf handles are vec2s. However,
1102 // since we only have a single scalar destination, we can
1103 // just allocate and free killed up-front.
1104 let ra = &mut self.ra[ssa.file()];
1105 let mut vra = VecRegAllocator::new(ra);
1106 let reg = vra.collect_vector(ssa);
1107 vra.free_killed(srcs_killed);
1108 vra.finish(pcopy);
1109 src_set_reg(&mut copy.src, reg);
1110 }
1111
1112 let mut del_copy = false;
1113 if let Dst::SSA(dst_vec) = &mut copy.dst {
1114 debug_assert!(dst_vec.comps() == 1);
1115 let dst_ssa = &dst_vec[0];
1116
1117 if self.try_coalesce(*dst_ssa, &copy.src) {
1118 del_copy = true;
1119 } else {
1120 copy.dst = self
1121 .alloc_scalar(ip, sum, phi_webs, *dst_ssa)
1122 .into();
1123 }
1124 }
1125
1126 self.ra.free_killed(dsts_killed);
1127
1128 if del_copy {
1129 None
1130 } else {
1131 Some(instr)
1132 }
1133 }
1134 Op::Pin(_) | Op::Unpin(_) => {
1135 assert!(instr.pred.is_true());
1136
1137 let (src, dst) = match &instr.op {
1138 Op::Pin(pin) => (&pin.src, &pin.dst),
1139 Op::Unpin(unpin) => (&unpin.src, &unpin.dst),
1140 _ => unreachable!(),
1141 };
1142
1143 // These basically act as a vector version of OpCopy except that
1144 // they only work on SSA values and we pin the destination if
1145 // it's OpPin.
1146 let src_vec = src.as_ssa().unwrap();
1147 let dst_vec = dst.as_ssa().unwrap();
1148 assert!(src_vec.comps() == dst_vec.comps());
1149
1150 if srcs_killed.len() == src_vec.comps().into()
1151 && src_vec.file() == dst_vec.file()
1152 {
1153 let ra = &mut self.ra[src_vec.file()];
1154 let mut vra = VecRegAllocator::new(ra);
1155 let reg = vra.collect_vector(src_vec);
1156 vra.finish(pcopy);
1157 for c in 0..src_vec.comps() {
1158 let c_reg = ra.free_ssa(src_vec[usize::from(c)]);
1159 debug_assert!(c_reg == reg.comp(c).base_idx());
1160 ra.assign_reg(dst_vec[usize::from(c)], c_reg);
1161 }
1162
1163 if matches!(&instr.op, Op::Pin(_)) {
1164 self.pin_vector(reg);
1165 }
1166 self.ra.free_killed(dsts_killed);
1167
1168 None
1169 } else {
1170 // Otherwise, turn into a parallel copy
1171 //
1172 // We can always allocate the destination first in this
1173 // case.
1174 assert!(dst_vec.comps() > 1 || srcs_killed.is_empty());
1175
1176 let dst_ra = &mut self.ra[dst_vec.file()];
1177 let mut vra = VecRegAllocator::new(dst_ra);
1178 let dst_reg = vra.alloc_vector(dst_vec);
1179 vra.finish(pcopy);
1180
1181 let mut pin_copy = OpParCopy::new();
1182 for c in 0..dst_reg.comps() {
1183 let src_reg = self.get_scalar(src_vec[usize::from(c)]);
1184 pin_copy.push(dst_reg.comp(c).into(), src_reg.into());
1185 }
1186
1187 if matches!(&instr.op, Op::Pin(_)) {
1188 self.pin_vector(dst_reg);
1189 }
1190 self.ra.free_killed(srcs_killed);
1191 self.ra.free_killed(dsts_killed);
1192
1193 Some(Instr::new(pin_copy))
1194 }
1195 }
1196 Op::ParCopy(pcopy) => {
1197 for (_, src) in pcopy.dsts_srcs.iter_mut() {
1198 if let Some(src_vec) = src_ssa_ref(src) {
1199 debug_assert!(src_vec.len() == 1);
1200 let reg = self.get_scalar(src_vec[0]);
1201 src_set_reg(src, reg);
1202 }
1203 }
1204
1205 self.ra.free_killed(srcs_killed);
1206
1207 // Try to coalesce destinations into sources, if possible
1208 pcopy.dsts_srcs.retain(|dst, src| match dst {
1209 Dst::None => false,
1210 Dst::SSA(dst_vec) => {
1211 debug_assert!(dst_vec.comps() == 1);
1212 !self.try_coalesce(dst_vec[0], src)
1213 }
1214 Dst::Reg(_) => true,
1215 });
1216
1217 for (dst, _) in pcopy.dsts_srcs.iter_mut() {
1218 if let Dst::SSA(dst_vec) = dst {
1219 debug_assert!(dst_vec.comps() == 1);
1220 *dst = self
1221 .alloc_scalar(ip, sum, phi_webs, dst_vec[0])
1222 .into();
1223 }
1224 }
1225
1226 self.ra.free_killed(dsts_killed);
1227
1228 pcopy.tmp = self.pcopy_tmp();
1229 if pcopy.is_empty() {
1230 None
1231 } else {
1232 Some(instr)
1233 }
1234 }
1235 Op::RegOut(out) => {
1236 for src in out.srcs.iter_mut() {
1237 if let Some(src_vec) = src_ssa_ref(src) {
1238 debug_assert!(src_vec.len() == 1);
1239 let reg = self.get_scalar(src_vec[0]);
1240 src_set_reg(src, reg);
1241 }
1242 }
1243
1244 self.ra.free_killed(srcs_killed);
1245 assert!(dsts_killed.is_empty());
1246
1247 // This should be the last instruction and its sources should
1248 // be the last free GPRs.
1249 debug_assert!(self.ra[RegFile::GPR].num_regs_used() == 0);
1250
1251 for (i, src) in out.srcs.iter().enumerate() {
1252 let reg = u32::try_from(i).unwrap();
1253 let dst = RegRef::new(RegFile::GPR, reg, 1);
1254 pcopy.push(dst.into(), src.clone());
1255 }
1256
1257 None
1258 }
1259 _ => {
1260 for file in self.ra.values_mut() {
1261 instr_assign_regs_file(
1262 &mut instr,
1263 ip,
1264 sum,
1265 phi_webs,
1266 srcs_killed,
1267 pcopy,
1268 file,
1269 );
1270 }
1271 self.ra.free_killed(dsts_killed);
1272 Some(instr)
1273 }
1274 }
1275 }
1276
1277 fn first_pass<BL: BlockLiveness>(
1278 &mut self,
1279 b: &mut BasicBlock,
1280 bl: &BL,
1281 pred_ra: Option<&PerRegFile<RegAllocator>>,
1282 phi_webs: &mut PhiWebs,
1283 ) {
1284 // Populate live in from the register file we're handed. We'll add more
1285 // live in when we process the OpPhiDst, if any.
1286 if let Some(pred_ra) = pred_ra {
1287 for (raf, pred_raf) in self.ra.values_mut().zip(pred_ra.values()) {
1288 for (ssa, reg) in &pred_raf.ssa_reg {
1289 if bl.is_live_in(ssa) {
1290 raf.assign_reg(*ssa, *reg);
1291 if pred_raf.reg_is_pinned(*reg) {
1292 raf.pin_reg(*reg);
1293 }
1294 self.live_in.push(LiveValue {
1295 live_ref: LiveRef::SSA(*ssa),
1296 reg_ref: RegRef::new(raf.file(), *reg, 1),
1297 });
1298 }
1299 }
1300 }
1301 }
1302
1303 let sum = SSAUseMap::for_block(b);
1304
1305 let mut instrs = Vec::new();
1306 let mut srcs_killed = KillSet::new();
1307 let mut dsts_killed = KillSet::new();
1308
1309 for (ip, instr) in b.instrs.drain(..).enumerate() {
1310 // Build up the kill set
1311 srcs_killed.clear();
1312 if let PredRef::SSA(ssa) = &instr.pred.pred_ref {
1313 if !bl.is_live_after_ip(ssa, ip) {
1314 srcs_killed.insert(*ssa);
1315 }
1316 }
1317 for src in instr.srcs() {
1318 for ssa in src.iter_ssa() {
1319 if !bl.is_live_after_ip(ssa, ip) {
1320 srcs_killed.insert(*ssa);
1321 }
1322 }
1323 }
1324
1325 dsts_killed.clear();
1326 for dst in instr.dsts() {
1327 if let Dst::SSA(vec) = dst {
1328 for ssa in vec.iter() {
1329 if !bl.is_live_after_ip(ssa, ip) {
1330 dsts_killed.insert(*ssa);
1331 }
1332 }
1333 }
1334 }
1335
1336 let mut pcopy = OpParCopy::new();
1337 pcopy.tmp = self.pcopy_tmp();
1338
1339 let instr = self.assign_regs_instr(
1340 instr,
1341 ip,
1342 &sum,
1343 phi_webs,
1344 &srcs_killed,
1345 &dsts_killed,
1346 &mut pcopy,
1347 );
1348
1349 if !pcopy.is_empty() {
1350 if DEBUG.annotate() {
1351 instrs.push(Instr::new(OpAnnotate {
1352 annotation: "generated by assign_regs".into(),
1353 }));
1354 }
1355 if !b.uniform {
1356 for dst in pcopy.dsts_as_slice() {
1357 if let Dst::Reg(reg) = dst {
1358 assert!(!reg.is_uniform());
1359 }
1360 }
1361 }
1362 instrs.push(Instr::new(pcopy));
1363 }
1364
1365 if let Some(instr) = instr {
1366 instrs.push(instr);
1367 }
1368 }
1369
1370 // Update phi_webs with the registers assigned in this block
1371 for ra in self.ra.values() {
1372 for (ssa, reg) in &ra.ssa_reg {
1373 phi_webs.set(*ssa, *reg);
1374 }
1375 }
1376
1377 // Sort live-in to maintain determinism
1378 self.live_in.sort();
1379
1380 b.instrs = instrs;
1381 }
1382
1383 fn second_pass(&self, target: &AssignRegsBlock, b: &mut BasicBlock) {
1384 let mut pcopy = OpParCopy::new();
1385 pcopy.tmp = self.pcopy_tmp();
1386
1387 for lv in &target.live_in {
1388 let src = match lv.live_ref {
1389 LiveRef::SSA(ssa) => SrcRef::from(self.get_scalar(ssa)),
1390 LiveRef::Phi(phi) => self.phi_out.get(&phi).unwrap().clone(),
1391 };
1392 let dst = lv.reg_ref;
1393 if let SrcRef::Reg(src_reg) = src {
1394 if dst == src_reg {
1395 continue;
1396 }
1397 }
1398 pcopy.push(dst.into(), src.into());
1399 }
1400
1401 if !pcopy.is_empty() {
1402 let ann = OpAnnotate {
1403 annotation: "generated by assign_regs".into(),
1404 };
1405 if b.branch().is_some() {
1406 b.instrs.insert(b.instrs.len() - 1, Instr::new(ann));
1407 b.instrs.insert(b.instrs.len() - 1, Instr::new(pcopy));
1408 } else {
1409 b.instrs.push(Instr::new(ann));
1410 b.instrs.push(Instr::new(pcopy));
1411 }
1412 }
1413 }
1414 }
1415
1416 impl Shader<'_> {
1417 pub fn assign_regs(&mut self) {
1418 assert!(self.functions.len() == 1);
1419 let f = &mut self.functions[0];
1420
1421 // Convert to CSSA before we spill or assign registers
1422 f.to_cssa();
1423
1424 let mut live = SimpleLiveness::for_function(f);
1425 let mut max_live = live.calc_max_live(f);
1426
1427 // We want at least one temporary GPR reserved for parallel copies.
1428 let mut tmp_gprs = 1_u8;
1429
1430 let spill_files =
1431 [RegFile::UPred, RegFile::Pred, RegFile::UGPR, RegFile::Bar];
1432 for file in spill_files {
1433 let num_regs = self.sm.num_regs(file);
1434 if max_live[file] > num_regs {
1435 f.spill_values(file, num_regs, &mut self.info);
1436
1437 // Re-calculate liveness after we spill
1438 live = SimpleLiveness::for_function(f);
1439 max_live = live.calc_max_live(f);
1440
1441 if file == RegFile::Bar {
1442 tmp_gprs = max(tmp_gprs, 2);
1443 }
1444 }
1445 }
1446
1447 // An instruction can have at most 4 vector sources/destinations. In
1448 // order to ensure we always succeed at allocation, regardless of
1449 // arbitrary choices, we need at least 16 GPRs.
1450 let mut gpr_limit = max(max_live[RegFile::GPR], 16);
1451 let mut total_gprs = gpr_limit + u32::from(tmp_gprs);
1452
1453 let mut max_gprs = self.sm.num_regs(RegFile::GPR);
1454
1455 if DEBUG.spill() {
1456 // To test spilling, reduce the number of registers to the minimum
1457 // practical for RA. We need at least 16 registers to satisfy RA
1458 // constraints for texture ops.
1459 max_gprs = 16;
1460
1461 // OpRegOut can use arbitrarily many GPRs
1462 for b in &f.blocks {
1463 for instr in b.instrs.iter().rev() {
1464 match &instr.op {
1465 Op::Exit(_) => (),
1466 Op::RegOut(op) => {
1467 let out_gprs =
1468 u32::try_from(op.srcs.len()).unwrap();
1469 max_gprs = max(max_gprs, out_gprs);
1470 }
1471 _ => break,
1472 }
1473 }
1474 }
1475
1476 // and another 2 for parallel copy
1477 max_gprs += 2;
1478 }
1479
1480 let hw_reserved_gprs = self.sm.hw_reserved_gprs();
1481 if let ShaderStageInfo::Compute(cs_info) = &self.info.stage {
1482 max_gprs = min(
1483 max_gprs,
1484 gpr_limit_from_local_size(&cs_info.local_size)
1485 - hw_reserved_gprs,
1486 );
1487 }
1488
1489 if total_gprs > max_gprs {
1490 // If we're spilling GPRs, we need to reserve 2 GPRs for OpParCopy
1491 // lowering because it needs to be able lower Mem copies which
1492 // require a temporary
1493 tmp_gprs = max(tmp_gprs, 2);
1494 total_gprs = max_gprs;
1495 gpr_limit = total_gprs - u32::from(tmp_gprs);
1496
1497 f.spill_values(RegFile::GPR, gpr_limit, &mut self.info);
1498
1499 // Re-calculate liveness one last time
1500 live = SimpleLiveness::for_function(f);
1501 } else {
1502 // GPRs are allocated in multiple of 8. That means we can give RA a
1503 // bit more freedom by making gprs up until the next multiple
1504 // available.
1505 let next_multiple_gprs = (total_gprs + hw_reserved_gprs)
1506 .next_multiple_of(8)
1507 - hw_reserved_gprs;
1508 let free_gprs = next_multiple_gprs.min(max_gprs) - total_gprs;
1509
1510 total_gprs += free_gprs;
1511 gpr_limit += free_gprs;
1512 }
1513
1514 self.info.num_gprs = total_gprs.try_into().unwrap();
1515
1516 let limit = PerRegFile::new_with(|file| {
1517 if file == RegFile::GPR {
1518 gpr_limit
1519 } else {
1520 self.sm.num_regs(file)
1521 }
1522 });
1523
1524 let mut phi_webs = PhiWebs::new(f);
1525
1526 let mut blocks: Vec<AssignRegsBlock> = Vec::new();
1527 for b_idx in 0..f.blocks.len() {
1528 let pred = f.blocks.pred_indices(b_idx);
1529 let pred_ra = if pred.is_empty() {
1530 None
1531 } else {
1532 // Start with the previous block's.
1533 Some(&blocks[pred[0]].ra)
1534 };
1535
1536 let bl = live.block_live(b_idx);
1537
1538 let mut arb = AssignRegsBlock::new(&limit, tmp_gprs);
1539 arb.first_pass(&mut f.blocks[b_idx], bl, pred_ra, &mut phi_webs);
1540
1541 assert!(blocks.len() == b_idx);
1542 blocks.push(arb);
1543 }
1544
1545 for b_idx in 0..f.blocks.len() {
1546 let arb = &blocks[b_idx];
1547 for sb_idx in f.blocks.succ_indices(b_idx).to_vec() {
1548 arb.second_pass(&blocks[sb_idx], &mut f.blocks[b_idx]);
1549 }
1550 }
1551 }
1552 }