rucc_codegen/lower.rs
1//! The selector: an IR function becomes a machine IR function.
2//!
3//! Design: `spec/10-backend.md` sections 10.2 and 10.3.
4//!
5//! What the matcher in [`crate::select`] does is answer one question about one term. What this
6//! does is ask it: walk a function, decide which terms are worth asking about, and build machine
7//! instructions out of what comes back. Nothing here decides what an IR term lowers to. That is
8//! in `rules/x86-64.rules` and it is proved before it is used, which is the whole point of the
9//! arrangement and the reason this file is short.
10//!
11//! # What it does with an instruction
12//!
13//! It tries the ways the instruction can be shown to the matcher, in order, and takes the first
14//! that a rule fires on. [`crate::term`] is what a way of showing one is, and the order is the
15//! most specific first: an operand that is a constant is offered as a constant before it is
16//! offered as a register, and an operand computed by an instruction of its own is offered as
17//! that instruction before it is offered as a register. A rule that wants an immediate too wide
18//! for the machine has a guard that turns it down, and the search carries on to the way of
19//! showing it that puts the constant in a register, which is the right answer and is one nobody
20//! had to write down.
21//!
22//! A constant is not lowered where it is written. It is materialized where a register for it is
23//! first wanted, which is what keeps a constant that every use folded into an immediate from
24//! leaving a dead instruction behind, and it also gives the value the shortest live range it
25//! could have. The instruction that materializes it comes from the rule set like everything else.
26//!
27//! # What it does not do yet
28//!
29//! Everything is in the general purpose registers, because every rule in the set is about an
30//! integer, so a call that passes a `double` and a function that returns one are both reported
31//! rather than lowered. So is an argument that travels on the stack, on either side of a call,
32//! and so is a call through an address rather than to a name.
33//!
34//! # A call
35//!
36//! Not a rule, because a rule pattern sees one term and what a call's operands are is whatever
37//! the signature made them. [`crate::abi`] builds one instead, out of the same description of the
38//! convention the arguments come from: the values it passes are reads constrained to the
39//! registers the convention places them in, what comes back is a write constrained to the
40//! register it comes back in, and every other register the callee is free to destroy is a write
41//! of that register and nothing else, which is all the allocator needs to keep a value out of it.
42//!
43//! What that costs the frame is an argument area, and nothing after selection could work out how
44//! big, so the size of the widest call is given back with the function. A function that makes no
45//! call at all is a leaf, and a leaf is the function that may use the red zone.
46//!
47//! # Where a block goes
48//!
49//! On the block, which is what machine IR does with an edge and is why the branches need no more
50//! rule language than the arithmetic did. A rule never names a block, so an unconditional jump
51//! has no rule at all and a conditional branch has one that is about its condition and nothing
52//! else. The arms are copied across after the block is filled, arguments and all, because an
53//! argument that is a constant is materialized where a register for it is first wanted and the
54//! end of the block is where an edge wants it.
55//!
56//! What this leaves behind is a function whose blocks are in the order the IR held them and whose
57//! branches are still branches on a register. Turning one into a `test` and a `jcc` is the block
58//! layout's, since which of the two arms falls through is the layout's answer, and [`crate::split`]
59//! has to run before allocation so that every edge carrying a value has somewhere to put it.
60//!
61//! A store and a return are the two things here that write no register. A store is emitted like
62//! everything else and the only difference is that there is no result to put anywhere, so the
63//! operands the target describes are all reads. A return is the same, and what it is for is its
64//! one operand: the target constrains it to the register the caller reads the value out of, and
65//! the allocator is what gets it there. The instruction that leaves is not chosen here at all,
66//! because the epilogue has to give the frame back first and [`crate::finish`] writes that after
67//! allocation, so a return of nothing is lowered to nothing.
68//!
69//! The entry block is the one block whose parameters are not block parameters here. They are the
70//! function's arguments, they are already somewhere when it starts, and [`crate::abi`] is what
71//! says where. An argument that arrives on the stack is reported rather than read, because where
72//! the stack put it is a distance into a frame and no frame exists until after allocation.
73//!
74//! Blocks are walked in the order the function holds them and a value is expected to be defined
75//! before it is used, which is true of the IR this is given because every pass before it keeps
76//! definitions ahead of uses.
77
78use std::fmt;
79
80use rucc_base::Interner;
81use rucc_ir::{Block, Def, Extra, Func, Inst, Opcode, Type, Value};
82use rucc_mir as mir;
83use rucc_target::x86_64;
84use rucc_target::{CallRegs, RegClass};
85
86use crate::abi::{self, Missing, Refused};
87use crate::frame::{Layout, Local};
88use crate::select::{Match, Piece, Rule, Table};
89use crate::term::{MAX_ARGS, PLAIN, Plan, Shown, Term, Terms};
90
91/// The prefix a rule file puts in front of a machine term, which says which target it belongs
92/// to and is not part of the opcode.
93const PREFIX: &str = "x64.";
94
95/// How wide an address is on this target, which is the width a cast between a pointer and an
96/// integer has to be at for the cast to be nothing.
97const ADDRESS_BITS: u32 = 64;
98
99/// Why a function could not be lowered.
100///
101/// One reason and then nothing. A function with no rule for something in it is a function this
102/// cannot finish, and the second thing it could not lower is not news.
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub enum Unsupported {
105 /// An instruction no rule fires on.
106 Inst {
107 /// The instruction that stopped it.
108 inst: Inst,
109 /// What the rule file would call it, or nothing if the rule language has no name for it
110 /// at all, which is what an instruction at a width nothing is written about looks like.
111 term: Option<&'static str>,
112 /// The opcode, which is what gets named when the rule language has no word for it.
113 ///
114 /// An opcode the rule language has no word for is exactly the opcode no rule lowers, so
115 /// without this the message would be empty in every case where somebody needs it.
116 opcode: Opcode,
117 /// What it produces, or nothing for an instruction that is only an effect.
118 ty: Option<Type>,
119 },
120 /// A parameter that does not arrive somewhere this can bring it in from.
121 ///
122 /// Not an instruction, which is why it is a separate arm: it is a fact about the signature
123 /// and there is nothing in the body of the function to point at.
124 Argument {
125 /// Its position in the signature.
126 index: usize,
127 /// What is wrong with where it arrives.
128 missing: Missing,
129 },
130 /// A call that passes or gives back a value this cannot put where the convention wants it.
131 Call {
132 /// The call.
133 inst: Inst,
134 /// Which value, and what is wrong with where it travels.
135 refused: Refused,
136 },
137 /// A stack slot whose size is not known until the function runs, which is what a variable
138 /// length array is.
139 ///
140 /// Not an instruction no rule covers. Growing the stack where the declaration stands is
141 /// arithmetic on the stack pointer, and everything else in the frame then has to be reached
142 /// through a frame pointer instead, and neither of those is a term a rule could be written
143 /// about or a thing the frame here knows how to lay out.
144 Dynamic {
145 /// The `alloca`.
146 inst: Inst,
147 },
148}
149
150impl Unsupported {
151 /// The instruction it is about, or nothing for the one arm that is about a signature.
152 ///
153 /// What a caller wants this for is the span. The function knows where every instruction in
154 /// it came from, so a caller holding both can point a message at the line somebody wrote
155 /// rather than at the file as a whole, and nothing here has to carry a span of its own.
156 pub fn inst(&self) -> Option<Inst> {
157 match *self {
158 Unsupported::Inst { inst, .. }
159 | Unsupported::Call { inst, .. }
160 | Unsupported::Dynamic { inst, .. } => Some(inst),
161 Unsupported::Argument { .. } => None,
162 }
163 }
164}
165
166impl fmt::Display for Unsupported {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 match *self {
169 Unsupported::Inst { term: Some(term), .. } => write!(f, "no rule lowers `{term}`"),
170 Unsupported::Inst { term: None, opcode, ty: Some(ty), .. } => {
171 write!(f, "no rule lowers a `{opcode}` producing a `{ty}`")
172 }
173 Unsupported::Inst { term: None, opcode, ty: None, .. } => {
174 write!(f, "no rule lowers a `{opcode}`")
175 }
176 Unsupported::Argument { index, missing } => {
177 write!(f, "parameter {index} {}", missing.why())
178 }
179 Unsupported::Call { refused: Refused { argument: Some(index), missing }, .. } => {
180 write!(f, "argument {index} of this call {}", missing.why())
181 }
182 Unsupported::Call { refused: Refused { argument: None, missing }, .. } => {
183 write!(f, "what this call gives back {}", missing.why())
184 }
185 Unsupported::Dynamic { .. } => {
186 f.write_str("nothing here grows the stack for a variable length array")
187 }
188 }
189 }
190}
191
192impl std::error::Error for Unsupported {}
193
194/// A lowered function, and what the frame needs that the machine IR does not hold.
195#[derive(Debug)]
196pub struct Lowered {
197 /// The function, in machine instructions.
198 pub func: mir::Func,
199 /// What it wants its stack to look like, which is separate from the function so that the two
200 /// can be read and written at the same time.
201 pub stack: Stack,
202}
203
204/// What a function's stack has to hold, as far as selection is able to say.
205///
206/// All of it is answered here because selection is where a call is built and where an `alloca`
207/// is read, and nothing after it could tell what either of them needed.
208#[derive(Debug, Default)]
209pub struct Stack {
210 /// How many bytes the widest call in the function needs below the stack pointer for the
211 /// arguments it passes there, or `None` for a function that makes no call at all.
212 ///
213 /// `None` is a leaf, which is the function that may use the red zone and the one whose stack
214 /// pointer does not have to be left aligned for anybody.
215 pub calls: Option<u32>,
216 /// The memory the function asked for itself, one entry for every `alloca` in it, in the order
217 /// the walk reached them.
218 pub locals: Vec<Local>,
219 /// Which instruction computes the address of which of those locals.
220 ///
221 /// An address in the frame is a distance from the stack pointer, and there is no frame until
222 /// after allocation, so the instruction is written here with nothing in its displacement and
223 /// [`crate::finish`] writes the number in once [`crate::frame::Frame`] knows it.
224 pub addresses: Vec<(mir::Inst, usize)>,
225 /// Which instruction reads which of the arguments the caller passed on the stack, as how far up
226 /// the caller's argument area it reads.
227 ///
228 /// Waiting on [`crate::finish`] for the same reason the addresses above are, and on one thing
229 /// more: where the caller's argument area is from inside this function depends on whether the
230 /// prologue had to force the stack pointer's alignment, so which register the load reads
231 /// through is not settled here either.
232 pub arguments: Vec<(mir::Inst, u32)>,
233}
234
235impl Stack {
236 /// The layout given, with the three fields only the lowering knows the answer to filled in.
237 ///
238 /// Everything else in a layout comes from the flags the function is compiled under or from the
239 /// allocation, so this takes one and returns it rather than building one.
240 #[must_use]
241 pub fn layout<'a>(&'a self, base: Layout<'a>) -> Layout<'a> {
242 Layout {
243 leaf: self.calls.is_none(),
244 outgoing: self.calls.unwrap_or(0),
245 locals: &self.locals,
246 ..base
247 }
248 }
249}
250
251/// The x86-64 machine IR for that function.
252///
253/// # Errors
254///
255/// The first instruction no rule fires on, which today is anything at a width the rule set is not
256/// written at, a parameter that does not arrive in a register this can read, or a call that
257/// passes something this cannot put where the convention wants it.
258pub fn func(
259 source: &Func,
260 names: &mut Interner,
261 conv: &'static CallRegs,
262) -> Result<Lowered, Unsupported> {
263 Lowering::new(source, names, conv).run()
264}
265
266/// One function being lowered.
267struct Lowering<'a> {
268 source: &'a Func,
269 names: &'a mut Interner,
270 out: mir::Func,
271 /// The machine register each IR value is in, once it has one.
272 regs: Vec<Option<mir::Reg>>,
273 /// For a constant that has been written into a register, the block it was written into,
274 /// which is the only block that register is any good in.
275 written: Vec<Option<mir::Block>>,
276 /// How many times each IR value is read, which is what says whether an instruction may be
277 /// folded into the one that reads it.
278 uses: Vec<u32>,
279 /// The block being filled.
280 at: Option<mir::Block>,
281 /// The machine IR block each IR block became.
282 blocks: Vec<Option<mir::Block>>,
283 /// The class an address is in, which is the general purpose one and is not a question: every
284 /// register an addressing mode names holds part of an address, and there is no machine here
285 /// that computes an address anywhere but in this file. Which class a *value* is in is
286 /// [`Lowering::class_of`], and it is a question, because a float is in the other one.
287 gpr: RegClass,
288 /// Where the convention this function is compiled for puts things, which is read for the
289 /// arguments and for the calls.
290 conv: &'static CallRegs,
291 /// What the function wants its stack to look like, filled in as the walk finds out.
292 stack: Stack,
293}
294
295impl<'a> Lowering<'a> {
296 fn new(source: &'a Func, names: &'a mut Interner, conv: &'static CallRegs) -> Self {
297 let counts = source.counts();
298 let name = source.name;
299 let mut uses = vec![0; counts.values];
300 for block in source.blocks() {
301 for inst in source.insts(block) {
302 for &arg in &source[source[inst].args] {
303 uses[arg.index()] += 1;
304 }
305 for call in source.successors(inst) {
306 for &arg in &source[call.args] {
307 uses[arg.index()] += 1;
308 }
309 }
310 }
311 }
312 Self {
313 source,
314 names,
315 out: mir::Func::new(name),
316 regs: vec![None; counts.values],
317 written: vec![None; counts.values],
318 blocks: vec![None; counts.blocks],
319 uses,
320 at: None,
321 gpr: x86_64::GPR,
322 conv,
323 stack: Stack::default(),
324 }
325 }
326
327 fn run(mut self) -> Result<Lowered, Unsupported> {
328 // Every block before any of them is filled, because a block that jumps forward has to
329 // name the block it jumps to and a machine IR block is named by a handle rather than by
330 // the IR block it came from.
331 for block in self.source.blocks() {
332 let out = self.out.create_block();
333 self.blocks[block.index()] = Some(out);
334 }
335 for block in self.source.blocks() {
336 self.block(block)?;
337 }
338 Ok(Lowered { func: self.out, stack: self.stack })
339 }
340
341 /// One block: its parameters, then every instruction in it that is not folded into another.
342 fn block(&mut self, block: Block) -> Result<(), Unsupported> {
343 let out = self.out_block(block);
344 self.at = Some(out);
345 if self.source.entry() == Some(block) {
346 self.arrive(block, out)?;
347 } else {
348 for ¶m in self.source[block].params.iter() {
349 let reg = self.out.append_param(out, self.class_of(self.source[param].ty));
350 self.regs[param.index()] = Some(reg);
351 }
352 }
353
354 // What each instruction matched, and which instructions were folded into another. The
355 // instruction that is folded comes before the one that folds it, so the decision has to
356 // be made for the whole block before any of it is written, and it is made backwards: an
357 // instruction that has been folded into a later one does not get to fold anything into
358 // itself, because the rule that took it only reached one level down.
359 let insts: Vec<Inst> = self.source.insts(block).collect();
360 let mut found: Vec<Option<Match<Term>>> = (0..insts.len()).map(|_| None).collect();
361 let mut folded: Vec<Inst> = Vec::new();
362 for (index, &inst) in insts.iter().enumerate().rev() {
363 if folded.contains(&inst) {
364 continue;
365 }
366 if let Some((plan, matched)) = self.select(inst) {
367 folded.extend(self.folds(inst, plan));
368 found[index] = Some(matched);
369 }
370 }
371
372 for (&inst, matched) in insts.iter().zip(found) {
373 if folded.contains(&inst) || self.writes_nothing(inst) {
374 continue;
375 }
376 // A call is built from the convention rather than matched, which is why it is the one
377 // opcode looked at by name here. Through an address it is a different instruction and
378 // the same convention, so the two arrive at the same place and differ in one line of
379 // it.
380 match self.source[inst].opcode {
381 Opcode::Call | Opcode::CallIndirect => {
382 self.called(inst)?;
383 continue;
384 }
385 // Built from the frame rather than matched, for the same shape of reason a call
386 // is built from the convention: what a rule replaces a term with is instructions,
387 // and what an `alloca` needs first is bytes, which the rule language has no way
388 // to ask for.
389 Opcode::Alloca => {
390 self.reserve(inst)?;
391 continue;
392 }
393 // The address of a name, built here for the same reason an `alloca` is: what a
394 // rule replaces a term with is instructions over values, and the operand of this
395 // one is a symbol, which is a thing the rule language has no way to bind and the
396 // solver has no way to say anything about. There is nothing in `lea sym(%rip)` a
397 // proof over bitvectors could discharge, because what makes it the right answer
398 // is the relocation and what the linker does with it.
399 Opcode::GlobalAddr => {
400 self.address_of(inst)?;
401 continue;
402 }
403 // A cast between a pointer and an integer of the same width, which on this
404 // machine is every one the front end writes. No instruction at all, so no rule
405 // could name one.
406 Opcode::PtrToInt | Opcode::IntToPtr => {
407 self.rename(inst)?;
408 continue;
409 }
410 _ => {}
411 }
412 let matched = matched.ok_or_else(|| self.unsupported(inst))?;
413 self.emit(inst, &matched)?;
414 }
415 self.edges(block, out)
416 }
417
418 /// One call, which is built from the convention rather than matched against the table for the
419 /// same reason the arguments of the function itself are.
420 ///
421 /// The arguments are read before the call is built, which is what materializes a constant
422 /// argument into a register, since no call passes an immediate.
423 ///
424 /// A call to a name and a call through an address are both here, and what tells them apart is
425 /// the opcode rather than whether a callee was recorded, which is the same thing the verifier
426 /// reads. Through an address the first operand is the address and the arguments are the ones
427 /// behind it, and everything after that is the same: where each argument goes, where the value
428 /// comes back and which registers are gone across it are the convention's answers and the
429 /// convention does not ask what is being called.
430 fn called(&mut self, inst: Inst) -> Result<(), Unsupported> {
431 let data = &self.source[inst];
432 let Extra::Call(info) = data.extra else { return Err(self.unsupported(inst)) };
433 let info = self.source[info];
434 let indirect = data.opcode == Opcode::CallIndirect;
435
436 let values: Vec<Value> = self.source[data.args].to_vec();
437 let callee = if indirect {
438 let &address = values.first().ok_or_else(|| self.unsupported(inst))?;
439 abi::Callee::Through(self.reg_of(address)?)
440 } else {
441 abi::Callee::Named(info.callee.ok_or_else(|| self.unsupported(inst))?)
442 };
443
444 let mut args = Vec::with_capacity(values.len());
445 for value in values.into_iter().skip(usize::from(indirect)) {
446 args.push((self.source[value].ty, self.reg_of(value)?));
447 }
448 let signature = &self.source[info.signature];
449 let variadic = signature.variadic;
450 let returns = signature.return_types().next();
451 // More than one value back is the convention's answer rather than a term's, the same way
452 // a return of two values is, and nothing here has a name for it.
453 if signature.return_types().count() > 1 {
454 return Err(self.unsupported(inst));
455 }
456
457 let block = self.at.expect("a block is being filled");
458 let what = abi::Calling { callee, args: &args, returns, variadic };
459 let made = abi::call(&mut self.out, block, &what, self.conv, self.names)
460 .map_err(|refused| Unsupported::Call { inst, refused })?;
461 let calls = &mut self.stack.calls;
462 *calls = Some(calls.unwrap_or(0).max(made.outgoing));
463 if let (Some(result), Some(reg)) = (data.first_result, made.result) {
464 self.regs[result.index()] = Some(reg);
465 }
466 Ok(())
467 }
468
469 /// One `alloca`: the bytes it asks for go on the list the frame is laid out from, and the
470 /// address of them is one instruction.
471 ///
472 /// The instruction is a `lea` off the stack pointer, which is the one register that reaches
473 /// the frame in every function, and its displacement is left at nothing because there is no
474 /// frame yet. Which instruction is waiting for which local is remembered, and
475 /// [`crate::finish`] fills the numbers in after [`crate::frame::Frame`] has placed them.
476 ///
477 /// There is deliberately no rule for `alloca` and no name for one in [`crate::term`], and
478 /// that is what stops it being folded into something else. An operand shown as the
479 /// instruction that computed it is offered to the matcher by its name, so an `alloca` with no
480 /// name is one no pattern can reach past, and the address it computes is always in a register
481 /// by the time anything reads it.
482 fn reserve(&mut self, inst: Inst) -> Result<(), Unsupported> {
483 let data = &self.source[inst];
484 // A variable length array carries the size it wants as an operand rather than in the
485 // instruction, which is the whole of what tells the two apart here.
486 if !self.source[data.args].is_empty() {
487 return Err(Unsupported::Dynamic { inst });
488 }
489 let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
490 let info = self.source[mem];
491 let size = u32::try_from(info.size).map_err(|_| Unsupported::Dynamic { inst })?;
492 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
493
494 // At least one, because the frame divides by the alignment and an object with no
495 // alignment at all is one the front end had nothing to say about rather than one that may
496 // go anywhere.
497 let index = self.stack.locals.len();
498 self.stack.locals.push(Local { size, align: info.align.max(1) });
499
500 let block = self.at.expect("a block is being filled");
501 let reg = self.new_reg(result);
502 let span = self.source.span(inst);
503 let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
504 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
505 let made =
506 self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
507 self.stack.addresses.push((made, index));
508 Ok(())
509 }
510
511 /// The address of a name: one `lea` off the instruction pointer, with the name on it.
512 ///
513 /// The same instruction an `alloca` gets and for a related reason. An address that is not in
514 /// the program is a `lea` of an addressing mode that names no register, and the mode carries
515 /// the symbol so that [`rucc_asm`] can write it relative to `%rip` and leave the relocation
516 /// for the assembler. Both halves of that already existed: the printer writes `sym(%rip)` and
517 /// the encoder emits the relocation, because a call to a name the file does not define needed
518 /// them first.
519 ///
520 /// There is deliberately no name for this in [`crate::term`], which is what stops the address
521 /// being folded into the instruction that reads it. Folding it is the right thing to do and
522 /// is what turns a load of a global from two instructions into one, but it is a separate
523 /// question about addressing modes and issue #282 is it. Until then the address is in a
524 /// register before anything uses it, which is correct and one instruction longer.
525 ///
526 /// What this does not do is give the name anything to refer to. A module carries its globals
527 /// and nothing writes them out, so a file that defines the variable it reads compiles to a
528 /// reference the linker cannot resolve. Issue #293 is the other half.
529 fn address_of(&mut self, inst: Inst) -> Result<(), Unsupported> {
530 let data = &self.source[inst];
531 let Extra::Symbol(symbol) = data.extra else { return Err(self.unsupported(inst)) };
532 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
533
534 let block = self.at.expect("a block is being filled");
535 let reg = self.new_reg(result);
536 let span = self.source.span(inst);
537 let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
538 self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::of(symbol)).finish();
539 Ok(())
540 }
541
542 /// A conversion that converts nothing: the result is the operand under another type.
543 ///
544 /// `ptrtoint` and `inttoptr` at one width are the whole of this. An address on this machine is
545 /// an integer as wide as the machine addresses, so a cast between the two changes what the
546 /// type system calls the value and changes nothing about the value, and the register holding
547 /// it is the register that already held it. The front end never writes either of them at any
548 /// other width, because it widens or narrows around the cast rather than through it, so the
549 /// two widths disagreeing here means the IR came from somewhere else and is refused rather
550 /// than guessed at.
551 ///
552 /// Reading the operand first is what materializes it when it is a constant, which is the case
553 /// that matters: a null pointer is an `inttoptr` of zero, and that zero has to reach a
554 /// register before anything can call it an address.
555 fn rename(&mut self, inst: Inst) -> Result<(), Unsupported> {
556 let data = &self.source[inst];
557 let [arg] = self.source[data.args] else { return Err(self.unsupported(inst)) };
558 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
559 if !self.is_address_width(self.source[arg].ty)
560 || !self.is_address_width(self.source[result].ty)
561 {
562 return Err(self.unsupported(inst));
563 }
564 let reg = self.reg_of(arg)?;
565 self.regs[result.index()] = Some(reg);
566 Ok(())
567 }
568
569 /// Whether a type is the width an address is, which is what makes a cast to or from one free.
570 fn is_address_width(&self, ty: Type) -> bool {
571 ty.is_ptr() || (ty.is_int() && ty.bits() == ADDRESS_BITS)
572 }
573
574 /// Where a block goes, which in machine IR is on the block rather than on its terminator.
575 ///
576 /// That is why no rule ever names a block: a branch is selected for what it reads and the
577 /// edges are copied across here, arguments and all. The arguments are read last, after every
578 /// instruction of the block is written, because an argument that is a constant is
579 /// materialized where it is first wanted and the end of the block is where an edge wants it.
580 ///
581 /// Which is not quite the end. A block that leaves two ways has the branch as its last
582 /// instruction, and anything appended after a branch is something the branch has already
583 /// jumped past, so a constant materialized here would be a register the block below reads and
584 /// nothing ever writes. The branch is put back on the end when that happened, which is the
585 /// only reordering anything in this crate does and is why the branch is remembered before a
586 /// single argument is read.
587 fn edges(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
588 let Some(term) = self.source.terminator(block) else { return Ok(()) };
589 let branch =
590 if self.source[term].opcode == Opcode::BrIf { self.out.terminator(out) } else { None };
591
592 let calls: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
593 let mut succs = Vec::with_capacity(calls.len());
594 for call in calls {
595 let args: Vec<Value> = self.source[call.args].to_vec();
596 let mut regs = Vec::with_capacity(args.len());
597 for value in args {
598 regs.push(self.reg_of(value)?);
599 }
600 succs.push(mir::BlockCall { block: self.out_block(call.block), args: regs });
601 }
602 if let Some(branch) = branch {
603 if self.out.terminator(out) != Some(branch) {
604 self.out.remove_inst(branch);
605 self.out.append_inst(out, branch);
606 }
607 }
608 *self.out.succs_mut(out) = succs;
609 Ok(())
610 }
611
612 /// The machine IR block an IR block became.
613 fn out_block(&self, block: Block) -> mir::Block {
614 self.blocks[block.index()].expect("every block was created before any was filled")
615 }
616
617 /// The parameters of the entry block, which are the function's arguments.
618 ///
619 /// They are not block parameters in the machine IR and they cannot be. A block parameter is
620 /// given its value by a move on the edge into the block, and there is no edge into an entry
621 /// block, so what arrives in a function is the convention's to say. [`crate::abi`] is what
622 /// says it.
623 ///
624 /// The ones past the last register arrived in the caller's memory and are read out of it, and
625 /// the loads that read them come back here so that the frame can finish them the way it
626 /// finishes an `alloca`.
627 fn arrive(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
628 let params = self.source[block].params.clone();
629 let types: Vec<Type> = params.iter().map(|&value| self.source[value].ty).collect();
630 let arrived = abi::entry(&mut self.out, out, &types, self.conv, self.names)
631 .map_err(|(index, missing)| Unsupported::Argument { index, missing })?;
632 for (¶m, reg) in params.iter().zip(arrived.regs) {
633 self.regs[param.index()] = Some(reg);
634 }
635 self.stack.arguments.extend(arrived.stack);
636 Ok(())
637 }
638
639 /// Whether an instruction is one no machine instruction is written for where it stands.
640 ///
641 /// Four of them, and none is a lowering decision, which is why none is a rule. A constant is
642 /// written where a register for it is first wanted rather than where the IR put it, and every
643 /// reader of one may have folded it into an immediate, in which case nowhere is the right
644 /// place. A return of nothing has nothing to put anywhere: the epilogue gives the frame back
645 /// and leaves, and it is appended to every block with no successors long after this has
646 /// finished, so a return with a value is one instruction here and a return without one is
647 /// none. An unconditional jump is the third, and there is even less of it: the edge is on the
648 /// block, and whether the block it goes to is the next one and needs no jump at all is the
649 /// block layout's answer rather than this one's.
650 ///
651 /// The fourth is a point control does not arrive at, in both of the forms the IR has for it:
652 /// the `unreachable` terminator the front end puts at the end of a function whose body can run
653 /// off the bottom, and the `unreachable_hint` a call to `__builtin_unreachable` becomes. What
654 /// to write for a place nothing reaches is a question with no wrong answer, and nothing is the
655 /// smallest one and the one gcc 16.2.0 gives at `-O0`. The terminator leaves the block with no
656 /// successors, so the epilogue lands at the end of it the way it does on any other block that
657 /// goes nowhere, and the function cannot fall out of its own last instruction into whatever
658 /// the assembler puts next.
659 fn writes_nothing(&self, inst: Inst) -> bool {
660 let data = &self.source[inst];
661 match data.opcode {
662 Opcode::IConst | Opcode::Jump | Opcode::Unreachable | Opcode::UnreachableHint => true,
663 Opcode::Return => self.source[data.args].is_empty(),
664 _ => false,
665 }
666 }
667
668 /// The rule that fires on an instruction, and what it bound.
669 ///
670 /// The plans are tried in order and the first that matches wins, which is the maximal munch
671 /// `spec/10-backend.md` asks for: a plan that offers more to the matcher is tried before one
672 /// that offers less.
673 fn select(&self, inst: Inst) -> Option<(Plan, Match<Term>)> {
674 for plan in self.plans(inst) {
675 let terms = Terms::new(self.source, inst, plan);
676 if let Some(matched) = TABLE.find(&terms, Term::Root) {
677 return Some((plan, matched));
678 }
679 }
680 None
681 }
682
683 /// Every way this instruction can be shown to the matcher, most offered first.
684 fn plans(&self, inst: Inst) -> Vec<Plan> {
685 let args = &self.source[self.source[inst].args];
686 let mut plans = vec![PLAIN];
687 for (index, &arg) in args.iter().enumerate().take(MAX_ARGS) {
688 let mut ways = Vec::new();
689 if self.foldable(inst, arg) {
690 ways.push(Shown::Expand);
691 }
692 if Terms::new(self.source, inst, PLAIN).constant(arg).is_some() {
693 ways.push(Shown::Const);
694 }
695 ways.push(Shown::Reg);
696 plans = plans
697 .into_iter()
698 .flat_map(|plan| {
699 ways.iter().map(move |&way| {
700 let mut next = plan;
701 next[index] = way;
702 next
703 })
704 })
705 .collect();
706 }
707 plans
708 }
709
710 /// Whether an operand may be shown as the instruction that computed it.
711 ///
712 /// It has to be in the same block, because a rule that folds one instruction into another
713 /// moves the work to where the second one is. It has to be read only by this instruction,
714 /// because folding it does not delete it for anybody else and doing the work twice is not a
715 /// saving. And it has to be something rather than a block parameter, and not a constant,
716 /// which is shown as a constant instead.
717 fn foldable(&self, into: Inst, value: Value) -> bool {
718 let Def::Result { inst, .. } = self.source[value].def else { return false };
719 if self.source[inst].opcode == Opcode::IConst || self.uses[value.index()] != 1 {
720 return false;
721 }
722 self.source.block_of(inst).is_some()
723 && self.source.block_of(inst) == self.source.block_of(into)
724 }
725
726 /// The instructions a match folded into the one it matched.
727 ///
728 /// The plan is what says this, not the bindings: a binding is a register or a number either
729 /// way, and an operand shown as the instruction that computed it is one no rule could have
730 /// matched without taking that instruction, because the plan offered the matcher nothing
731 /// else to call it.
732 fn folds(&self, inst: Inst, plan: Plan) -> Vec<Inst> {
733 let args = &self.source[self.source[inst].args];
734 args.iter()
735 .take(MAX_ARGS)
736 .enumerate()
737 .filter(|&(index, _)| plan[index] == Shown::Expand)
738 .filter_map(|(_, &arg)| match self.source[arg].def {
739 Def::Result { inst, .. } => Some(inst),
740 Def::Param { .. } => None,
741 })
742 .collect()
743 }
744
745 /// Build the machine instruction a match calls for.
746 fn emit(&mut self, inst: Inst, matched: &Match<Term>) -> Result<(), Unsupported> {
747 let rule: &Rule = TABLE.rule(matched);
748 let pieces = rule.replacement;
749 let Some(Piece::App { head, arity }) = pieces.first() else {
750 return Err(self.unsupported(inst));
751 };
752 let opcode = head.strip_prefix(PREFIX).ok_or_else(|| self.unsupported(inst))?;
753 let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
754
755 let mut read = Read::default();
756 let mut at = 1;
757 for _ in 0..*arity {
758 at = self.read(inst, pieces, at, &matched.bindings, &mut read)?;
759 }
760
761 let descs = form.operands();
762 let writes = descs.iter().take_while(|desc| desc.role.is_def()).count();
763 if descs.len() - writes != read.regs.len() {
764 return Err(self.unsupported(inst));
765 }
766
767 // The first thing the instruction writes is what it computes, and any others are
768 // registers the machine destroys on the way, which are fresh because nothing else is in
769 // them and nothing reads them. An instruction that writes nothing at all is one whose
770 // whole purpose is its effect, which is what a store is, and there is no result to put
771 // anywhere.
772 let mut regs = Vec::new();
773 if writes > 0 {
774 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
775 regs.push(self.new_reg(result));
776 // The rest are the registers the machine destroys on the way, and the class each is in
777 // is the one the instruction's description gives it rather than a guess, so that an
778 // instruction that wrecks a register in the other file says so.
779 regs.extend(descs[1..writes].iter().map(|desc| self.out.new_vreg(desc.class)));
780 } else if self.source[inst].first_result.is_some() {
781 // A rule that throws away a value the IR gave a name to would leave every reader of
782 // that name with nothing to read, so it is a rule this and the target disagree about.
783 return Err(self.unsupported(inst));
784 }
785 regs.extend(read.regs.iter().copied());
786
787 let block = self.at.expect("a block is being filled");
788 let opcode = mir::Opcode::new(self.names.intern(head));
789 let mut build = self.out.build(block, opcode).at(self.source.span(inst));
790 for (desc, reg) in descs.iter().zip(regs) {
791 let operand = mir::Operand {
792 reg,
793 class: desc.class,
794 role: desc.role,
795 constraint: desc.constraint,
796 };
797 build = build.operand(operand);
798 }
799 if let Some(mem) = read.mem {
800 build = build.mem(mem);
801 }
802 if let Some(imm) = read.imm {
803 build = build.imm(imm);
804 }
805 build.finish();
806 Ok(())
807 }
808
809 /// Read one argument of a replacement, which is a register, a number or an address.
810 ///
811 /// Gives back the position after it, because a replacement is flat and an address takes
812 /// arguments of its own.
813 fn read(
814 &mut self,
815 inst: Inst,
816 pieces: &'static [Piece],
817 at: usize,
818 bindings: &[Term],
819 out: &mut Read,
820 ) -> Result<usize, Unsupported> {
821 match pieces.get(at) {
822 Some(Piece::Int(value)) => {
823 out.imm = i64::try_from(*value).ok();
824 Ok(at + 1)
825 }
826 Some(Piece::Var { index, .. }) => {
827 match bindings.get(*index) {
828 Some(&Term::Reg(value)) => {
829 let reg = self.reg_of(value)?;
830 out.regs.push(reg);
831 }
832 Some(&Term::Num(value)) => out.imm = i64::try_from(value).ok(),
833 // A pattern binds a register or a number and nothing else, so this is a
834 // rule the matcher and this file disagree about.
835 _ => return Err(self.unsupported(inst)),
836 }
837 Ok(at + 1)
838 }
839 Some(Piece::App { head, arity }) => {
840 let kind = x86_64::address(head).ok_or_else(|| self.unsupported(inst))?;
841 let mut inner = Read::default();
842 let mut next = at + 1;
843 for _ in 0..*arity {
844 next = self.read(inst, pieces, next, bindings, &mut inner)?;
845 }
846 let mem = address(kind, &inner, self.gpr).ok_or_else(|| self.unsupported(inst))?;
847 out.mem = Some(mem);
848 Ok(next)
849 }
850 None => Err(self.unsupported(inst)),
851 }
852 }
853
854 /// The register a value is in, materializing it if it is a constant that has not been put in
855 /// one yet.
856 ///
857 /// A constant is written where it is wanted rather than where the IR defined it, and where it
858 /// is wanted is a block that need not be the one the IR defined it in. So the register holding
859 /// one is only good inside the block it was written into, and a second block that wants the
860 /// same constant gets its own. Anything else is a register read where nothing wrote it: the
861 /// IR guarantees a definition dominates its uses, and this moved the definition.
862 ///
863 /// Writing the number again is also the right answer and not merely the safe one. It is one
864 /// instruction that reads nothing, which is cheaper than holding a register live across a
865 /// branch for it, and it is what a rematerializing allocator would do with the value anyway.
866 fn reg_of(&mut self, value: Value) -> Result<mir::Reg, Unsupported> {
867 let constant = match self.source[value].def {
868 Def::Result { inst, .. } => {
869 (self.source[inst].opcode == Opcode::IConst).then_some(inst)
870 }
871 Def::Param { .. } => None,
872 };
873 let here = self.at.expect("a block is being filled");
874 if let Some(reg) = self.regs[value.index()] {
875 if constant.is_none() || self.written[value.index()] == Some(here) {
876 return Ok(reg);
877 }
878 }
879 if let Some(inst) = constant {
880 // Cleared so that the register the constant is written into is a new one rather than
881 // the one the block above wrote, which is still being read up there.
882 self.regs[value.index()] = None;
883 let matched = self
884 .select(inst)
885 .map(|(_, matched)| matched)
886 .ok_or_else(|| self.unsupported(inst))?;
887 self.emit(inst, &matched)?;
888 self.written[value.index()] = Some(here);
889 return Ok(self.regs[value.index()].expect("a constant is written into a register"));
890 }
891 Ok(self.new_reg(value))
892 }
893
894 /// Which register file a value of that type lives in.
895 ///
896 /// The vector one for the two float widths the machine has scalar instructions for, and the
897 /// general purpose one for everything else. A `long double` is in neither, and it is here
898 /// rather than in the vector class on purpose: it would be put in a register that cannot hold
899 /// it, and there is no rule that names one, so the instruction computing it is reported. The
900 /// wrong class would make that a wrong program instead of a refused one.
901 fn class_of(&self, ty: Type) -> RegClass {
902 match crate::term::float_slot(ty) {
903 Some(_) => self.conv.sse_class,
904 None => self.gpr,
905 }
906 }
907
908 /// A fresh register for a value, which is what the instruction computing it writes.
909 fn new_reg(&mut self, value: Value) -> mir::Reg {
910 if let Some(reg) = self.regs[value.index()] {
911 return reg;
912 }
913 let reg = self.out.new_vreg(self.class_of(self.source[value].ty));
914 self.regs[value.index()] = Some(reg);
915 reg
916 }
917
918 fn unsupported(&self, inst: Inst) -> Unsupported {
919 let data = &self.source[inst];
920 Unsupported::Inst {
921 inst,
922 term: Terms::new(self.source, inst, PLAIN).name(inst),
923 opcode: data.opcode,
924 ty: data.first_result.map(|result| self.source[result].ty),
925 }
926 }
927}
928
929/// What the arguments of one replacement came to.
930#[derive(Debug, Default)]
931struct Read {
932 regs: Vec<mir::Reg>,
933 imm: Option<i64>,
934 mem: Option<mir::Mem>,
935}
936
937/// The addressing mode an address constructor's arguments make.
938///
939/// One arm per constructor rather than a question asked of the kind, because what the arguments
940/// mean is the whole of what tells the four apart: the same register is a base in one and an
941/// index in another, and the same constant is a scale in one and a displacement in another.
942fn address(kind: x86_64::Address, read: &Read, gpr: RegClass) -> Option<mir::Mem> {
943 let mut regs = read.regs.iter().copied().map(|reg| mir::Operand::read(reg, gpr));
944 match kind {
945 x86_64::Address::BaseIndexScale => {
946 let base = regs.next()?;
947 let index = regs.next()?;
948 Some(mir::Mem::at(base).indexed(index, u8::try_from(read.imm?).ok()?))
949 }
950 x86_64::Address::IndexScale => Some(mir::Mem {
951 base: None,
952 index: Some(regs.next()?),
953 scale: u8::try_from(read.imm?).ok()?,
954 disp: 0,
955 symbol: None,
956 }),
957 x86_64::Address::Base => Some(mir::Mem::at(regs.next()?)),
958 // The rule that writes this has a guard saying the constant fits, so a displacement that
959 // does not is a rule and a target that disagree rather than a program this cannot compile.
960 x86_64::Address::BaseOffset => {
961 Some(mir::Mem { disp: i32::try_from(read.imm?).ok()?, ..mir::Mem::at(regs.next()?) })
962 }
963 }
964}
965
966/// The table this selector matches with.
967///
968/// One target for now, because one target has a rule file. Which table to use becomes a question
969/// the moment a second one does, and the answer will be the target the session was given rather
970/// than a constant here.
971static TABLE: &Table = &crate::select::x86_64::TABLE;
972
973#[cfg(test)]
974mod tests {
975 use rucc_ir::{Builder, CallInfo, Flags, InstData, MemInfo, MemOrder, Signature, Type};
976 use rucc_regalloc::assign::Env;
977 use rucc_target::x86_64::{FRAME, REGS, SYSV};
978
979 use super::*;
980 use crate::finish::finish;
981 use crate::frame::{Frame, Incoming, Layout};
982
983 /// A function of as many 64 bit parameters as the test wants, and the block they are in.
984 fn blank(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
985 let mut names = Interner::new();
986 let mut func = Func::new(names.intern("f"), Signature::new());
987 let block = func.create_block();
988 let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
989 (names, func, block, values)
990 }
991
992 /// An ordinary access: not atomic, and aligned enough that nothing here has an opinion.
993 /// Neither field reaches selection, which is the point of saying it once here.
994 fn plain() -> MemInfo {
995 MemInfo { size: 0, align: 1, order: MemOrder::NotAtomic, tbaa: None }
996 }
997
998 /// What the allocator is given: every integer register the convention offers except two, held
999 /// back so that a move on an edge has somewhere to break a cycle and a spilled value has
1000 /// somewhere to be read into. Which two does not matter, and holding back the last two the
1001 /// convention would reach for leaves every expectation below unchanged.
1002 fn env() -> Env {
1003 const SCRATCH: [rucc_target::PhysReg; 2] = [x86_64::R10, x86_64::R11];
1004 let order: Vec<rucc_target::PhysReg> =
1005 SYSV.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
1006 Env::new().with(x86_64::GPR, &order, &SCRATCH)
1007 }
1008
1009 /// The machine IR text a function lowers to.
1010 fn lower(names: &mut Interner, source: &Func) -> String {
1011 let out = func(source, names, &SYSV).expect("every instruction has a rule");
1012 mir::print_func(&out.func, names, ®S)
1013 }
1014
1015 #[test]
1016 fn an_addition_of_two_registers_is_one_instruction() {
1017 let i32 = Type::int(32);
1018 let (mut names, mut func, block, args) = blank(&[i32, i32]);
1019 let mut build = Builder::new(&mut func, block);
1020 build.binary(Opcode::Add, args[0], args[1], Flags::default());
1021
1022 assert_eq!(
1023 lower(&mut names, &func),
1024 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
1025 %1:gpr($rsi) = x64.arg_val_32\n %2:gpr(reuse 1) = x64.add_rr_32 %0, %1\n}\n"
1026 );
1027 }
1028
1029 #[test]
1030 fn a_constant_operand_becomes_an_immediate() {
1031 let i32 = Type::int(32);
1032 let (mut names, mut func, block, args) = blank(&[i32]);
1033 let mut build = Builder::new(&mut func, block);
1034 let seven = build.iconst(i32, 7);
1035 build.binary(Opcode::Add, args[0], seven, Flags::default());
1036
1037 // The constant is in the instruction and nothing was written to hold it, which is what
1038 // materializing one where a register for it is wanted buys.
1039 assert_eq!(
1040 lower(&mut names, &func),
1041 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
1042 %1:gpr(reuse 1) = x64.add_ri_32 %0, 7\n}\n"
1043 );
1044 }
1045
1046 #[test]
1047 fn a_constant_too_wide_for_an_immediate_goes_into_a_register() {
1048 let i64 = Type::int(64);
1049 let (mut names, mut func, block, args) = blank(&[i64]);
1050 let mut build = Builder::new(&mut func, block);
1051 let big = build.iconst(i64, i128::from(i32::MAX) + 1);
1052 build.binary(Opcode::Add, args[0], big, Flags::default());
1053
1054 // Nobody wrote this fallback down. The rule that takes an immediate has a guard that
1055 // turns a number this wide down, so it does not fire, and the next way of showing the
1056 // operand puts it in a register.
1057 assert_eq!(
1058 lower(&mut names, &func),
1059 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1060 %1:gpr = x64.mov_ri_64 2147483648\n %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n}\n"
1061 );
1062 }
1063
1064 #[test]
1065 fn an_index_calculation_folds_into_an_address() {
1066 let i64 = Type::int(64);
1067 let (mut names, mut func, block, args) = blank(&[i64, i64]);
1068 let mut build = Builder::new(&mut func, block);
1069 let four = build.iconst(i64, 4);
1070 let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
1071 build.binary(Opcode::Add, args[0], scaled, Flags::default());
1072
1073 // Three IR instructions and one machine instruction. The multiply is gone because the
1074 // rule that matched reached down and took it.
1075 assert_eq!(
1076 lower(&mut names, &func),
1077 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1078 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr = x64.lea_64 [%0 + %1*4]\n}\n"
1079 );
1080 }
1081
1082 #[test]
1083 fn an_instruction_read_twice_is_not_folded_into_either_reader() {
1084 let i64 = Type::int(64);
1085 let (mut names, mut func, block, args) = blank(&[i64, i64]);
1086 let mut build = Builder::new(&mut func, block);
1087 let four = build.iconst(i64, 4);
1088 let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
1089 let first = build.binary(Opcode::Add, args[0], scaled, Flags::default());
1090 build.binary(Opcode::Add, first, scaled, Flags::default());
1091
1092 // Folding it into both would compute it twice, which is not a saving, so it stays where
1093 // it is and both readers read the register it wrote.
1094 let text = lower(&mut names, &func);
1095 assert!(text.contains("x64.lea_64 [%1*4]"), "{text}");
1096 assert_eq!(text.matches("x64.add_rr_64").count(), 2, "{text}");
1097 }
1098
1099 #[test]
1100 fn a_shift_by_a_register_asks_for_it_in_cl() {
1101 let i32 = Type::int(32);
1102 let (mut names, mut func, block, args) = blank(&[i32, i32]);
1103 let mut build = Builder::new(&mut func, block);
1104 build.binary(Opcode::Shl, args[0], args[1], Flags::default());
1105
1106 // The fixed register is not in the rule. It is what the target says the instruction does
1107 // with its operands, and the allocator is what will act on it.
1108 let text = lower(&mut names, &func);
1109 assert!(text.contains("x64.shl_rcl_32 %0, %1($rcx)"), "{text}");
1110 }
1111
1112 #[test]
1113 fn a_division_names_the_registers_and_the_register_it_destroys() {
1114 let i32 = Type::int(32);
1115 let (mut names, mut func, block, args) = blank(&[i32, i32]);
1116 let mut build = Builder::new(&mut func, block);
1117 build.binary(Opcode::SDiv, args[0], args[1], Flags::default());
1118
1119 // Two definitions, because a division writes the remainder whether anybody wanted it or
1120 // not, and the second one is early because it is destroyed before the operands are read.
1121 let text = lower(&mut names, &func);
1122 assert!(
1123 text.contains("%2:gpr($rax), early %3:gpr($rdx) = x64.idiv_quo_32 %0($rax), %1"),
1124 "{text}"
1125 );
1126 }
1127
1128 #[test]
1129 fn a_load_reads_through_the_register_the_address_is_in() {
1130 let i64 = Type::int(64);
1131 let (mut names, mut func, block, args) = blank(&[i64]);
1132 let mut build = Builder::new(&mut func, block);
1133 build.load(Type::int(32), args[0], plain(), Flags::default());
1134
1135 assert_eq!(
1136 lower(&mut names, &func),
1137 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1138 %1:gpr = x64.mov_rm_32 [%0]\n}\n"
1139 );
1140 }
1141
1142 #[test]
1143 fn a_store_writes_no_register_and_the_value_it_writes_is_the_one_the_ir_gave_it() {
1144 let (mut names, mut func, block, args) = blank(&[Type::int(32), Type::int(64)]);
1145 let mut build = Builder::new(&mut func, block);
1146 build.store(args[0], args[1], plain(), Flags::default());
1147
1148 // The value is the first parameter and the address is the second, and the instruction
1149 // takes them the other way round. Getting that backwards would compile to a store of the
1150 // address into the value, which is a program that runs and does the wrong thing.
1151 assert_eq!(
1152 lower(&mut names, &func),
1153 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
1154 %1:gpr($rsi) = x64.arg_val_64\n x64.mov_mr_32 %0, [%1]\n}\n"
1155 );
1156 }
1157
1158 #[test]
1159 fn an_address_with_a_constant_added_folds_into_the_access() {
1160 let i64 = Type::int(64);
1161 let (mut names, mut func, block, args) = blank(&[i64]);
1162 let mut build = Builder::new(&mut func, block);
1163 let twelve = build.iconst(i64, 12);
1164 let field = build.binary(Opcode::Add, args[0], twelve, Flags::default());
1165 build.load(Type::int(64), field, plain(), Flags::default());
1166
1167 // Two IR instructions and one machine instruction, which is what every read of a field
1168 // of a structure comes to.
1169 assert_eq!(
1170 lower(&mut names, &func),
1171 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1172 %1:gpr = x64.mov_rm_64 [%0 + 12]\n}\n"
1173 );
1174 }
1175
1176 #[test]
1177 fn a_displacement_too_wide_to_encode_leaves_the_addition_where_it_is() {
1178 let i64 = Type::int(64);
1179 let (mut names, mut func, block, args) = blank(&[i64]);
1180 let mut build = Builder::new(&mut func, block);
1181 let big = build.iconst(i64, i128::from(i32::MAX) + 1);
1182 let far = build.binary(Opcode::Add, args[0], big, Flags::default());
1183 build.load(Type::int(32), far, plain(), Flags::default());
1184
1185 // A displacement is signed and 32 bits. The rule that folds one has a guard that turns
1186 // this down, so the addition stays and the load reads through what it produced. Nobody
1187 // wrote that fallback: it is the next way of showing the operand.
1188 let text = lower(&mut names, &func);
1189 assert!(text.contains("x64.mov_rm_32 [%2]"), "{text}");
1190 assert!(text.contains("x64.add_rr_64"), "{text}");
1191 }
1192
1193 #[test]
1194 fn a_store_of_a_value_that_was_loaded_is_two_instructions_and_no_arithmetic() {
1195 let i64 = Type::int(64);
1196 let (mut names, mut func, block, args) = blank(&[i64, i64]);
1197 let mut build = Builder::new(&mut func, block);
1198 let got = build.load(Type::int(8), args[0], plain(), Flags::default());
1199 build.store(got, args[1], plain(), Flags::default());
1200
1201 // A load feeding a store is the one place folding would be wrong: an x86-64 `mov` has at
1202 // most one memory operand, and there is no rule that takes two, so the load is left where
1203 // it is and the store reads the register it wrote.
1204 assert_eq!(
1205 lower(&mut names, &func),
1206 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1207 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr = x64.mov_rm_8 [%0]\n \
1208 x64.mov_mr_8 %2, [%1]\n}\n"
1209 );
1210 }
1211
1212 #[test]
1213 fn an_access_at_a_width_no_rule_is_written_at_is_reported() {
1214 let i64 = Type::int(64);
1215 let (mut names, mut source, block, args) = blank(&[i64]);
1216 let mut build = Builder::new(&mut source, block);
1217 build.load(Type::int(128), args[0], plain(), Flags::default());
1218
1219 // The width is the whole of what is wrong here, so the width is in the message: `load`
1220 // on its own is written about at every other width and would send a reader looking in
1221 // the wrong place.
1222 let failed = func(&source, &mut names, &SYSV).expect_err("nothing loads 128 bits");
1223 assert_eq!(failed.to_string(), "no rule lowers a `load` producing a `i128`");
1224 }
1225
1226 #[test]
1227 fn a_return_asks_for_the_value_in_the_register_the_caller_reads() {
1228 let (mut names, mut func, block, args) = blank(&[Type::int(32)]);
1229 let mut build = Builder::new(&mut func, block);
1230 build.ret(&[args[0]]);
1231
1232 // The register is not in the rule, the same way `cl` is not in the rule for a shift. It
1233 // is what the target says the instruction does with its operand, and the allocator is
1234 // what will act on it. There is no `ret` here, because giving the frame back has to
1235 // happen between this and leaving and the frame is not worked out yet.
1236 assert_eq!(
1237 lower(&mut names, &func),
1238 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
1239 x64.ret_val_32 %0($rax)\n}\n"
1240 );
1241 }
1242
1243 #[test]
1244 fn a_return_of_a_constant_puts_it_in_a_register_first() {
1245 let (mut names, mut func, block, _) = blank(&[]);
1246 let mut build = Builder::new(&mut func, block);
1247 let zero = build.iconst(Type::int(32), 0);
1248 build.ret(&[zero]);
1249
1250 // No rule returns an immediate, so the plan that offers one is turned down and the next
1251 // one materializes it. That is `int main(void) { return 0; }` in full, once the epilogue
1252 // is appended to it.
1253 assert_eq!(
1254 lower(&mut names, &func),
1255 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_32 0\n x64.ret_val_32 %0($rax)\n}\n"
1256 );
1257 }
1258
1259 #[test]
1260 fn a_return_of_nothing_is_no_instruction_at_all() {
1261 let (mut names, mut func, block, _) = blank(&[]);
1262 let mut build = Builder::new(&mut func, block);
1263 build.ret(&[]);
1264
1265 // Every part of leaving a function that returns nothing is the epilogue's, and the
1266 // epilogue goes in after allocation. A block with nothing in it is the right answer here
1267 // rather than a function that could not be lowered.
1268 assert_eq!(lower(&mut names, &func), "mfunc @f {\nblock0:\n}\n");
1269 }
1270
1271 #[test]
1272 fn the_allocator_is_what_moves_the_answer_into_the_return_register() {
1273 let (mut names, mut source, block, _) = blank(&[]);
1274 let mut build = Builder::new(&mut source, block);
1275 let zero = build.iconst(Type::int(32), 0);
1276 build.ret(&[zero]);
1277
1278 let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1279 let env = env();
1280 let allocation = rucc_regalloc::run(&mut out, &env);
1281 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1282 finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
1283
1284 // `int main(void) { return 0; }` end to end. Nothing here asked for `rax`: the rule said
1285 // the value goes back, the target said where, and the allocator is what made it true. The
1286 // epilogue is what leaves, and this function needs no frame, so it is the return alone.
1287 //
1288 // The copy is a register allocator that takes no hints. It hands `%0` a register at the
1289 // instruction that writes it, where it does not yet know that a later use insists on
1290 // `rax`, and `rax` is not free to hand out because that later use is holding it. So the
1291 // value goes somewhere else and is copied in. Every division and every shift by a
1292 // register already pays the same thing, and paying it once per return is what makes it
1293 // worth fixing rather than a new problem.
1294 assert_eq!(
1295 mir::print_func(&out, &names, ®S),
1296 "mfunc @f {\nblock0:\n $rcx = x64.mov_ri_32 0\n $rax = x64.mov_rr_64 $rcx\n \
1297 x64.ret_val_32 $rax($rax)\n x64.ret\n}\n"
1298 );
1299 }
1300
1301 #[test]
1302 fn a_function_of_two_arguments_is_a_whole_function_now() {
1303 let i32 = Type::int(32);
1304 let (mut names, mut source, block, args) = blank(&[i32, i32]);
1305 let mut build = Builder::new(&mut source, block);
1306 let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
1307 build.ret(&[sum]);
1308
1309 let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1310 let env = env();
1311 let allocation = rucc_regalloc::run(&mut out, &env);
1312 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1313 finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
1314
1315 // `int f(int a, int b) { return a + b; }` end to end, and this is the test the argument
1316 // side exists for. Before it there was no way to write one: the allocator refuses a
1317 // function whose entry block takes parameters, because there is no edge into an entry
1318 // block for the moves that give a block parameter its value to go on.
1319 //
1320 // Four moves that a good allocator writes none of, and it is the same allocator that
1321 // takes no hints as in the return above rather than anything new. It hands each argument
1322 // a register at the pseudo that defines it, without looking at the fixed register that
1323 // pseudo insists on, so every argument is copied straight back out of where it already
1324 // was. Issue #255 is this, and this function is the shortest program that shows what it
1325 // costs: one hint per argument and one per return would leave nothing here but the
1326 // addition. What the test is for meanwhile is that the answer is right, and it is: the
1327 // copy in front of a two address instruction is what makes its destination one of the
1328 // registers it reads, and the source operand keeps its own name because the destination
1329 // is what the encoder writes.
1330 assert_eq!(
1331 mir::print_func(&out, &names, ®S),
1332 "mfunc @f {\nblock0:\n $rdi($rdi) = x64.arg_val_32\n \
1333 $rax = x64.mov_rr_64 $rdi\n $rsi($rsi) = x64.arg_val_32\n \
1334 $rcx = x64.mov_rr_64 $rsi\n $rdx = x64.mov_rr_64 $rax\n \
1335 $rdx(reuse 1) = x64.add_rr_32 $rax, $rcx\n $rax = x64.mov_rr_64 $rdx\n \
1336 x64.ret_val_32 $rax($rax)\n x64.ret\n}\n"
1337 );
1338 }
1339
1340 #[test]
1341 fn an_argument_with_no_register_left_for_it_is_read_out_of_the_caller_s_stack() {
1342 let i64 = Type::int(64);
1343 let (mut names, mut source, block, args) = blank(&[i64; 7]);
1344 let mut build = Builder::new(&mut source, block);
1345 build.ret(&[args[6]]);
1346
1347 let lowered = func(&source, &mut names, &SYSV).expect("the seventh is read from memory");
1348
1349 // SysV passes six integers in registers and the seventh in the caller's memory, so six of
1350 // these are pseudos that encode to nothing and the seventh is a load that encodes to real
1351 // bytes. Its displacement is nothing here for the reason a local's is: there is no frame
1352 // yet. What the walk hands on is which instruction is waiting, and for how far up the
1353 // caller's argument area, which is the bottom of it because it is the first one there.
1354 assert_eq!(lowered.stack.arguments.len(), 1);
1355 assert_eq!(lowered.stack.arguments[0].1, 0);
1356 let text = mir::print_func(&lowered.func, &names, ®S);
1357 assert!(text.contains("%6:gpr = x64.mov_rm_64 [$rsp]"), "{text}");
1358 assert_eq!(text.matches("x64.arg_val_64").count(), 6, "{text}");
1359 }
1360
1361 #[test]
1362 fn the_frame_is_what_says_how_far_up_the_caller_s_stack_an_argument_is() {
1363 let i64 = Type::int(64);
1364 let (mut names, mut source, block, args) = blank(&[i64; 8]);
1365 let mut build = Builder::new(&mut source, block);
1366 let sum = build.binary(Opcode::Add, args[6], args[7], Flags::default());
1367 build.ret(&[sum]);
1368
1369 let lowered = func(&source, &mut names, &SYSV).expect("both are read from memory");
1370 let stack = lowered.stack;
1371 let mut out = lowered.func;
1372 let env = env();
1373 let allocation = rucc_regalloc::run(&mut out, &env);
1374 let layout = stack.layout(Layout::new(&SYSV, REGS));
1375 let frame = Frame::of(&out, &allocation, &layout);
1376 finish(&mut out, &allocation, &frame, &stack, &SYSV, &FRAME, &mut names);
1377
1378 // A leaf that takes no frame, so the stack pointer never moves and the only thing between
1379 // it and the caller's arguments is the return address the call pushed. The seventh
1380 // parameter is at the bottom of the caller's argument area and the eighth is one word
1381 // further up, which is the eight bytes between the two offsets.
1382 let text = mir::print_func(&out, &names, ®S);
1383 assert_eq!(frame.size(), 0);
1384 assert_eq!(frame.incoming(), Incoming::from_stack(8));
1385 assert!(text.contains("x64.mov_rm_64 [$rsp + 8]"), "{text}");
1386 assert!(text.contains("x64.mov_rm_64 [$rsp + 16]"), "{text}");
1387 }
1388
1389 #[test]
1390 fn a_realigned_frame_reaches_the_caller_s_arguments_through_the_frame_pointer() {
1391 let i64 = Type::int(64);
1392 let (mut names, mut source, block, args) = blank(&[i64; 7]);
1393 let wide = slot(&mut source, block, 64, 32);
1394 let mut build = Builder::new(&mut source, block);
1395 build.store(args[6], wide, plain(), Flags::default());
1396 build.ret(&[args[6]]);
1397
1398 let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1399 let stack = lowered.stack;
1400 let mut out = lowered.func;
1401 let env = env();
1402 let allocation = rucc_regalloc::run(&mut out, &env);
1403 let layout = stack.layout(Layout::new(&SYSV, REGS));
1404 let frame = Frame::of(&out, &allocation, &layout);
1405 finish(&mut out, &allocation, &frame, &stack, &SYSV, &FRAME, &mut names);
1406
1407 // A local wanting thirty two byte alignment makes the prologue force the stack pointer,
1408 // which throws away how far the caller's stack was. So the load the lowering wrote off the
1409 // stack pointer is rewritten to read through the frame pointer, at the one distance that
1410 // survives: the word the prologue pushed the frame pointer into, and the return address
1411 // above it.
1412 let text = mir::print_func(&out, &names, ®S);
1413 assert_eq!(frame.realign(), Some(32));
1414 assert_eq!(frame.incoming(), Incoming::from_frame(16));
1415 assert!(text.contains("x64.mov_rm_64 [$rbp + 16]"), "{text}");
1416 assert!(!text.contains("x64.mov_rm_64 [$rsp"), "{text}");
1417 }
1418
1419 #[test]
1420 fn a_jump_is_the_edge_and_nothing_else() {
1421 let i32 = Type::int(32);
1422 let (mut names, mut source, entry, args) = blank(&[i32]);
1423 let next = source.create_block();
1424 let got = source.append_param(next, i32);
1425 Builder::new(&mut source, entry).jump(next, &[args[0]]);
1426 Builder::new(&mut source, next).ret(&[got]);
1427
1428 // Two blocks and two instructions, and the jump is neither of them. What it was is the
1429 // arm on the first block, and what the arm carries is the argument it was called with.
1430 assert_eq!(
1431 lower(&mut names, &source),
1432 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32 block1(%0)\n\n\
1433 block1(%1:gpr):\n x64.ret_val_32 %1($rax)\n}\n"
1434 );
1435 }
1436
1437 /// A constant is written where it is wanted rather than where the IR defined it, and two
1438 /// blocks wanting the same one is two places. Writing it once and reading it in both is a
1439 /// register read where nothing wrote it, unless the block it was written in happens to
1440 /// dominate the other, which nothing here checks and which the second arm of a branch never
1441 /// does. Each block gets its own copy of the number instead.
1442 #[test]
1443 fn a_constant_two_blocks_want_is_written_in_both_of_them() {
1444 let i32 = Type::int(32);
1445 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1446 let then = source.create_block();
1447 let other = source.create_block();
1448 let join = source.create_block();
1449 let got = source.append_param(join, i32);
1450
1451 let mut build = Builder::new(&mut source, entry);
1452 let seven = build.iconst(i32, 7);
1453 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1454 build.br_if(cond, then, &[], other, &[]);
1455 // Both arms want the seven in a register, because a block argument is never an immediate,
1456 // and neither arm dominates the other.
1457 Builder::new(&mut source, then).jump(join, &[seven]);
1458 Builder::new(&mut source, other).jump(join, &[seven]);
1459 Builder::new(&mut source, join).ret(&[got]);
1460
1461 let text = lower(&mut names, &source);
1462 assert_eq!(text.matches("x64.mov_ri_32 7").count(), 2, "one seven per block: {text}");
1463 }
1464
1465 /// An argument on an edge out of a block that leaves two ways is read after every instruction
1466 /// of the block is written, and reading one can write an instruction, which would land after
1467 /// the branch that has already jumped past it. The branch goes back on the end.
1468 #[test]
1469 fn a_constant_an_edge_wants_is_written_before_the_branch_and_not_after_it() {
1470 let i32 = Type::int(32);
1471 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1472 let then = source.create_block();
1473 let join = source.create_block();
1474 let got = source.append_param(join, i32);
1475
1476 let mut build = Builder::new(&mut source, entry);
1477 let nine = build.iconst(i32, 9);
1478 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1479 build.br_if(cond, then, &[], join, &[nine]);
1480 Builder::new(&mut source, then).jump(join, &[args[0]]);
1481 Builder::new(&mut source, join).ret(&[got]);
1482
1483 let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1484 let entry = out.entry().expect("an entry block");
1485 let last = out.terminator(entry).expect("a block that leaves two ways has a branch");
1486 let branch = names.intern("x64.br_cond_8");
1487 assert_eq!(
1488 out[last].opcode,
1489 mir::Opcode::new(branch),
1490 "the branch is last: {}",
1491 mir::print_func(&out, &names, ®S)
1492 );
1493 }
1494
1495 #[test]
1496 fn a_conditional_branch_is_lowered_to_the_condition_and_nothing_about_where_it_goes() {
1497 let i32 = Type::int(32);
1498 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1499 let then = source.create_block();
1500 let other = source.create_block();
1501 let mut build = Builder::new(&mut source, entry);
1502 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1503 build.br_if(cond, then, &[], other, &[]);
1504 Builder::new(&mut source, then).ret(&[args[0]]);
1505 Builder::new(&mut source, other).ret(&[args[1]]);
1506
1507 // The comparison writes a byte and the branch reads it, and neither says a block. Both
1508 // arms are on the entry block, in the order the branch took them, so the arm that runs
1509 // when the condition holds is the first.
1510 assert_eq!(
1511 lower(&mut names, &source),
1512 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
1513 %1:gpr($rsi) = x64.arg_val_32\n %2:gpr = x64.cmp_set_l_32 %0, %1\n \
1514 x64.br_cond_8 %2, block1, block2\n\n\
1515 block1:\n x64.ret_val_32 %0($rax)\n\n\
1516 block2:\n x64.ret_val_32 %1($rax)\n}\n"
1517 );
1518 }
1519
1520 #[test]
1521 fn a_branch_over_a_block_is_a_whole_function_now() {
1522 let i32 = Type::int(32);
1523 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1524 let then = source.create_block();
1525 let other = source.create_block();
1526 let join = source.create_block();
1527 let got = source.append_param(join, i32);
1528 let mut build = Builder::new(&mut source, entry);
1529 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1530 build.br_if(cond, then, &[], other, &[]);
1531 let mut build = Builder::new(&mut source, then);
1532 let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
1533 build.jump(join, &[sum]);
1534 Builder::new(&mut source, other).jump(join, &[args[1]]);
1535 Builder::new(&mut source, join).ret(&[got]);
1536
1537 // `int f(int a, int b) { if (a < b) return a + b; else return b; }` end to end, written
1538 // the way a front end writes it: both arms of the branch are blocks of their own and the
1539 // return is the block they meet at. No edge here is critical, because the two arms out of
1540 // the entry carry nothing and the two arms into the join each leave a block that goes
1541 // nowhere else, so each has its own end to put its move at.
1542 let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1543 assert_eq!(crate::split::critical(&mut out), 0, "no edge here is critical");
1544 let env = env();
1545 let allocation = rucc_regalloc::run(&mut out, &env);
1546 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1547 finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
1548
1549 // One epilogue, on the join, which is the one block the function leaves from, and the
1550 // moves that give the join its parameter are at the end of each arm. Every register is
1551 // physical and the branch is still a branch on a register, because turning it into a
1552 // `test` and a `jcc` is the block layout's and there is no block layout yet.
1553 let text = mir::print_func(&out, &names, ®S);
1554 assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
1555 assert!(text.contains("x64.br_cond_8"), "{text}");
1556 assert!(text.contains("x64.add_rr_32"), "{text}");
1557 assert!(!text.contains('%'), "{text}");
1558 }
1559
1560 #[test]
1561 fn a_critical_edge_is_split_before_the_allocator_ever_sees_it() {
1562 let i32 = Type::int(32);
1563 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1564 let then = source.create_block();
1565 let join = source.create_block();
1566 let got = source.append_param(join, i32);
1567 let mut build = Builder::new(&mut source, entry);
1568 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1569 build.br_if(cond, then, &[], join, &[args[1]]);
1570 Builder::new(&mut source, then).jump(join, &[args[0]]);
1571 let mut build = Builder::new(&mut source, join);
1572 let twice = build.binary(Opcode::Add, got, got, Flags::default());
1573 build.ret(&[twice]);
1574
1575 // The else arm is critical: the entry block leaves two ways and the join is arrived at
1576 // two ways, and the arm carries a value. Without splitting it the allocator asserts,
1577 // because the move that gives the join its parameter would have to run at the end of a
1578 // block that also goes to the other arm.
1579 let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1580 assert_eq!(crate::split::critical(&mut out), 1);
1581 let env = env();
1582 let allocation = rucc_regalloc::run(&mut out, &env);
1583 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1584 finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
1585
1586 // The block the split added is where the move went, and it is the whole of that block.
1587 let text = mir::print_func(&out, &names, ®S);
1588 assert_eq!(out.block_count(), 4, "{text}");
1589 assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
1590 }
1591
1592 #[test]
1593 fn a_call_passes_what_the_convention_says_and_takes_back_what_it_says() {
1594 let i32 = Type::int(32);
1595 let (mut names, mut source, block, args) = blank(&[i32, i32]);
1596 let sig =
1597 source.add_signature(Signature::new().with_params(&[i32, i32]).with_returns(&[i32]));
1598 let callee = names.intern("g");
1599 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0], args[1]]);
1600 let got = source[call].first_result.expect("an integer comes back");
1601 Builder::new(&mut source, block).ret(&[got]);
1602
1603 // `int f(int a, int b) { return g(a, b); }`. The arguments arrived where the call wants
1604 // them, so what the call reads is what arrived, and the whole of the convention is in the
1605 // constraints rather than in a move.
1606 let text = lower(&mut names, &source);
1607 assert!(text.contains("= x64.call %0($rdi), %1($rsi), @g"), "{text}");
1608 assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
1609 // What the call writes is the value that comes back and then every register the callee is
1610 // free to destroy, in both classes, which is the whole of what stops the allocator from
1611 // leaving something in one of them.
1612 assert!(text.contains("%2:gpr($rax), $rcx, $rdx, $r8, $r9, $r10, $r11, $xmm0,"), "{text}");
1613 assert!(text.contains("$xmm15 = x64.call"), "{text}");
1614 }
1615
1616 #[test]
1617 fn what_the_frame_owes_a_call_comes_back_with_the_function() {
1618 let i32 = Type::int(32);
1619 let sig = |source: &mut Func| source.add_signature(Signature::new().with_params(&[i32]));
1620
1621 let (mut names, mut source, block, args) = blank(&[i32]);
1622 let sig = sig(&mut source);
1623 let callee = names.intern("g");
1624 Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
1625 let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1626
1627 // Nothing on the stack, so nothing owed, but not a leaf either: a function that calls
1628 // owes the callee an aligned stack pointer and may not use the red zone.
1629 assert_eq!(out.stack.calls, Some(0));
1630 let layout = out.stack.layout(Layout::new(&SYSV, REGS));
1631 assert!(!layout.leaf);
1632 assert_eq!(layout.outgoing, 0);
1633
1634 // The same call under the other convention owes thirty two bytes for the callee to spill
1635 // its register arguments into, which is a fact about the convention and not about the call.
1636 let out = func(&source, &mut names, &x86_64::WIN64).expect("every instruction has a rule");
1637 assert_eq!(out.stack.calls, Some(32));
1638
1639 // And a function that calls nothing is a leaf, which is what says it may use the red zone.
1640 let (mut names, mut source, block, args) = blank(&[i32]);
1641 Builder::new(&mut source, block).ret(&[args[0]]);
1642 let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1643 assert_eq!(out.stack.calls, None);
1644 assert!(out.stack.layout(Layout::new(&SYSV, REGS)).leaf);
1645 }
1646
1647 #[test]
1648 fn a_value_that_outlives_a_call_is_not_left_where_the_call_destroys_it() {
1649 let i32 = Type::int(32);
1650 let (mut names, mut source, block, args) = blank(&[i32]);
1651 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
1652 let callee = names.intern("g");
1653 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
1654 let got = source[call].first_result.expect("an integer comes back");
1655 let mut build = Builder::new(&mut source, block);
1656 let sum = build.binary(Opcode::Add, got, args[0], Flags::default());
1657 build.ret(&[sum]);
1658
1659 // `int f(int a) { return g(a) + a; }`, which is the smallest program that asks the
1660 // question: `a` is read after the call and `rdi` is a register the call destroys.
1661 let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1662 let layout = lowered.stack.layout(Layout::new(&SYSV, REGS));
1663 let mut out = lowered.func;
1664 let env = env();
1665 let allocation = rucc_regalloc::run(&mut out, &env);
1666 let frame = Frame::of(&out, &allocation, &layout);
1667 finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
1668
1669 // It went to a register the callee has to put back, and the prologue and epilogue are what
1670 // put it back, which is the whole bargain the two halves of a convention make.
1671 let text = mir::print_func(&out, &names, ®S);
1672 assert!(text.contains("$rbx"), "{text}");
1673 assert!(!text.contains('%'), "{text}");
1674 assert_eq!(text.matches("x64.call").count(), 1, "{text}");
1675 }
1676
1677 #[test]
1678 fn a_call_with_more_arguments_than_registers_writes_the_rest_into_the_outgoing_area() {
1679 let i64 = Type::int(64);
1680 let (mut names, mut source, block, args) = blank(&[i64]);
1681 let seven = vec![i64; 7];
1682 let sig = source.add_signature(Signature::new().with_params(&seven));
1683 let callee = names.intern("g");
1684 let passed = vec![args[0]; 7];
1685 Builder::new(&mut source, block).call(callee, sig, &passed);
1686
1687 let lowered = func(&source, &mut names, &SYSV).expect("the seventh goes to memory");
1688 // The bytes the call needs are on the layout the frame is worked out from, so that the
1689 // frame reserves as many as the widest call in the function asked for.
1690 assert_eq!(lowered.stack.calls, Some(8));
1691 let text = mir::print_func(&lowered.func, &names, ®S);
1692 assert!(text.contains("x64.mov_mr_64 %0, [$rsp]\n"), "{text}");
1693 }
1694
1695 #[test]
1696 fn a_call_this_cannot_make_is_reported_rather_than_made() {
1697 let (mut names, mut source, block, _) = blank(&[]);
1698 let sig = source
1699 .add_signature(Signature::new().with_returns(&[Type::float(rucc_ir::Float::F80)]));
1700 let callee = names.intern("g");
1701 Builder::new(&mut source, block).call(callee, sig, &[]);
1702 let failed = func(&source, &mut names, &SYSV).expect_err("a long double is on the x87");
1703 assert_eq!(failed.to_string(), "what this call gives back is on the x87 stack");
1704 }
1705
1706 #[test]
1707 fn a_call_through_an_address_goes_through_the_register_the_address_is_in() {
1708 let i32 = Type::int(32);
1709 let (mut names, mut source, block, args) = blank(&[Type::PTR, i32]);
1710 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
1711 let varargs = source.push_abis(&[]);
1712 let info = source.add_call(CallInfo { callee: None, signature: sig, varargs });
1713 let mut build = Builder::new(&mut source, block);
1714 let inst = InstData {
1715 args: build.func().push_values(&[args[0], args[1]]),
1716 extra: Extra::Call(info),
1717 ..InstData::new(Opcode::CallIndirect)
1718 };
1719 let called = build.inst(inst, &[i32]);
1720 let got = source[called].first_result.expect("an integer comes back");
1721 Builder::new(&mut source, block).ret(&[got]);
1722
1723 // `int f(int (*g)(int), int a) { return g(a); }`. The first operand is the address and
1724 // the arguments are the ones behind it, and everything else about the call is what a call
1725 // to a name would have been.
1726 let text = lower(&mut names, &source);
1727 assert!(text.contains("= x64.call_reg %0, %1($rdi)"), "{text}");
1728 assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
1729 assert!(!text.contains("@g"), "a call through an address names nobody: {text}");
1730 }
1731
1732 #[test]
1733 fn an_instruction_no_rule_covers_is_reported() {
1734 let i64 = Type::int(64);
1735 let (mut names, mut source, block, args) = blank(&[i64, i64]);
1736 let mut build = Builder::new(&mut source, block);
1737 build.ret(&[args[0], args[1]]);
1738
1739 // Two values back at once. Where each of them goes is the convention's answer rather than
1740 // a term's, so the rule language has no name for it and no rule fires.
1741 let failed = func(&source, &mut names, &SYSV).expect_err("nothing returns two values");
1742 assert_eq!(failed.to_string(), "no rule lowers a `return`");
1743
1744 // A `return` produces nothing, so there is no type in the message and nothing invents
1745 // one, and the instruction comes back so a caller can ask the function where it was.
1746 let inst = failed.inst().expect("the instruction it is about");
1747 assert_eq!(source[inst].opcode, Opcode::Return);
1748 }
1749
1750 /// A refusal about a signature has no instruction, which is what makes it the one arm apart.
1751 ///
1752 /// Everything else is about something written somewhere in the body and hands it back so a
1753 /// caller can ask the function where it came from. A parameter arrives before the first
1754 /// instruction runs, so there is nothing in the body to point at and the message is about
1755 /// the function.
1756 #[test]
1757 fn a_refusal_about_a_parameter_has_no_instruction_to_point_at() {
1758 let missing = Unsupported::Argument { index: 0, missing: Missing::OnX87 };
1759 assert_eq!(missing.inst(), None);
1760 }
1761
1762 /// An `alloca` of a fixed size, which is what every local whose address is taken becomes.
1763 fn slot(source: &mut Func, block: Block, size: u64, align: u32) -> Value {
1764 let info = MemInfo { size, align, ..plain() };
1765 let mut build = Builder::new(source, block);
1766 let mem = build.func().add_mem(info);
1767 build.value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR)
1768 }
1769
1770 #[test]
1771 fn a_local_is_memory_in_the_frame_and_one_instruction_that_says_where() {
1772 let (mut names, mut source, block, _) = blank(&[]);
1773 let slot = slot(&mut source, block, 4, 4);
1774 let mut build = Builder::new(&mut source, block);
1775 let nine = build.iconst(Type::int(32), 9);
1776 build.store(nine, slot, plain(), Flags::default());
1777 let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
1778 build.ret(&[loaded]);
1779
1780 let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1781
1782 // Four bytes on the list the frame is laid out from, and the one instruction that reads
1783 // where they went. Its displacement is nothing here because there is no frame yet, and
1784 // which instruction is waiting for which local is what `finish` is handed.
1785 assert_eq!(lowered.stack.locals, vec![Local { size: 4, align: 4 }]);
1786 assert_eq!(lowered.stack.addresses.len(), 1);
1787 assert_eq!(lowered.stack.addresses[0].1, 0);
1788 assert_eq!(
1789 mir::print_func(&lowered.func, &names, ®S),
1790 "mfunc @f {\nblock0:\n %0:gpr = x64.lea_64 [$rsp]\n \
1791 %1:gpr = x64.mov_ri_32 9\n x64.mov_mr_32 %1, [%0]\n \
1792 %2:gpr = x64.mov_rm_32 [%0]\n x64.ret_val_32 %2($rax)\n}\n"
1793 );
1794 }
1795
1796 #[test]
1797 fn the_frame_is_what_fills_the_address_of_a_local_in() {
1798 let (mut names, mut source, block, _) = blank(&[]);
1799 let slot = slot(&mut source, block, 4, 4);
1800 let mut build = Builder::new(&mut source, block);
1801 let nine = build.iconst(Type::int(32), 9);
1802 build.store(nine, slot, plain(), Flags::default());
1803 let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
1804 build.ret(&[loaded]);
1805
1806 let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1807 let stack = lowered.stack;
1808 let mut out = lowered.func;
1809 let env = env();
1810 let allocation = rucc_regalloc::run(&mut out, &env);
1811 let layout = stack.layout(Layout::new(&SYSV, REGS));
1812 let frame = Frame::of(&out, &allocation, &layout);
1813 finish(&mut out, &allocation, &frame, &stack, &SYSV, &FRAME, &mut names);
1814
1815 // `int f(void) { int x; x = 9; return x; }` with the address of `x` taken, end to end.
1816 // A leaf small enough to live in the red zone takes no frame at all, so the stack pointer
1817 // never moves and the four bytes are below it, which is what the negative offset is. The
1818 // instruction the lowering left with nothing in its displacement now has the answer in it.
1819 let text = mir::print_func(&out, &names, ®S);
1820 assert!(text.contains("$rax = x64.lea_64 [$rsp - 8]"), "{text}");
1821 assert!(!text.contains("x64.sub_ri_64"), "{text}");
1822 assert_eq!(frame.size(), 0);
1823 assert_eq!(frame.local(0), Some(-8));
1824 }
1825
1826 #[test]
1827 fn a_stack_slot_whose_size_is_not_known_until_it_runs_is_reported() {
1828 let i64 = Type::int(64);
1829 let (mut names, mut source, block, args) = blank(&[i64]);
1830 let info = MemInfo { size: 0, align: 16, ..plain() };
1831 let mut build = Builder::new(&mut source, block);
1832 let mem = build.func().add_mem(info);
1833 let size = build.func().push_values(&[args[0]]);
1834 let slot = build.value(
1835 InstData { args: size, extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) },
1836 Type::PTR,
1837 );
1838 Builder::new(&mut source, block).ret(&[slot]);
1839
1840 // A variable length array. Growing the stack where the declaration stands means moving the
1841 // stack pointer in the middle of the function and reaching everything else through a
1842 // frame pointer afterwards, and the frame here lays out neither.
1843 let failed = func(&source, &mut names, &SYSV).expect_err("nothing grows the stack");
1844 assert_eq!(failed.to_string(), "nothing here grows the stack for a variable length array");
1845 }
1846
1847 #[test]
1848 fn an_address_is_read_written_and_added_to_like_the_integer_it_is() {
1849 let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
1850 let mut build = Builder::new(&mut source, block);
1851 let stepped = build.func().push_values(&[args[0], args[1]]);
1852 let next =
1853 build.value(InstData { args: stepped, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
1854 let loaded = build.load(Type::int(32), next, plain(), Flags::default());
1855 build.ret(&[loaded]);
1856
1857 // `int f(int *p, long i) { return *(int *)((char *)p + i); }`. Nothing about this is new
1858 // in the rule set, which is the point: the two addresses arrive in registers because an
1859 // address is an integer as wide as one, and the arithmetic on them is the add it always
1860 // was, so every rule written about an add reaches it.
1861 //
1862 // The add stays its own instruction rather than folding into the address the load reads
1863 // from. Two registers with no scale on either is the one addressing mode the rules have no
1864 // load through, because the folds that exist are the displacement one and the scaled ones,
1865 // and this is neither. That is a peephole worth having and not a thing this changes.
1866 assert_eq!(
1867 lower(&mut names, &source),
1868 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1869 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n \
1870 %3:gpr = x64.mov_rm_32 [%2]\n x64.ret_val_32 %3($rax)\n}\n"
1871 );
1872 }
1873
1874 /// The address of a file scope name, which is what every use of a global and every string
1875 /// literal starts from.
1876 fn address_of(source: &mut Func, block: Block, names: &mut Interner, name: &str) -> Value {
1877 let symbol = names.intern(name);
1878 let mut build = Builder::new(source, block);
1879 build.value(
1880 InstData { extra: Extra::Symbol(symbol), ..InstData::new(Opcode::GlobalAddr) },
1881 Type::PTR,
1882 )
1883 }
1884
1885 #[test]
1886 fn the_address_of_a_name_is_one_instruction_carrying_the_name() {
1887 let (mut names, mut source, block, _) = blank(&[]);
1888 let counter = address_of(&mut source, block, &mut names, "counter");
1889 let mut build = Builder::new(&mut source, block);
1890 let loaded = build.load(Type::int(32), counter, plain(), Flags::default());
1891 build.ret(&[loaded]);
1892
1893 // `extern int counter; int f(void) { return counter; }`. The address is an addressing mode
1894 // that names no register and carries the symbol, which is what the assembler writes
1895 // relative to `%rip` and what the object writer leaves a relocation for.
1896 assert_eq!(
1897 lower(&mut names, &source),
1898 "mfunc @f {\nblock0:\n %0:gpr = x64.lea_64 [@counter]\n \
1899 %1:gpr = x64.mov_rm_32 [%0]\n x64.ret_val_32 %1($rax)\n}\n"
1900 );
1901 }
1902
1903 /// A cast between a pointer and an integer, at whatever width the result is asked for.
1904 fn cast(source: &mut Func, block: Block, opcode: Opcode, from: Value, to: Type) -> Value {
1905 let mut build = Builder::new(source, block);
1906 let args = build.func().push_values(&[from]);
1907 build.value(InstData { args, ..InstData::new(opcode) }, to)
1908 }
1909
1910 #[test]
1911 fn a_cast_between_a_pointer_and_an_integer_as_wide_is_no_instruction_at_all() {
1912 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
1913 let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(64));
1914 Builder::new(&mut source, block).ret(&[number]);
1915
1916 // `long f(void *p) { return (long)p; }`. An address on this machine is an integer as wide
1917 // as the machine addresses, so the cast changes what the type system calls the value and
1918 // changes nothing about the value, and the register holding it is the one that held it.
1919 assert_eq!(
1920 lower(&mut names, &source),
1921 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1922 x64.ret_val_64 %0($rax)\n}\n"
1923 );
1924 }
1925
1926 #[test]
1927 fn a_null_pointer_is_a_constant_that_reaches_a_register_before_anything_reads_it() {
1928 let (mut names, mut source, block, _) = blank(&[]);
1929 let mut build = Builder::new(&mut source, block);
1930 let zero = build.iconst(Type::int(64), 0);
1931 let null = cast(&mut source, block, Opcode::IntToPtr, zero, Type::PTR);
1932 Builder::new(&mut source, block).ret(&[null]);
1933
1934 // `void *f(void) { return 0; }`. The cast is nothing, and reading its operand is what
1935 // writes the zero down: a constant is materialized where it is wanted rather than where
1936 // the IR defined it, and without the read there would be no instruction at all.
1937 assert_eq!(
1938 lower(&mut names, &source),
1939 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_64 0\n x64.ret_val_64 %0($rax)\n}\n"
1940 );
1941 }
1942
1943 #[test]
1944 fn a_cast_between_a_pointer_and_a_narrower_integer_is_reported() {
1945 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
1946 let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(32));
1947 Builder::new(&mut source, block).ret(&[number]);
1948
1949 // The front end never writes one: it casts at the address width and truncates or extends
1950 // around it, so both of those are the rules they always were. IR from somewhere else that
1951 // does write one is refused rather than compiled to a move that keeps the high half.
1952 let failed = func(&source, &mut names, &SYSV).expect_err("no rule narrows an address");
1953 assert_eq!(failed.to_string(), "no rule lowers a `ptrtoint` producing a `i32`");
1954 }
1955}