rucc_codegen/pipeline.rs
1//! One IR function to one machine function, which is every pass in this crate in order.
2//!
3//! Design: `spec/10-backend.md` section 10.1, which is where the order comes from.
4//!
5//! Each pass here is written and tested on its own and each is useful on its own, but there is
6//! exactly one order they run in and until now that order lived in the tests. A caller outside
7//! this crate would have had to know that splitting critical edges comes after lowering and
8//! before allocation, that the frame is worked out after allocation because the spill slots are
9//! the largest thing in it, and that the prologue is written after the frame. None of that is a
10//! decision a driver should be making, so it is written down once, here.
11//!
12//! # What comes out
13//!
14//! A function whose every register is physical, whose every offset into the frame is a constant,
15//! and whose blocks are in the order they run in with the jumps that order needs. That is the
16//! point at which a function is one an encoder could read, and there is nothing left in it that
17//! is not an instruction of the machine it was compiled for.
18//!
19//! # What is still missing from the middle
20//!
21//! The optimizing path, all of it. What runs here is `spec/10-backend.md` section 10.3's fast
22//! path: one rule per term, a linear scan, and a block order from the shape of the CFG rather
23//! than from block frequency. No scheduling, and the redundant moves a coalescer would take out
24//! are still in the output.
25
26use rucc_base::Interner;
27use rucc_ir as ir;
28use rucc_mir as mir;
29use rucc_regalloc::assign::Env;
30use rucc_target::{
31 BitInsts, BranchInsts, CallRegs, FrameInsts, PhysReg, RegFile, TargetInfo, x86_64,
32};
33use rucc_tuple::Arch;
34
35use crate::bits;
36use crate::coverage::Fired;
37use crate::elsewhere::Elsewhere;
38use crate::expand;
39use crate::finish::{Convention, Padding, Probing, Protect, Tracing, finish};
40use crate::fold;
41use crate::frame::{Frame, Layout};
42use crate::layout;
43use crate::lower::{self, Unsupported};
44use crate::pressure::{Cost, Pressure};
45use crate::reload;
46use crate::retry;
47use crate::split;
48use crate::switch;
49use crate::varargs;
50use crate::weights;
51use crate::wide;
52use crate::widths;
53
54/// Everything about a machine that compiling a function for it needs.
55///
56/// The fields are different kinds of fact and they come from different places: where the
57/// convention puts things, what registers the machine has, which instructions build a frame,
58/// which instructions a branch becomes, and which registers the allocator may hand out. The last
59/// one is not a target fact on its own, because holding a register back as scratch is a decision
60/// about the allocator rather than about the machine, which is why it is built here rather than
61/// in [`rucc_target`].
62#[derive(Debug)]
63pub struct Machine {
64 /// Where the convention this function is compiled for puts things.
65 pub conv: &'static CallRegs,
66 /// The registers the machine has, which is what says how wide a spill slot of a class is.
67 pub file: RegFile,
68 /// The instructions that take a frame and give it back.
69 pub insts: &'static FrameInsts,
70 /// The instructions a branch becomes once the blocks are in an order.
71 pub branch: &'static BranchInsts,
72 /// How much of a register each of the machine's instructions reads and writes.
73 pub bits: &'static BitInsts,
74 /// What the allocator may hand out, and what it holds back.
75 pub env: Env,
76}
77
78/// The scratch registers held back from the allocator on x86-64.
79///
80/// Two, because a move on an edge may have to break a cycle and a spilled value has to be read
81/// into something, and those can want a register at the same instruction. Two is also what the
82/// instruction wanting most wants, which is one that reads two spilled values and writes a third,
83/// and `rewrite` says why the answer goes back into a register an operand arrived in rather than
84/// asking for a third.
85///
86/// It is not two because two was enough to start with and nobody looked again. There is no third
87/// to hold back. A scratch register has to be one the convention passes nothing in, since the
88/// rewriter puts moves in wherever it likes, and one the callee does not owe back, since the
89/// rewriter runs after the prologue has been decided and cannot ask for a register to be saved.
90/// On SysV that is `r10` and `r11` and nothing else, so if the rewriter ever does want a third the
91/// answer is not to take one here.
92const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
93
94/// How many of each class are held back.
95const SCRATCH_COUNT: usize = SCRATCH.len();
96
97impl Machine {
98 /// The x86-64 machine under that convention.
99 ///
100 /// Both files are offered. A value the selector produces is in one or the other, which is
101 /// decided by its type: an integer and an address are general purpose and a `float` or a
102 /// `double` is in a vector register, and the allocator is given each file separately because
103 /// no move goes between them.
104 #[must_use]
105 pub fn x86_64(conv: &'static CallRegs) -> Self {
106 let order: Vec<PhysReg> =
107 conv.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
108 // The vector file wants its own two, for the same two jobs, and they have to be two the
109 // convention does not preserve: a scratch register is written by a move the rewriter puts
110 // in, which is after the prologue has already been decided, so one the callee owes back
111 // would be one nothing saved. That rules out the upper ten on Windows and nothing at all
112 // on SysV, and taking the last two that are left lands on `xmm14` and `xmm15` there and on
113 // `xmm4` and `xmm5` on Windows, neither of which any argument travels in.
114 let free: Vec<PhysReg> =
115 conv.sse_order.iter().copied().filter(|®| !conv.preserves_sse(reg)).collect();
116 let at = free.len().saturating_sub(SCRATCH_COUNT);
117 let sse_scratch: Vec<PhysReg> = free[at..].to_vec();
118 let sse_order: Vec<PhysReg> =
119 conv.sse_order.iter().copied().filter(|reg| !sse_scratch.contains(reg)).collect();
120 Self {
121 conv,
122 file: x86_64::REGS,
123 insts: &x86_64::FRAME,
124 branch: &x86_64::BRANCH,
125 bits: &x86_64::BITS,
126 env: Env::new().with(x86_64::GPR, &order, &SCRATCH).with(
127 x86_64::XMM,
128 &sse_order,
129 &sse_scratch,
130 ),
131 }
132 }
133
134 /// The machine a target describes, or `None` when no backend in this crate covers it.
135 ///
136 /// [`TargetInfo`] already carries the convention, because the front end needs it to lay a
137 /// `va_list` out, so the only thing this decides is which architecture's frame instructions
138 /// and register file go with it. AArch64 and RISC-V are `None` until M6 fills them in, and a
139 /// caller that gets one reports a target it cannot compile for rather than compiling wrongly.
140 #[must_use]
141 pub fn for_target(target: &TargetInfo) -> Option<Self> {
142 let conv = target.call_regs?;
143 match target.tuple.arch() {
144 Arch::X86_64 => Some(Self::x86_64(conv)),
145 _ => None,
146 }
147 }
148}
149
150/// Whether every function calls a profiler on the way in, and where that call goes.
151///
152/// What `-pg` asks for, with `-mfentry` and `-mno-fentry` choosing between the last two. The choice
153/// has already been made against the target by the time this is built, which is why there is no
154/// answer here for a command line that named neither.
155#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
156pub enum Profile {
157 /// It does not, which is what nearly every command line asks for.
158 #[default]
159 No,
160 /// In front of the prologue, which is the hook a tracer can replace while the program runs.
161 Early,
162 /// Once the frame is taken, which is the hook that reads the frame pointer.
163 Late,
164}
165
166/// How much room every function opens with for something to be written over it later.
167///
168/// What `-fpatchable-function-entry=` asks for, as the two halves a prologue deals in rather than
169/// as the total and the part the flag is written in. The room can be on either side of the
170/// function's own label and the two sides are not the same thing: what is after the label is inside
171/// the function, which is what a patcher redirecting a call into it wants, and what is in front of
172/// it is outside, which is where a patcher that needs a whole instruction it can reach from the
173/// first one puts it.
174#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
175pub struct Room {
176 /// How many bytes go after the function's own label.
177 pub after: u32,
178 /// How many go in front of it.
179 pub before: u32,
180}
181
182impl Room {
183 /// Whether any room at all was asked for, which is what decides whether a function gets one.
184 ///
185 /// `=0` is a command line that asked for none, and gcc takes it and writes nothing, so the
186 /// question is about the numbers rather than about whether the flag was written.
187 #[must_use]
188 pub const fn any(self) -> bool {
189 self.after > 0 || self.before > 0
190 }
191}
192
193/// What the command line says about a frame, as opposed to what the machine says.
194#[derive(Debug, Clone, Copy, PartialEq, Eq)]
195pub struct Flags {
196 /// Whether every function keeps a frame pointer, which `-fno-omit-frame-pointer` asks for.
197 pub frame_pointer: bool,
198 /// Whether the red zone may be used, which `-mno-red-zone` and every kernel turns off.
199 pub red_zone: bool,
200 /// Whether a frame is taken a page at a time, which `-fstack-clash-protection` asks for.
201 pub stack_clash: bool,
202 /// Whether every function opens with a landing pad, which `-fcf-protection=branch` asks for.
203 pub landing: bool,
204 /// Whether every function calls a profiler on the way in, which `-pg` asks for.
205 pub profile: Profile,
206 /// How much room every function opens with for a patcher, which
207 /// `-fpatchable-function-entry=` asks for. See [`Room`].
208 pub patch: Room,
209 /// Whether the blocks are put in the order the weights say rather than in the order the
210 /// shape of the graph says, which `-freorder-blocks` asks for and every level above `-O0`
211 /// turns on. See [`crate::layout`].
212 pub reorder: bool,
213}
214
215impl Default for Flags {
216 /// No frame pointer, the red zone allowed, the frame taken in one subtraction, no landing pad,
217 /// no profiling, no room for a patcher and the blocks in the order the graph's shape gives,
218 /// which is what a convention that has a red zone says at `-O0` when nobody on the command
219 /// line has said otherwise.
220 fn default() -> Self {
221 Self {
222 frame_pointer: false,
223 red_zone: true,
224 stack_clash: false,
225 landing: false,
226 profile: Profile::No,
227 patch: Room::default(),
228 reorder: false,
229 }
230 }
231}
232
233/// Compiles one function, from the IR the middle end produced to machine instructions.
234///
235/// The function is taken by reference that can be written through, because the first pass is an
236/// IR to IR rewrite: a construct whose lowering is a new shape of control flow cannot be a rule,
237/// since a rule replaces a term with a term and has nowhere to put a block. So the IR that reaches
238/// selection is not quite the IR the middle end produced, and this is the only place that is true.
239/// `--emit=ir` prints before any of this runs.
240///
241/// `elsewhere` is the one thing here that is a fact about the module rather than about the
242/// function, and it is passed in rather than looked up because this only ever sees the one
243/// function. What it decides is how the address of a name is come by, which is the difference
244/// between an address this file can measure to and one only the linker knows.
245///
246/// # Errors
247///
248/// The first thing in it this cannot lower, which is what [`lower::func`] reports and is the only
249/// pass here that can refuse a function. Everything after lowering works on machine instructions
250/// that exist, so it either runs or it is a bug in this crate.
251pub fn compile(
252 source: &mut ir::Func,
253 names: &mut Interner,
254 machine: &Machine,
255 elsewhere: &Elsewhere,
256 flags: Flags,
257) -> Result<mir::Func, Unsupported> {
258 compile_recording(
259 source,
260 names,
261 machine,
262 elsewhere,
263 flags,
264 &mut Fired::new(),
265 &mut Pressure::new(),
266 )
267}
268
269/// The same compilation, with what it did along the way recorded.
270///
271/// Two functions rather than one that takes options, because a caller that does not want the
272/// numbers should not have to say so. What `fired` is for is `-Zrule-coverage`, which is how the
273/// harness in `tamnd/rucc-compat` turns coverage of the rule set into a number over a corpus. What
274/// `pressure` is for is `-Zregister-pressure`, which is how much of the frame the allocator had to
275/// use and is the metric `spec/safe-memory/13-performance.md` section 13.1 asks for.
276///
277/// Both are added to rather than replaced, so a caller can pass the same pair for every function of
278/// a module and every module of a command line and get the answer for all of them.
279///
280/// # Errors
281///
282/// The same as [`compile`]. A function that was refused contributes nothing to either, since a
283/// function that did not compile is not evidence about what a rule set or a frame would have done.
284pub fn compile_recording(
285 source: &mut ir::Func,
286 names: &mut Interner,
287 machine: &Machine,
288 elsewhere: &Elsewhere,
289 flags: Flags,
290 fired: &mut Fired,
291 pressure: &mut Pressure,
292) -> Result<mir::Func, Unsupported> {
293 switch::switches(source);
294 // Beside the switches rather than down with the rest of the rewriting, because both of them
295 // make blocks and nothing in `expand` may. Before the orderings as well, since the head of the
296 // loop it builds reads with an `atomic_load` and the pass below is what turns that into the
297 // plain load this machine does anyway.
298 retry::loops(source);
299 // Before the width legalisation and everything after it, because what an ordered access
300 // becomes here is a plain one and every pass below is written about a plain one by name.
301 expand::orderings(source, machine.conv.word);
302 // Above the splitting rather than below it, because an overflow check is the one instruction
303 // whose result is two things and the splitting has no answer for that, while the arithmetic it
304 // becomes here is adds, multiplies and comparisons the splitting knows already. Nothing is lost
305 // by running it this early: the widths it is written for are the widths the machine has, and
306 // the legalisation below never touches one of these anyway, so a check at a width neither pass
307 // is written for is refused by name either way round.
308 expand::overflows(source);
309 // Ahead of the width legalisation and not part of it, because the two go in opposite
310 // directions: an integer of forty bits becomes one of sixty four down there, and one of a
311 // hundred and twenty eight becomes two of sixty four here. Doing this first means a function
312 // holding both is one the pass below still works on, since by the time it runs the only widths
313 // left are ones it has an answer for.
314 wide::halves(source, names, machine.conv);
315 // Before everything, because every pass after it is written about widths the machine has and
316 // an integer of forty bits is not one of them.
317 widths::integers(source);
318 expand::bytes(source);
319 expand::counts(source);
320 expand::floats(source);
321 expand::bulk(source, names, machine.conv.word);
322 expand::rounds(source, machine.conv.stack_align);
323 varargs::lists(source, machine.conv);
324 let lowered = lower::func(source, names, machine.conv, elsewhere)?;
325 fired.merge(&lowered.fired);
326 let lower::Lowered { mut func, mut stack, blocks, .. } = lowered;
327 // Straight after selection, because this is the last moment the machine blocks and the IR
328 // blocks still stand one for one, and the pass that reads the numbers is the very last one
329 // there is. See `crate::weights`.
330 if flags.reorder {
331 weights::carry(source, &blocks, &mut func);
332 }
333 // Two things a frame that grows while it runs cannot be asked for at the same time, both of
334 // them refusals rather than wrong code.
335 if let Some(inst) = stack.grown_at {
336 // What `-fstack-clash-protection` buys is that no frame ever steps over a guard page
337 // without touching it, and a frame that grows while it runs steps by however much the
338 // declaration asked for. The prologue's own pages are touched below, and the ones a
339 // variable length array takes are not, so a function with both is refused rather than
340 // compiled to something that keeps the flag's name and not its promise.
341 if flags.stack_clash {
342 return Err(Unsupported::Dynamic { inst, growing: lower::Growing::Probed });
343 }
344 // The lowering refuses a variable length array that asks for more alignment than a call
345 // leaves the stack pointer on. A fixed local asking for it in the same function is the same
346 // refusal arrived at from the other side: the prologue would force the alignment, and
347 // forcing it and moving the stack pointer afterwards are two frames that each want the one
348 // register that still reaches the rest of the frame. See `Growing` in [`crate::frame`].
349 if stack.locals.iter().any(|local| local.align > machine.conv.stack_align) {
350 return Err(Unsupported::Dynamic { inst, growing: lower::Growing::Aligned });
351 }
352 }
353
354 // Before the fold below, which is the order section 37.6 puts the two in. A widening this takes
355 // out is one whose readers are sent to its source, and one of those readers may be an address
356 // computation, so asking which bits are read first means the fold sees the addresses as they
357 // will be rather than as they were.
358 bits::dead(&mut func, machine.bits, names);
359
360 // After selection, because the address instruction and the one that reads it are both machine
361 // instructions only once selection has written them, and before allocation, because what makes
362 // the pair safe to put together is that a virtual register is written once. The addresses into
363 // the frame and into the caller's argument area go through it like anything else, and the two
364 // lists `finish` reads are rewritten as they do, so an address that ends up inside its reader
365 // is still an address the frame layout knows to write an offset into.
366 let mut pending = fold::Pending {
367 addresses: &mut stack.addresses,
368 arguments: &mut stack.arguments,
369 dynamic: &mut stack.dynamic,
370 };
371 fold::addresses(&mut func, machine.insts, names, &mut pending);
372
373 // Whether this function carries a canary is the front end's answer, because what
374 // `-fstack-protector` asks about is the kind of local a function has and the types are gone by
375 // here. What the machine does about it is this crate's answer, and a target with nowhere to
376 // keep the word a canary is copied from does nothing, which is what the driver refuses a
377 // command line over before any of this runs.
378 let protect = source.attrs.set.contains(ir::AttrSet::STACK_PROTECT);
379 let guard = protect.then_some(machine.conv.guard.as_ref()).flatten();
380 // Nothing at all on a target with no hook to call, which is the same answer the protector gives
381 // on a target with nowhere to keep its word, and the driver refuses the command line over it
382 // before any of this runs.
383 let profile = match machine.conv.trace {
384 Some(_) => flags.profile,
385 None => Profile::No,
386 };
387 let base = stack.layout(Layout::new(machine.conv, machine.file));
388 let layout = Layout {
389 // The later hook reads the frame pointer to find out who called this function, so a
390 // function that calls it is given one whether or not anything else asked.
391 frame_pointer: flags.frame_pointer || profile == Profile::Late,
392 red_zone: flags.red_zone,
393 protect: guard.is_some(),
394 // A protected function calls the one that does not come back, on the arm where the check
395 // failed, so it is not a leaf however few calls the program wrote in it. That is what
396 // takes the red zone away from it and what makes its frame leave the stack pointer where
397 // a call needs it. The later hook is a call in the same position and costs the same.
398 //
399 // The earlier one is not, and this is the one place the difference shows. It runs before
400 // the prologue has written anything, so the bytes below the stack pointer it uses are ones
401 // this function has not put anything in yet, and a leaf that keeps its locals down there
402 // stays a leaf. gcc leaves it alone too.
403 leaf: base.leaf && guard.is_none() && profile != Profile::Late,
404 ..base
405 };
406
407 // Before allocation as well, and asked here rather than where it is used because what it asks
408 // is whether anything but the branch reads the byte a comparison wrote. A virtual register is
409 // written once and a physical one is not, so after allocation that question no longer has an
410 // answer.
411 let fusable = layout::fusable(&func, machine.branch, names);
412
413 // Before allocation, because an edge that carries values into a block arrived at more than
414 // one way, out of a block that leaves more than one way, has nowhere to put the moves those
415 // values turn into, and the allocator asserts rather than guessing.
416 split::critical(&mut func);
417 let called = names.resolve(func.name).to_owned();
418 let allocation = rucc_regalloc::run(&mut func, &machine.env, &called);
419 pressure.record(&called, Cost::of(&allocation));
420
421 // After allocation, because the largest area in most frames is the spill slots and nothing
422 // knows how many of those there are until the allocator has finished running out of registers.
423 let frame = Frame::of(&func, &allocation, &layout);
424 let scratch = machine.env.scratch(machine.conv.int_class);
425 let protect = guard.map(|guard| Protect {
426 guard,
427 branch: machine.branch,
428 scratch: [scratch[0], scratch[1]],
429 });
430 // A target with no instruction that touches a page without changing it does nothing about the
431 // flag, which is the same answer the protector gives on a target with nowhere to keep its word.
432 // Every target this crate has a back end for has one.
433 let probe = flags
434 .stack_clash
435 .then_some(machine.insts.probe.as_ref())
436 .flatten()
437 .map(|probe| Probing { probe, branch: machine.branch, scratch: [scratch[0], scratch[1]] });
438 // The same answer for a target with nothing that marks an address as one an indirect branch
439 // may arrive at, and the driver refuses the command line for the same reason it refuses the
440 // other two before any of this runs.
441 let landing = flags.landing.then_some(machine.insts.landing).flatten();
442 let trace = machine.conv.trace.and_then(|trace| match profile {
443 Profile::No => None,
444 Profile::Early => Some(Tracing { name: trace.early, early: true }),
445 Profile::Late => Some(Tracing { name: trace.late, early: false }),
446 });
447 // And once more for the room a patcher was promised, which is a run of the shortest
448 // instruction that does nothing and so needs the target to have one. Nothing is written on a
449 // target that does not, rather than a run of something longer: the flag counts bytes, and a
450 // patcher writing over the room starts at its front and wants every byte in it to be a place
451 // it could have started at.
452 let pad = flags.patch.any().then_some(machine.insts.pad).flatten().map(|name| Padding {
453 name,
454 before: flags.patch.before,
455 after: flags.patch.after,
456 });
457 let convention = Convention {
458 protect,
459 probe,
460 landing,
461 trace,
462 pad,
463 ..Convention::new(machine.conv, machine.insts)
464 };
465 let moves = finish(&mut func, &allocation, &frame, &stack, convention, names);
466
467 // After the moves are written, because a spill and the reload of it are written by different
468 // decisions of the allocator and what says the two are next to each other is the function they
469 // both went into. Before the layout, because the layout is where the instruction sequence
470 // stops being something a pass may edit.
471 reload::dead(&mut func, &moves);
472
473 // Last, because everything before this finds the blocks a function returns from by looking
474 // for the ones that go nowhere, and after this a block that falls through goes nowhere too.
475 layout::blocks(&mut func, machine.branch, names, &fusable, flags.reorder);
476 Ok(func)
477}
478
479#[cfg(test)]
480mod tests {
481 use rucc_ir::{Builder, Flags as IrFlags, Func, Opcode, Restrict, Signature, Type};
482 use rucc_target::x86_64::{REGS, SYSV, WIN64};
483
484 use super::*;
485
486 /// A function of two integers, and the block to fill.
487 fn blank(params: &[Type]) -> (Interner, Func, ir::Block, Vec<ir::Value>) {
488 let mut names = Interner::new();
489 let mut func = Func::new(names.intern("f"), Signature::new());
490 let block = func.create_block();
491 let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
492 (names, func, block, values)
493 }
494
495 #[test]
496 fn a_function_comes_out_with_no_virtual_register_left_in_it() {
497 let i32 = Type::int(32);
498 let (mut names, mut source, block, args) = blank(&[i32, i32]);
499 let mut build = Builder::new(&mut source, block);
500 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
501 build.ret(&[sum]);
502
503 let machine = Machine::x86_64(&SYSV);
504 let out =
505 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
506 .expect("every instruction has a rule");
507
508 // `int f(int a, int b) { return a + b; }` end to end. A leaf that spills nothing needs no
509 // frame at all, so there is no prologue to see. The one move left is the one the machine's
510 // addition needs, since the sum is written into the register the left operand was read
511 // from and the return wants it in `rax`.
512 assert_eq!(
513 mir::print_func(&out, &names, ®S),
514 "mfunc @f {\n\
515 block0:\n \
516 $rdi($rdi) = x64.arg_val_32\n \
517 $rsi($rsi) = x64.arg_val_32\n \
518 $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n \
519 $rax = x64.mov_rr_64 $rdi\n \
520 x64.ret_val_32 $rax($rax)\n \
521 x64.ret\n\
522 }\n"
523 );
524 }
525
526 /// What `-Zrule-coverage` is built out of: the rules a compilation fired, recorded as it went.
527 /// The second function adds to the first rather than replacing it, which is what makes one of
528 /// these files the answer for a whole command line rather than for whichever function was last.
529 #[test]
530 fn which_rules_lowered_a_function_is_something_the_compilation_can_be_asked_for() {
531 let i32 = Type::int(32);
532 let (mut names, mut source, block, args) = blank(&[i32, i32]);
533 let mut build = Builder::new(&mut source, block);
534 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
535 build.ret(&[sum]);
536
537 let machine = Machine::x86_64(&SYSV);
538 let mut fired = Fired::new();
539 compile_recording(
540 &mut source,
541 &mut names,
542 &machine,
543 &Elsewhere::default(),
544 Flags::default(),
545 &mut fired,
546 &mut Pressure::new(),
547 )
548 .expect("every instruction has a rule");
549 let one = fired.count();
550 assert!(one > 0, "an add and a return went through the table and nothing was recorded");
551
552 let listing = fired.listing(&crate::select::x86_64::TABLE);
553 assert_eq!(listing.lines().filter(|line| line.starts_with("fired ")).count(), one);
554 assert!(
555 listing.contains(&format!("{one} of ")),
556 "{}",
557 listing.lines().next().unwrap_or("")
558 );
559
560 // The same rules again plus the ones a subtraction needs, into the same record.
561 let (mut names, mut source, block, args) = blank(&[i32, i32]);
562 let mut build = Builder::new(&mut source, block);
563 let difference = build.binary(Opcode::Sub, args[0], args[1], IrFlags::default());
564 build.ret(&[difference]);
565 compile_recording(
566 &mut source,
567 &mut names,
568 &machine,
569 &Elsewhere::default(),
570 Flags::default(),
571 &mut fired,
572 &mut Pressure::new(),
573 )
574 .expect("every instruction has a rule");
575 assert!(fired.count() > one, "a subtraction is not an addition");
576 }
577
578 #[test]
579 fn a_function_that_calls_takes_a_frame_and_gives_it_back() {
580 let i32 = Type::int(32);
581 let (mut names, mut source, block, args) = blank(&[i32]);
582 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
583 let callee = names.intern("g");
584 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
585 let got = source[call].first_result.expect("an integer comes back");
586 let mut build = Builder::new(&mut source, block);
587 let sum = build.binary(Opcode::Add, got, args[0], IrFlags::default());
588 build.ret(&[sum]);
589
590 let machine = Machine::x86_64(&SYSV);
591 let out =
592 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
593 .expect("every instruction has a rule");
594
595 // `int f(int a) { return g(a) + a; }`. Not a leaf, so the stack pointer moves and the
596 // register the value that outlives the call went to is one the prologue saves.
597 let text = mir::print_func(&out, &names, ®S);
598 assert!(text.contains("x64.push_64 $rbx"), "{text}");
599 assert!(text.contains("$rbx = x64.pop_64"), "{text}");
600 assert!(text.contains("x64.call $rdi($rdi), @g"), "{text}");
601 assert!(!text.contains('%'), "{text}");
602 }
603
604 #[test]
605 fn the_other_convention_is_the_same_function_somewhere_else() {
606 let i32 = Type::int(32);
607 let (mut names, mut source, block, args) = blank(&[i32, i32]);
608 let mut build = Builder::new(&mut source, block);
609 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
610 build.ret(&[sum]);
611
612 let machine = Machine::x86_64(&WIN64);
613 let out =
614 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
615 .expect("every instruction has a rule");
616
617 // The arguments arrive in `rcx` and `rdx` here rather than in `rdi` and `rsi`, which is
618 // the whole of what changed, and it changed because the convention was asked.
619 let text = mir::print_func(&out, &names, ®S);
620 assert!(text.contains("$rcx($rcx) = x64.arg_val_32"), "{text}");
621 assert!(text.contains("$rdx($rdx) = x64.arg_val_32"), "{text}");
622 assert!(!text.contains("$rdi"), "{text}");
623 }
624
625 #[test]
626 fn a_function_with_a_branch_in_it_goes_through_every_pass() {
627 let i32 = Type::int(32);
628 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
629 let then = source.create_block();
630 let join = source.create_block();
631 let got = source.append_param(join, i32);
632 let mut build = Builder::new(&mut source, entry);
633 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
634 build.br_if(cond, then, &[], join, &[args[1]]);
635 Builder::new(&mut source, then).jump(join, &[args[0]]);
636 Builder::new(&mut source, join).ret(&[got]);
637
638 let machine = Machine::x86_64(&SYSV);
639 let out =
640 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
641 .expect("every instruction has a rule");
642
643 // The else arm is a critical edge carrying a value, so a block that nothing lowered is in
644 // there, which is the pass between lowering and allocation doing its job. Without it the
645 // allocator would have asserted rather than compiled this.
646 assert_eq!(out.block_count(), 4);
647
648 // `int f(int a, int b) { return a < b ? a : b; }` end to end, and the last pass is what
649 // this pins. The branch became a test and one jump, and it is the jump taken when the
650 // condition failed, because the arm the condition is true for is the block laid out next
651 // and a block falls into the block laid out next. The other arm is the empty block the
652 // edge splitting left, which is where the move the edge carries ended up, and it falls
653 // into the join as well. What is left is one jump in the whole function. Both arms write
654 // the join's parameter straight into `rax`, because the return at the bottom insists on
655 // that register and the moves the edges carry are free to name it.
656 let text = mir::print_func(&out, &names, ®S);
657 assert_eq!(
658 text,
659 "mfunc @f {\n\
660 block0:\n \
661 $rdi($rdi) = x64.arg_val_32\n \
662 $rsi($rsi) = x64.arg_val_32\n \
663 x64.cmp_rr_32 $rdi, $rsi\n \
664 x64.jcc_ge block2, block1\n\
665 \nblock1:\n \
666 $rax = x64.mov_rr_64 $rdi\n \
667 x64.jmp block3\n\
668 \nblock2:\n \
669 $rax = x64.mov_rr_64 $rsi, block3\n\
670 \nblock3:\n \
671 x64.ret_val_32 $rax($rax)\n \
672 x64.ret\n\
673 }\n"
674 );
675 }
676
677 /// A loop that swaps its two values round every time it goes, which is `gcd`, and which is
678 /// the smallest program that caught two ways of losing a value. Both were found by running
679 /// what came out rather than by reading it, and both are pinned here rather than only where
680 /// they were fixed, because what is wrong with either of them is only visible in the whole
681 /// function.
682 #[test]
683 fn a_loop_that_carries_its_values_round_keeps_all_of_them() {
684 let i32 = Type::int(32);
685 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
686 let head = source.create_block();
687 let body = source.create_block();
688 let exit = source.create_block();
689 let left = source.append_param(head, i32);
690 let right = source.append_param(head, i32);
691 Builder::new(&mut source, entry).jump(head, &[args[0], args[1]]);
692 let mut build = Builder::new(&mut source, head);
693 let zero = build.iconst(i32, 0);
694 let more = build.icmp(rucc_ir::IntPred::Ne, right, zero);
695 build.br_if(more, body, &[], exit, &[left]);
696 let mut build = Builder::new(&mut source, body);
697 let rest = build.binary(Opcode::SRem, left, right, IrFlags::default());
698 build.jump(head, &[right, rest]);
699 let result = source.append_param(exit, i32);
700 Builder::new(&mut source, exit).ret(&[result]);
701
702 let machine = Machine::x86_64(&SYSV);
703 let out =
704 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
705 .expect("every instruction has a rule");
706
707 // `int gcd(int a, int b) { while (b) { int t = a % b; a = b; b = t; } return a; }`. Two
708 // things in here were wrong and each of them returned three from a program that gcc
709 // returns forty two from.
710 //
711 // The first is in the entry block. The move the edge into the loop asks for writes `rsi`,
712 // and the second argument has to be taken out of `rsi` before it does. An edit at the end
713 // of a block used to go in front of the last instruction, on the reasoning that the last
714 // instruction is the branch, and the block's jump is not an instruction until the layout
715 // has run, so it went in front of the `arg_val` whose own move had not been made yet.
716 //
717 // The second is in the loop body. A division writes both a quotient and a remainder, and
718 // only the remainder is wanted here, so the quotient is a value nothing reads. It used to
719 // be given the same register as the remainder, because a value written early was live at
720 // one point and that point is in front of where the remainder is written. The copy that
721 // takes the quotient nowhere then landed on top of the remainder.
722 assert_eq!(
723 mir::print_func(&out, &names, ®S),
724 "mfunc @f {\n\
725 block0:\n \
726 $rdi($rdi) = x64.arg_val_32\n \
727 $rsi($rsi) = x64.arg_val_32\n \
728 $rcx = x64.mov_rr_64 $rdi, block1\n\
729 \nblock1:\n \
730 x64.cmp_ri_32 $rsi, 0\n \
731 x64.jcc_e block3, block2\n\
732 \nblock2:\n \
733 $rax = x64.mov_rr_64 $rcx\n \
734 $rdx($rdx), early $rax($rax) = x64.idiv_rem_32 $rax($rax), $rsi\n \
735 $rdi = x64.mov_rr_64 $rax\n \
736 $rcx = x64.mov_rr_64 $rsi\n \
737 $rsi = x64.mov_rr_64 $rdx\n \
738 x64.jmp block1\n\
739 \nblock3:\n \
740 $rax = x64.mov_rr_64 $rcx\n \
741 x64.ret_val_32 $rax($rax)\n \
742 x64.ret\n\
743 }\n"
744 );
745 }
746
747 /// `spec/10-backend.md` section 10.1 says `--emit=mir-final` round-trips, and a function with
748 /// a branch in it is the one where that is worth checking: after the layout has run, where a
749 /// jump goes is nowhere in the instruction, so the text has to carry it on the block and the
750 /// parser has to put it back on the block it came off.
751 #[test]
752 fn a_function_that_has_been_laid_out_reads_back_as_the_same_function() {
753 let i32 = Type::int(32);
754 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
755 let then = source.create_block();
756 let join = source.create_block();
757 let got = source.append_param(join, i32);
758 let mut build = Builder::new(&mut source, entry);
759 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
760 build.br_if(cond, then, &[], join, &[args[1]]);
761 Builder::new(&mut source, then).jump(join, &[args[0]]);
762 Builder::new(&mut source, join).ret(&[got]);
763
764 let machine = Machine::x86_64(&SYSV);
765 let out =
766 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
767 .expect("every instruction has a rule");
768
769 let text = mir::print_func(&out, &names, ®S);
770 let read = rucc_mir::parse(&text, &mut names, ®S).expect("what the printer wrote");
771 assert_eq!(mir::print(&read, &names, ®S), text);
772 }
773
774 #[test]
775 fn a_function_this_cannot_lower_is_reported_rather_than_compiled() {
776 let f80 = Type::float(rucc_ir::Float::F80);
777 let (mut names, mut source, block, args) = blank(&[f80, Type::int(64)]);
778 Builder::new(&mut source, block).ret(&args);
779
780 // One of these comes back on the x87 stack and a pair comes back in a pair of registers,
781 // and there is no pair with that stack in it. So this is refused rather than lowered, and
782 // it is the convention that refuses it rather than anything about the instructions.
783 let machine = Machine::x86_64(&SYSV);
784 let failed =
785 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
786 .expect_err("a long double cannot come back beside another value");
787 assert_eq!(failed.to_string(), "what this function gives back is on the x87 stack");
788 }
789
790 /// A `long double` in and a `long double` out, which is the whole of what the convention says
791 /// about the type and is two different answers rather than one.
792 ///
793 /// It arrives in the caller's argument area, so what the parameter is is the address of the
794 /// bytes and the function reads them where they are. It goes back on the x87 stack, so the
795 /// return is an `fld` and nothing else, and the value is still on that stack when the function
796 /// returns, which is the one time anything here leaves it that way.
797 ///
798 /// The addresses are gone from the instruction listing, which is [`crate::fold`]: an argument's
799 /// address is a `lea` off the stack pointer and the `fld` that reads it has room for that
800 /// address itself, so the offset the frame layout works out is written into the `fld`.
801 #[test]
802 fn a_long_double_arrives_in_memory_and_goes_back_on_the_x87_stack() {
803 let f80 = Type::float(rucc_ir::Float::F80);
804 let (mut names, mut source, block, args) = blank(&[f80, f80]);
805 let mut build = Builder::new(&mut source, block);
806 let sum = build.binary(Opcode::FAdd, args[0], args[1], IrFlags::default());
807 build.ret(&[sum]);
808
809 let machine = Machine::x86_64(&SYSV);
810 let out =
811 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
812 .expect("every instruction has a rule");
813
814 let text = mir::print_func(&out, &names, ®S);
815 // The two parameters, sixteen bytes apart, read out of the caller's frame rather than out
816 // of a register, and the answer left on the stack by the last instruction in the function.
817 assert!(text.contains("x64.fld_t [$rsp + 32]"), "{text}");
818 assert!(text.contains("x64.fld_t [$rsp + 48]"), "{text}");
819 assert!(!text.contains("x64.lea_64"), "an address every reader took is gone: {text}");
820 assert!(!text.contains("x64.ret_val"), "nothing comes back in a register: {text}");
821 // What comes after the `fld` is the epilogue, which gives the frame back and touches
822 // nothing in the unit, so the value is where the caller looks for it when the `ret` runs.
823 let end: Vec<&str> = text.lines().rev().skip(1).take(3).map(str::trim).collect();
824 assert_eq!(end, ["x64.ret", "$rsp = x64.add_ri_64 $rsp, 24", "x64.fld_t [$rsp]"], "{text}");
825 }
826
827 /// The whole of the second register class, end to end: two floats arrive in vector registers,
828 /// the arithmetic happens in one, and the answer goes back in the register the convention
829 /// names. Nothing here touches the general purpose file, which is the point.
830 #[test]
831 fn a_float_is_added_in_the_register_file_it_arrives_in() {
832 let f32 = Type::float(rucc_ir::Float::F32);
833 let (mut names, mut source, block, args) = blank(&[f32, f32]);
834 let mut build = Builder::new(&mut source, block);
835 let sum = build.binary(Opcode::FAdd, args[0], args[1], ir::Flags::default());
836 build.ret(&[sum]);
837
838 let machine = Machine::x86_64(&SYSV);
839 let out =
840 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
841 .expect("every instruction has a rule");
842
843 let text = mir::print_func(&out, &names, ®S);
844 assert!(text.contains("x64.addss_rr"), "{text}");
845 assert!(text.contains("$xmm0"), "{text}");
846 assert!(!text.contains("$rax"), "{text}");
847 }
848
849 /// A float moved between a register and memory, which is the instruction that decides which
850 /// file the value is in and is a different one from the `mov` that moves the same four bytes.
851 #[test]
852 fn a_float_read_from_memory_and_written_back_uses_the_scalar_moves() {
853 let f64 = Type::float(rucc_ir::Float::F64);
854 let (mut names, mut source, block, args) = blank(&[Type::PTR, f64]);
855 let mut build = Builder::new(&mut source, block);
856 let info = rucc_ir::MemInfo {
857 size: 8,
858 align: 8,
859 order: rucc_ir::MemOrder::NotAtomic,
860 tbaa: None,
861 owns: 0,
862 restrict: Restrict::NONE,
863 };
864 let read = build.load(f64, args[0], info, ir::Flags::default());
865 let sum = build.binary(Opcode::FAdd, read, args[1], ir::Flags::default());
866 build.store(sum, args[0], info, ir::Flags::default());
867 build.ret(&[sum]);
868
869 let machine = Machine::x86_64(&SYSV);
870 let out =
871 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
872 .expect("every instruction has a rule");
873
874 let text = mir::print_func(&out, &names, ®S);
875 assert!(text.contains("x64.movsd_rm"), "{text}");
876 assert!(text.contains("x64.movsd_mr"), "{text}");
877 // Not the aligned whole register move, which is what a spill uses and is the one
878 // instruction here that would read and write more than the program asked for.
879 assert!(!text.contains("x64.movaps_rm"), "{text}");
880 assert!(!text.contains("x64.movaps_mr"), "{text}");
881 }
882
883 /// Both conversions between an unsigned word and a `long double`, all the way to instructions.
884 ///
885 /// What the rewrite writes and what the x87 group in [`crate::lower`] has are two lists put
886 /// together in two different files, and this is where they meet. The rewrite is free to write
887 /// any instruction it likes at any width, and at this width almost none of them can be
888 /// lowered, so a correction written the way the narrower ones are written would pass its own
889 /// tests next door and fail here.
890 #[test]
891 fn an_unsigned_word_and_a_long_double_convert_into_each_other() {
892 let f80 = Type::float(rucc_ir::Float::F80);
893 let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
894 let mut build = Builder::new(&mut source, block);
895 let info = rucc_ir::MemInfo {
896 size: 16,
897 align: 16,
898 order: rucc_ir::MemOrder::NotAtomic,
899 tbaa: None,
900 owns: 0,
901 restrict: Restrict::NONE,
902 };
903 let wide = build.unary(Opcode::UIToFP, args[1], f80);
904 build.store(wide, args[0], info, ir::Flags::default());
905 let read = build.load(f80, args[0], info, ir::Flags::default());
906 let back = build.unary(Opcode::FPToUI, read, Type::int(64));
907 build.ret(&[back]);
908
909 let machine = Machine::x86_64(&SYSV);
910 let out =
911 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
912 .expect("every instruction has a rule");
913
914 let text = mir::print_func(&out, &names, ®S);
915 // The signed conversions in both directions, the constants that correct them, and the
916 // multiply that takes a correction or leaves it. Nothing here reaches a wide register.
917 assert!(text.contains("x64.fild_ll"), "the integer goes in as a signed one: {text}");
918 assert!(text.contains("x64.fistp_ll"), "and comes back out as one: {text}");
919 assert!(text.contains("x64.fmul_p"), "the correction is taken or not: {text}");
920 assert!(text.contains("x64.fadd_p"), "and applied one way: {text}");
921 assert!(text.contains("x64.fsubr_p"), "and the other: {text}");
922 assert!(!text.contains("xmm"), "no part of this is in a vector register: {text}");
923 }
924
925 /// A value carried from one register file to the other, which is what a conversion is. The
926 /// instruction reads one file and writes the other, and the allocator has to know that: a
927 /// conversion whose operands were both said to be in one file would put the answer in a
928 /// register the next instruction cannot reach.
929 #[test]
930 fn a_conversion_carries_the_value_into_the_other_register_file() {
931 let f64 = Type::float(rucc_ir::Float::F64);
932 let (mut names, mut source, block, args) = blank(&[f64]);
933 let mut build = Builder::new(&mut source, block);
934 let whole = build.unary(Opcode::FPToSI, args[0], Type::int(32));
935 let back = build.unary(Opcode::SIToFP, whole, f64);
936 build.ret(&[back]);
937
938 let machine = Machine::x86_64(&SYSV);
939 let out =
940 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
941 .expect("every instruction has a rule");
942
943 // The conversion that cuts towards zero rather than the one that rounds, which is what C
944 // means by the cast, and the argument and the answer in the register the convention names.
945 let text = mir::print_func(&out, &names, ®S);
946 assert!(text.contains("x64.cvttsd2si_32"), "{text}");
947 assert!(text.contains("x64.cvtsi2sd_32"), "{text}");
948 assert!(text.contains("$xmm0"), "{text}");
949 }
950
951 /// The other way of putting a float and a number together, which keeps every bit rather than
952 /// the value and is what a program reading the bits of a `double` asks for.
953 #[test]
954 fn a_bitcast_between_the_files_is_the_move_that_changes_no_bit() {
955 let f64 = Type::float(rucc_ir::Float::F64);
956 let (mut names, mut source, block, args) = blank(&[f64]);
957 let mut build = Builder::new(&mut source, block);
958 let bits = build.unary(Opcode::Bitcast, args[0], Type::int(64));
959 build.ret(&[bits]);
960
961 let machine = Machine::x86_64(&SYSV);
962 let out =
963 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
964 .expect("every instruction has a rule");
965
966 let text = mir::print_func(&out, &names, ®S);
967 assert!(text.contains("x64.movq_from_xmm"), "{text}");
968 assert!(!text.contains("cvt"), "{text}");
969 }
970
971 /// A comparison whose answer the machine has a condition for, which is most of them.
972 #[test]
973 fn a_float_comparison_is_the_compare_and_the_byte_a_condition_sets() {
974 let f64 = Type::float(rucc_ir::Float::F64);
975 let (mut names, mut source, block, args) = blank(&[f64, f64]);
976 let mut build = Builder::new(&mut source, block);
977 let less = build.fcmp(rucc_ir::FloatPred::Olt, args[0], args[1], ir::Flags::default());
978 let wide = build.unary(Opcode::ZExt, less, Type::int(32));
979 build.ret(&[wide]);
980
981 let machine = Machine::x86_64(&SYSV);
982 let out =
983 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
984 .expect("every instruction has a rule");
985
986 // Less than is greater than with the operands the other way round, and the machine has no
987 // condition for the first, so the rule that fires is the one that swaps them.
988 let text = mir::print_func(&out, &names, ®S);
989 assert!(text.contains("x64.ucomisd_set_a"), "{text}");
990 }
991
992 /// The two comparisons that are not one condition. An ordered equality is the flag that means
993 /// equal or unordered and the flag that says it was ordered, so the instruction writes a
994 /// second byte and reads it back, and what this is about is that the second byte gets a
995 /// register of its own rather than the one the answer is in.
996 #[test]
997 fn an_equality_between_floats_gets_a_register_for_the_byte_it_needs_twice() {
998 let f64 = Type::float(rucc_ir::Float::F64);
999 let (mut names, mut source, block, args) = blank(&[f64, f64]);
1000 let mut build = Builder::new(&mut source, block);
1001 let same = build.fcmp(rucc_ir::FloatPred::Oeq, args[0], args[1], ir::Flags::default());
1002 let wide = build.unary(Opcode::ZExt, same, Type::int(32));
1003 build.ret(&[wide]);
1004
1005 let machine = Machine::x86_64(&SYSV);
1006 let out =
1007 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1008 .expect("every instruction has a rule");
1009
1010 let text = mir::print_func(&out, &names, ®S);
1011 let line = text
1012 .lines()
1013 .find(|line| line.contains("x64.ucomisd_set_e_and_np"))
1014 .expect("the rule for an ordered equality fired");
1015 let written: Vec<&str> = line
1016 .split_once('=')
1017 .expect("the instruction writes something")
1018 .0
1019 .split(',')
1020 .map(str::trim)
1021 .collect();
1022 assert_eq!(written.len(), 2, "{line}");
1023 assert_ne!(written[0], written[1], "{line}");
1024 }
1025
1026 /// A float literal, which is the last float thing a C program writes that had no lowering.
1027 /// The rewrite that puts it in reach is in `expand`, and what this is about is that the two
1028 /// halves meet: the constant is spelled in a general purpose register and moved across.
1029 #[test]
1030 fn a_float_constant_is_the_bits_in_a_register_and_the_move_that_carries_them_over() {
1031 let f64 = Type::float(rucc_ir::Float::F64);
1032 let (mut names, mut source, block, _) = blank(&[]);
1033 let mut build = Builder::new(&mut source, block);
1034 let half = build.fconst(f64, 0x3fe0_0000_0000_0000);
1035 build.ret(&[half]);
1036
1037 let machine = Machine::x86_64(&SYSV);
1038 let out =
1039 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1040 .expect("every instruction has a rule");
1041
1042 let text = mir::print_func(&out, &names, ®S);
1043 assert!(text.contains("x64.mov_ri_64"), "{text}");
1044 assert!(text.contains("x64.movq_to_xmm"), "{text}");
1045 }
1046
1047 /// A negation, which is the sign bit flipped and nothing else touched, so what the machine
1048 /// does is an exclusive or in a general purpose register rather than any float instruction.
1049 #[test]
1050 fn a_negation_is_the_sign_bit_flipped_and_no_float_instruction_at_all() {
1051 let f64 = Type::float(rucc_ir::Float::F64);
1052 let (mut names, mut source, block, args) = blank(&[f64]);
1053 let mut build = Builder::new(&mut source, block);
1054 let less = build.unary(Opcode::FNeg, args[0], f64);
1055 build.ret(&[less]);
1056
1057 let machine = Machine::x86_64(&SYSV);
1058 let out =
1059 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1060 .expect("every instruction has a rule");
1061
1062 let text = mir::print_func(&out, &names, ®S);
1063 assert!(text.contains("x64.xor_rr_64"), "{text}");
1064 assert!(!text.contains("sub"), "a negation is not a subtraction: {text}");
1065 }
1066
1067 #[test]
1068 fn the_flags_reach_the_frame() {
1069 let i32 = Type::int(32);
1070 let (mut names, mut source, block, args) = blank(&[i32]);
1071 Builder::new(&mut source, block).ret(&[args[0]]);
1072
1073 let machine = Machine::x86_64(&SYSV);
1074 let flags = Flags { frame_pointer: true, profile: Profile::No, ..Flags::default() };
1075 let out = compile(&mut source, &mut names, &machine, &Elsewhere::default(), flags)
1076 .expect("every instruction has a rule");
1077
1078 // A function that keeps a frame pointer keeps it whether it needed one or not, which is
1079 // what `-fno-omit-frame-pointer` is for and is the only thing this test is about.
1080 let text = mir::print_func(&out, &names, ®S);
1081 assert!(text.contains("x64.push_64 $rbp"), "{text}");
1082 assert!(text.contains("$rbp = x64.mov_rr_64 $rsp"), "{text}");
1083 }
1084
1085 #[test]
1086 fn a_target_says_which_machine_it_is_and_which_convention_it_uses() {
1087 let triple = |text: &str| text.parse::<rucc_target::Triple>().expect("a triple");
1088 let info = TargetInfo::new(triple("x86_64-unknown-linux-gnu"));
1089 let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
1090 assert!(std::ptr::eq(machine.conv, &SYSV));
1091
1092 let info = TargetInfo::new(triple("x86_64-pc-windows-msvc"));
1093 let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
1094 assert!(std::ptr::eq(machine.conv, &WIN64));
1095
1096 // Not a target this crate has a backend for, and saying so is the whole point: a caller
1097 // that got a machine here would compile x86-64 instructions for an AArch64 program.
1098 let info = TargetInfo::new(triple("aarch64-unknown-linux-gnu"));
1099 assert!(Machine::for_target(&info).is_none());
1100 }
1101}