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, 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}
151
152impl Default for Flags {
153 fn default() -> Self {
156 Self { frame_pointer: false, red_zone: true }
157 }
158}
159
160pub fn compile(
179 source: &mut ir::Func,
180 names: &mut Interner,
181 machine: &Machine,
182 elsewhere: &Elsewhere,
183 flags: Flags,
184) -> Result<mir::Func, Unsupported> {
185 compile_recording(
186 source,
187 names,
188 machine,
189 elsewhere,
190 flags,
191 &mut Fired::new(),
192 &mut Pressure::new(),
193 )
194}
195
196pub fn compile_recording(
212 source: &mut ir::Func,
213 names: &mut Interner,
214 machine: &Machine,
215 elsewhere: &Elsewhere,
216 flags: Flags,
217 fired: &mut Fired,
218 pressure: &mut Pressure,
219) -> Result<mir::Func, Unsupported> {
220 switch::switches(source);
221 retry::loops(source);
226 expand::orderings(source, machine.conv.word);
229 widths::integers(source);
232 expand::bytes(source);
233 expand::counts(source);
234 expand::overflows(source);
235 expand::floats(source);
236 expand::bulk(source, names, machine.conv.word);
237 varargs::lists(source, machine.conv);
238 let lowered = lower::func(source, names, machine.conv, elsewhere)?;
239 fired.merge(&lowered.fired);
240 let lower::Lowered { mut func, stack, .. } = lowered;
241 let protect = source.attrs.set.contains(ir::AttrSet::STACK_PROTECT);
247 let guard = protect.then_some(machine.conv.guard.as_ref()).flatten();
248 let base = stack.layout(Layout::new(machine.conv, machine.file));
249 let layout = Layout {
250 frame_pointer: flags.frame_pointer,
251 red_zone: flags.red_zone,
252 protect: guard.is_some(),
253 leaf: base.leaf && guard.is_none(),
258 ..base
259 };
260
261 let waiting: HashSet<mir::Inst> = stack
267 .addresses
268 .iter()
269 .map(|&(inst, _)| inst)
270 .chain(stack.arguments.iter().map(|&(inst, _)| inst))
271 .collect();
272 fold::addresses(&mut func, machine.insts, names, &waiting);
273
274 let fusable = layout::fusable(&func, machine.branch, names);
279
280 split::critical(&mut func);
284 let called = names.resolve(func.name).to_owned();
285 let allocation = rucc_regalloc::run(&mut func, &machine.env, &called);
286 pressure.record(&called, Cost::of(&allocation));
287
288 let frame = Frame::of(&func, &allocation, &layout);
291 let scratch = machine.env.scratch(machine.conv.int_class);
292 let protect = guard.map(|guard| Protect {
293 guard,
294 branch: machine.branch,
295 scratch: [scratch[0], scratch[1]],
296 });
297 let convention = Convention { protect, ..Convention::new(machine.conv, machine.insts) };
298 finish(&mut func, &allocation, &frame, &stack, convention, names);
299
300 layout::blocks(&mut func, machine.branch, names, &fusable);
303 Ok(func)
304}
305
306#[cfg(test)]
307mod tests {
308 use rucc_ir::{Builder, Flags as IrFlags, Func, Opcode, Restrict, Signature, Type};
309 use rucc_target::x86_64::{REGS, SYSV, WIN64};
310
311 use super::*;
312
313 fn blank(params: &[Type]) -> (Interner, Func, ir::Block, Vec<ir::Value>) {
315 let mut names = Interner::new();
316 let mut func = Func::new(names.intern("f"), Signature::new());
317 let block = func.create_block();
318 let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
319 (names, func, block, values)
320 }
321
322 #[test]
323 fn a_function_comes_out_with_no_virtual_register_left_in_it() {
324 let i32 = Type::int(32);
325 let (mut names, mut source, block, args) = blank(&[i32, i32]);
326 let mut build = Builder::new(&mut source, block);
327 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
328 build.ret(&[sum]);
329
330 let machine = Machine::x86_64(&SYSV);
331 let out =
332 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
333 .expect("every instruction has a rule");
334
335 assert_eq!(
340 mir::print_func(&out, &names, ®S),
341 "mfunc @f {\n\
342 block0:\n \
343 $rdi($rdi) = x64.arg_val_32\n \
344 $rsi($rsi) = x64.arg_val_32\n \
345 $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n \
346 $rax = x64.mov_rr_64 $rdi\n \
347 x64.ret_val_32 $rax($rax)\n \
348 x64.ret\n\
349 }\n"
350 );
351 }
352
353 #[test]
357 fn which_rules_lowered_a_function_is_something_the_compilation_can_be_asked_for() {
358 let i32 = Type::int(32);
359 let (mut names, mut source, block, args) = blank(&[i32, i32]);
360 let mut build = Builder::new(&mut source, block);
361 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
362 build.ret(&[sum]);
363
364 let machine = Machine::x86_64(&SYSV);
365 let mut fired = Fired::new();
366 compile_recording(
367 &mut source,
368 &mut names,
369 &machine,
370 &Elsewhere::default(),
371 Flags::default(),
372 &mut fired,
373 &mut Pressure::new(),
374 )
375 .expect("every instruction has a rule");
376 let one = fired.count();
377 assert!(one > 0, "an add and a return went through the table and nothing was recorded");
378
379 let listing = fired.listing(&crate::select::x86_64::TABLE);
380 assert_eq!(listing.lines().filter(|line| line.starts_with("fired ")).count(), one);
381 assert!(
382 listing.contains(&format!("{one} of ")),
383 "{}",
384 listing.lines().next().unwrap_or("")
385 );
386
387 let (mut names, mut source, block, args) = blank(&[i32, i32]);
389 let mut build = Builder::new(&mut source, block);
390 let difference = build.binary(Opcode::Sub, args[0], args[1], IrFlags::default());
391 build.ret(&[difference]);
392 compile_recording(
393 &mut source,
394 &mut names,
395 &machine,
396 &Elsewhere::default(),
397 Flags::default(),
398 &mut fired,
399 &mut Pressure::new(),
400 )
401 .expect("every instruction has a rule");
402 assert!(fired.count() > one, "a subtraction is not an addition");
403 }
404
405 #[test]
406 fn a_function_that_calls_takes_a_frame_and_gives_it_back() {
407 let i32 = Type::int(32);
408 let (mut names, mut source, block, args) = blank(&[i32]);
409 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
410 let callee = names.intern("g");
411 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
412 let got = source[call].first_result.expect("an integer comes back");
413 let mut build = Builder::new(&mut source, block);
414 let sum = build.binary(Opcode::Add, got, args[0], IrFlags::default());
415 build.ret(&[sum]);
416
417 let machine = Machine::x86_64(&SYSV);
418 let out =
419 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
420 .expect("every instruction has a rule");
421
422 let text = mir::print_func(&out, &names, ®S);
425 assert!(text.contains("x64.push_64 $rbx"), "{text}");
426 assert!(text.contains("$rbx = x64.pop_64"), "{text}");
427 assert!(text.contains("x64.call $rdi($rdi), @g"), "{text}");
428 assert!(!text.contains('%'), "{text}");
429 }
430
431 #[test]
432 fn the_other_convention_is_the_same_function_somewhere_else() {
433 let i32 = Type::int(32);
434 let (mut names, mut source, block, args) = blank(&[i32, i32]);
435 let mut build = Builder::new(&mut source, block);
436 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
437 build.ret(&[sum]);
438
439 let machine = Machine::x86_64(&WIN64);
440 let out =
441 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
442 .expect("every instruction has a rule");
443
444 let text = mir::print_func(&out, &names, ®S);
447 assert!(text.contains("$rcx($rcx) = x64.arg_val_32"), "{text}");
448 assert!(text.contains("$rdx($rdx) = x64.arg_val_32"), "{text}");
449 assert!(!text.contains("$rdi"), "{text}");
450 }
451
452 #[test]
453 fn a_function_with_a_branch_in_it_goes_through_every_pass() {
454 let i32 = Type::int(32);
455 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
456 let then = source.create_block();
457 let join = source.create_block();
458 let got = source.append_param(join, i32);
459 let mut build = Builder::new(&mut source, entry);
460 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
461 build.br_if(cond, then, &[], join, &[args[1]]);
462 Builder::new(&mut source, then).jump(join, &[args[0]]);
463 Builder::new(&mut source, join).ret(&[got]);
464
465 let machine = Machine::x86_64(&SYSV);
466 let out =
467 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
468 .expect("every instruction has a rule");
469
470 assert_eq!(out.block_count(), 4);
474
475 let text = mir::print_func(&out, &names, ®S);
484 assert_eq!(
485 text,
486 "mfunc @f {\n\
487 block0:\n \
488 $rdi($rdi) = x64.arg_val_32\n \
489 $rsi($rsi) = x64.arg_val_32\n \
490 x64.cmp_rr_32 $rdi, $rsi\n \
491 x64.jcc_ge block2, block1\n\
492 \nblock1:\n \
493 $rax = x64.mov_rr_64 $rdi\n \
494 x64.jmp block3\n\
495 \nblock2:\n \
496 $rax = x64.mov_rr_64 $rsi, block3\n\
497 \nblock3:\n \
498 x64.ret_val_32 $rax($rax)\n \
499 x64.ret\n\
500 }\n"
501 );
502 }
503
504 #[test]
510 fn a_loop_that_carries_its_values_round_keeps_all_of_them() {
511 let i32 = Type::int(32);
512 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
513 let head = source.create_block();
514 let body = source.create_block();
515 let exit = source.create_block();
516 let left = source.append_param(head, i32);
517 let right = source.append_param(head, i32);
518 Builder::new(&mut source, entry).jump(head, &[args[0], args[1]]);
519 let mut build = Builder::new(&mut source, head);
520 let zero = build.iconst(i32, 0);
521 let more = build.icmp(rucc_ir::IntPred::Ne, right, zero);
522 build.br_if(more, body, &[], exit, &[left]);
523 let mut build = Builder::new(&mut source, body);
524 let rest = build.binary(Opcode::SRem, left, right, IrFlags::default());
525 build.jump(head, &[right, rest]);
526 let result = source.append_param(exit, i32);
527 Builder::new(&mut source, exit).ret(&[result]);
528
529 let machine = Machine::x86_64(&SYSV);
530 let out =
531 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
532 .expect("every instruction has a rule");
533
534 assert_eq!(
550 mir::print_func(&out, &names, ®S),
551 "mfunc @f {\n\
552 block0:\n \
553 $rdi($rdi) = x64.arg_val_32\n \
554 $rsi($rsi) = x64.arg_val_32\n \
555 $rcx = x64.mov_rr_64 $rdi, block1\n\
556 \nblock1:\n \
557 x64.cmp_ri_32 $rsi, 0\n \
558 x64.jcc_e block3, block2\n\
559 \nblock2:\n \
560 $rax = x64.mov_rr_64 $rcx\n \
561 $rdx($rdx), early $rax($rax) = x64.idiv_rem_32 $rax($rax), $rsi\n \
562 $rdi = x64.mov_rr_64 $rax\n \
563 $rcx = x64.mov_rr_64 $rsi\n \
564 $rsi = x64.mov_rr_64 $rdx\n \
565 x64.jmp block1\n\
566 \nblock3:\n \
567 $rax = x64.mov_rr_64 $rcx\n \
568 x64.ret_val_32 $rax($rax)\n \
569 x64.ret\n\
570 }\n"
571 );
572 }
573
574 #[test]
579 fn a_function_that_has_been_laid_out_reads_back_as_the_same_function() {
580 let i32 = Type::int(32);
581 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
582 let then = source.create_block();
583 let join = source.create_block();
584 let got = source.append_param(join, i32);
585 let mut build = Builder::new(&mut source, entry);
586 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
587 build.br_if(cond, then, &[], join, &[args[1]]);
588 Builder::new(&mut source, then).jump(join, &[args[0]]);
589 Builder::new(&mut source, join).ret(&[got]);
590
591 let machine = Machine::x86_64(&SYSV);
592 let out =
593 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
594 .expect("every instruction has a rule");
595
596 let text = mir::print_func(&out, &names, ®S);
597 let read = rucc_mir::parse(&text, &mut names, ®S).expect("what the printer wrote");
598 assert_eq!(mir::print(&read, &names, ®S), text);
599 }
600
601 #[test]
602 fn a_function_this_cannot_lower_is_reported_rather_than_compiled() {
603 let f80 = Type::float(rucc_ir::Float::F80);
604 let (mut names, mut source, block, args) = blank(&[f80, Type::int(64)]);
605 Builder::new(&mut source, block).ret(&args);
606
607 let machine = Machine::x86_64(&SYSV);
611 let failed =
612 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
613 .expect_err("a long double cannot come back beside another value");
614 assert_eq!(failed.to_string(), "what this function gives back is on the x87 stack");
615 }
616
617 #[test]
625 fn a_long_double_arrives_in_memory_and_goes_back_on_the_x87_stack() {
626 let f80 = Type::float(rucc_ir::Float::F80);
627 let (mut names, mut source, block, args) = blank(&[f80, f80]);
628 let mut build = Builder::new(&mut source, block);
629 let sum = build.binary(Opcode::FAdd, args[0], args[1], IrFlags::default());
630 build.ret(&[sum]);
631
632 let machine = Machine::x86_64(&SYSV);
633 let out =
634 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
635 .expect("every instruction has a rule");
636
637 let text = mir::print_func(&out, &names, ®S);
638 assert!(text.contains("x64.lea_64 [$rsp + 32]"), "{text}");
641 assert!(text.contains("x64.lea_64 [$rsp + 48]"), "{text}");
642 assert!(!text.contains("x64.ret_val"), "nothing comes back in a register: {text}");
643 let end: Vec<&str> = text.lines().rev().skip(1).take(3).map(str::trim).collect();
646 assert_eq!(end, ["x64.ret", "$rsp = x64.add_ri_64 $rsp, 24", "x64.fld_t [$rax]"], "{text}");
647 }
648
649 #[test]
653 fn a_float_is_added_in_the_register_file_it_arrives_in() {
654 let f32 = Type::float(rucc_ir::Float::F32);
655 let (mut names, mut source, block, args) = blank(&[f32, f32]);
656 let mut build = Builder::new(&mut source, block);
657 let sum = build.binary(Opcode::FAdd, args[0], args[1], ir::Flags::default());
658 build.ret(&[sum]);
659
660 let machine = Machine::x86_64(&SYSV);
661 let out =
662 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
663 .expect("every instruction has a rule");
664
665 let text = mir::print_func(&out, &names, ®S);
666 assert!(text.contains("x64.addss_rr"), "{text}");
667 assert!(text.contains("$xmm0"), "{text}");
668 assert!(!text.contains("$rax"), "{text}");
669 }
670
671 #[test]
674 fn a_float_read_from_memory_and_written_back_uses_the_scalar_moves() {
675 let f64 = Type::float(rucc_ir::Float::F64);
676 let (mut names, mut source, block, args) = blank(&[Type::PTR, f64]);
677 let mut build = Builder::new(&mut source, block);
678 let info = rucc_ir::MemInfo {
679 size: 8,
680 align: 8,
681 order: rucc_ir::MemOrder::NotAtomic,
682 tbaa: None,
683 restrict: Restrict::NONE,
684 };
685 let read = build.load(f64, args[0], info, ir::Flags::default());
686 let sum = build.binary(Opcode::FAdd, read, args[1], ir::Flags::default());
687 build.store(sum, args[0], info, ir::Flags::default());
688 build.ret(&[sum]);
689
690 let machine = Machine::x86_64(&SYSV);
691 let out =
692 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
693 .expect("every instruction has a rule");
694
695 let text = mir::print_func(&out, &names, ®S);
696 assert!(text.contains("x64.movsd_rm"), "{text}");
697 assert!(text.contains("x64.movsd_mr"), "{text}");
698 assert!(!text.contains("x64.movaps_rm"), "{text}");
701 assert!(!text.contains("x64.movaps_mr"), "{text}");
702 }
703
704 #[test]
712 fn an_unsigned_word_and_a_long_double_convert_into_each_other() {
713 let f80 = Type::float(rucc_ir::Float::F80);
714 let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
715 let mut build = Builder::new(&mut source, block);
716 let info = rucc_ir::MemInfo {
717 size: 16,
718 align: 16,
719 order: rucc_ir::MemOrder::NotAtomic,
720 tbaa: None,
721 restrict: Restrict::NONE,
722 };
723 let wide = build.unary(Opcode::UIToFP, args[1], f80);
724 build.store(wide, args[0], info, ir::Flags::default());
725 let read = build.load(f80, args[0], info, ir::Flags::default());
726 let back = build.unary(Opcode::FPToUI, read, Type::int(64));
727 build.ret(&[back]);
728
729 let machine = Machine::x86_64(&SYSV);
730 let out =
731 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
732 .expect("every instruction has a rule");
733
734 let text = mir::print_func(&out, &names, ®S);
735 assert!(text.contains("x64.fild_ll"), "the integer goes in as a signed one: {text}");
738 assert!(text.contains("x64.fistp_ll"), "and comes back out as one: {text}");
739 assert!(text.contains("x64.fmul_p"), "the correction is taken or not: {text}");
740 assert!(text.contains("x64.fadd_p"), "and applied one way: {text}");
741 assert!(text.contains("x64.fsubr_p"), "and the other: {text}");
742 assert!(!text.contains("xmm"), "no part of this is in a vector register: {text}");
743 }
744
745 #[test]
750 fn a_conversion_carries_the_value_into_the_other_register_file() {
751 let f64 = Type::float(rucc_ir::Float::F64);
752 let (mut names, mut source, block, args) = blank(&[f64]);
753 let mut build = Builder::new(&mut source, block);
754 let whole = build.unary(Opcode::FPToSI, args[0], Type::int(32));
755 let back = build.unary(Opcode::SIToFP, whole, f64);
756 build.ret(&[back]);
757
758 let machine = Machine::x86_64(&SYSV);
759 let out =
760 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
761 .expect("every instruction has a rule");
762
763 let text = mir::print_func(&out, &names, ®S);
766 assert!(text.contains("x64.cvttsd2si_32"), "{text}");
767 assert!(text.contains("x64.cvtsi2sd_32"), "{text}");
768 assert!(text.contains("$xmm0"), "{text}");
769 }
770
771 #[test]
774 fn a_bitcast_between_the_files_is_the_move_that_changes_no_bit() {
775 let f64 = Type::float(rucc_ir::Float::F64);
776 let (mut names, mut source, block, args) = blank(&[f64]);
777 let mut build = Builder::new(&mut source, block);
778 let bits = build.unary(Opcode::Bitcast, args[0], Type::int(64));
779 build.ret(&[bits]);
780
781 let machine = Machine::x86_64(&SYSV);
782 let out =
783 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
784 .expect("every instruction has a rule");
785
786 let text = mir::print_func(&out, &names, ®S);
787 assert!(text.contains("x64.movq_from_xmm"), "{text}");
788 assert!(!text.contains("cvt"), "{text}");
789 }
790
791 #[test]
793 fn a_float_comparison_is_the_compare_and_the_byte_a_condition_sets() {
794 let f64 = Type::float(rucc_ir::Float::F64);
795 let (mut names, mut source, block, args) = blank(&[f64, f64]);
796 let mut build = Builder::new(&mut source, block);
797 let less = build.fcmp(rucc_ir::FloatPred::Olt, args[0], args[1], ir::Flags::default());
798 let wide = build.unary(Opcode::ZExt, less, Type::int(32));
799 build.ret(&[wide]);
800
801 let machine = Machine::x86_64(&SYSV);
802 let out =
803 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
804 .expect("every instruction has a rule");
805
806 let text = mir::print_func(&out, &names, ®S);
809 assert!(text.contains("x64.ucomisd_set_a"), "{text}");
810 }
811
812 #[test]
817 fn an_equality_between_floats_gets_a_register_for_the_byte_it_needs_twice() {
818 let f64 = Type::float(rucc_ir::Float::F64);
819 let (mut names, mut source, block, args) = blank(&[f64, f64]);
820 let mut build = Builder::new(&mut source, block);
821 let same = build.fcmp(rucc_ir::FloatPred::Oeq, args[0], args[1], ir::Flags::default());
822 let wide = build.unary(Opcode::ZExt, same, Type::int(32));
823 build.ret(&[wide]);
824
825 let machine = Machine::x86_64(&SYSV);
826 let out =
827 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
828 .expect("every instruction has a rule");
829
830 let text = mir::print_func(&out, &names, ®S);
831 let line = text
832 .lines()
833 .find(|line| line.contains("x64.ucomisd_set_e_and_np"))
834 .expect("the rule for an ordered equality fired");
835 let written: Vec<&str> = line
836 .split_once('=')
837 .expect("the instruction writes something")
838 .0
839 .split(',')
840 .map(str::trim)
841 .collect();
842 assert_eq!(written.len(), 2, "{line}");
843 assert_ne!(written[0], written[1], "{line}");
844 }
845
846 #[test]
850 fn a_float_constant_is_the_bits_in_a_register_and_the_move_that_carries_them_over() {
851 let f64 = Type::float(rucc_ir::Float::F64);
852 let (mut names, mut source, block, _) = blank(&[]);
853 let mut build = Builder::new(&mut source, block);
854 let half = build.fconst(f64, 0x3fe0_0000_0000_0000);
855 build.ret(&[half]);
856
857 let machine = Machine::x86_64(&SYSV);
858 let out =
859 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
860 .expect("every instruction has a rule");
861
862 let text = mir::print_func(&out, &names, ®S);
863 assert!(text.contains("x64.mov_ri_64"), "{text}");
864 assert!(text.contains("x64.movq_to_xmm"), "{text}");
865 }
866
867 #[test]
870 fn a_negation_is_the_sign_bit_flipped_and_no_float_instruction_at_all() {
871 let f64 = Type::float(rucc_ir::Float::F64);
872 let (mut names, mut source, block, args) = blank(&[f64]);
873 let mut build = Builder::new(&mut source, block);
874 let less = build.unary(Opcode::FNeg, args[0], f64);
875 build.ret(&[less]);
876
877 let machine = Machine::x86_64(&SYSV);
878 let out =
879 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
880 .expect("every instruction has a rule");
881
882 let text = mir::print_func(&out, &names, ®S);
883 assert!(text.contains("x64.xor_rr_64"), "{text}");
884 assert!(!text.contains("sub"), "a negation is not a subtraction: {text}");
885 }
886
887 #[test]
888 fn the_flags_reach_the_frame() {
889 let i32 = Type::int(32);
890 let (mut names, mut source, block, args) = blank(&[i32]);
891 Builder::new(&mut source, block).ret(&[args[0]]);
892
893 let machine = Machine::x86_64(&SYSV);
894 let flags = Flags { frame_pointer: true, red_zone: true };
895 let out = compile(&mut source, &mut names, &machine, &Elsewhere::default(), flags)
896 .expect("every instruction has a rule");
897
898 let text = mir::print_func(&out, &names, ®S);
901 assert!(text.contains("x64.push_64 $rbp"), "{text}");
902 assert!(text.contains("$rbp = x64.mov_rr_64 $rsp"), "{text}");
903 }
904
905 #[test]
906 fn a_target_says_which_machine_it_is_and_which_convention_it_uses() {
907 let triple = |text: &str| text.parse::<rucc_target::Triple>().expect("a triple");
908 let info = TargetInfo::new(triple("x86_64-unknown-linux-gnu"));
909 let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
910 assert!(std::ptr::eq(machine.conv, &SYSV));
911
912 let info = TargetInfo::new(triple("x86_64-pc-windows-msvc"));
913 let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
914 assert!(std::ptr::eq(machine.conv, &WIN64));
915
916 let info = TargetInfo::new(triple("aarch64-unknown-linux-gnu"));
919 assert!(Machine::for_target(&info).is_none());
920 }
921}