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::{Abi, Block, Def, Extra, Func, Inst, Linkage, MemOrder, Opcode, Param, 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::coverage::Fired;
88use crate::frame::{Layout, Local};
89use crate::select::{Match, Piece, Rule, Table};
90use crate::term::{MAX_ARGS, PLAIN, Plan, Shown, Term, Terms};
91use crate::varargs;
92
93/// The prefix a rule file puts in front of a machine term, which says which target it belongs
94/// to and is not part of the opcode.
95pub(crate) const PREFIX: &str = "x64.";
96
97/// How wide an address is on this target, which is the width a cast between a pointer and an
98/// integer has to be at for the cast to be nothing.
99const ADDRESS_BITS: u32 = 64;
100
101/// Why a function could not be lowered.
102///
103/// One reason and then nothing. A function with no rule for something in it is a function this
104/// cannot finish, and the second thing it could not lower is not news.
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub enum Unsupported {
107 /// An instruction no rule fires on.
108 Inst {
109 /// The instruction that stopped it.
110 inst: Inst,
111 /// What the rule file would call it, or nothing if the rule language has no name for it
112 /// at all, which is what an instruction at a width nothing is written about looks like.
113 term: Option<&'static str>,
114 /// The opcode, which is what gets named when the rule language has no word for it.
115 ///
116 /// An opcode the rule language has no word for is exactly the opcode no rule lowers, so
117 /// without this the message would be empty in every case where somebody needs it.
118 opcode: Opcode,
119 /// What it produces, or nothing for an instruction that is only an effect.
120 ty: Option<Type>,
121 },
122 /// A parameter that does not arrive somewhere this can bring it in from.
123 ///
124 /// Not an instruction, which is why it is a separate arm: it is a fact about the signature
125 /// and there is nothing in the body of the function to point at.
126 Argument {
127 /// Its position in the signature.
128 index: usize,
129 /// What is wrong with where it arrives.
130 missing: Missing,
131 },
132 /// A call that passes or gives back a value this cannot put where the convention wants it.
133 Call {
134 /// The call.
135 inst: Inst,
136 /// Which value, and what is wrong with where it travels.
137 refused: Refused,
138 },
139 /// A `return` this cannot put where the convention wants it.
140 ///
141 /// A separate arm from [`Unsupported::Inst`] because it is not an instruction no rule fires
142 /// on. A return of more than one value is built from the convention rather than matched, the
143 /// same way a call is, so what goes wrong with one is what goes wrong with a call and not the
144 /// absence of a rule.
145 Returned {
146 /// The `return`.
147 inst: Inst,
148 /// What is wrong with where one of the values travels.
149 missing: Missing,
150 },
151 /// A stack slot whose size is not known until the function runs, which is what a variable
152 /// length array is.
153 ///
154 /// Not an instruction no rule covers. Growing the stack where the declaration stands is
155 /// arithmetic on the stack pointer, and everything else in the frame then has to be reached
156 /// through a frame pointer instead, and neither of those is a term a rule could be written
157 /// about or a thing the frame here knows how to lay out.
158 Dynamic {
159 /// The `alloca`.
160 inst: Inst,
161 },
162}
163
164impl Unsupported {
165 /// The instruction it is about, or nothing for the one arm that is about a signature.
166 ///
167 /// What a caller wants this for is the span. The function knows where every instruction in
168 /// it came from, so a caller holding both can point a message at the line somebody wrote
169 /// rather than at the file as a whole, and nothing here has to carry a span of its own.
170 pub fn inst(&self) -> Option<Inst> {
171 match *self {
172 Unsupported::Inst { inst, .. }
173 | Unsupported::Call { inst, .. }
174 | Unsupported::Returned { inst, .. }
175 | Unsupported::Dynamic { inst, .. } => Some(inst),
176 Unsupported::Argument { .. } => None,
177 }
178 }
179}
180
181impl fmt::Display for Unsupported {
182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183 match *self {
184 Unsupported::Inst { term: Some(term), .. } => write!(f, "no rule lowers `{term}`"),
185 Unsupported::Inst { term: None, opcode, ty: Some(ty), .. } => {
186 write!(f, "no rule lowers a `{opcode}` producing a `{ty}`")
187 }
188 Unsupported::Inst { term: None, opcode, ty: None, .. } => {
189 write!(f, "no rule lowers a `{opcode}`")
190 }
191 Unsupported::Argument { index, missing } => {
192 write!(f, "parameter {index} {}", missing.why())
193 }
194 Unsupported::Call { refused: Refused { argument: Some(index), missing }, .. } => {
195 write!(f, "argument {index} of this call {}", missing.why())
196 }
197 Unsupported::Call { refused: Refused { argument: None, missing }, .. } => {
198 write!(f, "what this call gives back {}", missing.why())
199 }
200 Unsupported::Returned { missing, .. } => {
201 write!(f, "what this function gives back {}", missing.why())
202 }
203 Unsupported::Dynamic { .. } => {
204 f.write_str("nothing here grows the stack for a variable length array")
205 }
206 }
207 }
208}
209
210impl std::error::Error for Unsupported {}
211
212/// A lowered function, and what the frame needs that the machine IR does not hold.
213#[derive(Debug)]
214pub struct Lowered {
215 /// The function, in machine instructions.
216 pub func: mir::Func,
217 /// What it wants its stack to look like, which is separate from the function so that the two
218 /// can be read and written at the same time.
219 pub stack: Stack,
220 /// Which rules of the table lowered it, which is what `-Zrule-coverage` asks for and what
221 /// `crate::coverage` writes down.
222 pub fired: Fired,
223}
224
225/// What a function's stack has to hold, as far as selection is able to say.
226///
227/// All of it is answered here because selection is where a call is built and where an `alloca`
228/// is read, and nothing after it could tell what either of them needed.
229#[derive(Debug, Default)]
230pub struct Stack {
231 /// How many bytes the widest call in the function needs below the stack pointer for the
232 /// arguments it passes there, or `None` for a function that makes no call at all.
233 ///
234 /// `None` is a leaf, which is the function that may use the red zone and the one whose stack
235 /// pointer does not have to be left aligned for anybody.
236 pub calls: Option<u32>,
237 /// The memory the function asked for itself, one entry for every `alloca` in it, in the order
238 /// the walk reached them.
239 pub locals: Vec<Local>,
240 /// Which instruction computes the address of which of those locals.
241 ///
242 /// An address in the frame is a distance from the stack pointer, and there is no frame until
243 /// after allocation, so the instruction is written here with nothing in its displacement and
244 /// [`crate::finish`] writes the number in once [`crate::frame::Frame`] knows it.
245 pub addresses: Vec<(mir::Inst, usize)>,
246 /// Which instruction reads which of the arguments the caller passed on the stack, as how far up
247 /// the caller's argument area it reads.
248 ///
249 /// Waiting on [`crate::finish`] for the same reason the addresses above are, and on one thing
250 /// more: where the caller's argument area is from inside this function depends on whether the
251 /// prologue had to force the stack pointer's alignment, so which register the load reads
252 /// through is not settled here either.
253 pub arguments: Vec<(mir::Inst, u32)>,
254}
255
256impl Stack {
257 /// The layout given, with the three fields only the lowering knows the answer to filled in.
258 ///
259 /// Everything else in a layout comes from the flags the function is compiled under or from the
260 /// allocation, so this takes one and returns it rather than building one.
261 #[must_use]
262 pub fn layout<'a>(&'a self, base: Layout<'a>) -> Layout<'a> {
263 Layout {
264 leaf: self.calls.is_none(),
265 outgoing: self.calls.unwrap_or(0),
266 locals: &self.locals,
267 ..base
268 }
269 }
270}
271
272/// The x86-64 machine IR for that function.
273///
274/// # Errors
275///
276/// The first instruction no rule fires on, which today is anything at a width the rule set is not
277/// written at, a parameter that does not arrive in a register this can read, or a call that
278/// passes something this cannot put where the convention wants it.
279pub fn func(
280 source: &Func,
281 names: &mut Interner,
282 conv: &'static CallRegs,
283) -> Result<Lowered, Unsupported> {
284 Lowering::new(source, names, conv).run()
285}
286
287/// One function being lowered.
288struct Lowering<'a> {
289 source: &'a Func,
290 names: &'a mut Interner,
291 out: mir::Func,
292 /// The machine register each IR value is in, once it has one.
293 regs: Vec<Option<mir::Reg>>,
294 /// For a constant that has been written into a register, the block it was written into,
295 /// which is the only block that register is any good in.
296 written: Vec<Option<mir::Block>>,
297 /// How many times each IR value is read, which is what says whether an instruction may be
298 /// folded into the one that reads it.
299 uses: Vec<u32>,
300 /// The block being filled.
301 at: Option<mir::Block>,
302 /// The machine IR block each IR block became.
303 blocks: Vec<Option<mir::Block>>,
304 /// The class an address is in, which is the general purpose one and is not a question: every
305 /// register an addressing mode names holds part of an address, and there is no machine here
306 /// that computes an address anywhere but in this file. Which class a *value* is in is
307 /// [`Lowering::class_of`], and it is a question, because a float is in the other one.
308 gpr: RegClass,
309 /// Where the convention this function is compiled for puts things, which is read for the
310 /// arguments and for the calls.
311 conv: &'static CallRegs,
312 /// What the function wants its stack to look like, filled in as the walk finds out.
313 stack: Stack,
314 /// What a `va_start` in this function has to write, or nothing for a function that takes no
315 /// arguments its signature does not name.
316 ///
317 /// Worked out once, when the entry block binds the parameters, because every number in it is
318 /// about where those parameters left the walk over the argument registers and there is nowhere
319 /// else that knows.
320 varargs: Option<Varargs>,
321 /// Which rules have fired so far.
322 fired: Fired,
323}
324
325/// What a `va_start` in a variadic function writes into the list it is given.
326///
327/// Three of the four are settled here and the fourth is not a number at all yet: where the save
328/// area is and where the caller's argument area is are both distances into a frame that does not
329/// exist until after allocation, so both are `lea` instructions [`crate::finish`] fills in.
330#[derive(Debug, Clone, Copy, PartialEq, Eq)]
331struct Varargs {
332 /// Which of the function's stack objects is the register save area.
333 save: usize,
334 /// How far up the caller's argument area the first argument the signature does not name is,
335 /// which is the whole of that area the named ones did not take.
336 incoming: u32,
337 /// What `gp_offset` starts at, which is past the general purpose registers the named arguments
338 /// took.
339 integers: u32,
340 /// What `fp_offset` starts at, which is past the vector ones.
341 floats: u32,
342}
343
344/// How far a function's name reaches, narrowed from the linkage the IR gave it.
345///
346/// The IR has five and an object file says three, and the two the linker cannot tell apart are
347/// the two weak ones: which of them a symbol had is a fact the optimizer reads and the linker has
348/// no way to record. A function is never `Common`, since that is what a tentative definition of an
349/// object is and there is no tentative definition of a function, and it is written here rather
350/// than left out so that a linkage added later has to come past this.
351const fn binding(linkage: Linkage) -> mir::Binding {
352 match linkage {
353 Linkage::Internal => mir::Binding::Local,
354 Linkage::Weak | Linkage::LinkOnce => mir::Binding::Weak,
355 Linkage::External | Linkage::Common => mir::Binding::Global,
356 }
357}
358
359impl<'a> Lowering<'a> {
360 fn new(source: &'a Func, names: &'a mut Interner, conv: &'static CallRegs) -> Self {
361 let counts = source.counts();
362 let name = source.name;
363 let mut uses = vec![0; counts.values];
364 for block in source.blocks() {
365 for inst in source.insts(block) {
366 for &arg in &source[source[inst].args] {
367 uses[arg.index()] += 1;
368 }
369 for call in source.successors(inst) {
370 for &arg in &source[call.args] {
371 uses[arg.index()] += 1;
372 }
373 }
374 }
375 }
376 let mut out = mir::Func::new(name);
377 out.align = source.align;
378 out.binding = binding(source.linkage);
379 Self {
380 source,
381 names,
382 out,
383 regs: vec![None; counts.values],
384 written: vec![None; counts.values],
385 blocks: vec![None; counts.blocks],
386 uses,
387 at: None,
388 gpr: x86_64::GPR,
389 conv,
390 stack: Stack::default(),
391 varargs: None,
392 fired: Fired::new(),
393 }
394 }
395
396 fn run(mut self) -> Result<Lowered, Unsupported> {
397 // Every block before any of them is filled, because a block that jumps forward has to
398 // name the block it jumps to and a machine IR block is named by a handle rather than by
399 // the IR block it came from.
400 for block in self.source.blocks() {
401 let out = self.out.create_block();
402 self.blocks[block.index()] = Some(out);
403 }
404 for block in self.source.blocks() {
405 self.block(block)?;
406 }
407 Ok(Lowered { func: self.out, stack: self.stack, fired: self.fired })
408 }
409
410 /// One block: its parameters, then every instruction in it that is not folded into another.
411 fn block(&mut self, block: Block) -> Result<(), Unsupported> {
412 let out = self.out_block(block);
413 self.at = Some(out);
414 if self.source.entry() == Some(block) {
415 self.arrive(block, out)?;
416 } else {
417 for ¶m in self.source[block].params.iter() {
418 let reg = self.out.append_param(out, self.class_of(self.source[param].ty));
419 self.regs[param.index()] = Some(reg);
420 }
421 }
422
423 // What each instruction matched, and which instructions were folded into another. The
424 // instruction that is folded comes before the one that folds it, so the decision has to
425 // be made for the whole block before any of it is written, and it is made backwards: an
426 // instruction that has been folded into a later one does not get to fold anything into
427 // itself, because the rule that took it only reached one level down.
428 let insts: Vec<Inst> = self.source.insts(block).collect();
429 let mut found: Vec<Option<Match<Term>>> = (0..insts.len()).map(|_| None).collect();
430 let mut folded: Vec<Inst> = Vec::new();
431 for (index, &inst) in insts.iter().enumerate().rev() {
432 if folded.contains(&inst) {
433 continue;
434 }
435 if let Some((plan, matched)) = self.select(inst) {
436 folded.extend(self.folds(inst, plan));
437 found[index] = Some(matched);
438 }
439 }
440
441 for (&inst, matched) in insts.iter().zip(found) {
442 if folded.contains(&inst) || self.writes_nothing(inst) {
443 continue;
444 }
445 // A call is built from the convention rather than matched, which is why it is the one
446 // opcode looked at by name here. Through an address it is a different instruction and
447 // the same convention, so the two arrive at the same place and differ in one line of
448 // it.
449 match self.source[inst].opcode {
450 Opcode::Call | Opcode::CallIndirect => {
451 self.called(inst)?;
452 continue;
453 }
454 // Built from the frame rather than matched, for the same shape of reason a call
455 // is built from the convention: what a rule replaces a term with is instructions,
456 // and what an `alloca` needs first is bytes, which the rule language has no way
457 // to ask for.
458 Opcode::Alloca => {
459 self.reserve(inst)?;
460 continue;
461 }
462 // The address of a name, built here for the same reason an `alloca` is: what a
463 // rule replaces a term with is instructions over values, and the operand of this
464 // one is a symbol, which is a thing the rule language has no way to bind and the
465 // solver has no way to say anything about. There is nothing in `lea sym(%rip)` a
466 // proof over bitvectors could discharge, because what makes it the right answer
467 // is the relocation and what the linker does with it.
468 Opcode::GlobalAddr => {
469 self.address_of(inst)?;
470 continue;
471 }
472 // Built from the frame for the reason an `alloca` is, and from the convention for
473 // the reason a call is: three of the four fields it writes are distances that do
474 // not exist until the frame does, and the fourth is where the walk over the
475 // argument registers stopped. A function that is not variadic has no such walk to
476 // report, so it has nothing here and is refused below, which is the right answer
477 // for a `va_start` in one.
478 Opcode::VaStart if self.varargs.is_some() => {
479 self.va_start(inst)?;
480 continue;
481 }
482 // A return of more than one value, which is a structure small enough to come
483 // back in a pair of registers. Built from the convention for the reason a call
484 // is: which register each half goes in depends on the halves in front of it,
485 // because the two register files are walked separately, and a pattern over a term
486 // cannot see them. A return of one value is a term with a name and a rule, and it
487 // stays one.
488 //
489 // A return of none in a function whose answer went through memory is here too,
490 // and for a different reason: what it gives back is not written in the IR at all.
491 // The convention says the address the caller handed over comes back, and only the
492 // signature says this function was handed one.
493 Opcode::Return
494 if self.source[self.source[inst].args].len() > 1 || self.sret().is_some() =>
495 {
496 self.returned(inst)?;
497 continue;
498 }
499 // A cast between a pointer and an integer of the same width, which on this
500 // machine is every one the front end writes. No instruction at all, so no rule
501 // could name one.
502 Opcode::PtrToInt | Opcode::IntToPtr => {
503 self.rename(inst)?;
504 continue;
505 }
506 // A barrier, which is one instruction or none depending on the ordering. Written
507 // by name because there is nothing about it a rule could be proved against, the
508 // way there is nothing to prove about the address of a symbol.
509 Opcode::Fence => {
510 self.barrier(inst)?;
511 continue;
512 }
513 _ => {}
514 }
515 let matched = matched.ok_or_else(|| self.unsupported(inst))?;
516 self.emit(inst, &matched)?;
517 // After it is built rather than when it matched, so that what is recorded is the rules
518 // this function was lowered by and not the rules something was tried with.
519 self.fired.mark(matched.rule);
520 }
521 self.edges(block, out)
522 }
523
524 /// One call, which is built from the convention rather than matched against the table for the
525 /// same reason the arguments of the function itself are.
526 ///
527 /// The arguments are read before the call is built, which is what materializes a constant
528 /// argument into a register, since no call passes an immediate.
529 ///
530 /// A call to a name and a call through an address are both here, and what tells them apart is
531 /// the opcode rather than whether a callee was recorded, which is the same thing the verifier
532 /// reads. Through an address the first operand is the address and the arguments are the ones
533 /// behind it, and everything after that is the same: where each argument goes, where the value
534 /// comes back and which registers are gone across it are the convention's answers and the
535 /// convention does not ask what is being called.
536 fn called(&mut self, inst: Inst) -> Result<(), Unsupported> {
537 let data = &self.source[inst];
538 let Extra::Call(info) = data.extra else { return Err(self.unsupported(inst)) };
539 let info = self.source[info];
540 let indirect = data.opcode == Opcode::CallIndirect;
541
542 let values: Vec<Value> = self.source[data.args].to_vec();
543 let callee = if indirect {
544 let &address = values.first().ok_or_else(|| self.unsupported(inst))?;
545 abi::Callee::Through(self.reg_of(address)?)
546 } else {
547 abi::Callee::Named(info.callee.ok_or_else(|| self.unsupported(inst))?)
548 };
549
550 // What the ABI asks of each argument, read out before any of them is, because reading one
551 // borrows the function this is a table in. The ones the signature names are the signature's
552 // answer and the ones behind them are the call's, which is where a structure passed to a
553 // variadic callee by value says that its bytes travel: there is no parameter to say it on.
554 let signature = &self.source[info.signature];
555 let variadic = signature.variadic;
556 let named: Vec<Abi> = signature.params.iter().map(|param| param.abi).collect();
557 let beyond: Vec<Abi> = self.source[info.varargs].to_vec();
558 // Every value that comes back and not only the first. A structure small enough to travel
559 // in registers comes back in up to two of them, and which register each half is in is the
560 // convention's answer, which is why the whole list goes to the same place the arguments do
561 // rather than to a rule.
562 let returns: Vec<Type> = signature.return_types().collect();
563
564 let mut args = Vec::with_capacity(values.len());
565 for (index, value) in values.into_iter().skip(usize::from(indirect)).enumerate() {
566 let abi = named.get(index).or_else(|| beyond.get(index - named.len()));
567 let abi = abi.copied().unwrap_or_default();
568 args.push(abi::Passing { ty: self.source[value].ty, reg: self.reg_of(value)?, abi });
569 }
570 let block = self.at.expect("a block is being filled");
571 let what = abi::Calling { callee, args: &args, returns: &returns, variadic };
572 let made = abi::call(&mut self.out, block, &what, self.conv, self.names)
573 .map_err(|refused| Unsupported::Call { inst, refused })?;
574 let calls = &mut self.stack.calls;
575 *calls = Some(calls.unwrap_or(0).max(made.outgoing));
576 for (result, ®) in self.source[inst].results().zip(&made.results) {
577 self.regs[result.index()] = Some(reg);
578 }
579 Ok(())
580 }
581
582 /// The pointer a function returning through memory was handed, or nothing in a function that
583 /// was not.
584 ///
585 /// It is the first parameter and the signature is what says so, since in the IR it is an
586 /// ordinary pointer and reads like one everywhere in the body. A function with a signature
587 /// like that and no entry block has nothing to give back and no body to give it back from.
588 fn sret(&self) -> Option<Value> {
589 let first = self.source.signature().params.first()?;
590 if !matches!(first.abi, Abi::Sret { .. }) {
591 return None;
592 }
593 self.source[self.source.entry()?].params.first().copied()
594 }
595
596 /// One `return` the convention has to write, as the place each value has to be in by the end.
597 ///
598 /// One pseudo per value, each a read constrained to a return register, which is what a return
599 /// of one value already is and is the whole of what either does. The `ret` itself comes from
600 /// the epilogue for both, long after this, because the frame has to be given back first.
601 ///
602 /// The two register files are counted separately, so a structure of a `double` and a `long`
603 /// leaves the `double` in the first vector register and the `long` in the first integer one
604 /// rather than in the second of either. That is the same walk `rucc_codegen::abi` makes on
605 /// the other side of the call, which is what makes the two ends agree.
606 ///
607 /// A function whose answer went through memory gives back the address it was handed, in front
608 /// of nothing else, because a signature that returns that way returns nothing else. That the
609 /// caller already knows the address is not enough: it is allowed to read the register instead,
610 /// and a caller that does gets whatever the allocator last left there. In a leaf function that
611 /// is usually the right answer by accident, and one call in the body is enough to make it a
612 /// wild pointer, which is why this is written rather than left to luck.
613 ///
614 /// Where everything goes is worked out before anything is written, so a return this cannot
615 /// make leaves no half of one behind.
616 fn returned(&mut self, inst: Inst) -> Result<(), Unsupported> {
617 let values: Vec<Value> = self.source[self.source[inst].args].to_vec();
618 let (mut ints, mut floats) = (0usize, 0usize);
619 let mut parts = Vec::with_capacity(values.len() + 1);
620 for value in self.sret().into_iter().chain(values) {
621 let ty = self.source[value].ty;
622 let at = if crate::term::float_slot(ty).is_some() { &mut floats } else { &mut ints };
623 // Why it cannot come back, and not only that it cannot. A type that travels nowhere
624 // says so itself, and a type that travels perfectly well ran out of registers.
625 let missing = abi::refuses(ty).unwrap_or(Missing::NoRoom);
626 let name = abi::ret_of(ty, *at).ok_or(Unsupported::Returned { inst, missing })?;
627 *at += 1;
628 // The register is the target's answer and not one worked out here, the same as it is
629 // for a return of one value, so that both halves of a pair and every rule that writes
630 // half of one are reading the same table.
631 let opcode = name.strip_prefix(PREFIX).expect("a machine instruction of this target");
632 let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
633 let [desc] = form.operands() else { return Err(self.unsupported(inst)) };
634 parts.push((self.names.intern(name), self.reg_of(value)?, *desc));
635 }
636
637 let block = self.at.expect("a block is being filled");
638 let span = self.source.span(inst);
639 for (opcode, reg, desc) in parts {
640 let operand = mir::Operand {
641 reg,
642 class: desc.class,
643 role: desc.role,
644 constraint: desc.constraint,
645 };
646 self.out.build(block, mir::Opcode::new(opcode)).at(span).operand(operand).finish();
647 }
648 Ok(())
649 }
650
651 /// One `alloca`: the bytes it asks for go on the list the frame is laid out from, and the
652 /// address of them is one instruction.
653 ///
654 /// The instruction is a `lea` off the stack pointer, which is the one register that reaches
655 /// the frame in every function, and its displacement is left at nothing because there is no
656 /// frame yet. Which instruction is waiting for which local is remembered, and
657 /// [`crate::finish`] fills the numbers in after [`crate::frame::Frame`] has placed them.
658 ///
659 /// There is deliberately no rule for `alloca` and no name for one in [`crate::term`], and
660 /// that is what stops it being folded into something else. An operand shown as the
661 /// instruction that computed it is offered to the matcher by its name, so an `alloca` with no
662 /// name is one no pattern can reach past, and the address it computes is always in a register
663 /// by the time anything reads it.
664 fn reserve(&mut self, inst: Inst) -> Result<(), Unsupported> {
665 let data = &self.source[inst];
666 // A variable length array carries the size it wants as an operand rather than in the
667 // instruction, which is the whole of what tells the two apart here.
668 if !self.source[data.args].is_empty() {
669 return Err(Unsupported::Dynamic { inst });
670 }
671 let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
672 let info = self.source[mem];
673 let size = u32::try_from(info.size).map_err(|_| Unsupported::Dynamic { inst })?;
674 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
675
676 // At least one, because the frame divides by the alignment and an object with no
677 // alignment at all is one the front end had nothing to say about rather than one that may
678 // go anywhere.
679 let index = self.stack.locals.len();
680 self.stack.locals.push(Local { size, align: info.align.max(1) });
681
682 let block = self.at.expect("a block is being filled");
683 let reg = self.new_reg(result);
684 let span = self.source.span(inst);
685 let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
686 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
687 let made =
688 self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
689 self.stack.addresses.push((made, index));
690 Ok(())
691 }
692
693 /// One `va_start`, as the four fields of the list it was handed.
694 ///
695 /// Two of them are numbers this already knows, and each costs an instruction to put in a
696 /// register before it can be stored, because the machine here has no store of an immediate to
697 /// memory. The other two are addresses in the frame, and each is a `lea` [`crate::finish`]
698 /// finishes: the save area is one of the function's own stack objects, and the caller's
699 /// argument area is where the parameters that had no register came from, which is the same
700 /// place and the same fixup a parameter past the sixth already uses.
701 ///
702 /// What is written is exactly the four fields [`crate::varargs`] describes, in the order they
703 /// are laid out, so that reading this beside that table is the whole of the check.
704 fn va_start(&mut self, inst: Inst) -> Result<(), Unsupported> {
705 let Some(&list) = self.source[self.source[inst].args].first() else {
706 return Err(self.unsupported(inst));
707 };
708 let started = self.varargs.ok_or_else(|| self.unsupported(inst))?;
709 let list = self.reg_of(list)?;
710 let block = self.at.expect("a block is being filled");
711 let span = self.source.span(inst);
712
713 for (at, count) in
714 [(varargs::GP_OFFSET, started.integers), (varargs::FP_OFFSET, started.floats)]
715 {
716 let held = self.out.new_vreg(self.gpr);
717 let load = mir::Opcode::new(self.names.intern("x64.mov_ri_32"));
718 self.out.build(block, load).at(span).def(held, self.gpr).imm(i64::from(count)).finish();
719
720 let store = mir::Opcode::new(self.names.intern("x64.mov_mr_32"));
721 let mem = self.field(list, at);
722 self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
723 }
724
725 // The first argument the signature did not name, which is as far up the caller's argument
726 // area as the ones it did name reached. Nothing here knows where that area is, so the
727 // distance is recorded the way a parameter read out of it is and finished with it.
728 let overflow = self.out.new_vreg(self.gpr);
729 let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
730 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
731 let made = self
732 .out
733 .build(block, lea)
734 .at(span)
735 .def(overflow, self.gpr)
736 .mem(mir::Mem::at(sp))
737 .finish();
738 self.stack.arguments.push((made, started.incoming));
739
740 let save = self.frame_address(block, started.save);
741 for (at, held) in [(varargs::OVERFLOW, overflow), (varargs::SAVE_AREA, save)] {
742 let store = mir::Opcode::new(self.names.intern("x64.mov_mr_64"));
743 let mem = self.field(list, at);
744 self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
745 }
746 Ok(())
747 }
748
749 /// One field of a list, as the addressing mode that reaches it.
750 fn field(&self, list: mir::Reg, at: i64) -> mir::Mem {
751 let base = mir::Operand::read(list, self.gpr);
752 mir::Mem::at(base).plus(i32::try_from(at).expect("a field of a list is a small offset"))
753 }
754
755 /// The address of a name: one `lea` off the instruction pointer, with the name on it.
756 ///
757 /// The same instruction an `alloca` gets and for a related reason. An address that is not in
758 /// the program is a `lea` of an addressing mode that names no register, and the mode carries
759 /// the symbol so that [`rucc_asm`] can write it relative to `%rip` and leave the relocation
760 /// for the assembler. Both halves of that already existed: the printer writes `sym(%rip)` and
761 /// the encoder emits the relocation, because a call to a name the file does not define needed
762 /// them first.
763 ///
764 /// There is deliberately no name for this in [`crate::term`], which is what stops the address
765 /// being folded into the instruction that reads it. Folding it is the right thing to do and
766 /// is what turns a load of a global from two instructions into one, but it is a separate
767 /// question about addressing modes and issue #282 is it. Until then the address is in a
768 /// register before anything uses it, which is correct and one instruction longer.
769 ///
770 /// What this does not do is give the name anything to refer to. A module carries its globals
771 /// and nothing writes them out, so a file that defines the variable it reads compiles to a
772 /// reference the linker cannot resolve. Issue #293 is the other half.
773 fn address_of(&mut self, inst: Inst) -> Result<(), Unsupported> {
774 let data = &self.source[inst];
775 let Extra::Symbol(symbol) = data.extra else { return Err(self.unsupported(inst)) };
776 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
777
778 let block = self.at.expect("a block is being filled");
779 let reg = self.new_reg(result);
780 let span = self.source.span(inst);
781 let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
782 self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::of(symbol)).finish();
783 Ok(())
784 }
785
786 /// A conversion that converts nothing: the result is the operand under another type.
787 ///
788 /// `ptrtoint` and `inttoptr` at one width are the whole of this. An address on this machine is
789 /// an integer as wide as the machine addresses, so a cast between the two changes what the
790 /// type system calls the value and changes nothing about the value, and the register holding
791 /// it is the register that already held it. The front end never writes either of them at any
792 /// other width, because it widens or narrows around the cast rather than through it, so the
793 /// two widths disagreeing here means the IR came from somewhere else and is refused rather
794 /// than guessed at.
795 ///
796 /// Reading the operand first is what materializes it when it is a constant, which is the case
797 /// that matters: a null pointer is an `inttoptr` of zero, and that zero has to reach a
798 /// register before anything can call it an address.
799 fn rename(&mut self, inst: Inst) -> Result<(), Unsupported> {
800 let data = &self.source[inst];
801 let [arg] = self.source[data.args] else { return Err(self.unsupported(inst)) };
802 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
803 if !self.is_address_width(self.source[arg].ty)
804 || !self.is_address_width(self.source[result].ty)
805 {
806 return Err(self.unsupported(inst));
807 }
808 let reg = self.reg_of(arg)?;
809 self.regs[result.index()] = Some(reg);
810 Ok(())
811 }
812
813 /// One barrier, which on this machine is one instruction at the strongest ordering and no
814 /// instruction at all at every other one.
815 ///
816 /// x86-64 is total store order, so the only reordering the machine does is a store followed by
817 /// a load of a different address, and the only ordering that forbids that is sequential
818 /// consistency. An acquire, a release and an acquire release fence are therefore already true
819 /// of every program running here, and what a program wanted from writing one is that the
820 /// compiler not move memory accesses across it. The optimizer has finished by the time this
821 /// runs and nothing below reorders one access past another, so the constraint is already
822 /// discharged and there is nothing to write.
823 ///
824 /// The strongest one is `mfence`, which is what gcc 16.2.0 writes for
825 /// `__atomic_thread_fence(__ATOMIC_SEQ_CST)` and for `__sync_synchronize`. A locked instruction
826 /// on the stack is faster on most parts and is what some compilers write instead; it is also a
827 /// write to memory the program did not ask for, and the plain barrier is the one that says what
828 /// it means.
829 ///
830 /// Written here by name rather than by a rule, for the same reason a `lea` of a symbol is:
831 /// there is nothing in a barrier that a proof over bitvectors could discharge. It computes
832 /// nothing, so there is no equality to state, and what makes it the right answer is the memory
833 /// model, which the rule language cannot talk about.
834 fn barrier(&mut self, inst: Inst) -> Result<(), Unsupported> {
835 let Extra::Order(order) = self.source[inst].extra else {
836 return Err(self.unsupported(inst));
837 };
838 if order != MemOrder::SeqCst {
839 return Ok(());
840 }
841 let block = self.at.expect("a block is being filled");
842 let span = self.source.span(inst);
843 let fence = mir::Opcode::new(self.names.intern("x64.mfence"));
844 self.out.build(block, fence).at(span).finish();
845 Ok(())
846 }
847
848 /// Whether a type is the width an address is, which is what makes a cast to or from one free.
849 fn is_address_width(&self, ty: Type) -> bool {
850 ty.is_ptr() || (ty.is_int() && ty.bits() == ADDRESS_BITS)
851 }
852
853 /// Where a block goes, which in machine IR is on the block rather than on its terminator.
854 ///
855 /// That is why no rule ever names a block: a branch is selected for what it reads and the
856 /// edges are copied across here, arguments and all. The arguments are read last, after every
857 /// instruction of the block is written, because an argument that is a constant is
858 /// materialized where it is first wanted and the end of the block is where an edge wants it.
859 ///
860 /// Which is not quite the end. A block that leaves two ways has the branch as its last
861 /// instruction, and anything appended after a branch is something the branch has already
862 /// jumped past, so a constant materialized here would be a register the block below reads and
863 /// nothing ever writes. The branch is put back on the end when that happened, which is the
864 /// only reordering anything in this crate does and is why the branch is remembered before a
865 /// single argument is read.
866 fn edges(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
867 let Some(term) = self.source.terminator(block) else { return Ok(()) };
868 let branch =
869 if self.source[term].opcode == Opcode::BrIf { self.out.terminator(out) } else { None };
870
871 let calls: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
872 let mut succs = Vec::with_capacity(calls.len());
873 for call in calls {
874 let args: Vec<Value> = self.source[call.args].to_vec();
875 let mut regs = Vec::with_capacity(args.len());
876 for value in args {
877 regs.push(self.reg_of(value)?);
878 }
879 succs.push(mir::BlockCall { block: self.out_block(call.block), args: regs });
880 }
881 if let Some(branch) = branch {
882 if self.out.terminator(out) != Some(branch) {
883 self.out.remove_inst(branch);
884 self.out.append_inst(out, branch);
885 }
886 }
887 *self.out.succs_mut(out) = succs;
888 Ok(())
889 }
890
891 /// The machine IR block an IR block became.
892 fn out_block(&self, block: Block) -> mir::Block {
893 self.blocks[block.index()].expect("every block was created before any was filled")
894 }
895
896 /// The parameters of the entry block, which are the function's arguments.
897 ///
898 /// They are not block parameters in the machine IR and they cannot be. A block parameter is
899 /// given its value by a move on the edge into the block, and there is no edge into an entry
900 /// block, so what arrives in a function is the convention's to say. [`crate::abi`] is what
901 /// says it.
902 ///
903 /// The ones past the last register arrived in the caller's memory and are read out of it, and
904 /// the loads that read them come back here so that the frame can finish them the way it
905 /// finishes an `alloca`.
906 fn arrive(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
907 let params = self.source[block].params.clone();
908 // The type of each is the block's answer and what the ABI asks of it is the signature's,
909 // and the two lists are the same list: a parameter the classification turned into a
910 // pointer is a pointer in the block too. A block with more parameters than the signature
911 // names is not one the front end writes, and each of those is taken as a plain value.
912 let asked: Vec<Abi> = self.source.signature().params.iter().map(|it| it.abi).collect();
913 let types: Vec<Param> = params
914 .iter()
915 .enumerate()
916 .map(|(index, &value)| {
917 let abi = asked.get(index).copied().unwrap_or_default();
918 Param { ty: self.source[value].ty, abi }
919 })
920 .collect();
921 // A save area for a function that takes arguments its signature does not name, on a
922 // convention whose list is the four field one. Windows is the other kind and has no area at
923 // all, so a `va_start` in one is refused rather than built wrong.
924 let variadic = self.source.signature().variadic && !self.conv.shared_positions;
925 let area = variadic.then(|| varargs::Area::of(self.conv));
926 let arrived = abi::entry(&mut self.out, out, &types, self.conv, self.names, area)
927 .map_err(|(index, missing)| Unsupported::Argument { index, missing })?;
928 for (¶m, reg) in params.iter().zip(&arrived.regs) {
929 self.regs[param.index()] = Some(*reg);
930 }
931 if let Some(area) = area {
932 self.save_area(out, &arrived, area);
933 }
934 self.stack.arguments.extend(arrived.stack);
935 Ok(())
936 }
937
938 /// The prologue of a variadic function, which is every argument register it was handed written
939 /// into the frame.
940 ///
941 /// Every one the signature did not name, that is. Which of those hold anything is a thing only
942 /// the caller knew and there is nothing here to ask, so all of them are written, and the ones a
943 /// named parameter took are not, because `va_start` sets the two offsets past them and nothing
944 /// ever reads their slots.
945 ///
946 /// What that costs is up to fourteen stores in the prologue of a function that may read none of
947 /// them, and the convention's answer to that is the count of vector registers in `%al`, which
948 /// lets a callee skip the eight vector stores when the call passed no floats. Skipping them is a
949 /// branch in a prologue, and a prologue is written long after this by [`crate::finish`], which
950 /// has no blocks to branch between. So they are all written every time, which is correct and is
951 /// what `-O0` costs. Issue #323 is the branch.
952 ///
953 /// A vector register is written eight bytes at a time and not sixteen, for the reason
954 /// [`crate::varargs`] gives: the upper half of a slot is not something any reader of a list
955 /// looks at.
956 ///
957 /// The address is computed once into a register rather than written as a displacement off the
958 /// stack pointer, because a displacement into a frame is not known until after allocation and
959 /// one `lea` costs less than a fixup list for a dozen stores. It is the same `lea` an `alloca`
960 /// gets and [`crate::finish`] fills it in the same way.
961 fn save_area(&mut self, out: mir::Block, arrived: &abi::Arrived, area: varargs::Area) {
962 let save = self.stack.locals.len();
963 self.stack.locals.push(Local { size: area.size, align: varargs::VECTOR_SLOT });
964 self.varargs = Some(Varargs {
965 save,
966 incoming: arrived.used,
967 integers: u32::try_from(arrived.took.0).unwrap_or(0) * area.stride(false),
968 floats: area.starts_at(true)
969 + u32::try_from(arrived.took.1).unwrap_or(0) * area.stride(true),
970 });
971
972 let base = self.frame_address(out, save);
973 for &(reg, class, at) in &arrived.spare {
974 let name = if class == self.gpr { "x64.mov_mr_64" } else { "x64.movsd_mr" };
975 let store = mir::Opcode::new(self.names.intern(name));
976 let up = i32::try_from(at).expect("a register save area under two gigabytes");
977 let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
978 self.out.build(out, store).uses(reg, class).mem(mem).finish();
979 }
980 }
981
982 /// The address of one of the function's stack objects, in a fresh register.
983 ///
984 /// Written with nothing in its displacement, because where an object is in a frame is not known
985 /// until after allocation, and given to [`crate::finish`] to fill in the way an `alloca` is.
986 fn frame_address(&mut self, out: mir::Block, local: usize) -> mir::Reg {
987 let reg = self.out.new_vreg(self.gpr);
988 let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
989 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
990 let made = self.out.build(out, lea).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
991 self.stack.addresses.push((made, local));
992 reg
993 }
994
995 /// Whether an instruction is one no machine instruction is written for where it stands.
996 ///
997 /// Four of them, and none is a lowering decision, which is why none is a rule. A constant is
998 /// written where a register for it is first wanted rather than where the IR put it, and every
999 /// reader of one may have folded it into an immediate, in which case nowhere is the right
1000 /// place. A return of nothing has nothing to put anywhere: the epilogue gives the frame back
1001 /// and leaves, and it is appended to every block with no successors long after this has
1002 /// finished, so a return with a value is one instruction here and a return without one is
1003 /// none. Unless the value went back through memory, in which case there is something to put
1004 /// somewhere after all and the IR does not carry it: the address the caller handed over has
1005 /// to be in `rax` on the way out, and [`Lowering::returned`] is what writes that.
1006 ///
1007 /// An unconditional jump is the third, and there is even less of it: the edge is on the
1008 /// block, and whether the block it goes to is the next one and needs no jump at all is the
1009 /// block layout's answer rather than this one's.
1010 ///
1011 /// The fourth is a point control does not arrive at, in both of the forms the IR has for it:
1012 /// the `unreachable` terminator the front end puts at the end of a function whose body can run
1013 /// off the bottom, and the `unreachable_hint` a call to `__builtin_unreachable` becomes. What
1014 /// to write for a place nothing reaches is a question with no wrong answer, and nothing is the
1015 /// smallest one and the one gcc 16.2.0 gives at `-O0`. The terminator leaves the block with no
1016 /// successors, so the epilogue lands at the end of it the way it does on any other block that
1017 /// goes nowhere, and the function cannot fall out of its own last instruction into whatever
1018 /// the assembler puts next.
1019 fn writes_nothing(&self, inst: Inst) -> bool {
1020 let data = &self.source[inst];
1021 match data.opcode {
1022 Opcode::IConst | Opcode::Jump | Opcode::Unreachable | Opcode::UnreachableHint => true,
1023 Opcode::Return => self.source[data.args].is_empty() && self.sret().is_none(),
1024 _ => false,
1025 }
1026 }
1027
1028 /// The rule that fires on an instruction, and what it bound.
1029 ///
1030 /// The plans are tried in order and the first that matches wins, which is the maximal munch
1031 /// `spec/10-backend.md` asks for: a plan that offers more to the matcher is tried before one
1032 /// that offers less.
1033 fn select(&self, inst: Inst) -> Option<(Plan, Match<Term>)> {
1034 for plan in self.plans(inst) {
1035 let terms = Terms::new(self.source, inst, plan);
1036 if let Some(matched) = TABLE.find(&terms, Term::Root) {
1037 return Some((plan, matched));
1038 }
1039 }
1040 None
1041 }
1042
1043 /// Every way this instruction can be shown to the matcher, most offered first.
1044 fn plans(&self, inst: Inst) -> Vec<Plan> {
1045 let args = &self.source[self.source[inst].args];
1046 let mut plans = vec![PLAIN];
1047 for (index, &arg) in args.iter().enumerate().take(MAX_ARGS) {
1048 let mut ways = Vec::new();
1049 if self.foldable(inst, arg) {
1050 ways.push(Shown::Expand);
1051 }
1052 if Terms::new(self.source, inst, PLAIN).constant(arg).is_some() {
1053 ways.push(Shown::Const);
1054 }
1055 ways.push(Shown::Reg);
1056 plans = plans
1057 .into_iter()
1058 .flat_map(|plan| {
1059 ways.iter().map(move |&way| {
1060 let mut next = plan;
1061 next[index] = way;
1062 next
1063 })
1064 })
1065 .collect();
1066 }
1067 plans
1068 }
1069
1070 /// Whether an operand may be shown as the instruction that computed it.
1071 ///
1072 /// It has to be in the same block, because a rule that folds one instruction into another
1073 /// moves the work to where the second one is. It has to be read only by this instruction,
1074 /// because folding it does not delete it for anybody else and doing the work twice is not a
1075 /// saving. And it has to be something rather than a block parameter, and not a constant,
1076 /// which is shown as a constant instead.
1077 fn foldable(&self, into: Inst, value: Value) -> bool {
1078 let Def::Result { inst, .. } = self.source[value].def else { return false };
1079 if self.source[inst].opcode == Opcode::IConst || self.uses[value.index()] != 1 {
1080 return false;
1081 }
1082 self.source.block_of(inst).is_some()
1083 && self.source.block_of(inst) == self.source.block_of(into)
1084 }
1085
1086 /// The instructions a match folded into the one it matched.
1087 ///
1088 /// The plan is what says this, not the bindings: a binding is a register or a number either
1089 /// way, and an operand shown as the instruction that computed it is one no rule could have
1090 /// matched without taking that instruction, because the plan offered the matcher nothing
1091 /// else to call it.
1092 fn folds(&self, inst: Inst, plan: Plan) -> Vec<Inst> {
1093 let args = &self.source[self.source[inst].args];
1094 args.iter()
1095 .take(MAX_ARGS)
1096 .enumerate()
1097 .filter(|&(index, _)| plan[index] == Shown::Expand)
1098 .filter_map(|(_, &arg)| match self.source[arg].def {
1099 Def::Result { inst, .. } => Some(inst),
1100 Def::Param { .. } => None,
1101 })
1102 .collect()
1103 }
1104
1105 /// Build the machine instruction a match calls for.
1106 fn emit(&mut self, inst: Inst, matched: &Match<Term>) -> Result<(), Unsupported> {
1107 let rule: &Rule = TABLE.rule(matched);
1108 let pieces = rule.replacement;
1109 let Some(Piece::App { head, arity }) = pieces.first() else {
1110 return Err(self.unsupported(inst));
1111 };
1112 let opcode = head.strip_prefix(PREFIX).ok_or_else(|| self.unsupported(inst))?;
1113 let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
1114
1115 let mut read = Read::default();
1116 let mut at = 1;
1117 for _ in 0..*arity {
1118 at = self.read(inst, pieces, at, &matched.bindings, &mut read)?;
1119 }
1120
1121 let descs = form.operands();
1122 let writes = descs.iter().take_while(|desc| desc.role.is_def()).count();
1123 if descs.len() - writes != read.regs.len() {
1124 return Err(self.unsupported(inst));
1125 }
1126
1127 // The first thing the instruction writes is what it computes, and any others are
1128 // registers the machine destroys on the way, which are fresh because nothing else is in
1129 // them and nothing reads them. An instruction that writes nothing at all is one whose
1130 // whole purpose is its effect, which is what a store is, and there is no result to put
1131 // anywhere.
1132 let mut regs = Vec::new();
1133 if writes > 0 {
1134 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
1135 regs.push(self.new_reg(result));
1136 // The rest are the registers the machine destroys on the way, and the class each is in
1137 // is the one the instruction's description gives it rather than a guess, so that an
1138 // instruction that wrecks a register in the other file says so.
1139 regs.extend(descs[1..writes].iter().map(|desc| self.out.new_vreg(desc.class)));
1140 } else if self.source[inst].first_result.is_some() {
1141 // A rule that throws away a value the IR gave a name to would leave every reader of
1142 // that name with nothing to read, so it is a rule this and the target disagree about.
1143 return Err(self.unsupported(inst));
1144 }
1145 regs.extend(read.regs.iter().copied());
1146
1147 let block = self.at.expect("a block is being filled");
1148 let opcode = mir::Opcode::new(self.names.intern(head));
1149 let mut build = self.out.build(block, opcode).at(self.source.span(inst));
1150 for (desc, reg) in descs.iter().zip(regs) {
1151 let operand = mir::Operand {
1152 reg,
1153 class: desc.class,
1154 role: desc.role,
1155 constraint: desc.constraint,
1156 };
1157 build = build.operand(operand);
1158 }
1159 if let Some(mem) = read.mem {
1160 build = build.mem(mem);
1161 }
1162 if let Some(imm) = read.imm {
1163 build = build.imm(imm);
1164 }
1165 build.finish();
1166 Ok(())
1167 }
1168
1169 /// Read one argument of a replacement, which is a register, a number or an address.
1170 ///
1171 /// Gives back the position after it, because a replacement is flat and an address takes
1172 /// arguments of its own.
1173 fn read(
1174 &mut self,
1175 inst: Inst,
1176 pieces: &'static [Piece],
1177 at: usize,
1178 bindings: &[Term],
1179 out: &mut Read,
1180 ) -> Result<usize, Unsupported> {
1181 match pieces.get(at) {
1182 Some(Piece::Int(value)) => {
1183 out.imm = i64::try_from(*value).ok();
1184 Ok(at + 1)
1185 }
1186 Some(Piece::Var { index, .. }) => {
1187 match bindings.get(*index) {
1188 Some(&Term::Reg(value)) => {
1189 let reg = self.reg_of(value)?;
1190 out.regs.push(reg);
1191 }
1192 Some(&Term::Num(value)) => out.imm = i64::try_from(value).ok(),
1193 // A pattern binds a register or a number and nothing else, so this is a
1194 // rule the matcher and this file disagree about.
1195 _ => return Err(self.unsupported(inst)),
1196 }
1197 Ok(at + 1)
1198 }
1199 Some(Piece::App { head, arity }) => {
1200 let kind = x86_64::address(head).ok_or_else(|| self.unsupported(inst))?;
1201 let mut inner = Read::default();
1202 let mut next = at + 1;
1203 for _ in 0..*arity {
1204 next = self.read(inst, pieces, next, bindings, &mut inner)?;
1205 }
1206 let mem = address(kind, &inner, self.gpr).ok_or_else(|| self.unsupported(inst))?;
1207 out.mem = Some(mem);
1208 Ok(next)
1209 }
1210 None => Err(self.unsupported(inst)),
1211 }
1212 }
1213
1214 /// The register a value is in, materializing it if it is a constant that has not been put in
1215 /// one yet.
1216 ///
1217 /// A constant is written where it is wanted rather than where the IR defined it, and where it
1218 /// is wanted is a block that need not be the one the IR defined it in. So the register holding
1219 /// one is only good inside the block it was written into, and a second block that wants the
1220 /// same constant gets its own. Anything else is a register read where nothing wrote it: the
1221 /// IR guarantees a definition dominates its uses, and this moved the definition.
1222 ///
1223 /// Writing the number again is also the right answer and not merely the safe one. It is one
1224 /// instruction that reads nothing, which is cheaper than holding a register live across a
1225 /// branch for it, and it is what a rematerializing allocator would do with the value anyway.
1226 fn reg_of(&mut self, value: Value) -> Result<mir::Reg, Unsupported> {
1227 let constant = match self.source[value].def {
1228 Def::Result { inst, .. } => {
1229 (self.source[inst].opcode == Opcode::IConst).then_some(inst)
1230 }
1231 Def::Param { .. } => None,
1232 };
1233 let here = self.at.expect("a block is being filled");
1234 if let Some(reg) = self.regs[value.index()] {
1235 if constant.is_none() || self.written[value.index()] == Some(here) {
1236 return Ok(reg);
1237 }
1238 }
1239 if let Some(inst) = constant {
1240 // Cleared so that the register the constant is written into is a new one rather than
1241 // the one the block above wrote, which is still being read up there.
1242 self.regs[value.index()] = None;
1243 let matched = self
1244 .select(inst)
1245 .map(|(_, matched)| matched)
1246 .ok_or_else(|| self.unsupported(inst))?;
1247 self.emit(inst, &matched)?;
1248 // The same mark the loop over the instructions makes, and it has to be made here as
1249 // well because this is the only place a constant is ever selected: the loop skips one
1250 // where the IR wrote it, so a rule that lowers a constant fires from nowhere else and
1251 // would be reported as a rule nothing reaches.
1252 self.fired.mark(matched.rule);
1253 self.written[value.index()] = Some(here);
1254 return Ok(self.regs[value.index()].expect("a constant is written into a register"));
1255 }
1256 Ok(self.new_reg(value))
1257 }
1258
1259 /// Which register file a value of that type lives in.
1260 ///
1261 /// The vector one for the two float widths the machine has scalar instructions for, and the
1262 /// general purpose one for everything else. A `long double` is in neither, and it is here
1263 /// rather than in the vector class on purpose: it would be put in a register that cannot hold
1264 /// it, and there is no rule that names one, so the instruction computing it is reported. The
1265 /// wrong class would make that a wrong program instead of a refused one.
1266 fn class_of(&self, ty: Type) -> RegClass {
1267 match crate::term::float_slot(ty) {
1268 Some(_) => self.conv.sse_class,
1269 None => self.gpr,
1270 }
1271 }
1272
1273 /// A fresh register for a value, which is what the instruction computing it writes.
1274 fn new_reg(&mut self, value: Value) -> mir::Reg {
1275 if let Some(reg) = self.regs[value.index()] {
1276 return reg;
1277 }
1278 let reg = self.out.new_vreg(self.class_of(self.source[value].ty));
1279 self.regs[value.index()] = Some(reg);
1280 reg
1281 }
1282
1283 fn unsupported(&self, inst: Inst) -> Unsupported {
1284 let data = &self.source[inst];
1285 Unsupported::Inst {
1286 inst,
1287 term: Terms::new(self.source, inst, PLAIN).name(inst),
1288 opcode: data.opcode,
1289 ty: data.first_result.map(|result| self.source[result].ty),
1290 }
1291 }
1292}
1293
1294/// What the arguments of one replacement came to.
1295#[derive(Debug, Default)]
1296struct Read {
1297 regs: Vec<mir::Reg>,
1298 imm: Option<i64>,
1299 mem: Option<mir::Mem>,
1300}
1301
1302/// The addressing mode an address constructor's arguments make.
1303///
1304/// One arm per constructor rather than a question asked of the kind, because what the arguments
1305/// mean is the whole of what tells the four apart: the same register is a base in one and an
1306/// index in another, and the same constant is a scale in one and a displacement in another.
1307fn address(kind: x86_64::Address, read: &Read, gpr: RegClass) -> Option<mir::Mem> {
1308 let mut regs = read.regs.iter().copied().map(|reg| mir::Operand::read(reg, gpr));
1309 match kind {
1310 x86_64::Address::BaseIndexScale => {
1311 let base = regs.next()?;
1312 let index = regs.next()?;
1313 Some(mir::Mem::at(base).indexed(index, u8::try_from(read.imm?).ok()?))
1314 }
1315 x86_64::Address::IndexScale => Some(mir::Mem {
1316 base: None,
1317 index: Some(regs.next()?),
1318 scale: u8::try_from(read.imm?).ok()?,
1319 disp: 0,
1320 symbol: None,
1321 }),
1322 x86_64::Address::Base => Some(mir::Mem::at(regs.next()?)),
1323 // The rule that writes this has a guard saying the constant fits, so a displacement that
1324 // does not is a rule and a target that disagree rather than a program this cannot compile.
1325 x86_64::Address::BaseOffset => {
1326 Some(mir::Mem { disp: i32::try_from(read.imm?).ok()?, ..mir::Mem::at(regs.next()?) })
1327 }
1328 }
1329}
1330
1331/// The table this selector matches with.
1332///
1333/// One target for now, because one target has a rule file. Which table to use becomes a question
1334/// the moment a second one does, and the answer will be the target the session was given rather
1335/// than a constant here.
1336static TABLE: &Table = &crate::select::x86_64::TABLE;
1337
1338#[cfg(test)]
1339mod tests {
1340 use rucc_ir::{
1341 Builder, CallInfo, Flags, InstData, MemInfo, MemOrder, Restrict, Signature, Type,
1342 };
1343 use rucc_regalloc::assign::Env;
1344 use rucc_target::x86_64::{FRAME, REGS, SYSV};
1345
1346 use super::*;
1347 use crate::finish::finish;
1348 use crate::frame::{Frame, Incoming, Layout};
1349
1350 /// A function of as many 64 bit parameters as the test wants, and the block they are in.
1351 fn blank(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
1352 let mut names = Interner::new();
1353 let mut func = Func::new(names.intern("f"), Signature::new());
1354 let block = func.create_block();
1355 let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
1356 (names, func, block, values)
1357 }
1358
1359 /// An ordinary access: not atomic, and aligned enough that nothing here has an opinion.
1360 /// Neither field reaches selection, which is the point of saying it once here.
1361 fn plain() -> MemInfo {
1362 MemInfo {
1363 size: 0,
1364 align: 1,
1365 order: MemOrder::NotAtomic,
1366 tbaa: None,
1367 restrict: Restrict::NONE,
1368 }
1369 }
1370
1371 /// What the allocator is given: every integer register the convention offers except two, held
1372 /// back so that a move on an edge has somewhere to break a cycle and a spilled value has
1373 /// somewhere to be read into. Which two does not matter, and holding back the last two the
1374 /// convention would reach for leaves every expectation below unchanged.
1375 fn env() -> Env {
1376 const SCRATCH: [rucc_target::PhysReg; 2] = [x86_64::R10, x86_64::R11];
1377 let order: Vec<rucc_target::PhysReg> =
1378 SYSV.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
1379 Env::new().with(x86_64::GPR, &order, &SCRATCH)
1380 }
1381
1382 /// The machine IR text a function lowers to.
1383 fn lower(names: &mut Interner, source: &Func) -> String {
1384 let out = func(source, names, &SYSV).expect("every instruction has a rule");
1385 mir::print_func(&out.func, names, ®S)
1386 }
1387
1388 #[test]
1389 fn an_addition_of_two_registers_is_one_instruction() {
1390 let i32 = Type::int(32);
1391 let (mut names, mut func, block, args) = blank(&[i32, i32]);
1392 let mut build = Builder::new(&mut func, block);
1393 build.binary(Opcode::Add, args[0], args[1], Flags::default());
1394
1395 assert_eq!(
1396 lower(&mut names, &func),
1397 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
1398 %1:gpr($rsi) = x64.arg_val_32\n %2:gpr(reuse 1) = x64.add_rr_32 %0, %1\n}\n"
1399 );
1400 }
1401
1402 #[test]
1403 fn a_constant_operand_becomes_an_immediate() {
1404 let i32 = Type::int(32);
1405 let (mut names, mut func, block, args) = blank(&[i32]);
1406 let mut build = Builder::new(&mut func, block);
1407 let seven = build.iconst(i32, 7);
1408 build.binary(Opcode::Add, args[0], seven, Flags::default());
1409
1410 // The constant is in the instruction and nothing was written to hold it, which is what
1411 // materializing one where a register for it is wanted buys.
1412 assert_eq!(
1413 lower(&mut names, &func),
1414 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
1415 %1:gpr(reuse 1) = x64.add_ri_32 %0, 7\n}\n"
1416 );
1417 }
1418
1419 #[test]
1420 fn a_constant_too_wide_for_an_immediate_goes_into_a_register() {
1421 let i64 = Type::int(64);
1422 let (mut names, mut func, block, args) = blank(&[i64]);
1423 let mut build = Builder::new(&mut func, block);
1424 let big = build.iconst(i64, i128::from(i32::MAX) + 1);
1425 build.binary(Opcode::Add, args[0], big, Flags::default());
1426
1427 // Nobody wrote this fallback down. The rule that takes an immediate has a guard that
1428 // turns a number this wide down, so it does not fire, and the next way of showing the
1429 // operand puts it in a register.
1430 assert_eq!(
1431 lower(&mut names, &func),
1432 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1433 %1:gpr = x64.mov_ri_64 2147483648\n %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n}\n"
1434 );
1435 }
1436
1437 #[test]
1438 fn an_index_calculation_folds_into_an_address() {
1439 let i64 = Type::int(64);
1440 let (mut names, mut func, block, args) = blank(&[i64, i64]);
1441 let mut build = Builder::new(&mut func, block);
1442 let four = build.iconst(i64, 4);
1443 let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
1444 build.binary(Opcode::Add, args[0], scaled, Flags::default());
1445
1446 // Three IR instructions and one machine instruction. The multiply is gone because the
1447 // rule that matched reached down and took it.
1448 assert_eq!(
1449 lower(&mut names, &func),
1450 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1451 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr = x64.lea_64 [%0 + %1*4]\n}\n"
1452 );
1453 }
1454
1455 #[test]
1456 fn an_instruction_read_twice_is_not_folded_into_either_reader() {
1457 let i64 = Type::int(64);
1458 let (mut names, mut func, block, args) = blank(&[i64, i64]);
1459 let mut build = Builder::new(&mut func, block);
1460 let four = build.iconst(i64, 4);
1461 let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
1462 let first = build.binary(Opcode::Add, args[0], scaled, Flags::default());
1463 build.binary(Opcode::Add, first, scaled, Flags::default());
1464
1465 // Folding it into both would compute it twice, which is not a saving, so it stays where
1466 // it is and both readers read the register it wrote.
1467 let text = lower(&mut names, &func);
1468 assert!(text.contains("x64.lea_64 [%1*4]"), "{text}");
1469 assert_eq!(text.matches("x64.add_rr_64").count(), 2, "{text}");
1470 }
1471
1472 #[test]
1473 fn a_shift_by_a_register_asks_for_it_in_cl() {
1474 let i32 = Type::int(32);
1475 let (mut names, mut func, block, args) = blank(&[i32, i32]);
1476 let mut build = Builder::new(&mut func, block);
1477 build.binary(Opcode::Shl, args[0], args[1], Flags::default());
1478
1479 // The fixed register is not in the rule. It is what the target says the instruction does
1480 // with its operands, and the allocator is what will act on it.
1481 let text = lower(&mut names, &func);
1482 assert!(text.contains("x64.shl_rcl_32 %0, %1($rcx)"), "{text}");
1483 }
1484
1485 #[test]
1486 fn a_division_names_the_registers_and_the_register_it_destroys() {
1487 let i32 = Type::int(32);
1488 let (mut names, mut func, block, args) = blank(&[i32, i32]);
1489 let mut build = Builder::new(&mut func, block);
1490 build.binary(Opcode::SDiv, args[0], args[1], Flags::default());
1491
1492 // Two definitions, because a division writes the remainder whether anybody wanted it or
1493 // not, and the second one is early because it is destroyed before the operands are read.
1494 let text = lower(&mut names, &func);
1495 assert!(
1496 text.contains("%2:gpr($rax), early %3:gpr($rdx) = x64.idiv_quo_32 %0($rax), %1"),
1497 "{text}"
1498 );
1499 }
1500
1501 #[test]
1502 fn a_load_reads_through_the_register_the_address_is_in() {
1503 let i64 = Type::int(64);
1504 let (mut names, mut func, block, args) = blank(&[i64]);
1505 let mut build = Builder::new(&mut func, block);
1506 build.load(Type::int(32), args[0], plain(), Flags::default());
1507
1508 assert_eq!(
1509 lower(&mut names, &func),
1510 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1511 %1:gpr = x64.mov_rm_32 [%0]\n}\n"
1512 );
1513 }
1514
1515 #[test]
1516 fn a_store_writes_no_register_and_the_value_it_writes_is_the_one_the_ir_gave_it() {
1517 let (mut names, mut func, block, args) = blank(&[Type::int(32), Type::int(64)]);
1518 let mut build = Builder::new(&mut func, block);
1519 build.store(args[0], args[1], plain(), Flags::default());
1520
1521 // The value is the first parameter and the address is the second, and the instruction
1522 // takes them the other way round. Getting that backwards would compile to a store of the
1523 // address into the value, which is a program that runs and does the wrong thing.
1524 assert_eq!(
1525 lower(&mut names, &func),
1526 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
1527 %1:gpr($rsi) = x64.arg_val_64\n x64.mov_mr_32 %0, [%1]\n}\n"
1528 );
1529 }
1530
1531 #[test]
1532 fn an_address_with_a_constant_added_folds_into_the_access() {
1533 let i64 = Type::int(64);
1534 let (mut names, mut func, block, args) = blank(&[i64]);
1535 let mut build = Builder::new(&mut func, block);
1536 let twelve = build.iconst(i64, 12);
1537 let field = build.binary(Opcode::Add, args[0], twelve, Flags::default());
1538 build.load(Type::int(64), field, plain(), Flags::default());
1539
1540 // Two IR instructions and one machine instruction, which is what every read of a field
1541 // of a structure comes to.
1542 assert_eq!(
1543 lower(&mut names, &func),
1544 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1545 %1:gpr = x64.mov_rm_64 [%0 + 12]\n}\n"
1546 );
1547 }
1548
1549 #[test]
1550 fn a_displacement_too_wide_to_encode_leaves_the_addition_where_it_is() {
1551 let i64 = Type::int(64);
1552 let (mut names, mut func, block, args) = blank(&[i64]);
1553 let mut build = Builder::new(&mut func, block);
1554 let big = build.iconst(i64, i128::from(i32::MAX) + 1);
1555 let far = build.binary(Opcode::Add, args[0], big, Flags::default());
1556 build.load(Type::int(32), far, plain(), Flags::default());
1557
1558 // A displacement is signed and 32 bits. The rule that folds one has a guard that turns
1559 // this down, so the addition stays and the load reads through what it produced. Nobody
1560 // wrote that fallback: it is the next way of showing the operand.
1561 let text = lower(&mut names, &func);
1562 assert!(text.contains("x64.mov_rm_32 [%2]"), "{text}");
1563 assert!(text.contains("x64.add_rr_64"), "{text}");
1564 }
1565
1566 #[test]
1567 fn a_store_of_a_value_that_was_loaded_is_two_instructions_and_no_arithmetic() {
1568 let i64 = Type::int(64);
1569 let (mut names, mut func, block, args) = blank(&[i64, i64]);
1570 let mut build = Builder::new(&mut func, block);
1571 let got = build.load(Type::int(8), args[0], plain(), Flags::default());
1572 build.store(got, args[1], plain(), Flags::default());
1573
1574 // A load feeding a store is the one place folding would be wrong: an x86-64 `mov` has at
1575 // most one memory operand, and there is no rule that takes two, so the load is left where
1576 // it is and the store reads the register it wrote.
1577 assert_eq!(
1578 lower(&mut names, &func),
1579 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1580 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr = x64.mov_rm_8 [%0]\n \
1581 x64.mov_mr_8 %2, [%1]\n}\n"
1582 );
1583 }
1584
1585 #[test]
1586 fn an_access_at_a_width_no_rule_is_written_at_is_reported() {
1587 let i64 = Type::int(64);
1588 let (mut names, mut source, block, args) = blank(&[i64]);
1589 let mut build = Builder::new(&mut source, block);
1590 build.load(Type::int(128), args[0], plain(), Flags::default());
1591
1592 // The width is the whole of what is wrong here, so the width is in the message: `load`
1593 // on its own is written about at every other width and would send a reader looking in
1594 // the wrong place.
1595 let failed = func(&source, &mut names, &SYSV).expect_err("nothing loads 128 bits");
1596 assert_eq!(failed.to_string(), "no rule lowers a `load` producing a `i128`");
1597 }
1598
1599 #[test]
1600 fn a_return_asks_for_the_value_in_the_register_the_caller_reads() {
1601 let (mut names, mut func, block, args) = blank(&[Type::int(32)]);
1602 let mut build = Builder::new(&mut func, block);
1603 build.ret(&[args[0]]);
1604
1605 // The register is not in the rule, the same way `cl` is not in the rule for a shift. It
1606 // is what the target says the instruction does with its operand, and the allocator is
1607 // what will act on it. There is no `ret` here, because giving the frame back has to
1608 // happen between this and leaving and the frame is not worked out yet.
1609 assert_eq!(
1610 lower(&mut names, &func),
1611 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
1612 x64.ret_val_32 %0($rax)\n}\n"
1613 );
1614 }
1615
1616 #[test]
1617 fn a_return_of_two_values_asks_for_the_second_register_as_well() {
1618 let i64 = Type::int(64);
1619 let (mut names, mut func, block, args) = blank(&[i64, i64]);
1620 let mut build = Builder::new(&mut func, block);
1621 build.ret(&[args[0], args[1]]);
1622
1623 // `struct { long a, b; } f(long a, long b)`, after the front end has classified it. Both
1624 // halves are integers, so the second is in the second integer return register, and both
1625 // pseudos say so the same way the one for a single value does.
1626 assert_eq!(
1627 lower(&mut names, &func),
1628 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1629 %1:gpr($rsi) = x64.arg_val_64\n x64.ret_val_64 %0($rax)\n \
1630 x64.ret_val2_64 %1($rdx)\n}\n"
1631 );
1632 }
1633
1634 #[test]
1635 fn two_values_back_in_different_files_are_both_the_first_of_their_own() {
1636 let f64 = Type::float(rucc_ir::Float::F64);
1637 let (mut names, mut func, block, args) = blank(&[f64, Type::int(64)]);
1638 let mut build = Builder::new(&mut func, block);
1639 build.ret(&[args[0], args[1]]);
1640
1641 // `struct { double a; long b; } f(double a, long b)`. The two files are counted apart, so
1642 // neither half is the second of anything and the `double` is in `xmm0` rather than in the
1643 // register a second `double` would have been in. Getting this wrong is not a crash: the
1644 // caller reads a register nobody wrote, and this is where that is ruled out.
1645 assert_eq!(
1646 lower(&mut names, &func),
1647 "mfunc @f {\nblock0:\n %0:xmm($xmm0) = x64.arg_val_f64\n \
1648 %1:gpr($rdi) = x64.arg_val_64\n x64.ret_val_f64 %0($xmm0)\n \
1649 x64.ret_val_64 %1($rax)\n}\n"
1650 );
1651 }
1652
1653 #[test]
1654 fn two_of_the_same_file_back_take_the_first_two_of_it() {
1655 let f64 = Type::float(rucc_ir::Float::F64);
1656 let (mut names, mut func, block, args) = blank(&[f64, f64]);
1657 let mut build = Builder::new(&mut func, block);
1658 build.ret(&[args[0], args[1]]);
1659
1660 // `struct { double x, y; } f(double x, double y)`, which is the vector half of the pair
1661 // above and counts in its own file the same way.
1662 assert_eq!(
1663 lower(&mut names, &func),
1664 "mfunc @f {\nblock0:\n %0:xmm($xmm0) = x64.arg_val_f64\n \
1665 %1:xmm($xmm1) = x64.arg_val_f64\n x64.ret_val_f64 %0($xmm0)\n \
1666 x64.ret_val2_f64 %1($xmm1)\n}\n"
1667 );
1668 }
1669
1670 /// A function whose answer goes back through memory, with the pointer to the space for it in
1671 /// front of whatever else it takes. Only the signature says it is one.
1672 fn returning_through_memory(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
1673 let mut names = Interner::new();
1674 let sret = Abi::Sret { size: 32, align: 8 };
1675 let mut signature = Signature::new().and_param(Param::with_abi(Type::PTR, sret));
1676 signature.params.extend(params.iter().copied().map(Param::new));
1677 let mut func = Func::new(names.intern("f"), signature);
1678 let block = func.create_block();
1679 let space = func.append_param(block, Type::PTR);
1680 let values = std::iter::once(space)
1681 .chain(params.iter().map(|&ty| func.append_param(block, ty)))
1682 .collect();
1683 (names, func, block, values)
1684 }
1685
1686 #[test]
1687 fn the_space_a_return_through_memory_was_given_goes_back_in_the_first_return_register() {
1688 let (mut names, mut func, block, _) = returning_through_memory(&[]);
1689 Builder::new(&mut func, block).ret(&[]);
1690
1691 // `struct big f(void)`, where `big` is too large to come back in registers. The `return`
1692 // carries nothing, because the value went into the space the caller handed over, and the
1693 // document still says that address comes back in `rax`. Nothing in the IR says it, so the
1694 // convention says it, and the pseudo is the one any other pointer return would use.
1695 assert_eq!(
1696 lower(&mut names, &func),
1697 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1698 x64.ret_val_64 %0($rax)\n}\n"
1699 );
1700 }
1701
1702 #[test]
1703 fn what_the_function_did_in_between_does_not_take_the_register_off_it() {
1704 let (mut names, mut func, block, args) = returning_through_memory(&[Type::int(32)]);
1705 let mut build = Builder::new(&mut func, block);
1706 build.store(args[1], args[0], plain(), Flags::default());
1707 build.ret(&[]);
1708
1709 // The register is a read at the end and not a move at the start, so it is live across
1710 // everything between the two and the allocator has to keep it somewhere. In a function
1711 // with a call in it that somewhere is a callee saved register, and the address comes back
1712 // into `rax` here rather than whatever the last instruction happened to leave there. That
1713 // is issue #333, and a store is enough to show the value outlives the entry block.
1714 let text = lower(&mut names, &func);
1715 assert!(text.contains("x64.mov_mr_32 %1, [%0]"), "{text}");
1716 assert!(text.ends_with(" x64.ret_val_64 %0($rax)\n}\n"), "{text}");
1717 }
1718
1719 #[test]
1720 fn a_pointer_that_is_only_a_pointer_is_not_given_back() {
1721 let (mut names, mut func, block, args) = blank(&[Type::PTR]);
1722 let mut build = Builder::new(&mut func, block);
1723 build.store(args[0], args[0], plain(), Flags::default());
1724 build.ret(&[]);
1725
1726 // `void f(void **p)`. It takes a pointer first and returns nothing, which is the shape of
1727 // the one above and none of its meaning, and what tells them apart is the signature. A
1728 // `void` function leaves `rax` alone.
1729 assert!(!lower(&mut names, &func).contains("ret_val"));
1730 }
1731
1732 #[test]
1733 fn a_return_of_a_constant_puts_it_in_a_register_first() {
1734 let (mut names, mut func, block, _) = blank(&[]);
1735 let mut build = Builder::new(&mut func, block);
1736 let zero = build.iconst(Type::int(32), 0);
1737 build.ret(&[zero]);
1738
1739 // No rule returns an immediate, so the plan that offers one is turned down and the next
1740 // one materializes it. That is `int main(void) { return 0; }` in full, once the epilogue
1741 // is appended to it.
1742 assert_eq!(
1743 lower(&mut names, &func),
1744 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_32 0\n x64.ret_val_32 %0($rax)\n}\n"
1745 );
1746 }
1747
1748 #[test]
1749 fn the_rule_that_writes_a_constant_down_is_recorded_as_a_rule_that_fired() {
1750 let (mut names, mut func, block, _) = blank(&[]);
1751 let mut build = Builder::new(&mut func, block);
1752 let zero = build.iconst(Type::int(32), 0);
1753 build.ret(&[zero]);
1754
1755 // The loop over the instructions passes a constant by, because a constant is written where
1756 // a register for it is first wanted rather than where the IR put it. So the only place a
1757 // rule about one is ever selected is the materialization, and a mark made in the loop
1758 // alone would report every rule about a constant as a rule nothing reaches.
1759 let out = super::func(&func, &mut names, &SYSV).expect("every instruction has a rule");
1760 let rules = &crate::select::x86_64::TABLE.rules;
1761 let fired: Vec<&str> = rules
1762 .iter()
1763 .enumerate()
1764 .filter(|(index, _)| out.fired.has(*index))
1765 .map(|(_, rule)| rule.pattern)
1766 .collect();
1767 assert!(fired.contains(&"(iconst.i32 k)"), "{fired:?}");
1768 }
1769
1770 #[test]
1771 fn a_return_of_nothing_is_no_instruction_at_all() {
1772 let (mut names, mut func, block, _) = blank(&[]);
1773 let mut build = Builder::new(&mut func, block);
1774 build.ret(&[]);
1775
1776 // Every part of leaving a function that returns nothing is the epilogue's, and the
1777 // epilogue goes in after allocation. A block with nothing in it is the right answer here
1778 // rather than a function that could not be lowered.
1779 assert_eq!(lower(&mut names, &func), "mfunc @f {\nblock0:\n}\n");
1780 }
1781
1782 #[test]
1783 fn the_allocator_is_what_moves_the_answer_into_the_return_register() {
1784 let (mut names, mut source, block, _) = blank(&[]);
1785 let mut build = Builder::new(&mut source, block);
1786 let zero = build.iconst(Type::int(32), 0);
1787 build.ret(&[zero]);
1788
1789 let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1790 let env = env();
1791 let allocation = rucc_regalloc::run(&mut out, &env);
1792 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1793 finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
1794
1795 // `int main(void) { return 0; }` end to end. Nothing here asked for `rax`: the rule said
1796 // the value goes back, the target said where, and the allocator is what made it true. The
1797 // epilogue is what leaves, and this function needs no frame, so it is the return alone.
1798 //
1799 // Two instructions and no copy, which is what a hint buys. The return insists on `rax`,
1800 // so `rax` is the register the allocator tries first for the value the return reads, and
1801 // the constant is written straight into it.
1802 assert_eq!(
1803 mir::print_func(&out, &names, ®S),
1804 "mfunc @f {\nblock0:\n $rax = x64.mov_ri_32 0\n \
1805 x64.ret_val_32 $rax($rax)\n x64.ret\n}\n"
1806 );
1807 }
1808
1809 #[test]
1810 fn a_function_of_two_arguments_is_a_whole_function_now() {
1811 let i32 = Type::int(32);
1812 let (mut names, mut source, block, args) = blank(&[i32, i32]);
1813 let mut build = Builder::new(&mut source, block);
1814 let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
1815 build.ret(&[sum]);
1816
1817 let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1818 let env = env();
1819 let allocation = rucc_regalloc::run(&mut out, &env);
1820 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1821 finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
1822
1823 // `int f(int a, int b) { return a + b; }` end to end, and this is the test the argument
1824 // side exists for. Before it there was no way to write one: the allocator refuses a
1825 // function whose entry block takes parameters, because there is no edge into an entry
1826 // block for the moves that give a block parameter its value to go on.
1827 //
1828 // One move, and it is the one the machine's addition needs rather than one the allocator
1829 // owes anybody. Each argument stays in the register it arrived in, because the pseudo
1830 // that defines it insists on that register and the allocator now tries it first, and the
1831 // sum stays in the register the addition wrote it to until the return reads it out. The
1832 // copy in front of a two address instruction is what makes its destination one of the
1833 // registers it reads, and the source operand keeps its own name because the destination
1834 // is what the encoder writes.
1835 assert_eq!(
1836 mir::print_func(&out, &names, ®S),
1837 "mfunc @f {\nblock0:\n $rdi($rdi) = x64.arg_val_32\n \
1838 $rsi($rsi) = x64.arg_val_32\n \
1839 $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n $rax = x64.mov_rr_64 $rdi\n \
1840 x64.ret_val_32 $rax($rax)\n x64.ret\n}\n"
1841 );
1842 }
1843
1844 #[test]
1845 fn an_argument_with_no_register_left_for_it_is_read_out_of_the_caller_s_stack() {
1846 let i64 = Type::int(64);
1847 let (mut names, mut source, block, args) = blank(&[i64; 7]);
1848 let mut build = Builder::new(&mut source, block);
1849 build.ret(&[args[6]]);
1850
1851 let lowered = func(&source, &mut names, &SYSV).expect("the seventh is read from memory");
1852
1853 // SysV passes six integers in registers and the seventh in the caller's memory, so six of
1854 // these are pseudos that encode to nothing and the seventh is a load that encodes to real
1855 // bytes. Its displacement is nothing here for the reason a local's is: there is no frame
1856 // yet. What the walk hands on is which instruction is waiting, and for how far up the
1857 // caller's argument area, which is the bottom of it because it is the first one there.
1858 assert_eq!(lowered.stack.arguments.len(), 1);
1859 assert_eq!(lowered.stack.arguments[0].1, 0);
1860 let text = mir::print_func(&lowered.func, &names, ®S);
1861 assert!(text.contains("%6:gpr = x64.mov_rm_64 [$rsp]"), "{text}");
1862 assert_eq!(text.matches("x64.arg_val_64").count(), 6, "{text}");
1863 }
1864
1865 #[test]
1866 fn the_frame_is_what_says_how_far_up_the_caller_s_stack_an_argument_is() {
1867 let i64 = Type::int(64);
1868 let (mut names, mut source, block, args) = blank(&[i64; 8]);
1869 let mut build = Builder::new(&mut source, block);
1870 let sum = build.binary(Opcode::Add, args[6], args[7], Flags::default());
1871 build.ret(&[sum]);
1872
1873 let lowered = func(&source, &mut names, &SYSV).expect("both are read from memory");
1874 let stack = lowered.stack;
1875 let mut out = lowered.func;
1876 let env = env();
1877 let allocation = rucc_regalloc::run(&mut out, &env);
1878 let layout = stack.layout(Layout::new(&SYSV, REGS));
1879 let frame = Frame::of(&out, &allocation, &layout);
1880 finish(&mut out, &allocation, &frame, &stack, &SYSV, &FRAME, &mut names);
1881
1882 // A leaf that takes no frame, so the stack pointer never moves and the only thing between
1883 // it and the caller's arguments is the return address the call pushed. The seventh
1884 // parameter is at the bottom of the caller's argument area and the eighth is one word
1885 // further up, which is the eight bytes between the two offsets.
1886 let text = mir::print_func(&out, &names, ®S);
1887 assert_eq!(frame.size(), 0);
1888 assert_eq!(frame.incoming(), Incoming::from_stack(8));
1889 assert!(text.contains("x64.mov_rm_64 [$rsp + 8]"), "{text}");
1890 assert!(text.contains("x64.mov_rm_64 [$rsp + 16]"), "{text}");
1891 }
1892
1893 #[test]
1894 fn a_realigned_frame_reaches_the_caller_s_arguments_through_the_frame_pointer() {
1895 let i64 = Type::int(64);
1896 let (mut names, mut source, block, args) = blank(&[i64; 7]);
1897 let wide = slot(&mut source, block, 64, 32);
1898 let mut build = Builder::new(&mut source, block);
1899 build.store(args[6], wide, plain(), Flags::default());
1900 build.ret(&[args[6]]);
1901
1902 let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1903 let stack = lowered.stack;
1904 let mut out = lowered.func;
1905 let env = env();
1906 let allocation = rucc_regalloc::run(&mut out, &env);
1907 let layout = stack.layout(Layout::new(&SYSV, REGS));
1908 let frame = Frame::of(&out, &allocation, &layout);
1909 finish(&mut out, &allocation, &frame, &stack, &SYSV, &FRAME, &mut names);
1910
1911 // A local wanting thirty two byte alignment makes the prologue force the stack pointer,
1912 // which throws away how far the caller's stack was. So the load the lowering wrote off the
1913 // stack pointer is rewritten to read through the frame pointer, at the one distance that
1914 // survives: the word the prologue pushed the frame pointer into, and the return address
1915 // above it.
1916 let text = mir::print_func(&out, &names, ®S);
1917 assert_eq!(frame.realign(), Some(32));
1918 assert_eq!(frame.incoming(), Incoming::from_frame(16));
1919 assert!(text.contains("x64.mov_rm_64 [$rbp + 16]"), "{text}");
1920 assert!(!text.contains("x64.mov_rm_64 [$rsp"), "{text}");
1921 }
1922
1923 #[test]
1924 fn a_jump_is_the_edge_and_nothing_else() {
1925 let i32 = Type::int(32);
1926 let (mut names, mut source, entry, args) = blank(&[i32]);
1927 let next = source.create_block();
1928 let got = source.append_param(next, i32);
1929 Builder::new(&mut source, entry).jump(next, &[args[0]]);
1930 Builder::new(&mut source, next).ret(&[got]);
1931
1932 // Two blocks and two instructions, and the jump is neither of them. What it was is the
1933 // arm on the first block, and what the arm carries is the argument it was called with.
1934 assert_eq!(
1935 lower(&mut names, &source),
1936 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32 block1(%0)\n\n\
1937 block1(%1:gpr):\n x64.ret_val_32 %1($rax)\n}\n"
1938 );
1939 }
1940
1941 /// A constant is written where it is wanted rather than where the IR defined it, and two
1942 /// blocks wanting the same one is two places. Writing it once and reading it in both is a
1943 /// register read where nothing wrote it, unless the block it was written in happens to
1944 /// dominate the other, which nothing here checks and which the second arm of a branch never
1945 /// does. Each block gets its own copy of the number instead.
1946 #[test]
1947 fn a_constant_two_blocks_want_is_written_in_both_of_them() {
1948 let i32 = Type::int(32);
1949 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1950 let then = source.create_block();
1951 let other = source.create_block();
1952 let join = source.create_block();
1953 let got = source.append_param(join, i32);
1954
1955 let mut build = Builder::new(&mut source, entry);
1956 let seven = build.iconst(i32, 7);
1957 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1958 build.br_if(cond, then, &[], other, &[]);
1959 // Both arms want the seven in a register, because a block argument is never an immediate,
1960 // and neither arm dominates the other.
1961 Builder::new(&mut source, then).jump(join, &[seven]);
1962 Builder::new(&mut source, other).jump(join, &[seven]);
1963 Builder::new(&mut source, join).ret(&[got]);
1964
1965 let text = lower(&mut names, &source);
1966 assert_eq!(text.matches("x64.mov_ri_32 7").count(), 2, "one seven per block: {text}");
1967 }
1968
1969 /// An argument on an edge out of a block that leaves two ways is read after every instruction
1970 /// of the block is written, and reading one can write an instruction, which would land after
1971 /// the branch that has already jumped past it. The branch goes back on the end.
1972 #[test]
1973 fn a_constant_an_edge_wants_is_written_before_the_branch_and_not_after_it() {
1974 let i32 = Type::int(32);
1975 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1976 let then = source.create_block();
1977 let join = source.create_block();
1978 let got = source.append_param(join, i32);
1979
1980 let mut build = Builder::new(&mut source, entry);
1981 let nine = build.iconst(i32, 9);
1982 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1983 build.br_if(cond, then, &[], join, &[nine]);
1984 Builder::new(&mut source, then).jump(join, &[args[0]]);
1985 Builder::new(&mut source, join).ret(&[got]);
1986
1987 let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1988 let entry = out.entry().expect("an entry block");
1989 let last = out.terminator(entry).expect("a block that leaves two ways has a branch");
1990 let branch = names.intern("x64.br_cond_8");
1991 assert_eq!(
1992 out[last].opcode,
1993 mir::Opcode::new(branch),
1994 "the branch is last: {}",
1995 mir::print_func(&out, &names, ®S)
1996 );
1997 }
1998
1999 #[test]
2000 fn a_conditional_branch_is_lowered_to_the_condition_and_nothing_about_where_it_goes() {
2001 let i32 = Type::int(32);
2002 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
2003 let then = source.create_block();
2004 let other = source.create_block();
2005 let mut build = Builder::new(&mut source, entry);
2006 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
2007 build.br_if(cond, then, &[], other, &[]);
2008 Builder::new(&mut source, then).ret(&[args[0]]);
2009 Builder::new(&mut source, other).ret(&[args[1]]);
2010
2011 // The comparison writes a byte and the branch reads it, and neither says a block. Both
2012 // arms are on the entry block, in the order the branch took them, so the arm that runs
2013 // when the condition holds is the first.
2014 assert_eq!(
2015 lower(&mut names, &source),
2016 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
2017 %1:gpr($rsi) = x64.arg_val_32\n %2:gpr = x64.cmp_set_l_32 %0, %1\n \
2018 x64.br_cond_8 %2, block1, block2\n\n\
2019 block1:\n x64.ret_val_32 %0($rax)\n\n\
2020 block2:\n x64.ret_val_32 %1($rax)\n}\n"
2021 );
2022 }
2023
2024 #[test]
2025 fn a_branch_over_a_block_is_a_whole_function_now() {
2026 let i32 = Type::int(32);
2027 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
2028 let then = source.create_block();
2029 let other = source.create_block();
2030 let join = source.create_block();
2031 let got = source.append_param(join, i32);
2032 let mut build = Builder::new(&mut source, entry);
2033 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
2034 build.br_if(cond, then, &[], other, &[]);
2035 let mut build = Builder::new(&mut source, then);
2036 let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
2037 build.jump(join, &[sum]);
2038 Builder::new(&mut source, other).jump(join, &[args[1]]);
2039 Builder::new(&mut source, join).ret(&[got]);
2040
2041 // `int f(int a, int b) { if (a < b) return a + b; else return b; }` end to end, written
2042 // the way a front end writes it: both arms of the branch are blocks of their own and the
2043 // return is the block they meet at. No edge here is critical, because the two arms out of
2044 // the entry carry nothing and the two arms into the join each leave a block that goes
2045 // nowhere else, so each has its own end to put its move at.
2046 let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
2047 assert_eq!(crate::split::critical(&mut out), 0, "no edge here is critical");
2048 let env = env();
2049 let allocation = rucc_regalloc::run(&mut out, &env);
2050 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
2051 finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
2052
2053 // One epilogue, on the join, which is the one block the function leaves from, and the
2054 // moves that give the join its parameter are at the end of each arm. Every register is
2055 // physical and the branch is still a branch on a register, because turning it into a
2056 // `test` and a `jcc` is the block layout's and there is no block layout yet.
2057 let text = mir::print_func(&out, &names, ®S);
2058 assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
2059 assert!(text.contains("x64.br_cond_8"), "{text}");
2060 assert!(text.contains("x64.add_rr_32"), "{text}");
2061 assert!(!text.contains('%'), "{text}");
2062 }
2063
2064 #[test]
2065 fn a_critical_edge_is_split_before_the_allocator_ever_sees_it() {
2066 let i32 = Type::int(32);
2067 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
2068 let then = source.create_block();
2069 let join = source.create_block();
2070 let got = source.append_param(join, i32);
2071 let mut build = Builder::new(&mut source, entry);
2072 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
2073 build.br_if(cond, then, &[], join, &[args[1]]);
2074 Builder::new(&mut source, then).jump(join, &[args[0]]);
2075 let mut build = Builder::new(&mut source, join);
2076 let twice = build.binary(Opcode::Add, got, got, Flags::default());
2077 build.ret(&[twice]);
2078
2079 // The else arm is critical: the entry block leaves two ways and the join is arrived at
2080 // two ways, and the arm carries a value. Without splitting it the allocator asserts,
2081 // because the move that gives the join its parameter would have to run at the end of a
2082 // block that also goes to the other arm.
2083 let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
2084 assert_eq!(crate::split::critical(&mut out), 1);
2085 let env = env();
2086 let allocation = rucc_regalloc::run(&mut out, &env);
2087 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
2088 finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
2089
2090 // The block the split added is where the move went, and it is the whole of that block.
2091 let text = mir::print_func(&out, &names, ®S);
2092 assert_eq!(out.block_count(), 4, "{text}");
2093 assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
2094 }
2095
2096 #[test]
2097 fn a_call_passes_what_the_convention_says_and_takes_back_what_it_says() {
2098 let i32 = Type::int(32);
2099 let (mut names, mut source, block, args) = blank(&[i32, i32]);
2100 let sig =
2101 source.add_signature(Signature::new().with_params(&[i32, i32]).with_returns(&[i32]));
2102 let callee = names.intern("g");
2103 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0], args[1]]);
2104 let got = source[call].first_result.expect("an integer comes back");
2105 Builder::new(&mut source, block).ret(&[got]);
2106
2107 // `int f(int a, int b) { return g(a, b); }`. The arguments arrived where the call wants
2108 // them, so what the call reads is what arrived, and the whole of the convention is in the
2109 // constraints rather than in a move.
2110 let text = lower(&mut names, &source);
2111 assert!(text.contains("= x64.call %0($rdi), %1($rsi), @g"), "{text}");
2112 assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
2113 // What the call writes is the value that comes back and then every register the callee is
2114 // free to destroy, in both classes, which is the whole of what stops the allocator from
2115 // leaving something in one of them.
2116 assert!(text.contains("%2:gpr($rax), $rcx, $rdx, $r8, $r9, $r10, $r11, $xmm0,"), "{text}");
2117 assert!(text.contains("$xmm15 = x64.call"), "{text}");
2118 }
2119
2120 #[test]
2121 fn what_the_frame_owes_a_call_comes_back_with_the_function() {
2122 let i32 = Type::int(32);
2123 let sig = |source: &mut Func| source.add_signature(Signature::new().with_params(&[i32]));
2124
2125 let (mut names, mut source, block, args) = blank(&[i32]);
2126 let sig = sig(&mut source);
2127 let callee = names.intern("g");
2128 Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
2129 let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
2130
2131 // Nothing on the stack, so nothing owed, but not a leaf either: a function that calls
2132 // owes the callee an aligned stack pointer and may not use the red zone.
2133 assert_eq!(out.stack.calls, Some(0));
2134 let layout = out.stack.layout(Layout::new(&SYSV, REGS));
2135 assert!(!layout.leaf);
2136 assert_eq!(layout.outgoing, 0);
2137
2138 // The same call under the other convention owes thirty two bytes for the callee to spill
2139 // its register arguments into, which is a fact about the convention and not about the call.
2140 let out = func(&source, &mut names, &x86_64::WIN64).expect("every instruction has a rule");
2141 assert_eq!(out.stack.calls, Some(32));
2142
2143 // And a function that calls nothing is a leaf, which is what says it may use the red zone.
2144 let (mut names, mut source, block, args) = blank(&[i32]);
2145 Builder::new(&mut source, block).ret(&[args[0]]);
2146 let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
2147 assert_eq!(out.stack.calls, None);
2148 assert!(out.stack.layout(Layout::new(&SYSV, REGS)).leaf);
2149 }
2150
2151 #[test]
2152 fn a_value_that_outlives_a_call_is_not_left_where_the_call_destroys_it() {
2153 let i32 = Type::int(32);
2154 let (mut names, mut source, block, args) = blank(&[i32]);
2155 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
2156 let callee = names.intern("g");
2157 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
2158 let got = source[call].first_result.expect("an integer comes back");
2159 let mut build = Builder::new(&mut source, block);
2160 let sum = build.binary(Opcode::Add, got, args[0], Flags::default());
2161 build.ret(&[sum]);
2162
2163 // `int f(int a) { return g(a) + a; }`, which is the smallest program that asks the
2164 // question: `a` is read after the call and `rdi` is a register the call destroys.
2165 let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
2166 let layout = lowered.stack.layout(Layout::new(&SYSV, REGS));
2167 let mut out = lowered.func;
2168 let env = env();
2169 let allocation = rucc_regalloc::run(&mut out, &env);
2170 let frame = Frame::of(&out, &allocation, &layout);
2171 finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
2172
2173 // It went to a register the callee has to put back, and the prologue and epilogue are what
2174 // put it back, which is the whole bargain the two halves of a convention make.
2175 let text = mir::print_func(&out, &names, ®S);
2176 assert!(text.contains("$rbx"), "{text}");
2177 assert!(!text.contains('%'), "{text}");
2178 assert_eq!(text.matches("x64.call").count(), 1, "{text}");
2179 }
2180
2181 #[test]
2182 fn a_call_with_more_arguments_than_registers_writes_the_rest_into_the_outgoing_area() {
2183 let i64 = Type::int(64);
2184 let (mut names, mut source, block, args) = blank(&[i64]);
2185 let seven = vec![i64; 7];
2186 let sig = source.add_signature(Signature::new().with_params(&seven));
2187 let callee = names.intern("g");
2188 let passed = vec![args[0]; 7];
2189 Builder::new(&mut source, block).call(callee, sig, &passed);
2190
2191 let lowered = func(&source, &mut names, &SYSV).expect("the seventh goes to memory");
2192 // The bytes the call needs are on the layout the frame is worked out from, so that the
2193 // frame reserves as many as the widest call in the function asked for.
2194 assert_eq!(lowered.stack.calls, Some(8));
2195 let text = mir::print_func(&lowered.func, &names, ®S);
2196 assert!(text.contains("x64.mov_mr_64 %0, [$rsp]\n"), "{text}");
2197 }
2198
2199 #[test]
2200 fn a_call_this_cannot_make_is_reported_rather_than_made() {
2201 let (mut names, mut source, block, _) = blank(&[]);
2202 let sig = source
2203 .add_signature(Signature::new().with_returns(&[Type::float(rucc_ir::Float::F80)]));
2204 let callee = names.intern("g");
2205 Builder::new(&mut source, block).call(callee, sig, &[]);
2206 let failed = func(&source, &mut names, &SYSV).expect_err("a long double is on the x87");
2207 assert_eq!(failed.to_string(), "what this call gives back is on the x87 stack");
2208 }
2209
2210 #[test]
2211 fn a_call_through_an_address_goes_through_the_register_the_address_is_in() {
2212 let i32 = Type::int(32);
2213 let (mut names, mut source, block, args) = blank(&[Type::PTR, i32]);
2214 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
2215 let varargs = source.push_abis(&[]);
2216 let info = source.add_call(CallInfo { callee: None, signature: sig, varargs });
2217 let mut build = Builder::new(&mut source, block);
2218 let inst = InstData {
2219 args: build.func().push_values(&[args[0], args[1]]),
2220 extra: Extra::Call(info),
2221 ..InstData::new(Opcode::CallIndirect)
2222 };
2223 let called = build.inst(inst, &[i32]);
2224 let got = source[called].first_result.expect("an integer comes back");
2225 Builder::new(&mut source, block).ret(&[got]);
2226
2227 // `int f(int (*g)(int), int a) { return g(a); }`. The first operand is the address and
2228 // the arguments are the ones behind it, and everything else about the call is what a call
2229 // to a name would have been.
2230 let text = lower(&mut names, &source);
2231 assert!(text.contains("= x64.call_reg %0, %1($rdi)"), "{text}");
2232 assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
2233 assert!(!text.contains("@g"), "a call through an address names nobody: {text}");
2234 }
2235
2236 #[test]
2237 fn an_instruction_no_rule_covers_is_reported() {
2238 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
2239 let mut build = Builder::new(&mut source, block);
2240 let operands = build.func().push_values(&[args[0]]);
2241 build.inst(InstData { args: operands, ..InstData::new(Opcode::Prefetch) }, &[]);
2242
2243 // A hint about an address, which nothing writes an instruction for yet. Nothing about it
2244 // is a width or a register, so there is nothing for the message to add beyond the name.
2245 let failed = func(&source, &mut names, &SYSV).expect_err("no rule writes a prefetch");
2246 assert_eq!(failed.to_string(), "no rule lowers a `prefetch`");
2247
2248 // A `prefetch` produces nothing, so there is no type in the message and nothing invents
2249 // one, and the instruction comes back so a caller can ask the function where it was.
2250 let inst = failed.inst().expect("the instruction it is about");
2251 assert_eq!(source[inst].opcode, Opcode::Prefetch);
2252 }
2253
2254 /// A barrier is written by name here, and what it is depends on the ordering and on nothing
2255 /// else. `crate::expand` is where the reasoning about this machine's memory model lives.
2256 #[test]
2257 fn a_barrier_is_one_instruction_at_the_strongest_ordering_and_none_below_it() {
2258 for order in MemOrder::all().filter(|&order| order != MemOrder::NotAtomic) {
2259 let (mut names, mut source, block, _) = blank(&[]);
2260 let mut build = Builder::new(&mut source, block);
2261 build
2262 .inst(InstData { extra: Extra::Order(order), ..InstData::new(Opcode::Fence) }, &[]);
2263
2264 let text = lower(&mut names, &source);
2265 assert_eq!(text.contains("x64.mfence"), order == MemOrder::SeqCst, "{order:?}: {text}");
2266 }
2267 }
2268
2269 #[test]
2270 fn more_values_back_than_the_convention_has_registers_for_is_reported() {
2271 let i64 = Type::int(64);
2272 let (mut names, mut source, block, args) = blank(&[i64, i64, i64]);
2273 let mut build = Builder::new(&mut source, block);
2274 build.ret(&[args[0], args[1], args[2]]);
2275
2276 // Two integers come back in `rax` and `rdx` and a third has nowhere to go, which is not a
2277 // gap in the rules but the convention saying no. The front end classifies before it gets
2278 // here, so this is the shape that would mean the classification went wrong.
2279 let failed = func(&source, &mut names, &SYSV).expect_err("only two come back");
2280 assert_eq!(
2281 failed.to_string(),
2282 "what this function gives back takes more registers than this convention has for it"
2283 );
2284
2285 let inst = failed.inst().expect("the instruction it is about");
2286 assert_eq!(source[inst].opcode, Opcode::Return);
2287 }
2288
2289 /// A refusal about a signature has no instruction, which is what makes it the one arm apart.
2290 ///
2291 /// Everything else is about something written somewhere in the body and hands it back so a
2292 /// caller can ask the function where it came from. A parameter arrives before the first
2293 /// instruction runs, so there is nothing in the body to point at and the message is about
2294 /// the function.
2295 #[test]
2296 fn a_refusal_about_a_parameter_has_no_instruction_to_point_at() {
2297 let missing = Unsupported::Argument { index: 0, missing: Missing::OnX87 };
2298 assert_eq!(missing.inst(), None);
2299 }
2300
2301 /// An `alloca` of a fixed size, which is what every local whose address is taken becomes.
2302 fn slot(source: &mut Func, block: Block, size: u64, align: u32) -> Value {
2303 let info = MemInfo { size, align, ..plain() };
2304 let mut build = Builder::new(source, block);
2305 let mem = build.func().add_mem(info);
2306 build.value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR)
2307 }
2308
2309 #[test]
2310 fn a_local_is_memory_in_the_frame_and_one_instruction_that_says_where() {
2311 let (mut names, mut source, block, _) = blank(&[]);
2312 let slot = slot(&mut source, block, 4, 4);
2313 let mut build = Builder::new(&mut source, block);
2314 let nine = build.iconst(Type::int(32), 9);
2315 build.store(nine, slot, plain(), Flags::default());
2316 let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
2317 build.ret(&[loaded]);
2318
2319 let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
2320
2321 // Four bytes on the list the frame is laid out from, and the one instruction that reads
2322 // where they went. Its displacement is nothing here because there is no frame yet, and
2323 // which instruction is waiting for which local is what `finish` is handed.
2324 assert_eq!(lowered.stack.locals, vec![Local { size: 4, align: 4 }]);
2325 assert_eq!(lowered.stack.addresses.len(), 1);
2326 assert_eq!(lowered.stack.addresses[0].1, 0);
2327 assert_eq!(
2328 mir::print_func(&lowered.func, &names, ®S),
2329 "mfunc @f {\nblock0:\n %0:gpr = x64.lea_64 [$rsp]\n \
2330 %1:gpr = x64.mov_ri_32 9\n x64.mov_mr_32 %1, [%0]\n \
2331 %2:gpr = x64.mov_rm_32 [%0]\n x64.ret_val_32 %2($rax)\n}\n"
2332 );
2333 }
2334
2335 #[test]
2336 fn the_frame_is_what_fills_the_address_of_a_local_in() {
2337 let (mut names, mut source, block, _) = blank(&[]);
2338 let slot = slot(&mut source, block, 4, 4);
2339 let mut build = Builder::new(&mut source, block);
2340 let nine = build.iconst(Type::int(32), 9);
2341 build.store(nine, slot, plain(), Flags::default());
2342 let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
2343 build.ret(&[loaded]);
2344
2345 let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
2346 let stack = lowered.stack;
2347 let mut out = lowered.func;
2348 let env = env();
2349 let allocation = rucc_regalloc::run(&mut out, &env);
2350 let layout = stack.layout(Layout::new(&SYSV, REGS));
2351 let frame = Frame::of(&out, &allocation, &layout);
2352 finish(&mut out, &allocation, &frame, &stack, &SYSV, &FRAME, &mut names);
2353
2354 // `int f(void) { int x; x = 9; return x; }` with the address of `x` taken, end to end.
2355 // A leaf small enough to live in the red zone takes no frame at all, so the stack pointer
2356 // never moves and the four bytes are below it, which is what the negative offset is. The
2357 // instruction the lowering left with nothing in its displacement now has the answer in it.
2358 let text = mir::print_func(&out, &names, ®S);
2359 assert!(text.contains("$rax = x64.lea_64 [$rsp - 8]"), "{text}");
2360 assert!(!text.contains("x64.sub_ri_64"), "{text}");
2361 assert_eq!(frame.size(), 0);
2362 assert_eq!(frame.local(0), Some(-8));
2363 }
2364
2365 #[test]
2366 fn a_stack_slot_whose_size_is_not_known_until_it_runs_is_reported() {
2367 let i64 = Type::int(64);
2368 let (mut names, mut source, block, args) = blank(&[i64]);
2369 let info = MemInfo { size: 0, align: 16, ..plain() };
2370 let mut build = Builder::new(&mut source, block);
2371 let mem = build.func().add_mem(info);
2372 let size = build.func().push_values(&[args[0]]);
2373 let slot = build.value(
2374 InstData { args: size, extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) },
2375 Type::PTR,
2376 );
2377 Builder::new(&mut source, block).ret(&[slot]);
2378
2379 // A variable length array. Growing the stack where the declaration stands means moving the
2380 // stack pointer in the middle of the function and reaching everything else through a
2381 // frame pointer afterwards, and the frame here lays out neither.
2382 let failed = func(&source, &mut names, &SYSV).expect_err("nothing grows the stack");
2383 assert_eq!(failed.to_string(), "nothing here grows the stack for a variable length array");
2384 }
2385
2386 #[test]
2387 fn an_address_is_read_written_and_added_to_like_the_integer_it_is() {
2388 let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
2389 let mut build = Builder::new(&mut source, block);
2390 let stepped = build.func().push_values(&[args[0], args[1]]);
2391 let next =
2392 build.value(InstData { args: stepped, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2393 let loaded = build.load(Type::int(32), next, plain(), Flags::default());
2394 build.ret(&[loaded]);
2395
2396 // `int f(int *p, long i) { return *(int *)((char *)p + i); }`. Nothing about this is new
2397 // in the rule set, which is the point: the two addresses arrive in registers because an
2398 // address is an integer as wide as one, and the arithmetic on them is the add it always
2399 // was, so every rule written about an add reaches it.
2400 //
2401 // The add stays its own instruction rather than folding into the address the load reads
2402 // from. Two registers with no scale on either is the one addressing mode the rules have no
2403 // load through, because the folds that exist are the displacement one and the scaled ones,
2404 // and this is neither. That is a peephole worth having and not a thing this changes.
2405 assert_eq!(
2406 lower(&mut names, &source),
2407 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
2408 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n \
2409 %3:gpr = x64.mov_rm_32 [%2]\n x64.ret_val_32 %3($rax)\n}\n"
2410 );
2411 }
2412
2413 /// The address of a file scope name, which is what every use of a global and every string
2414 /// literal starts from.
2415 fn address_of(source: &mut Func, block: Block, names: &mut Interner, name: &str) -> Value {
2416 let symbol = names.intern(name);
2417 let mut build = Builder::new(source, block);
2418 build.value(
2419 InstData { extra: Extra::Symbol(symbol), ..InstData::new(Opcode::GlobalAddr) },
2420 Type::PTR,
2421 )
2422 }
2423
2424 #[test]
2425 fn the_address_of_a_name_is_one_instruction_carrying_the_name() {
2426 let (mut names, mut source, block, _) = blank(&[]);
2427 let counter = address_of(&mut source, block, &mut names, "counter");
2428 let mut build = Builder::new(&mut source, block);
2429 let loaded = build.load(Type::int(32), counter, plain(), Flags::default());
2430 build.ret(&[loaded]);
2431
2432 // `extern int counter; int f(void) { return counter; }`. The address is an addressing mode
2433 // that names no register and carries the symbol, which is what the assembler writes
2434 // relative to `%rip` and what the object writer leaves a relocation for.
2435 assert_eq!(
2436 lower(&mut names, &source),
2437 "mfunc @f {\nblock0:\n %0:gpr = x64.lea_64 [@counter]\n \
2438 %1:gpr = x64.mov_rm_32 [%0]\n x64.ret_val_32 %1($rax)\n}\n"
2439 );
2440 }
2441
2442 /// A cast between a pointer and an integer, at whatever width the result is asked for.
2443 fn cast(source: &mut Func, block: Block, opcode: Opcode, from: Value, to: Type) -> Value {
2444 let mut build = Builder::new(source, block);
2445 let args = build.func().push_values(&[from]);
2446 build.value(InstData { args, ..InstData::new(opcode) }, to)
2447 }
2448
2449 #[test]
2450 fn a_cast_between_a_pointer_and_an_integer_as_wide_is_no_instruction_at_all() {
2451 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
2452 let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(64));
2453 Builder::new(&mut source, block).ret(&[number]);
2454
2455 // `long f(void *p) { return (long)p; }`. An address on this machine is an integer as wide
2456 // as the machine addresses, so the cast changes what the type system calls the value and
2457 // changes nothing about the value, and the register holding it is the one that held it.
2458 assert_eq!(
2459 lower(&mut names, &source),
2460 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
2461 x64.ret_val_64 %0($rax)\n}\n"
2462 );
2463 }
2464
2465 #[test]
2466 fn a_null_pointer_is_a_constant_that_reaches_a_register_before_anything_reads_it() {
2467 let (mut names, mut source, block, _) = blank(&[]);
2468 let mut build = Builder::new(&mut source, block);
2469 let zero = build.iconst(Type::int(64), 0);
2470 let null = cast(&mut source, block, Opcode::IntToPtr, zero, Type::PTR);
2471 Builder::new(&mut source, block).ret(&[null]);
2472
2473 // `void *f(void) { return 0; }`. The cast is nothing, and reading its operand is what
2474 // writes the zero down: a constant is materialized where it is wanted rather than where
2475 // the IR defined it, and without the read there would be no instruction at all.
2476 assert_eq!(
2477 lower(&mut names, &source),
2478 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_64 0\n x64.ret_val_64 %0($rax)\n}\n"
2479 );
2480 }
2481
2482 #[test]
2483 fn the_five_linkages_the_ir_has_narrow_to_the_three_an_object_file_can_say() {
2484 let readings = [
2485 (Linkage::External, mir::Binding::Global),
2486 (Linkage::Common, mir::Binding::Global),
2487 (Linkage::Internal, mir::Binding::Local),
2488 (Linkage::Weak, mir::Binding::Weak),
2489 (Linkage::LinkOnce, mir::Binding::Weak),
2490 ];
2491 for (linkage, wanted) in readings {
2492 let (mut names, mut source, block, _) = blank(&[]);
2493 source.linkage = linkage;
2494 Builder::new(&mut source, block).ret(&[]);
2495 let out = func(&source, &mut names, &SYSV).expect("a return");
2496 // The narrowing is done here rather than where the object is written, because a
2497 // machine function is all the assembler and the writer are ever handed.
2498 assert_eq!(out.func.binding, wanted, "{linkage:?}");
2499 }
2500 }
2501
2502 #[test]
2503 fn a_cast_between_a_pointer_and_a_narrower_integer_is_reported() {
2504 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
2505 let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(32));
2506 Builder::new(&mut source, block).ret(&[number]);
2507
2508 // The front end never writes one: it casts at the address width and truncates or extends
2509 // around it, so both of those are the rules they always were. IR from somewhere else that
2510 // does write one is refused rather than compiled to a move that keeps the high half.
2511 let failed = func(&source, &mut names, &SYSV).expect_err("no rule narrows an address");
2512 assert_eq!(failed.to_string(), "no rule lowers a `ptrtoint` producing a `i32`");
2513 }
2514}