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