1use std::collections::HashSet;
27
28use rucc_base::Interner;
29use rucc_ir as ir;
30use rucc_mir as mir;
31use rucc_regalloc::assign::Env;
32use rucc_target::{BranchInsts, CallRegs, FrameInsts, PhysReg, RegFile, TargetInfo, x86_64};
33use rucc_tuple::Arch;
34
35use crate::coverage::Fired;
36use crate::elsewhere::Elsewhere;
37use crate::expand;
38use crate::finish::{Convention, Probing, Protect, finish};
39use crate::fold;
40use crate::frame::{Frame, Layout};
41use crate::layout;
42use crate::lower::{self, Unsupported};
43use crate::pressure::{Cost, Pressure};
44use crate::retry;
45use crate::split;
46use crate::switch;
47use crate::varargs;
48use crate::widths;
49
50#[derive(Debug)]
59pub struct Machine {
60 pub conv: &'static CallRegs,
62 pub file: RegFile,
64 pub insts: &'static FrameInsts,
66 pub branch: &'static BranchInsts,
68 pub env: Env,
70}
71
72const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
87
88const SCRATCH_COUNT: usize = SCRATCH.len();
90
91impl Machine {
92 #[must_use]
99 pub fn x86_64(conv: &'static CallRegs) -> Self {
100 let order: Vec<PhysReg> =
101 conv.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
102 let free: Vec<PhysReg> =
109 conv.sse_order.iter().copied().filter(|®| !conv.preserves_sse(reg)).collect();
110 let at = free.len().saturating_sub(SCRATCH_COUNT);
111 let sse_scratch: Vec<PhysReg> = free[at..].to_vec();
112 let sse_order: Vec<PhysReg> =
113 conv.sse_order.iter().copied().filter(|reg| !sse_scratch.contains(reg)).collect();
114 Self {
115 conv,
116 file: x86_64::REGS,
117 insts: &x86_64::FRAME,
118 branch: &x86_64::BRANCH,
119 env: Env::new().with(x86_64::GPR, &order, &SCRATCH).with(
120 x86_64::XMM,
121 &sse_order,
122 &sse_scratch,
123 ),
124 }
125 }
126
127 #[must_use]
134 pub fn for_target(target: &TargetInfo) -> Option<Self> {
135 let conv = target.call_regs?;
136 match target.tuple.arch() {
137 Arch::X86_64 => Some(Self::x86_64(conv)),
138 _ => None,
139 }
140 }
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub struct Flags {
146 pub frame_pointer: bool,
148 pub red_zone: bool,
150 pub stack_clash: bool,
152 pub landing: bool,
154}
155
156impl Default for Flags {
157 fn default() -> Self {
161 Self { frame_pointer: false, red_zone: true, stack_clash: false, landing: false }
162 }
163}
164
165pub fn compile(
184 source: &mut ir::Func,
185 names: &mut Interner,
186 machine: &Machine,
187 elsewhere: &Elsewhere,
188 flags: Flags,
189) -> Result<mir::Func, Unsupported> {
190 compile_recording(
191 source,
192 names,
193 machine,
194 elsewhere,
195 flags,
196 &mut Fired::new(),
197 &mut Pressure::new(),
198 )
199}
200
201pub fn compile_recording(
217 source: &mut ir::Func,
218 names: &mut Interner,
219 machine: &Machine,
220 elsewhere: &Elsewhere,
221 flags: Flags,
222 fired: &mut Fired,
223 pressure: &mut Pressure,
224) -> Result<mir::Func, Unsupported> {
225 switch::switches(source);
226 retry::loops(source);
231 expand::orderings(source, machine.conv.word);
234 widths::integers(source);
237 expand::bytes(source);
238 expand::counts(source);
239 expand::overflows(source);
240 expand::floats(source);
241 expand::bulk(source, names, machine.conv.word);
242 varargs::lists(source, machine.conv);
243 let lowered = lower::func(source, names, machine.conv, elsewhere)?;
244 fired.merge(&lowered.fired);
245 let lower::Lowered { mut func, stack, .. } = lowered;
246 let protect = source.attrs.set.contains(ir::AttrSet::STACK_PROTECT);
252 let guard = protect.then_some(machine.conv.guard.as_ref()).flatten();
253 let base = stack.layout(Layout::new(machine.conv, machine.file));
254 let layout = Layout {
255 frame_pointer: flags.frame_pointer,
256 red_zone: flags.red_zone,
257 protect: guard.is_some(),
258 leaf: base.leaf && guard.is_none(),
263 ..base
264 };
265
266 let waiting: HashSet<mir::Inst> = stack
272 .addresses
273 .iter()
274 .map(|&(inst, _)| inst)
275 .chain(stack.arguments.iter().map(|&(inst, _)| inst))
276 .collect();
277 fold::addresses(&mut func, machine.insts, names, &waiting);
278
279 let fusable = layout::fusable(&func, machine.branch, names);
284
285 split::critical(&mut func);
289 let called = names.resolve(func.name).to_owned();
290 let allocation = rucc_regalloc::run(&mut func, &machine.env, &called);
291 pressure.record(&called, Cost::of(&allocation));
292
293 let frame = Frame::of(&func, &allocation, &layout);
296 let scratch = machine.env.scratch(machine.conv.int_class);
297 let protect = guard.map(|guard| Protect {
298 guard,
299 branch: machine.branch,
300 scratch: [scratch[0], scratch[1]],
301 });
302 let probe = flags
306 .stack_clash
307 .then_some(machine.insts.probe.as_ref())
308 .flatten()
309 .map(|probe| Probing { probe, branch: machine.branch, scratch: [scratch[0], scratch[1]] });
310 let landing = flags.landing.then_some(machine.insts.landing).flatten();
314 let convention =
315 Convention { protect, probe, landing, ..Convention::new(machine.conv, machine.insts) };
316 finish(&mut func, &allocation, &frame, &stack, convention, names);
317
318 layout::blocks(&mut func, machine.branch, names, &fusable);
321 Ok(func)
322}
323
324#[cfg(test)]
325mod tests {
326 use rucc_ir::{Builder, Flags as IrFlags, Func, Opcode, Restrict, Signature, Type};
327 use rucc_target::x86_64::{REGS, SYSV, WIN64};
328
329 use super::*;
330
331 fn blank(params: &[Type]) -> (Interner, Func, ir::Block, Vec<ir::Value>) {
333 let mut names = Interner::new();
334 let mut func = Func::new(names.intern("f"), Signature::new());
335 let block = func.create_block();
336 let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
337 (names, func, block, values)
338 }
339
340 #[test]
341 fn a_function_comes_out_with_no_virtual_register_left_in_it() {
342 let i32 = Type::int(32);
343 let (mut names, mut source, block, args) = blank(&[i32, i32]);
344 let mut build = Builder::new(&mut source, block);
345 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
346 build.ret(&[sum]);
347
348 let machine = Machine::x86_64(&SYSV);
349 let out =
350 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
351 .expect("every instruction has a rule");
352
353 assert_eq!(
358 mir::print_func(&out, &names, ®S),
359 "mfunc @f {\n\
360 block0:\n \
361 $rdi($rdi) = x64.arg_val_32\n \
362 $rsi($rsi) = x64.arg_val_32\n \
363 $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n \
364 $rax = x64.mov_rr_64 $rdi\n \
365 x64.ret_val_32 $rax($rax)\n \
366 x64.ret\n\
367 }\n"
368 );
369 }
370
371 #[test]
375 fn which_rules_lowered_a_function_is_something_the_compilation_can_be_asked_for() {
376 let i32 = Type::int(32);
377 let (mut names, mut source, block, args) = blank(&[i32, i32]);
378 let mut build = Builder::new(&mut source, block);
379 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
380 build.ret(&[sum]);
381
382 let machine = Machine::x86_64(&SYSV);
383 let mut fired = Fired::new();
384 compile_recording(
385 &mut source,
386 &mut names,
387 &machine,
388 &Elsewhere::default(),
389 Flags::default(),
390 &mut fired,
391 &mut Pressure::new(),
392 )
393 .expect("every instruction has a rule");
394 let one = fired.count();
395 assert!(one > 0, "an add and a return went through the table and nothing was recorded");
396
397 let listing = fired.listing(&crate::select::x86_64::TABLE);
398 assert_eq!(listing.lines().filter(|line| line.starts_with("fired ")).count(), one);
399 assert!(
400 listing.contains(&format!("{one} of ")),
401 "{}",
402 listing.lines().next().unwrap_or("")
403 );
404
405 let (mut names, mut source, block, args) = blank(&[i32, i32]);
407 let mut build = Builder::new(&mut source, block);
408 let difference = build.binary(Opcode::Sub, args[0], args[1], IrFlags::default());
409 build.ret(&[difference]);
410 compile_recording(
411 &mut source,
412 &mut names,
413 &machine,
414 &Elsewhere::default(),
415 Flags::default(),
416 &mut fired,
417 &mut Pressure::new(),
418 )
419 .expect("every instruction has a rule");
420 assert!(fired.count() > one, "a subtraction is not an addition");
421 }
422
423 #[test]
424 fn a_function_that_calls_takes_a_frame_and_gives_it_back() {
425 let i32 = Type::int(32);
426 let (mut names, mut source, block, args) = blank(&[i32]);
427 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
428 let callee = names.intern("g");
429 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
430 let got = source[call].first_result.expect("an integer comes back");
431 let mut build = Builder::new(&mut source, block);
432 let sum = build.binary(Opcode::Add, got, args[0], IrFlags::default());
433 build.ret(&[sum]);
434
435 let machine = Machine::x86_64(&SYSV);
436 let out =
437 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
438 .expect("every instruction has a rule");
439
440 let text = mir::print_func(&out, &names, ®S);
443 assert!(text.contains("x64.push_64 $rbx"), "{text}");
444 assert!(text.contains("$rbx = x64.pop_64"), "{text}");
445 assert!(text.contains("x64.call $rdi($rdi), @g"), "{text}");
446 assert!(!text.contains('%'), "{text}");
447 }
448
449 #[test]
450 fn the_other_convention_is_the_same_function_somewhere_else() {
451 let i32 = Type::int(32);
452 let (mut names, mut source, block, args) = blank(&[i32, i32]);
453 let mut build = Builder::new(&mut source, block);
454 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
455 build.ret(&[sum]);
456
457 let machine = Machine::x86_64(&WIN64);
458 let out =
459 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
460 .expect("every instruction has a rule");
461
462 let text = mir::print_func(&out, &names, ®S);
465 assert!(text.contains("$rcx($rcx) = x64.arg_val_32"), "{text}");
466 assert!(text.contains("$rdx($rdx) = x64.arg_val_32"), "{text}");
467 assert!(!text.contains("$rdi"), "{text}");
468 }
469
470 #[test]
471 fn a_function_with_a_branch_in_it_goes_through_every_pass() {
472 let i32 = Type::int(32);
473 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
474 let then = source.create_block();
475 let join = source.create_block();
476 let got = source.append_param(join, i32);
477 let mut build = Builder::new(&mut source, entry);
478 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
479 build.br_if(cond, then, &[], join, &[args[1]]);
480 Builder::new(&mut source, then).jump(join, &[args[0]]);
481 Builder::new(&mut source, join).ret(&[got]);
482
483 let machine = Machine::x86_64(&SYSV);
484 let out =
485 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
486 .expect("every instruction has a rule");
487
488 assert_eq!(out.block_count(), 4);
492
493 let text = mir::print_func(&out, &names, ®S);
502 assert_eq!(
503 text,
504 "mfunc @f {\n\
505 block0:\n \
506 $rdi($rdi) = x64.arg_val_32\n \
507 $rsi($rsi) = x64.arg_val_32\n \
508 x64.cmp_rr_32 $rdi, $rsi\n \
509 x64.jcc_ge block2, block1\n\
510 \nblock1:\n \
511 $rax = x64.mov_rr_64 $rdi\n \
512 x64.jmp block3\n\
513 \nblock2:\n \
514 $rax = x64.mov_rr_64 $rsi, block3\n\
515 \nblock3:\n \
516 x64.ret_val_32 $rax($rax)\n \
517 x64.ret\n\
518 }\n"
519 );
520 }
521
522 #[test]
528 fn a_loop_that_carries_its_values_round_keeps_all_of_them() {
529 let i32 = Type::int(32);
530 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
531 let head = source.create_block();
532 let body = source.create_block();
533 let exit = source.create_block();
534 let left = source.append_param(head, i32);
535 let right = source.append_param(head, i32);
536 Builder::new(&mut source, entry).jump(head, &[args[0], args[1]]);
537 let mut build = Builder::new(&mut source, head);
538 let zero = build.iconst(i32, 0);
539 let more = build.icmp(rucc_ir::IntPred::Ne, right, zero);
540 build.br_if(more, body, &[], exit, &[left]);
541 let mut build = Builder::new(&mut source, body);
542 let rest = build.binary(Opcode::SRem, left, right, IrFlags::default());
543 build.jump(head, &[right, rest]);
544 let result = source.append_param(exit, i32);
545 Builder::new(&mut source, exit).ret(&[result]);
546
547 let machine = Machine::x86_64(&SYSV);
548 let out =
549 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
550 .expect("every instruction has a rule");
551
552 assert_eq!(
568 mir::print_func(&out, &names, ®S),
569 "mfunc @f {\n\
570 block0:\n \
571 $rdi($rdi) = x64.arg_val_32\n \
572 $rsi($rsi) = x64.arg_val_32\n \
573 $rcx = x64.mov_rr_64 $rdi, block1\n\
574 \nblock1:\n \
575 x64.cmp_ri_32 $rsi, 0\n \
576 x64.jcc_e block3, block2\n\
577 \nblock2:\n \
578 $rax = x64.mov_rr_64 $rcx\n \
579 $rdx($rdx), early $rax($rax) = x64.idiv_rem_32 $rax($rax), $rsi\n \
580 $rdi = x64.mov_rr_64 $rax\n \
581 $rcx = x64.mov_rr_64 $rsi\n \
582 $rsi = x64.mov_rr_64 $rdx\n \
583 x64.jmp block1\n\
584 \nblock3:\n \
585 $rax = x64.mov_rr_64 $rcx\n \
586 x64.ret_val_32 $rax($rax)\n \
587 x64.ret\n\
588 }\n"
589 );
590 }
591
592 #[test]
597 fn a_function_that_has_been_laid_out_reads_back_as_the_same_function() {
598 let i32 = Type::int(32);
599 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
600 let then = source.create_block();
601 let join = source.create_block();
602 let got = source.append_param(join, i32);
603 let mut build = Builder::new(&mut source, entry);
604 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
605 build.br_if(cond, then, &[], join, &[args[1]]);
606 Builder::new(&mut source, then).jump(join, &[args[0]]);
607 Builder::new(&mut source, join).ret(&[got]);
608
609 let machine = Machine::x86_64(&SYSV);
610 let out =
611 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
612 .expect("every instruction has a rule");
613
614 let text = mir::print_func(&out, &names, ®S);
615 let read = rucc_mir::parse(&text, &mut names, ®S).expect("what the printer wrote");
616 assert_eq!(mir::print(&read, &names, ®S), text);
617 }
618
619 #[test]
620 fn a_function_this_cannot_lower_is_reported_rather_than_compiled() {
621 let f80 = Type::float(rucc_ir::Float::F80);
622 let (mut names, mut source, block, args) = blank(&[f80, Type::int(64)]);
623 Builder::new(&mut source, block).ret(&args);
624
625 let machine = Machine::x86_64(&SYSV);
629 let failed =
630 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
631 .expect_err("a long double cannot come back beside another value");
632 assert_eq!(failed.to_string(), "what this function gives back is on the x87 stack");
633 }
634
635 #[test]
643 fn a_long_double_arrives_in_memory_and_goes_back_on_the_x87_stack() {
644 let f80 = Type::float(rucc_ir::Float::F80);
645 let (mut names, mut source, block, args) = blank(&[f80, f80]);
646 let mut build = Builder::new(&mut source, block);
647 let sum = build.binary(Opcode::FAdd, args[0], args[1], IrFlags::default());
648 build.ret(&[sum]);
649
650 let machine = Machine::x86_64(&SYSV);
651 let out =
652 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
653 .expect("every instruction has a rule");
654
655 let text = mir::print_func(&out, &names, ®S);
656 assert!(text.contains("x64.lea_64 [$rsp + 32]"), "{text}");
659 assert!(text.contains("x64.lea_64 [$rsp + 48]"), "{text}");
660 assert!(!text.contains("x64.ret_val"), "nothing comes back in a register: {text}");
661 let end: Vec<&str> = text.lines().rev().skip(1).take(3).map(str::trim).collect();
664 assert_eq!(end, ["x64.ret", "$rsp = x64.add_ri_64 $rsp, 24", "x64.fld_t [$rax]"], "{text}");
665 }
666
667 #[test]
671 fn a_float_is_added_in_the_register_file_it_arrives_in() {
672 let f32 = Type::float(rucc_ir::Float::F32);
673 let (mut names, mut source, block, args) = blank(&[f32, f32]);
674 let mut build = Builder::new(&mut source, block);
675 let sum = build.binary(Opcode::FAdd, args[0], args[1], ir::Flags::default());
676 build.ret(&[sum]);
677
678 let machine = Machine::x86_64(&SYSV);
679 let out =
680 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
681 .expect("every instruction has a rule");
682
683 let text = mir::print_func(&out, &names, ®S);
684 assert!(text.contains("x64.addss_rr"), "{text}");
685 assert!(text.contains("$xmm0"), "{text}");
686 assert!(!text.contains("$rax"), "{text}");
687 }
688
689 #[test]
692 fn a_float_read_from_memory_and_written_back_uses_the_scalar_moves() {
693 let f64 = Type::float(rucc_ir::Float::F64);
694 let (mut names, mut source, block, args) = blank(&[Type::PTR, f64]);
695 let mut build = Builder::new(&mut source, block);
696 let info = rucc_ir::MemInfo {
697 size: 8,
698 align: 8,
699 order: rucc_ir::MemOrder::NotAtomic,
700 tbaa: None,
701 restrict: Restrict::NONE,
702 };
703 let read = build.load(f64, args[0], info, ir::Flags::default());
704 let sum = build.binary(Opcode::FAdd, read, args[1], ir::Flags::default());
705 build.store(sum, args[0], info, ir::Flags::default());
706 build.ret(&[sum]);
707
708 let machine = Machine::x86_64(&SYSV);
709 let out =
710 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
711 .expect("every instruction has a rule");
712
713 let text = mir::print_func(&out, &names, ®S);
714 assert!(text.contains("x64.movsd_rm"), "{text}");
715 assert!(text.contains("x64.movsd_mr"), "{text}");
716 assert!(!text.contains("x64.movaps_rm"), "{text}");
719 assert!(!text.contains("x64.movaps_mr"), "{text}");
720 }
721
722 #[test]
730 fn an_unsigned_word_and_a_long_double_convert_into_each_other() {
731 let f80 = Type::float(rucc_ir::Float::F80);
732 let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
733 let mut build = Builder::new(&mut source, block);
734 let info = rucc_ir::MemInfo {
735 size: 16,
736 align: 16,
737 order: rucc_ir::MemOrder::NotAtomic,
738 tbaa: None,
739 restrict: Restrict::NONE,
740 };
741 let wide = build.unary(Opcode::UIToFP, args[1], f80);
742 build.store(wide, args[0], info, ir::Flags::default());
743 let read = build.load(f80, args[0], info, ir::Flags::default());
744 let back = build.unary(Opcode::FPToUI, read, Type::int(64));
745 build.ret(&[back]);
746
747 let machine = Machine::x86_64(&SYSV);
748 let out =
749 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
750 .expect("every instruction has a rule");
751
752 let text = mir::print_func(&out, &names, ®S);
753 assert!(text.contains("x64.fild_ll"), "the integer goes in as a signed one: {text}");
756 assert!(text.contains("x64.fistp_ll"), "and comes back out as one: {text}");
757 assert!(text.contains("x64.fmul_p"), "the correction is taken or not: {text}");
758 assert!(text.contains("x64.fadd_p"), "and applied one way: {text}");
759 assert!(text.contains("x64.fsubr_p"), "and the other: {text}");
760 assert!(!text.contains("xmm"), "no part of this is in a vector register: {text}");
761 }
762
763 #[test]
768 fn a_conversion_carries_the_value_into_the_other_register_file() {
769 let f64 = Type::float(rucc_ir::Float::F64);
770 let (mut names, mut source, block, args) = blank(&[f64]);
771 let mut build = Builder::new(&mut source, block);
772 let whole = build.unary(Opcode::FPToSI, args[0], Type::int(32));
773 let back = build.unary(Opcode::SIToFP, whole, f64);
774 build.ret(&[back]);
775
776 let machine = Machine::x86_64(&SYSV);
777 let out =
778 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
779 .expect("every instruction has a rule");
780
781 let text = mir::print_func(&out, &names, ®S);
784 assert!(text.contains("x64.cvttsd2si_32"), "{text}");
785 assert!(text.contains("x64.cvtsi2sd_32"), "{text}");
786 assert!(text.contains("$xmm0"), "{text}");
787 }
788
789 #[test]
792 fn a_bitcast_between_the_files_is_the_move_that_changes_no_bit() {
793 let f64 = Type::float(rucc_ir::Float::F64);
794 let (mut names, mut source, block, args) = blank(&[f64]);
795 let mut build = Builder::new(&mut source, block);
796 let bits = build.unary(Opcode::Bitcast, args[0], Type::int(64));
797 build.ret(&[bits]);
798
799 let machine = Machine::x86_64(&SYSV);
800 let out =
801 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
802 .expect("every instruction has a rule");
803
804 let text = mir::print_func(&out, &names, ®S);
805 assert!(text.contains("x64.movq_from_xmm"), "{text}");
806 assert!(!text.contains("cvt"), "{text}");
807 }
808
809 #[test]
811 fn a_float_comparison_is_the_compare_and_the_byte_a_condition_sets() {
812 let f64 = Type::float(rucc_ir::Float::F64);
813 let (mut names, mut source, block, args) = blank(&[f64, f64]);
814 let mut build = Builder::new(&mut source, block);
815 let less = build.fcmp(rucc_ir::FloatPred::Olt, args[0], args[1], ir::Flags::default());
816 let wide = build.unary(Opcode::ZExt, less, Type::int(32));
817 build.ret(&[wide]);
818
819 let machine = Machine::x86_64(&SYSV);
820 let out =
821 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
822 .expect("every instruction has a rule");
823
824 let text = mir::print_func(&out, &names, ®S);
827 assert!(text.contains("x64.ucomisd_set_a"), "{text}");
828 }
829
830 #[test]
835 fn an_equality_between_floats_gets_a_register_for_the_byte_it_needs_twice() {
836 let f64 = Type::float(rucc_ir::Float::F64);
837 let (mut names, mut source, block, args) = blank(&[f64, f64]);
838 let mut build = Builder::new(&mut source, block);
839 let same = build.fcmp(rucc_ir::FloatPred::Oeq, args[0], args[1], ir::Flags::default());
840 let wide = build.unary(Opcode::ZExt, same, Type::int(32));
841 build.ret(&[wide]);
842
843 let machine = Machine::x86_64(&SYSV);
844 let out =
845 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
846 .expect("every instruction has a rule");
847
848 let text = mir::print_func(&out, &names, ®S);
849 let line = text
850 .lines()
851 .find(|line| line.contains("x64.ucomisd_set_e_and_np"))
852 .expect("the rule for an ordered equality fired");
853 let written: Vec<&str> = line
854 .split_once('=')
855 .expect("the instruction writes something")
856 .0
857 .split(',')
858 .map(str::trim)
859 .collect();
860 assert_eq!(written.len(), 2, "{line}");
861 assert_ne!(written[0], written[1], "{line}");
862 }
863
864 #[test]
868 fn a_float_constant_is_the_bits_in_a_register_and_the_move_that_carries_them_over() {
869 let f64 = Type::float(rucc_ir::Float::F64);
870 let (mut names, mut source, block, _) = blank(&[]);
871 let mut build = Builder::new(&mut source, block);
872 let half = build.fconst(f64, 0x3fe0_0000_0000_0000);
873 build.ret(&[half]);
874
875 let machine = Machine::x86_64(&SYSV);
876 let out =
877 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
878 .expect("every instruction has a rule");
879
880 let text = mir::print_func(&out, &names, ®S);
881 assert!(text.contains("x64.mov_ri_64"), "{text}");
882 assert!(text.contains("x64.movq_to_xmm"), "{text}");
883 }
884
885 #[test]
888 fn a_negation_is_the_sign_bit_flipped_and_no_float_instruction_at_all() {
889 let f64 = Type::float(rucc_ir::Float::F64);
890 let (mut names, mut source, block, args) = blank(&[f64]);
891 let mut build = Builder::new(&mut source, block);
892 let less = build.unary(Opcode::FNeg, args[0], f64);
893 build.ret(&[less]);
894
895 let machine = Machine::x86_64(&SYSV);
896 let out =
897 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
898 .expect("every instruction has a rule");
899
900 let text = mir::print_func(&out, &names, ®S);
901 assert!(text.contains("x64.xor_rr_64"), "{text}");
902 assert!(!text.contains("sub"), "a negation is not a subtraction: {text}");
903 }
904
905 #[test]
906 fn the_flags_reach_the_frame() {
907 let i32 = Type::int(32);
908 let (mut names, mut source, block, args) = blank(&[i32]);
909 Builder::new(&mut source, block).ret(&[args[0]]);
910
911 let machine = Machine::x86_64(&SYSV);
912 let flags =
913 Flags { frame_pointer: true, red_zone: true, stack_clash: false, landing: false };
914 let out = compile(&mut source, &mut names, &machine, &Elsewhere::default(), flags)
915 .expect("every instruction has a rule");
916
917 let text = mir::print_func(&out, &names, ®S);
920 assert!(text.contains("x64.push_64 $rbp"), "{text}");
921 assert!(text.contains("$rbp = x64.mov_rr_64 $rsp"), "{text}");
922 }
923
924 #[test]
925 fn a_target_says_which_machine_it_is_and_which_convention_it_uses() {
926 let triple = |text: &str| text.parse::<rucc_target::Triple>().expect("a triple");
927 let info = TargetInfo::new(triple("x86_64-unknown-linux-gnu"));
928 let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
929 assert!(std::ptr::eq(machine.conv, &SYSV));
930
931 let info = TargetInfo::new(triple("x86_64-pc-windows-msvc"));
932 let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
933 assert!(std::ptr::eq(machine.conv, &WIN64));
934
935 let info = TargetInfo::new(triple("aarch64-unknown-linux-gnu"));
938 assert!(Machine::for_target(&info).is_none());
939 }
940}