1use rucc_base::Interner;
27use rucc_ir as ir;
28use rucc_mir as mir;
29use rucc_regalloc::assign::Env;
30use rucc_target::{Arch, BranchInsts, CallRegs, FrameInsts, PhysReg, RegFile, TargetInfo, x86_64};
31
32use crate::coverage::Fired;
33use crate::expand;
34use crate::finish::finish;
35use crate::frame::{Frame, Layout};
36use crate::layout;
37use crate::lower::{self, Unsupported};
38use crate::split;
39use crate::varargs;
40use crate::widths;
41
42#[derive(Debug)]
51pub struct Machine {
52 pub conv: &'static CallRegs,
54 pub file: RegFile,
56 pub insts: &'static FrameInsts,
58 pub branch: &'static BranchInsts,
60 pub env: Env,
62}
63
64const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
71
72const SCRATCH_COUNT: usize = SCRATCH.len();
74
75impl Machine {
76 #[must_use]
83 pub fn x86_64(conv: &'static CallRegs) -> Self {
84 let order: Vec<PhysReg> =
85 conv.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
86 let free: Vec<PhysReg> =
93 conv.sse_order.iter().copied().filter(|®| !conv.preserves_sse(reg)).collect();
94 let at = free.len().saturating_sub(SCRATCH_COUNT);
95 let sse_scratch: Vec<PhysReg> = free[at..].to_vec();
96 let sse_order: Vec<PhysReg> =
97 conv.sse_order.iter().copied().filter(|reg| !sse_scratch.contains(reg)).collect();
98 Self {
99 conv,
100 file: x86_64::REGS,
101 insts: &x86_64::FRAME,
102 branch: &x86_64::BRANCH,
103 env: Env::new().with(x86_64::GPR, &order, &SCRATCH).with(
104 x86_64::XMM,
105 &sse_order,
106 &sse_scratch,
107 ),
108 }
109 }
110
111 #[must_use]
118 pub fn for_target(target: &TargetInfo) -> Option<Self> {
119 let conv = target.call_regs?;
120 match target.triple.arch {
121 Arch::X86_64 => Some(Self::x86_64(conv)),
122 Arch::Aarch64 | Arch::Riscv64 => None,
123 }
124 }
125}
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub struct Flags {
130 pub frame_pointer: bool,
132 pub red_zone: bool,
134}
135
136impl Default for Flags {
137 fn default() -> Self {
140 Self { frame_pointer: false, red_zone: true }
141 }
142}
143
144pub fn compile(
158 source: &mut ir::Func,
159 names: &mut Interner,
160 machine: &Machine,
161 flags: Flags,
162) -> Result<mir::Func, Unsupported> {
163 compile_recording(source, names, machine, flags, &mut Fired::new())
164}
165
166pub fn compile_recording(
180 source: &mut ir::Func,
181 names: &mut Interner,
182 machine: &Machine,
183 flags: Flags,
184 fired: &mut Fired,
185) -> Result<mir::Func, Unsupported> {
186 expand::switches(source);
187 widths::integers(source);
190 expand::bytes(source);
191 expand::counts(source);
192 expand::floats(source);
193 expand::bulk(source, names, machine.conv.word);
194 varargs::lists(source, machine.conv);
195 let lowered = lower::func(source, names, machine.conv)?;
196 fired.merge(&lowered.fired);
197 let lower::Lowered { mut func, stack, .. } = lowered;
198 let layout = Layout {
199 frame_pointer: flags.frame_pointer,
200 red_zone: flags.red_zone,
201 ..stack.layout(Layout::new(machine.conv, machine.file))
202 };
203
204 split::critical(&mut func);
208 let allocation = rucc_regalloc::run(&mut func, &machine.env);
209
210 let frame = Frame::of(&func, &allocation, &layout);
213 finish(&mut func, &allocation, &frame, &stack, machine.conv, machine.insts, names);
214
215 layout::blocks(&mut func, machine.branch, names);
218 Ok(func)
219}
220
221#[cfg(test)]
222mod tests {
223 use rucc_ir::{Builder, Flags as IrFlags, Func, Opcode, Restrict, Signature, Type};
224 use rucc_target::x86_64::{REGS, SYSV, WIN64};
225
226 use super::*;
227
228 fn blank(params: &[Type]) -> (Interner, Func, ir::Block, Vec<ir::Value>) {
230 let mut names = Interner::new();
231 let mut func = Func::new(names.intern("f"), Signature::new());
232 let block = func.create_block();
233 let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
234 (names, func, block, values)
235 }
236
237 #[test]
238 fn a_function_comes_out_with_no_virtual_register_left_in_it() {
239 let i32 = Type::int(32);
240 let (mut names, mut source, block, args) = blank(&[i32, i32]);
241 let mut build = Builder::new(&mut source, block);
242 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
243 build.ret(&[sum]);
244
245 let machine = Machine::x86_64(&SYSV);
246 let out = compile(&mut source, &mut names, &machine, Flags::default())
247 .expect("every instruction has a rule");
248
249 assert_eq!(
254 mir::print_func(&out, &names, ®S),
255 "mfunc @f {\n\
256 block0:\n \
257 $rdi($rdi) = x64.arg_val_32\n \
258 $rsi($rsi) = x64.arg_val_32\n \
259 $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n \
260 $rax = x64.mov_rr_64 $rdi\n \
261 x64.ret_val_32 $rax($rax)\n \
262 x64.ret\n\
263 }\n"
264 );
265 }
266
267 #[test]
271 fn which_rules_lowered_a_function_is_something_the_compilation_can_be_asked_for() {
272 let i32 = Type::int(32);
273 let (mut names, mut source, block, args) = blank(&[i32, i32]);
274 let mut build = Builder::new(&mut source, block);
275 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
276 build.ret(&[sum]);
277
278 let machine = Machine::x86_64(&SYSV);
279 let mut fired = Fired::new();
280 compile_recording(&mut source, &mut names, &machine, Flags::default(), &mut fired)
281 .expect("every instruction has a rule");
282 let one = fired.count();
283 assert!(one > 0, "an add and a return went through the table and nothing was recorded");
284
285 let listing = fired.listing(&crate::select::x86_64::TABLE);
286 assert_eq!(listing.lines().filter(|line| line.starts_with("fired ")).count(), one);
287 assert!(
288 listing.contains(&format!("{one} of ")),
289 "{}",
290 listing.lines().next().unwrap_or("")
291 );
292
293 let (mut names, mut source, block, args) = blank(&[i32, i32]);
295 let mut build = Builder::new(&mut source, block);
296 let difference = build.binary(Opcode::Sub, args[0], args[1], IrFlags::default());
297 build.ret(&[difference]);
298 compile_recording(&mut source, &mut names, &machine, Flags::default(), &mut fired)
299 .expect("every instruction has a rule");
300 assert!(fired.count() > one, "a subtraction is not an addition");
301 }
302
303 #[test]
304 fn a_function_that_calls_takes_a_frame_and_gives_it_back() {
305 let i32 = Type::int(32);
306 let (mut names, mut source, block, args) = blank(&[i32]);
307 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
308 let callee = names.intern("g");
309 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
310 let got = source[call].first_result.expect("an integer comes back");
311 let mut build = Builder::new(&mut source, block);
312 let sum = build.binary(Opcode::Add, got, args[0], IrFlags::default());
313 build.ret(&[sum]);
314
315 let machine = Machine::x86_64(&SYSV);
316 let out = compile(&mut source, &mut names, &machine, Flags::default())
317 .expect("every instruction has a rule");
318
319 let text = mir::print_func(&out, &names, ®S);
322 assert!(text.contains("x64.push_64 $rbx"), "{text}");
323 assert!(text.contains("$rbx = x64.pop_64"), "{text}");
324 assert!(text.contains("x64.call $rdi($rdi), @g"), "{text}");
325 assert!(!text.contains('%'), "{text}");
326 }
327
328 #[test]
329 fn the_other_convention_is_the_same_function_somewhere_else() {
330 let i32 = Type::int(32);
331 let (mut names, mut source, block, args) = blank(&[i32, i32]);
332 let mut build = Builder::new(&mut source, block);
333 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
334 build.ret(&[sum]);
335
336 let machine = Machine::x86_64(&WIN64);
337 let out = compile(&mut source, &mut names, &machine, Flags::default())
338 .expect("every instruction has a rule");
339
340 let text = mir::print_func(&out, &names, ®S);
343 assert!(text.contains("$rcx($rcx) = x64.arg_val_32"), "{text}");
344 assert!(text.contains("$rdx($rdx) = x64.arg_val_32"), "{text}");
345 assert!(!text.contains("$rdi"), "{text}");
346 }
347
348 #[test]
349 fn a_function_with_a_branch_in_it_goes_through_every_pass() {
350 let i32 = Type::int(32);
351 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
352 let then = source.create_block();
353 let join = source.create_block();
354 let got = source.append_param(join, i32);
355 let mut build = Builder::new(&mut source, entry);
356 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
357 build.br_if(cond, then, &[], join, &[args[1]]);
358 Builder::new(&mut source, then).jump(join, &[args[0]]);
359 Builder::new(&mut source, join).ret(&[got]);
360
361 let machine = Machine::x86_64(&SYSV);
362 let out = compile(&mut source, &mut names, &machine, Flags::default())
363 .expect("every instruction has a rule");
364
365 assert_eq!(out.block_count(), 4);
369
370 let text = mir::print_func(&out, &names, ®S);
379 assert_eq!(
380 text,
381 "mfunc @f {\n\
382 block0:\n \
383 $rdi($rdi) = x64.arg_val_32\n \
384 $rsi($rsi) = x64.arg_val_32\n \
385 $rax = x64.cmp_set_l_32 $rdi, $rsi\n \
386 x64.test_rr_8 $rax\n \
387 x64.jcc_e block2, block1\n\
388 \nblock1:\n \
389 $rax = x64.mov_rr_64 $rdi\n \
390 x64.jmp block3\n\
391 \nblock2:\n \
392 $rax = x64.mov_rr_64 $rsi, block3\n\
393 \nblock3:\n \
394 x64.ret_val_32 $rax($rax)\n \
395 x64.ret\n\
396 }\n"
397 );
398 }
399
400 #[test]
406 fn a_loop_that_carries_its_values_round_keeps_all_of_them() {
407 let i32 = Type::int(32);
408 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
409 let head = source.create_block();
410 let body = source.create_block();
411 let exit = source.create_block();
412 let left = source.append_param(head, i32);
413 let right = source.append_param(head, i32);
414 Builder::new(&mut source, entry).jump(head, &[args[0], args[1]]);
415 let mut build = Builder::new(&mut source, head);
416 let zero = build.iconst(i32, 0);
417 let more = build.icmp(rucc_ir::IntPred::Ne, right, zero);
418 build.br_if(more, body, &[], exit, &[left]);
419 let mut build = Builder::new(&mut source, body);
420 let rest = build.binary(Opcode::SRem, left, right, IrFlags::default());
421 build.jump(head, &[right, rest]);
422 let result = source.append_param(exit, i32);
423 Builder::new(&mut source, exit).ret(&[result]);
424
425 let machine = Machine::x86_64(&SYSV);
426 let out = compile(&mut source, &mut names, &machine, Flags::default())
427 .expect("every instruction has a rule");
428
429 assert_eq!(
445 mir::print_func(&out, &names, ®S),
446 "mfunc @f {\n\
447 block0:\n \
448 $rdi($rdi) = x64.arg_val_32\n \
449 $rsi($rsi) = x64.arg_val_32\n \
450 $rcx = x64.mov_rr_64 $rdi, block1\n\
451 \nblock1:\n \
452 $rax = x64.mov_ri_32 0\n \
453 $rax = x64.cmp_set_ne_32 $rsi, $rax\n \
454 x64.test_rr_8 $rax\n \
455 x64.jcc_e block3, block2\n\
456 \nblock2:\n \
457 $rax = x64.mov_rr_64 $rcx\n \
458 $rdx($rdx), early $rax($rax) = x64.idiv_rem_32 $rax($rax), $rsi\n \
459 $rdi = x64.mov_rr_64 $rax\n \
460 $rcx = x64.mov_rr_64 $rsi\n \
461 $rsi = x64.mov_rr_64 $rdx\n \
462 x64.jmp block1\n\
463 \nblock3:\n \
464 $rax = x64.mov_rr_64 $rcx\n \
465 x64.ret_val_32 $rax($rax)\n \
466 x64.ret\n\
467 }\n"
468 );
469 }
470
471 #[test]
476 fn a_function_that_has_been_laid_out_reads_back_as_the_same_function() {
477 let i32 = Type::int(32);
478 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
479 let then = source.create_block();
480 let join = source.create_block();
481 let got = source.append_param(join, i32);
482 let mut build = Builder::new(&mut source, entry);
483 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
484 build.br_if(cond, then, &[], join, &[args[1]]);
485 Builder::new(&mut source, then).jump(join, &[args[0]]);
486 Builder::new(&mut source, join).ret(&[got]);
487
488 let machine = Machine::x86_64(&SYSV);
489 let out = compile(&mut source, &mut names, &machine, Flags::default())
490 .expect("every instruction has a rule");
491
492 let text = mir::print_func(&out, &names, ®S);
493 let read = rucc_mir::parse(&text, &mut names, ®S).expect("what the printer wrote");
494 assert_eq!(mir::print(&read, &names, ®S), text);
495 }
496
497 #[test]
498 fn a_function_this_cannot_lower_is_reported_rather_than_compiled() {
499 let f80 = Type::float(rucc_ir::Float::F80);
500 let (mut names, mut source, block, args) = blank(&[f80]);
501 Builder::new(&mut source, block).ret(&[args[0]]);
502
503 let machine = Machine::x86_64(&SYSV);
504 let failed = compile(&mut source, &mut names, &machine, Flags::default())
505 .expect_err("a long double arrives on the x87 stack");
506 assert_eq!(failed.to_string(), "parameter 0 is on the x87 stack");
507 }
508
509 #[test]
513 fn a_float_is_added_in_the_register_file_it_arrives_in() {
514 let f32 = Type::float(rucc_ir::Float::F32);
515 let (mut names, mut source, block, args) = blank(&[f32, f32]);
516 let mut build = Builder::new(&mut source, block);
517 let sum = build.binary(Opcode::FAdd, args[0], args[1], ir::Flags::default());
518 build.ret(&[sum]);
519
520 let machine = Machine::x86_64(&SYSV);
521 let out = compile(&mut source, &mut names, &machine, Flags::default())
522 .expect("every instruction has a rule");
523
524 let text = mir::print_func(&out, &names, ®S);
525 assert!(text.contains("x64.addss_rr"), "{text}");
526 assert!(text.contains("$xmm0"), "{text}");
527 assert!(!text.contains("$rax"), "{text}");
528 }
529
530 #[test]
533 fn a_float_read_from_memory_and_written_back_uses_the_scalar_moves() {
534 let f64 = Type::float(rucc_ir::Float::F64);
535 let (mut names, mut source, block, args) = blank(&[Type::PTR, f64]);
536 let mut build = Builder::new(&mut source, block);
537 let info = rucc_ir::MemInfo {
538 size: 8,
539 align: 8,
540 order: rucc_ir::MemOrder::NotAtomic,
541 tbaa: None,
542 restrict: Restrict::NONE,
543 };
544 let read = build.load(f64, args[0], info, ir::Flags::default());
545 let sum = build.binary(Opcode::FAdd, read, args[1], ir::Flags::default());
546 build.store(sum, args[0], info, ir::Flags::default());
547 build.ret(&[sum]);
548
549 let machine = Machine::x86_64(&SYSV);
550 let out = compile(&mut source, &mut names, &machine, Flags::default())
551 .expect("every instruction has a rule");
552
553 let text = mir::print_func(&out, &names, ®S);
554 assert!(text.contains("x64.movsd_rm"), "{text}");
555 assert!(text.contains("x64.movsd_mr"), "{text}");
556 assert!(!text.contains("x64.movaps_rm"), "{text}");
559 assert!(!text.contains("x64.movaps_mr"), "{text}");
560 }
561
562 #[test]
567 fn a_conversion_carries_the_value_into_the_other_register_file() {
568 let f64 = Type::float(rucc_ir::Float::F64);
569 let (mut names, mut source, block, args) = blank(&[f64]);
570 let mut build = Builder::new(&mut source, block);
571 let whole = build.unary(Opcode::FPToSI, args[0], Type::int(32));
572 let back = build.unary(Opcode::SIToFP, whole, f64);
573 build.ret(&[back]);
574
575 let machine = Machine::x86_64(&SYSV);
576 let out = compile(&mut source, &mut names, &machine, Flags::default())
577 .expect("every instruction has a rule");
578
579 let text = mir::print_func(&out, &names, ®S);
582 assert!(text.contains("x64.cvttsd2si_32"), "{text}");
583 assert!(text.contains("x64.cvtsi2sd_32"), "{text}");
584 assert!(text.contains("$xmm0"), "{text}");
585 }
586
587 #[test]
590 fn a_bitcast_between_the_files_is_the_move_that_changes_no_bit() {
591 let f64 = Type::float(rucc_ir::Float::F64);
592 let (mut names, mut source, block, args) = blank(&[f64]);
593 let mut build = Builder::new(&mut source, block);
594 let bits = build.unary(Opcode::Bitcast, args[0], Type::int(64));
595 build.ret(&[bits]);
596
597 let machine = Machine::x86_64(&SYSV);
598 let out = compile(&mut source, &mut names, &machine, Flags::default())
599 .expect("every instruction has a rule");
600
601 let text = mir::print_func(&out, &names, ®S);
602 assert!(text.contains("x64.movq_from_xmm"), "{text}");
603 assert!(!text.contains("cvt"), "{text}");
604 }
605
606 #[test]
608 fn a_float_comparison_is_the_compare_and_the_byte_a_condition_sets() {
609 let f64 = Type::float(rucc_ir::Float::F64);
610 let (mut names, mut source, block, args) = blank(&[f64, f64]);
611 let mut build = Builder::new(&mut source, block);
612 let less = build.fcmp(rucc_ir::FloatPred::Olt, args[0], args[1], ir::Flags::default());
613 let wide = build.unary(Opcode::ZExt, less, Type::int(32));
614 build.ret(&[wide]);
615
616 let machine = Machine::x86_64(&SYSV);
617 let out = compile(&mut source, &mut names, &machine, Flags::default())
618 .expect("every instruction has a rule");
619
620 let text = mir::print_func(&out, &names, ®S);
623 assert!(text.contains("x64.ucomisd_set_a"), "{text}");
624 }
625
626 #[test]
631 fn an_equality_between_floats_gets_a_register_for_the_byte_it_needs_twice() {
632 let f64 = Type::float(rucc_ir::Float::F64);
633 let (mut names, mut source, block, args) = blank(&[f64, f64]);
634 let mut build = Builder::new(&mut source, block);
635 let same = build.fcmp(rucc_ir::FloatPred::Oeq, args[0], args[1], ir::Flags::default());
636 let wide = build.unary(Opcode::ZExt, same, Type::int(32));
637 build.ret(&[wide]);
638
639 let machine = Machine::x86_64(&SYSV);
640 let out = compile(&mut source, &mut names, &machine, Flags::default())
641 .expect("every instruction has a rule");
642
643 let text = mir::print_func(&out, &names, ®S);
644 let line = text
645 .lines()
646 .find(|line| line.contains("x64.ucomisd_set_e_and_np"))
647 .expect("the rule for an ordered equality fired");
648 let written: Vec<&str> = line
649 .split_once('=')
650 .expect("the instruction writes something")
651 .0
652 .split(',')
653 .map(str::trim)
654 .collect();
655 assert_eq!(written.len(), 2, "{line}");
656 assert_ne!(written[0], written[1], "{line}");
657 }
658
659 #[test]
663 fn a_float_constant_is_the_bits_in_a_register_and_the_move_that_carries_them_over() {
664 let f64 = Type::float(rucc_ir::Float::F64);
665 let (mut names, mut source, block, _) = blank(&[]);
666 let mut build = Builder::new(&mut source, block);
667 let half = build.fconst(f64, 0x3fe0_0000_0000_0000);
668 build.ret(&[half]);
669
670 let machine = Machine::x86_64(&SYSV);
671 let out = compile(&mut source, &mut names, &machine, Flags::default())
672 .expect("every instruction has a rule");
673
674 let text = mir::print_func(&out, &names, ®S);
675 assert!(text.contains("x64.mov_ri_64"), "{text}");
676 assert!(text.contains("x64.movq_to_xmm"), "{text}");
677 }
678
679 #[test]
682 fn a_negation_is_the_sign_bit_flipped_and_no_float_instruction_at_all() {
683 let f64 = Type::float(rucc_ir::Float::F64);
684 let (mut names, mut source, block, args) = blank(&[f64]);
685 let mut build = Builder::new(&mut source, block);
686 let less = build.unary(Opcode::FNeg, args[0], f64);
687 build.ret(&[less]);
688
689 let machine = Machine::x86_64(&SYSV);
690 let out = compile(&mut source, &mut names, &machine, Flags::default())
691 .expect("every instruction has a rule");
692
693 let text = mir::print_func(&out, &names, ®S);
694 assert!(text.contains("x64.xor_rr_64"), "{text}");
695 assert!(!text.contains("sub"), "a negation is not a subtraction: {text}");
696 }
697
698 #[test]
699 fn the_flags_reach_the_frame() {
700 let i32 = Type::int(32);
701 let (mut names, mut source, block, args) = blank(&[i32]);
702 Builder::new(&mut source, block).ret(&[args[0]]);
703
704 let machine = Machine::x86_64(&SYSV);
705 let flags = Flags { frame_pointer: true, red_zone: true };
706 let out = compile(&mut source, &mut names, &machine, flags)
707 .expect("every instruction has a rule");
708
709 let text = mir::print_func(&out, &names, ®S);
712 assert!(text.contains("x64.push_64 $rbp"), "{text}");
713 assert!(text.contains("$rbp = x64.mov_rr_64 $rsp"), "{text}");
714 }
715
716 #[test]
717 fn a_target_says_which_machine_it_is_and_which_convention_it_uses() {
718 let triple = |text: &str| text.parse::<rucc_target::Triple>().expect("a triple");
719 let info = TargetInfo::new(triple("x86_64-unknown-linux-gnu"));
720 let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
721 assert!(std::ptr::eq(machine.conv, &SYSV));
722
723 let info = TargetInfo::new(triple("x86_64-pc-windows-msvc"));
724 let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
725 assert!(std::ptr::eq(machine.conv, &WIN64));
726
727 let info = TargetInfo::new(triple("aarch64-unknown-linux-gnu"));
730 assert!(Machine::for_target(&info).is_none());
731 }
732}