1use std::fmt;
53
54use rucc_mir::{Constraint, Func, Inst, Reg, Role};
55use rucc_target::{PhysReg, RegClass};
56
57use crate::assign::{Assignment, Place};
58use crate::live::{Live, Range};
59use crate::order::{Order, Point};
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum Problem {
64 Nowhere {
66 reg: Reg,
68 },
69 Shared {
72 first: Reg,
74 second: Reg,
76 place: Place,
78 },
79 InTheWay {
82 reg: Reg,
84 at: PhysReg,
86 inst: Inst,
88 },
89 NotOnTheStack {
91 reg: Reg,
93 inst: Inst,
95 },
96 NeverWritten {
99 reg: Reg,
101 },
102}
103
104impl fmt::Display for Problem {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 match self {
107 Problem::Nowhere { reg } => write!(f, "{} has nowhere to live", name(*reg)),
108 Problem::Shared { first, second, place } => {
109 let (first, second) = (name(*first), name(*second));
110 write!(f, "{first} and {second} are both live and both in {}", place_name(*place))
111 }
112 Problem::InTheWay { reg, at, inst } => {
113 let reg = name(*reg);
114 let inst = inst.index();
115 write!(f, "{reg} is in register {}, which instruction {inst} wants", at.number())
116 }
117 Problem::NotOnTheStack { reg, inst } => {
118 let reg = name(*reg);
119 write!(f, "{reg} is not on the stack, and instruction {} needs it", inst.index())
120 }
121 Problem::NeverWritten { reg } => {
122 write!(f, "{} is read before anything writes it", name(*reg))
123 }
124 }
125 }
126}
127
128#[must_use]
139pub fn check(func: &Func, order: &Order, live: &Live, assignment: &Assignment) -> Vec<Problem> {
140 let mut problems = Vec::new();
141 if let Some(entry) = func.entry() {
144 for reg in live.live_in(entry) {
145 problems.push(Problem::NeverWritten { reg });
146 }
147 }
148 let reuses = reuses(func, order);
149 let mut values = Vec::new();
150 for (number, reuse) in reuses.iter().enumerate() {
151 let reg = Reg::virtual_reg(u32::try_from(number).expect("a register number"));
152 let (Some(mut range), Some(class)) = (live.range(reg), func.class_of(reg)) else {
153 continue;
154 };
155 let Some(place) = assignment.place(reg) else {
156 problems.push(Problem::Nowhere { reg });
157 continue;
158 };
159 if let Some(reuse) = reuse {
164 range.start = range.start.min(reuse.at);
165 }
166 values.push(Value { reg, class, range, place });
167 }
168 overlaps(&values, &reuses, live, &mut problems);
169 instructions(func, order, assignment, &values, &reuses, &mut problems);
170 problems
171}
172
173#[must_use]
175pub fn report(problems: &[Problem]) -> String {
176 let places = if problems.len() == 1 { "place" } else { "places" };
177 let mut report = format!("the allocation is wrong in {} {places}", problems.len());
178 for problem in problems {
179 report.push_str("\n ");
180 report.push_str(&problem.to_string());
181 }
182 report
183}
184
185#[derive(Debug, Clone, Copy)]
187struct Value {
188 reg: Reg,
189 class: RegClass,
190 range: Range,
191 place: Place,
192}
193
194#[derive(Debug, Clone, Copy)]
196struct Reuse {
197 source: Reg,
198 at: Point,
199}
200
201fn overlaps(values: &[Value], reuses: &[Option<Reuse>], live: &Live, problems: &mut Vec<Problem>) {
206 let mut sorted = values.to_vec();
207 sorted.sort_by_key(|value| (value.range.start, value.reg));
208 let mut active: Vec<Value> = Vec::new();
209 for value in sorted {
210 active.retain(|held| held.range.end >= value.range.start);
211 for held in &active {
212 if !together(*held, value) || coalesced(*held, value, reuses, live) {
213 continue;
214 }
215 problems.push(Problem::Shared {
216 first: held.reg,
217 second: value.reg,
218 place: value.place,
219 });
220 }
221 active.push(value);
222 }
223}
224
225fn together(first: Value, second: Value) -> bool {
231 match (first.place, second.place) {
232 (Place::Reg(first_at), Place::Reg(second_at)) => {
233 first_at == second_at && first.class == second.class
234 }
235 (Place::Slot(first_slot), Place::Slot(second_slot)) => first_slot == second_slot,
236 _ => false,
237 }
238}
239
240fn coalesced(first: Value, second: Value, reuses: &[Option<Reuse>], live: &Live) -> bool {
247 let pair = |source: Value, dest: Value| {
248 let Some(reuse) = reuses[index(dest.reg)] else { return false };
249 reuse.source == source.reg && live.range(source.reg).is_some_and(|r| r.end == reuse.at)
250 };
251 pair(first, second) || pair(second, first)
252}
253
254fn instructions(
257 func: &Func,
258 order: &Order,
259 assignment: &Assignment,
260 values: &[Value],
261 reuses: &[Option<Reuse>],
262 problems: &mut Vec<Problem>,
263) {
264 for block in func.blocks() {
265 for inst in func.insts(block) {
266 for operand in &func[func[inst].operands] {
267 if operand.constraint == Constraint::Stack
268 && matches!(assignment.place(operand.reg), Some(Place::Reg(_)))
269 {
270 problems.push(Problem::NotOnTheStack { reg: operand.reg, inst });
271 }
272 let at = match operand.constraint {
276 Constraint::Fixed(at) => Some(at),
277 _ => operand.reg.phys(),
278 };
279 let Some(at) = at else { continue };
280 let early = order.early(inst);
281 let point = if operand.role == Role::Def { order.late(inst) } else { early };
282 for value in values {
283 let mine = value.reg == operand.reg
284 || reuses[index(value.reg)].is_some_and(|reuse| {
285 reuse.source == operand.reg
286 && reuse.at == early
287 && value.place == Place::Reg(at)
288 });
289 if mine || value.class != operand.class {
290 continue;
291 }
292 if value.place == Place::Reg(at) && value.range.covers(point) {
293 problems.push(Problem::InTheWay { reg: value.reg, at, inst });
294 }
295 }
296 }
297 }
298 }
299}
300
301fn reuses(func: &Func, order: &Order) -> Vec<Option<Reuse>> {
303 let mut reuses = vec![None; func.vregs()];
304 for block in func.blocks() {
305 for inst in func.insts(block) {
306 let operands = &func[func[inst].operands];
307 for operand in operands {
308 let Constraint::Reuse(other) = operand.constraint else { continue };
309 let number = operand.reg.number().and_then(|number| usize::try_from(number).ok());
310 let Some(number) = number else { continue };
311 let source = operands[usize::from(other)].reg;
312 reuses[number] = Some(Reuse { source, at: order.early(inst) });
313 }
314 }
315 }
316 reuses
317}
318
319fn index(reg: Reg) -> usize {
322 reg.number().and_then(|number| usize::try_from(number).ok()).unwrap_or(0)
323}
324
325fn name(reg: Reg) -> String {
327 match reg.number() {
328 Some(number) => format!("%{number}"),
329 None => format!("register {}", reg.phys().expect("a physical register").number()),
330 }
331}
332
333fn place_name(place: Place) -> String {
336 match place {
337 Place::Reg(at) => format!("register {}", at.number()),
338 Place::Slot(slot) => format!("slot {slot}"),
339 }
340}
341
342#[cfg(test)]
343mod tests {
344 use rucc_base::Interner;
345 use rucc_mir::{Opcode, Operand};
346 use rucc_target::x86_64::{GPR, RAX, RCX, SYSV};
347
348 use super::*;
349 use crate::assign::{Env, assign};
350
351 fn env() -> Env {
353 let (order, scratch) = SYSV.int_order.split_at(SYSV.int_order.len() - 3);
354 Env::new().with(GPR, order, scratch)
355 }
356
357 fn allocated(func: &Func) -> Vec<String> {
360 let order = Order::of(func);
361 let live = Live::of(func, &order);
362 let assignment = assign(func, &order, &live, &env());
363 said(func, &order, &live, &assignment)
364 }
365
366 fn said(func: &Func, order: &Order, live: &Live, assignment: &Assignment) -> Vec<String> {
368 check(func, order, live, assignment).iter().map(ToString::to_string).collect()
369 }
370
371 fn read(func: &Func) -> (Order, Live) {
373 let order = Order::of(func);
374 let live = Live::of(func, &order);
375 (order, live)
376 }
377
378 #[test]
379 fn an_allocation_the_allocator_worked_out_has_nothing_wrong_with_it() {
380 let mut names = Interner::new();
381 let mut func = Func::new(names.intern("f"));
382 let opcode = Opcode::new(names.intern("x64.nop"));
383 let block = func.create_block();
384 let first = func.new_vreg(GPR);
385 let second = func.new_vreg(GPR);
386 func.build(block, opcode).def(first, GPR).finish();
387 func.build(block, opcode).def(second, GPR).finish();
388 func.build(block, opcode).uses(first, GPR).uses(second, GPR).finish();
389
390 assert_eq!(allocated(&func), Vec::<String>::new());
391 }
392
393 #[test]
394 fn a_value_with_nowhere_to_live_is_found() {
395 let mut names = Interner::new();
396 let mut func = Func::new(names.intern("f"));
397 let opcode = Opcode::new(names.intern("x64.nop"));
398 let block = func.create_block();
399 let only = func.new_vreg(GPR);
400 func.build(block, opcode).def(only, GPR).finish();
401 func.build(block, opcode).uses(only, GPR).finish();
402
403 let (order, live) = read(&func);
404 let assignment = Assignment::empty(func.vregs());
405
406 assert_eq!(said(&func, &order, &live, &assignment), ["%0 has nowhere to live"]);
407 }
408
409 #[test]
410 fn a_value_read_before_anything_writes_it_is_found() {
411 let mut names = Interner::new();
412 let mut func = Func::new(names.intern("f"));
413 let opcode = Opcode::new(names.intern("x64.nop"));
414 let block = func.create_block();
415 let never = func.new_vreg(GPR);
416 func.build(block, opcode).uses(never, GPR).finish();
417
418 let (order, live) = read(&func);
419 let mut assignment = Assignment::empty(func.vregs());
420 assignment.put(never, Place::Reg(RAX));
421
422 assert_eq!(
423 said(&func, &order, &live, &assignment),
424 ["%0 is read before anything writes it"]
425 );
426 }
427
428 #[test]
429 fn two_values_that_are_both_wanted_and_share_a_register_are_found() {
430 let mut names = Interner::new();
431 let mut func = Func::new(names.intern("f"));
432 let opcode = Opcode::new(names.intern("x64.nop"));
433 let block = func.create_block();
434 let first = func.new_vreg(GPR);
435 let second = func.new_vreg(GPR);
436 func.build(block, opcode).def(first, GPR).finish();
437 func.build(block, opcode).def(second, GPR).finish();
438 func.build(block, opcode).uses(first, GPR).uses(second, GPR).finish();
439
440 let (order, live) = read(&func);
441 let mut assignment = Assignment::empty(func.vregs());
442 assignment.put(first, Place::Reg(RAX));
443 assignment.put(second, Place::Reg(RAX));
444
445 let said = said(&func, &order, &live, &assignment);
446 assert_eq!(said, ["%0 and %1 are both live and both in register 0"]);
447 }
448
449 #[test]
450 fn two_values_that_are_both_wanted_and_share_a_slot_are_found() {
451 let mut names = Interner::new();
452 let mut func = Func::new(names.intern("f"));
453 let opcode = Opcode::new(names.intern("x64.nop"));
454 let block = func.create_block();
455 let first = func.new_vreg(GPR);
456 let second = func.new_vreg(GPR);
457 func.build(block, opcode).def(first, GPR).finish();
458 func.build(block, opcode).def(second, GPR).finish();
459 func.build(block, opcode).uses(first, GPR).uses(second, GPR).finish();
460
461 let (order, live) = read(&func);
462 let mut assignment = Assignment::empty(func.vregs());
463 let slot = assignment.take_slot(GPR);
464 assignment.put(first, Place::Slot(slot));
465 assignment.put(second, Place::Slot(slot));
466
467 let said = said(&func, &order, &live, &assignment);
468 assert_eq!(said, ["%0 and %1 are both live and both in slot 0"]);
469 }
470
471 #[test]
472 fn two_values_that_are_never_both_wanted_may_share_anything() {
473 let mut names = Interner::new();
474 let mut func = Func::new(names.intern("f"));
475 let opcode = Opcode::new(names.intern("x64.nop"));
476 let block = func.create_block();
477 let first = func.new_vreg(GPR);
478 let second = func.new_vreg(GPR);
479 func.build(block, opcode).def(first, GPR).finish();
480 func.build(block, opcode).uses(first, GPR).finish();
481 func.build(block, opcode).def(second, GPR).finish();
482 func.build(block, opcode).uses(second, GPR).finish();
483
484 let (order, live) = read(&func);
485 let mut assignment = Assignment::empty(func.vregs());
486 assignment.put(first, Place::Reg(RAX));
487 assignment.put(second, Place::Reg(RAX));
488
489 assert_eq!(said(&func, &order, &live, &assignment), Vec::<String>::new());
490 }
491
492 #[test]
493 fn a_value_left_in_a_register_an_instruction_wants_is_found() {
494 let mut names = Interner::new();
495 let mut func = Func::new(names.intern("f"));
496 let nop = Opcode::new(names.intern("x64.nop"));
497 let divide = Opcode::new(names.intern("x64.idiv"));
498 let block = func.create_block();
499 let held = func.new_vreg(GPR);
500 let dividend = func.new_vreg(GPR);
501 func.build(block, nop).def(held, GPR).finish();
502 func.build(block, nop).def(dividend, GPR).finish();
503 func.build(block, divide)
506 .operand(Operand::read(dividend, GPR).with(Constraint::Fixed(RAX)))
507 .finish();
508 func.build(block, nop).uses(held, GPR).finish();
509
510 let (order, live) = read(&func);
511 let mut assignment = Assignment::empty(func.vregs());
512 assignment.put(held, Place::Reg(RAX));
513 assignment.put(dividend, Place::Reg(RCX));
514
515 let said = said(&func, &order, &live, &assignment);
516 assert_eq!(said, ["%0 is in register 0, which instruction 2 wants"]);
517 }
518
519 #[test]
520 fn the_value_an_instruction_wants_a_register_for_may_be_in_it_already() {
521 let mut names = Interner::new();
522 let mut func = Func::new(names.intern("f"));
523 let nop = Opcode::new(names.intern("x64.nop"));
524 let divide = Opcode::new(names.intern("x64.idiv"));
525 let block = func.create_block();
526 let dividend = func.new_vreg(GPR);
527 func.build(block, nop).def(dividend, GPR).finish();
528 func.build(block, divide)
529 .operand(Operand::read(dividend, GPR).with(Constraint::Fixed(RAX)))
530 .finish();
531
532 let (order, live) = read(&func);
533 let mut assignment = Assignment::empty(func.vregs());
534 assignment.put(dividend, Place::Reg(RAX));
535
536 assert_eq!(said(&func, &order, &live, &assignment), Vec::<String>::new());
539 }
540
541 #[test]
542 fn a_value_that_can_only_be_read_from_memory_and_is_in_a_register_is_found() {
543 let mut names = Interner::new();
544 let mut func = Func::new(names.intern("f"));
545 let nop = Opcode::new(names.intern("x64.nop"));
546 let wide = Opcode::new(names.intern("x64.wide"));
547 let block = func.create_block();
548 let only = func.new_vreg(GPR);
549 func.build(block, nop).def(only, GPR).finish();
550 func.build(block, wide).operand(Operand::read(only, GPR).with(Constraint::Stack)).finish();
551
552 let (order, live) = read(&func);
553 let mut assignment = Assignment::empty(func.vregs());
554 assignment.put(only, Place::Reg(RAX));
555
556 let said = said(&func, &order, &live, &assignment);
557 assert_eq!(said, ["%0 is not on the stack, and instruction 1 needs it"]);
558 }
559
560 #[test]
561 fn a_two_address_instruction_may_write_the_register_it_read_a_finished_value_from() {
562 let mut names = Interner::new();
563 let mut func = Func::new(names.intern("f"));
564 let nop = Opcode::new(names.intern("x64.nop"));
565 let add = Opcode::new(names.intern("x64.add"));
566 let block = func.create_block();
567 let left = func.new_vreg(GPR);
568 let right = func.new_vreg(GPR);
569 let sum = func.new_vreg(GPR);
570 func.build(block, nop).def(left, GPR).finish();
571 func.build(block, nop).def(right, GPR).finish();
572 func.build(block, add)
573 .operand(Operand::write(sum, GPR).with(Constraint::Reuse(1)))
574 .uses(left, GPR)
575 .uses(right, GPR)
576 .finish();
577 func.build(block, nop).uses(sum, GPR).finish();
578
579 let (order, live) = read(&func);
580 let mut assignment = Assignment::empty(func.vregs());
581 assignment.put(left, Place::Reg(RAX));
582 assignment.put(right, Place::Reg(RCX));
583 assignment.put(sum, Place::Reg(RAX));
584
585 assert_eq!(said(&func, &order, &live, &assignment), Vec::<String>::new());
588 }
589
590 #[test]
591 fn a_two_address_instruction_may_not_write_over_a_value_wanted_afterwards() {
592 let mut names = Interner::new();
593 let mut func = Func::new(names.intern("f"));
594 let nop = Opcode::new(names.intern("x64.nop"));
595 let add = Opcode::new(names.intern("x64.add"));
596 let block = func.create_block();
597 let left = func.new_vreg(GPR);
598 let right = func.new_vreg(GPR);
599 let sum = func.new_vreg(GPR);
600 func.build(block, nop).def(left, GPR).finish();
601 func.build(block, nop).def(right, GPR).finish();
602 func.build(block, add)
603 .operand(Operand::write(sum, GPR).with(Constraint::Reuse(1)))
604 .uses(left, GPR)
605 .uses(right, GPR)
606 .finish();
607 func.build(block, nop).uses(sum, GPR).uses(left, GPR).finish();
608
609 let (order, live) = read(&func);
610 let mut assignment = Assignment::empty(func.vregs());
611 assignment.put(left, Place::Reg(RAX));
612 assignment.put(right, Place::Reg(RCX));
613 assignment.put(sum, Place::Reg(RAX));
614
615 let said = said(&func, &order, &live, &assignment);
618 assert_eq!(said, ["%0 and %2 are both live and both in register 0"]);
619 }
620
621 #[test]
622 fn a_two_address_instruction_may_not_write_the_register_it_reads_its_other_operand_from() {
623 let mut names = Interner::new();
624 let mut func = Func::new(names.intern("f"));
625 let nop = Opcode::new(names.intern("x64.nop"));
626 let add = Opcode::new(names.intern("x64.add"));
627 let block = func.create_block();
628 let left = func.new_vreg(GPR);
629 let right = func.new_vreg(GPR);
630 let sum = func.new_vreg(GPR);
631 func.build(block, nop).def(left, GPR).finish();
632 func.build(block, nop).def(right, GPR).finish();
633 func.build(block, add)
634 .operand(Operand::write(sum, GPR).with(Constraint::Reuse(1)))
635 .uses(left, GPR)
636 .uses(right, GPR)
637 .finish();
638 func.build(block, nop).uses(sum, GPR).finish();
639
640 let (order, live) = read(&func);
641 let mut assignment = Assignment::empty(func.vregs());
642 assignment.put(left, Place::Reg(RAX));
643 assignment.put(right, Place::Reg(RCX));
644 assignment.put(sum, Place::Reg(RCX));
645
646 let said = said(&func, &order, &live, &assignment);
649 assert_eq!(said, ["%1 and %2 are both live and both in register 1"]);
650 }
651
652 #[test]
653 fn a_report_names_every_problem() {
654 let mut names = Interner::new();
655 let mut func = Func::new(names.intern("f"));
656 let opcode = Opcode::new(names.intern("x64.nop"));
657 let block = func.create_block();
658 let first = func.new_vreg(GPR);
659 let second = func.new_vreg(GPR);
660 func.build(block, opcode).def(first, GPR).finish();
661 func.build(block, opcode).def(second, GPR).finish();
662 func.build(block, opcode).uses(first, GPR).uses(second, GPR).finish();
663
664 let (order, live) = read(&func);
665 let mut assignment = Assignment::empty(func.vregs());
666 assignment.put(first, Place::Reg(RAX));
667 assignment.put(second, Place::Reg(RAX));
668
669 let problems = check(&func, &order, &live, &assignment);
670 assert_eq!(
671 report(&problems),
672 "the allocation is wrong in 1 place\n %0 and %1 are both live and both in register 0"
673 );
674 assert_eq!(report(&[]), "the allocation is wrong in 0 places");
675 }
676}