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::collections::{HashMap, HashSet};
79use std::fmt;
80
81use rucc_base::{Interner, Symbol};
82use rucc_diag::Span;
83use rucc_ir::{
84 Abi, AsmOperand, AsmOperands, AttrSet, Block, Def, Extra, Flags, FloatPred, Func, Inst,
85 Linkage, MemOrder, Opcode, Param, PrefetchHint, RmwOp, Type, Value, Visibility,
86};
87use rucc_mir as mir;
88use rucc_target::template::{template_name, template_reg};
89use rucc_target::{
90 Address, CallRegs, Constraint, OperandDesc, PhysReg, RegClass, Role, VaList, Variadic,
91};
92use rucc_target::{aarch64, x86_64};
93
94use crate::abi::{self, Missing, Refused};
95use crate::coverage::Fired;
96use crate::elsewhere::Elsewhere;
97use crate::frame::{Layout, Local};
98use crate::select::{Match, Piece, Pointer, Reach, Rule, Selector};
99use crate::term::{MAX_ARGS, PLAIN, Plan, Shown, Term, Terms};
100use crate::varargs;
101
102/// The instruction a template's `jmp` to a name outside it becomes.
103///
104/// The same instruction [`x86_64::FRAME`] names for the end of a tail call, named here as well
105/// because what reaches this one is a template in a function with no prologue and no epilogue,
106/// which is nothing to do with the frame.
107/// See [`x86_64::Step::Away`].
108const AWAY: &str = "jmp_away";
109
110/// How wide an address is on this target, which is the width a cast between a pointer and an
111/// integer has to be at for the cast to be nothing.
112const ADDRESS_BITS: u32 = 64;
113
114/// How much of a register an operand of an `asm` statement fills, which is the width of its type
115/// with two exceptions. A pointer is an address, and a truth value is the byte it is stored in: a
116/// program that writes `sete %0` into a `_Bool` is asking for exactly that byte, which is what tcc's
117/// own test of the width of one checks.
118fn held_bits(ty: Type) -> u32 {
119 if ty.is_ptr() {
120 ADDRESS_BITS
121 } else if ty.bits() == 1 {
122 8
123 } else {
124 ty.bits()
125 }
126}
127
128/// How many bytes a `long double` takes in memory, and what it is aligned to, which are the same
129/// number and are both more than the ten bytes that mean anything.
130///
131/// The psABI's answer rather than a choice here. `sizeof (long double)` is sixteen on this
132/// machine, so an array of them is laid out this way whatever a slot holding one does, and a slot
133/// that agreed with the array is one fewer thing to get wrong.
134const X87_BYTES: u32 = 16;
135
136/// How many values the x87 stack holds at once.
137///
138/// Eight, which is the machine's number rather than a choice here, and it matters in one place:
139/// the parameters of a block are copied through the stack so that they all move at once, and a
140/// block with more of them than this has nowhere to put the ninth.
141const X87_DEPTH: usize = 8;
142
143/// How far into the buffer of a `__builtin_setjmp` each of the four words it writes is.
144///
145/// The first three are gcc's, measured against gcc 16.2.0 on x86-64 at `-O0`: the frame pointer,
146/// the address control comes back to, and the stack pointer, in that order. The fourth is this
147/// compiler's own. gcc has no word for the answer because it writes a second block that sets the
148/// answer to one and is arrived at from the restore, and this writes the answer through memory
149/// instead, for the reason [`Lowering::saves_place`] gives.
150///
151/// None of the four is an interface. The buffer is the program's memory and its five words are
152/// the front end's promise about how much of it there is, but nothing except the matching restore
153/// ever reads a word of it, and a buffer written by one compiler was never going to be one another
154/// compiler could come back through.
155const JUMP_FRAME: i32 = 0;
156
157/// Where the address control comes back to is. See [`JUMP_FRAME`].
158const JUMP_PC: i32 = 8;
159
160/// Where the stack pointer is. See [`JUMP_FRAME`].
161const JUMP_STACK: i32 = 16;
162
163/// Where the address of the word the answer arrives in is. See [`JUMP_FRAME`].
164const JUMP_ANSWER: i32 = 24;
165
166/// How many bytes the word a `__builtin_setjmp` answers with takes in the frame, and what it is
167/// aligned to, which are the same number because it is one machine word.
168const JUMP_WORD: u32 = 8;
169
170/// How many registers the restore needs to hold things in while it puts the frame back.
171///
172/// Four, and every one of them is a register nothing else in the function may be in, which is why
173/// they are counted here rather than asked for one at a time. See [`Lowering::comes_back`].
174const JUMP_REGS: usize = 4;
175
176/// How many bytes the block `__builtin_apply_args` answers takes, which is a word for where the
177/// arguments in memory are, a word of nothing and then the register save area of a variadic
178/// function. See [`Lowering::save_arguments`].
179const APPLY_ARGS: u32 = 192;
180
181/// How far into that block the registers start, which is how far the save area has moved up.
182const APPLY_REGS: u32 = 16;
183
184/// How many bytes the block `__builtin_apply` answers takes, which is two words and two vectors.
185const APPLY_BACK: u32 = 48;
186
187/// How many bytes a value passes through on its way between a register and the x87 stack.
188///
189/// Eight, because the widest thing that crosses is a `double` or a sixty four bit integer, and
190/// nothing crosses at eighty bits: a value that wide is already in the frame and the stack reaches
191/// it where it is.
192const X87_CROSSING: u32 = 8;
193
194/// Where the rounding field of the x87 control word is and what it has to be set to for the unit
195/// to cut towards zero, which is the one rounding C asks for that the unit does not do by default.
196///
197/// Both bits on is truncate. The field is ORed into the word that was already there rather than
198/// written over it, so the precision control and the exception masks somebody else set stay set.
199const X87_TRUNCATE: i64 = 0x0c00;
200
201/// Whether a type is the one this machine has no register for.
202///
203/// Only the eighty bit float is, and that is a fact about x86-64 rather than about floats: every
204/// other scalar the front end produces is in a general purpose register or a vector one, and this
205/// one is on the x87 stack while it is being worked on and in memory the rest of the time. So it
206/// has no place in [`Lowering::class_of`] and no name in [`crate::term`], and every instruction
207/// that touches one is written out by hand in this file.
208fn on_x87(ty: Type) -> bool {
209 ty.is_scalar() && ty.is_float() && ty.bits() == 80
210}
211
212/// Where one operand of an assembly statement is, on each side of the assembly.
213///
214/// Two registers rather than one, because an operand written `+` is a value that arrives and a
215/// value that leaves and those are two values. The machine IR has one definition per register by
216/// construction, so an instruction of the template that reads the operand and writes it has to name
217/// a different register in each place, and what makes the two one register in the end is the
218/// [`Constraint::Reuse`] the instruction's description carries: the allocator reads it, gives both
219/// the same physical register, and copies the incoming value somewhere first when something else is
220/// still using it.
221///
222/// Most operands have one of the two. An input has only a place it is read from and an output
223/// written `=` has only a place it is written to, and asking either of them for the other is an
224/// operand read where the opcode writes or written where it reads, which [`Lowering::placed`]
225/// refuses.
226#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
227struct Place {
228 /// The register the value arrives in, for an operand something reads.
229 read: Option<mir::Reg>,
230 /// The register the value leaves in, for an operand something writes.
231 write: Option<mir::Reg>,
232}
233
234/// Whether that operand of the statement is one the assembly may read, and so where a read of it
235/// gets its value from.
236///
237/// [`bound`] asks this question of an operand a constraint letter named and this asks it of one the
238/// template numbered, which is the same question twice because a two-address instruction reaches
239/// its first source both ways. `mulq %3` reaches `rax` by the letter on the output and libgmp says
240/// what is in it with `"%0"` on an input. `addq %5,%q1` reaches its first source by numbering the
241/// output, and libgmp says what is in it with `"0"` on an input in the same way.
242///
243/// So an output written `=` has no value of its own and is still readable when an input is tied to
244/// it, and the value the read wants is that input's. An output written `+` carries its own value
245/// and answers with that. An output nothing is tied to answers `None`, which is a program that told
246/// the compiler the assembly only writes the operand while the instruction reads it before it
247/// writes it, and is refused where it is asked.
248fn read_as(list: &[AsmOperand<'_>], index: usize) -> Option<Value> {
249 let operand = list.get(index)?;
250 if operand.value.is_some() {
251 return operand.value;
252 }
253 operand.result?;
254 list.iter().find(|entry| entry.tied == Some(index)).and_then(|entry| entry.value)
255}
256
257/// Which of an assembly statement's operands is in that register, for an instruction that reaches
258/// the register without its text saying so.
259///
260/// The constraint is what says so, and it is the only thing in such a statement that could:
261/// `"=a"` is an output in `rax`, `"c"` is an input in `rcx`, an operand that is a local register
262/// variable is in the register its declaration named, and a register nothing names is a register
263/// nobody has said anything about. So a write looks among the outputs and a read among the inputs,
264/// and an output written `+` answers for either, since it is read before it is written. See
265/// [`pinned`], which is the one question asked of both ways of saying it.
266///
267/// The other way a read of such a register is said is a matching constraint. `"=a"` on an output
268/// and `"0"` on an input is the program saying that one register holds the input on the way in and
269/// the output on the way out, and it is how a statement fills a register the instruction reads and
270/// writes without writing the register down twice. The letter is on the output, which has no value
271/// to read, and the value is on the input, which has no letter, and the answer is the output: its
272/// place is read out of the register the input arrived in, and in a template with a loop in it the
273/// place moves on to wherever the last write left it, which is what a read on the next time round
274/// wants. tcc steps a pointer along a string with `lodsb` and `"=&S"` tied to `"0"`, and a read of
275/// the input would start the string again every time round.
276///
277/// And a read of a register an output alone is in is a read of that output, the same as a read of
278/// an output the template numbered. tcc copies a string with `lodsb` and `stosb` and `"=&a"` on an
279/// output nothing is tied to, and what `stosb` stores is what `lodsb` loaded one line up, which is
280/// the output as the template left it rather than anything the statement handed in.
281///
282/// `None` is a register the instruction uses and the statement put nothing in, which is the usual
283/// answer rather than an unusual one. `cpuid` writes four registers and a program that wanted one
284/// of them names one. See [`Lowering::spare`], which is where that one goes.
285fn bound(list: &[AsmOperand<'_>], reg: PhysReg, role: Role) -> Option<usize> {
286 let output =
287 list.iter().position(|operand| operand.result.is_some() && pinned(operand) == Some(reg));
288 if role.is_def() {
289 return output;
290 }
291 // The output first when something is in it on the way in, which is what `+` and a matching
292 // constraint both say, since its place is where a write earlier in the template left it and
293 // the read wants that. See [`read_as`] for what it holds before anything wrote it.
294 let arrives = |at: usize| read_as(list, at).is_some();
295 if let Some(at) = output.filter(|&at| arrives(at)) {
296 return Some(at);
297 }
298 let named = list.iter().position(|operand| {
299 operand.result.is_none() && operand.value.is_some() && pinned(operand) == Some(reg)
300 });
301 named.or(output)
302}
303
304/// The register one of an assembly statement's operands is in, whichever of the two ways said it.
305///
306/// A constraint letter is one way and is the only way a program can say one of the six registers
307/// that have a letter. A local register variable is the other, and it is the only way to say any
308/// of the rest: there is no letter for `r12`, which is the whole reason the extension exists, so
309/// the declaration says it and the front end wrote the name into the constraint. The name is read
310/// against this machine's table here, the same place the letter is read against it, and a name the
311/// machine has not got answers nothing, which leaves the operand where an operand nobody placed
312/// goes.
313///
314/// The sigil gcc allows in front of a name is taken off here, because what a name is written with
315/// is syntax and which register it means is this question.
316fn pinned(operand: &AsmOperand<'_>) -> Option<PhysReg> {
317 match operand.named {
318 Some(name) => {
319 let (reg, _) = x86_64::gpr_named(name.strip_prefix('%').unwrap_or(name))?;
320 Some(reg)
321 }
322 None => operand.fixed.and_then(x86_64::gpr_letter),
323 }
324}
325
326/// Whether a constraint says nothing but what it says on every machine.
327///
328/// [`AsmOperands::read`] gives the x86 meaning to every letter it knows, and most of the letters
329/// mean something else on AArch64: `Q` is an address in one register there rather than one of four
330/// registers, and `a` to `d` name nothing. So an AArch64 statement is taken only with the letters
331/// the two agree on, which are a register, a constant, memory, the immediate ranges and a matching
332/// number, and anything else is refused rather than read as x86. `w` and `Q` are the exceptions.
333/// `w` is a register on both, and which file it is in is decided by the caller with
334/// [`vector_letter`]. `Q` is read as `m` by the caller before the list is read. A
335/// register the front end named in braces is read against AArch64's own names, so what is inside
336/// them is not a letter.
337fn shared_letters(constraint: &str) -> bool {
338 let mut inside = false;
339 constraint.chars().all(|c| match c {
340 '{' => {
341 inside = true;
342 true
343 }
344 '}' => {
345 inside = false;
346 true
347 }
348 _ if inside => true,
349 _ => matches!(
350 c,
351 '=' | '+' | '&' | '%' | 'r' | 'w' | 'Q' | 'm' | 'o' | 'V' | 'g' | 'X' | 'i' | 'n'
352 | 'p' | 'I'..='N' | '0'..='9'
353 ),
354 })
355}
356
357/// A constraint list with every letter outside braces put through `swap`, and what is inside them,
358/// which is a register's name rather than letters, left alone.
359fn letters_outside(constraints: &str, swap: impl Fn(char) -> char) -> String {
360 let mut inside = false;
361 constraints
362 .chars()
363 .map(|c| {
364 match c {
365 '{' => inside = true,
366 '}' => inside = false,
367 _ if !inside => return swap(c),
368 _ => {}
369 }
370 c
371 })
372 .collect()
373}
374
375/// Whether an AArch64 constraint asks for a floating point or vector register, which is what `w`
376/// means there. A register named in braces is not a letter, so a `w` inside one is not read.
377fn vector_letter(constraint: &str) -> bool {
378 let mut inside = false;
379 constraint.chars().any(|c| {
380 match c {
381 '{' => inside = true,
382 '}' => inside = false,
383 _ => {}
384 }
385 !inside && c == 'w'
386 })
387}
388
389/// The x86-64 vector register one entry of a clobber list names, spelled `xmm0` or `ymm0` with or
390/// without the sigil, or nothing for any other entry. Only the sixteen there are without AVX-512,
391/// so `zmm0` and `xmm16` are still refused as names this has no register for.
392fn vector_named(entry: &str) -> Option<PhysReg> {
393 let entry = entry.trim().trim_matches('"');
394 let entry = entry.strip_prefix('%').unwrap_or(entry);
395 let number = entry.strip_prefix("xmm").or_else(|| entry.strip_prefix("ymm"))?;
396 if number.len() > 1 && number.starts_with('0') {
397 return None;
398 }
399 let number: u8 = number.parse().ok()?;
400 (number < 16).then(|| x86_64::xmm(number))
401}
402
403/// Whether a line of a template names, by number, an operand `wanted` says yes to.
404///
405/// `%%` is a percent sign rather than an operand, and a modifier letter may stand between the sign
406/// and the number.
407fn names_one(line: &str, wanted: impl Fn(usize) -> bool) -> bool {
408 let mut rest = line;
409 while let Some(at) = rest.find('%') {
410 let after = &rest[at + 1..];
411 if let Some(escaped) = after.strip_prefix('%') {
412 rest = escaped;
413 continue;
414 }
415 let after = after.strip_prefix(|c: char| c.is_ascii_alphabetic()).unwrap_or(after);
416 let digits = after.len() - after.trim_start_matches(|c: char| c.is_ascii_digit()).len();
417 if after[..digits].parse().is_ok_and(&wanted) {
418 return true;
419 }
420 rest = &after[digits..];
421 }
422 false
423}
424
425/// Why a function could not be lowered.
426///
427/// One reason and then nothing. A function with no rule for something in it is a function this
428/// cannot finish, and the second thing it could not lower is not news.
429#[derive(Debug, Clone, PartialEq, Eq)]
430pub enum Unsupported {
431 /// An instruction no rule fires on.
432 Inst {
433 /// The instruction that stopped it.
434 inst: Inst,
435 /// What the rule file would call it, or nothing if the rule language has no name for it
436 /// at all, which is what an instruction at a width nothing is written about looks like.
437 term: Option<&'static str>,
438 /// The opcode, which is what gets named when the rule language has no word for it.
439 ///
440 /// An opcode the rule language has no word for is exactly the opcode no rule lowers, so
441 /// without this the message would be empty in every case where somebody needs it.
442 opcode: Opcode,
443 /// What it produces, or nothing for an instruction that is only an effect.
444 ty: Option<Type>,
445 },
446 /// A parameter that does not arrive somewhere this can bring it in from.
447 ///
448 /// Not an instruction, which is why it is a separate arm: it is a fact about the signature
449 /// and there is nothing in the body of the function to point at.
450 Argument {
451 /// Its position in the signature.
452 index: usize,
453 /// What is wrong with where it arrives.
454 missing: Missing,
455 },
456 /// A call that passes or gives back a value this cannot put where the convention wants it.
457 Call {
458 /// The call.
459 inst: Inst,
460 /// Which value, and what is wrong with where it travels.
461 refused: Refused,
462 },
463 /// A `return` this cannot put where the convention wants it.
464 ///
465 /// A separate arm from [`Unsupported::Inst`] because it is not an instruction no rule fires
466 /// on. A return of more than one value is built from the convention rather than matched, the
467 /// same way a call is, so what goes wrong with one is what goes wrong with a call and not the
468 /// absence of a rule.
469 Returned {
470 /// The `return`.
471 inst: Inst,
472 /// What is wrong with where one of the values travels.
473 missing: Missing,
474 },
475 /// A stack slot the frame cannot give the bytes it asked for.
476 ///
477 /// Not an instruction no rule covers. An `alloca` is built here rather than matched, so what
478 /// goes wrong with one is what the frame can and cannot hold rather than what the rules spell.
479 Dynamic {
480 /// The `alloca`.
481 inst: Inst,
482 /// What the frame could not do about it.
483 growing: Growing,
484 },
485 /// More parameters of a type that travels on the x87 stack than the stack is deep.
486 ///
487 /// Not an instruction either, for the reason a function's parameter is not one: it is a fact
488 /// about the block and there is nothing in the block to point at. What crosses an edge for one
489 /// of these is the address of where the value is, and the block copies the bytes into a slot
490 /// of its own, all of them through the stack at once so that a block carrying two of them
491 /// swapped is copied in an order that is right. Eight is as many as the stack holds, and a
492 /// ninth would have to be copied before or after the rest, which is the order that could be
493 /// wrong.
494 Phi {
495 /// Which block it arrives at.
496 block: Block,
497 /// How many of them arrive there, which is the whole of what is wrong.
498 count: usize,
499 /// What they are.
500 ty: Type,
501 },
502 /// An `asm` statement this cannot build.
503 ///
504 /// Not an instruction no rule fires on, for the reason a call is not one: what it stands for is
505 /// whatever its template says, and no pattern over terms can read a string.
506 Assembly {
507 /// The `inline_asm`.
508 inst: Inst,
509 /// What about it is not built here yet.
510 refused: Written,
511 },
512 /// A `register long x asm ("...")` naming something this machine has not got.
513 ///
514 /// Not an instruction no rule fires on. There is a rule's worth of instruction here and what
515 /// is wrong is the string beside it, which is a name rather than a term, so the message says
516 /// the name. Which names a machine has is the machine's own question and this is where it is
517 /// asked, at the table a clobber list is read against.
518 Register {
519 /// The `register_value`.
520 inst: Inst,
521 /// The name the program wrote, as it wrote it.
522 name: String,
523 },
524 /// A naked function whose frame is not empty.
525 ///
526 /// Not an instruction no rule fires on, and there is nothing in the body to point at: the
527 /// function asked for no prologue and then wanted bytes only a prologue takes. Refused rather
528 /// than given the bytes anyway, because an offset into a frame nothing set up reaches into
529 /// whatever the caller left below its own stack pointer, which is wrong code that assembles.
530 /// See [`crate::frame::Layout::naked`].
531 Naked {
532 /// How many bytes it wanted, which is the whole of what is wrong.
533 bytes: u32,
534 },
535 /// Something the x86-64 lowering writes by hand and nothing has written for this machine yet.
536 ///
537 /// Refused rather than written with the x86 instructions, which is what the walk would do
538 /// otherwise, since these are the places it names them itself.
539 Unported {
540 /// The instruction, or nothing for the one that is about a signature.
541 inst: Option<Inst>,
542 /// Which of them.
543 what: Unported,
544 },
545}
546
547/// What [`Unsupported::Unported`] is about.
548#[derive(Debug, Clone, Copy, PartialEq, Eq)]
549pub enum Unported {
550 /// The thread pointer on Apple's platforms, which keep it somewhere other than Linux does.
551 Thread,
552}
553
554impl Unported {
555 /// The whole message, since there is nothing to put in front of it.
556 #[must_use]
557 pub fn why(self) -> &'static str {
558 match self {
559 Unported::Thread => "the thread pointer is not written for this platform yet",
560 }
561 }
562}
563
564/// What about an `asm` statement is not built yet.
565#[derive(Debug, Clone, Copy, PartialEq, Eq)]
566pub enum Written {
567 /// A template with instructions in it.
568 Template,
569 /// An `asm goto`, whose labels make the statement a terminator.
570 Goto,
571 /// An operand this cannot put where the constraint says it goes.
572 Operand,
573 /// A clobber list naming something this has no register for.
574 Clobber,
575 /// A `jmp` out of the function in a function that has an epilogue behind it.
576 Away,
577}
578
579impl Written {
580 /// The rest of the sentence that starts with the statement.
581 #[must_use]
582 pub fn why(self) -> &'static str {
583 match self {
584 // The template is the assembler's to read and there is no assembler here yet, so a
585 // template with anything in it is a string nothing can turn into bytes. An empty one is
586 // no instructions, and no instructions is something this can write.
587 Written::Template => "has instructions in its template, which nothing here assembles",
588 Written::Goto => "jumps to a label, which nothing here builds an edge for",
589 Written::Operand => "has an operand this cannot place",
590 Written::Clobber => "says it destroys a register this has no name for",
591 Written::Away => {
592 "jumps out of the function, which only a function that is `naked` may do, since \
593 anywhere else there is an epilogue behind it to give the frame back"
594 }
595 }
596 }
597}
598
599/// What the frame could not do about a stack slot.
600#[derive(Debug, Clone, Copy, PartialEq, Eq)]
601pub enum Growing {
602 /// An object of a size the number a frame counts bytes in does not reach.
603 Huge,
604 /// A variable length array wanting more alignment than a call leaves the stack pointer with.
605 ///
606 /// Rounding the stack pointer down again after the bytes have been taken would put it
607 /// somewhere no constant reaches the rest of the frame from, so a frame like this needs a
608 /// second base register held for the whole of the function. Nothing here holds one.
609 ///
610 /// [`crate::expand::rounds`] takes the array away before this sees it, by asking for the
611 /// alignment in extra bytes and handing out an address inside them, so what is left of this
612 /// is IR that arrived without going through that pass and the fixed local in
613 /// [`crate::pipeline`] that wants the same thing from the other side.
614 Aligned,
615 /// A variable length array in a function written without a prologue.
616 ///
617 /// A frame that grows is reached from a frame pointer, and establishing one is the first two
618 /// instructions of a prologue that `__attribute__((naked))` asked there be none of. See
619 /// [`crate::frame::Layout::naked`].
620 Naked,
621}
622
623impl Growing {
624 /// The rest of the sentence that starts with the slot.
625 #[must_use]
626 pub fn why(self) -> &'static str {
627 match self {
628 Growing::Huge => "is more bytes than a frame counts",
629 Growing::Aligned => {
630 "wants more alignment than the stack pointer is left on, which needs a base \
631 register nothing here keeps"
632 }
633 Growing::Naked => {
634 "is in a function that is `naked`, which has no prologue to point a frame pointer \
635 at it with"
636 }
637 }
638 }
639}
640
641impl Unsupported {
642 /// The instruction it is about, or nothing for the one arm that is about a signature.
643 ///
644 /// What a caller wants this for is the span. The function knows where every instruction in
645 /// it came from, so a caller holding both can point a message at the line somebody wrote
646 /// rather than at the file as a whole, and nothing here has to carry a span of its own.
647 pub fn inst(&self) -> Option<Inst> {
648 match *self {
649 Unsupported::Inst { inst, .. }
650 | Unsupported::Call { inst, .. }
651 | Unsupported::Returned { inst, .. }
652 | Unsupported::Dynamic { inst, .. }
653 | Unsupported::Assembly { inst, .. }
654 | Unsupported::Register { inst, .. } => Some(inst),
655 Unsupported::Unported { inst, .. } => inst,
656 Unsupported::Argument { .. } | Unsupported::Phi { .. } | Unsupported::Naked { .. } => {
657 None
658 }
659 }
660 }
661}
662
663impl fmt::Display for Unsupported {
664 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
665 match *self {
666 Unsupported::Inst { term: Some(term), .. } => write!(f, "no rule lowers `{term}`"),
667 Unsupported::Inst { term: None, opcode, ty: Some(ty), .. } => {
668 write!(f, "no rule lowers a `{opcode}` producing a `{ty}`")
669 }
670 Unsupported::Inst { term: None, opcode, ty: None, .. } => {
671 write!(f, "no rule lowers a `{opcode}`")
672 }
673 Unsupported::Argument { index, missing } => {
674 write!(f, "parameter {index} {}", missing.why())
675 }
676 Unsupported::Call { refused: Refused { argument: Some(index), missing }, .. } => {
677 write!(f, "argument {index} of this call {}", missing.why())
678 }
679 Unsupported::Call { refused: Refused { argument: None, missing }, .. } => {
680 write!(f, "what this call gives back {}", missing.why())
681 }
682 Unsupported::Returned { missing, .. } => {
683 write!(f, "what this function gives back {}", missing.why())
684 }
685 Unsupported::Dynamic { growing, .. } => {
686 write!(f, "this local {}", growing.why())
687 }
688 Unsupported::Phi { block, count, ty } => {
689 let block = block.index();
690 write!(
691 f,
692 "block{block} takes {count} parameters of type `{ty}` and only {X87_DEPTH} can cross an edge at once"
693 )
694 }
695 Unsupported::Assembly { refused, .. } => write!(f, "this `asm` {}", refused.why()),
696 Unsupported::Unported { what, .. } => f.write_str(what.why()),
697 Unsupported::Register { ref name, .. } => {
698 write!(
699 f,
700 "this object is kept in `{name}`, which is not a register this machine has"
701 )
702 }
703 Unsupported::Naked { bytes } => write!(
704 f,
705 "this function is `naked` and wants {bytes} bytes of frame, which there is no prologue to take"
706 ),
707 }
708 }
709}
710
711impl std::error::Error for Unsupported {}
712
713/// A lowered function, and what the frame needs that the machine IR does not hold.
714#[derive(Debug)]
715pub struct Lowered {
716 /// The function, in machine instructions.
717 pub func: mir::Func,
718 /// What it wants its stack to look like, which is separate from the function so that the two
719 /// can be read and written at the same time.
720 pub stack: Stack,
721 /// Which rules of the table lowered it, which is what `-Zrule-coverage` asks for and what
722 /// `crate::coverage` writes down.
723 pub fired: Fired,
724 /// Which machine IR block each IR block became, indexed by the IR block's own index, and
725 /// nothing for a block the walk never reached.
726 ///
727 /// Here because it is the only place the correspondence exists. Selection makes one block per
728 /// block, in the same order and with the arms in the same order, so anything the IR knows
729 /// about a block can be carried down through this and nothing else, and
730 /// [`crate::weights::carry`] is what does.
731 pub blocks: Vec<Option<mir::Block>>,
732}
733
734/// What a function's stack has to hold, as far as selection is able to say.
735///
736/// All of it is answered here because selection is where a call is built and where an `alloca`
737/// is read, and nothing after it could tell what either of them needed.
738#[derive(Debug, Default)]
739pub struct Stack {
740 /// How many bytes the widest call in the function needs below the stack pointer for the
741 /// arguments it passes there, or `None` for a function that makes no call at all.
742 ///
743 /// `None` is a leaf, which is the function that may use the red zone and the one whose stack
744 /// pointer does not have to be left aligned for anybody.
745 pub calls: Option<u32>,
746 /// The memory the function asked for itself, one entry for every `alloca` in it, in the order
747 /// the walk reached them.
748 pub locals: Vec<Local>,
749 /// Which instruction computes the address of which of those locals.
750 ///
751 /// An address in the frame is a distance from the stack pointer, and there is no frame until
752 /// after allocation, so the instruction is written here with nothing in its displacement and
753 /// [`crate::finish`] writes the number in once [`crate::frame::Frame`] knows it.
754 pub addresses: Vec<(mir::Inst, usize)>,
755 /// Which of those locals is which declaration in the source, for the ones the program declared.
756 ///
757 /// The number is the one the IR function carries and means nothing here. What it is for is the
758 /// debugging information, which has to say where a named local ended up and cannot ask the
759 /// frame directly: the frame knows a local by the order the `alloca` for it was lowered in and
760 /// by nothing else.
761 ///
762 /// Shorter than the list above rather than the same length, because most of what a function
763 /// keeps in its frame is memory an expression wanted somewhere to put.
764 pub declared: Vec<(usize, u32)>,
765 /// Which instruction computes the address of a piece of memory whose size the function works
766 /// out while it runs, which is what a variable length array is.
767 ///
768 /// Waiting on [`crate::finish`] for a different number from the one the addresses above are:
769 /// the bytes were taken off the stack pointer by the instruction in front of this one, so where
770 /// they start is however much of the bottom of the frame belongs to the arguments of a call,
771 /// and that is not known until the frame is.
772 pub dynamic: Vec<mir::Inst>,
773 /// Which instruction takes those bytes off the stack pointer, one for every one of them, in the
774 /// order the walk reached them.
775 ///
776 /// Read by [`crate::finish`] on a command line that asked for the stack to be touched a page at
777 /// a time, which is the one thing that has to find these again: the bytes are in a register by
778 /// then, so the walk down to them is a loop, and a loop is written around an instruction rather
779 /// than in front of a block. Nothing else looks at them, because everything else about a frame
780 /// that grows is answered by the address the instruction below this one computes.
781 pub grown: Vec<mir::Inst>,
782 /// Where the function first moves the stack pointer while it runs, if it does at all.
783 ///
784 /// Two things are read off this. One is whether at all, which is what [`crate::frame::Layout`]
785 /// wants, because a frame that moves its stack pointer has a different shape from one that does
786 /// not and the layout is built before the instructions are looked at again. See `Growing` in
787 /// [`crate::frame`]. The other is where, so that a caller that cannot accept such a frame has
788 /// somewhere to point when it says so.
789 pub grown_at: Option<Inst>,
790 /// Which instruction reads which of the arguments the caller passed on the stack, as how far up
791 /// the caller's argument area it reads.
792 ///
793 /// Waiting on [`crate::finish`] for the same reason the addresses above are, and on one thing
794 /// more: where the caller's argument area is from inside this function depends on whether the
795 /// prologue had to force the stack pointer's alignment, so which register the load reads
796 /// through is not settled here either.
797 pub arguments: Vec<(mir::Inst, u32)>,
798 /// Whether the function asked where its own frame is, which is what `__builtin_frame_address`
799 /// and `__builtin_return_address` both start from.
800 ///
801 /// A function like that keeps a frame pointer whatever the flags say, because the register is
802 /// the answer to the first of them and the start of the walk for every depth above zero. There
803 /// is no other way to reach it: the distance from the stack pointer to the frame is a number
804 /// the layout works out, and what a walk up the chain needs is the link the prologue saved.
805 pub walks_frames: bool,
806 /// Whether the function saved a place for a `__builtin_longjmp` to come back to, which is what
807 /// `__builtin_setjmp` does.
808 ///
809 /// A function like that keeps a frame pointer whatever the flags say as well, and for a reason
810 /// of the same shape: the two registers the restore puts back are the frame pointer and the
811 /// stack pointer, and a frame that did not keep the first of them has nothing in it saying
812 /// where the caller's frame is for the epilogue to find after control has come back.
813 pub saves_place: bool,
814 /// The calls a `tail_call` became that [`crate::tail::jumps`] may turn into a jump, which is
815 /// the ones that passed everything in registers.
816 pub tails: Vec<crate::tail::Tail>,
817}
818
819impl Stack {
820 /// The layout given, with the three fields only the lowering knows the answer to filled in.
821 ///
822 /// Everything else in a layout comes from the flags the function is compiled under or from the
823 /// allocation, so this takes one and returns it rather than building one.
824 ///
825 /// A function that saved a place is not a leaf whatever it called. What a leaf buys is the red
826 /// zone, which is the words below the stack pointer nothing else may write, and a function
827 /// control comes back into from a `__builtin_longjmp` has already had something else running
828 /// down there: whatever it called and whatever that called, or a signal handler on the same
829 /// stack. Every one of those has written over the red zone by the time control arrives, so a
830 /// value this function left there would not be there any more.
831 #[must_use]
832 pub fn layout<'a>(&'a self, base: Layout<'a>) -> Layout<'a> {
833 Layout {
834 leaf: self.calls.is_none() && !self.saves_place,
835 outgoing: self.calls.unwrap_or(0),
836 locals: &self.locals,
837 grows: self.grown_at.is_some(),
838 ..base
839 }
840 }
841}
842
843/// The machine IR for that function, for the machine the selector describes.
844///
845/// # Errors
846///
847/// The first instruction no rule fires on, which today is anything at a width the rule set is not
848/// written at, a parameter that does not arrive in a register this can read, or a call that
849/// passes something this cannot put where the convention wants it.
850pub fn func(
851 source: &Func,
852 names: &mut Interner,
853 selector: &'static Selector,
854 conv: &'static CallRegs,
855 elsewhere: &Elsewhere,
856) -> Result<Lowered, Unsupported> {
857 Lowering::new(source, names, selector, conv, elsewhere).run()
858}
859
860/// What the matcher settled on for one block, indexed the way the block's instructions are.
861struct Decided {
862 /// What each instruction matched, and nothing for one that matched no rule or was folded
863 /// into a later one.
864 found: Vec<Option<Match<Term>>>,
865 /// How each instruction showed its operands to the matcher, which is what says what it took.
866 plans: Vec<Option<Plan>>,
867 /// The instructions some other instruction took, which are the ones with nothing to write.
868 folded: Vec<Inst>,
869}
870
871/// The instruction in front of an assignment that starts a declaration on a value, and the first
872/// machine instruction after it once the block is filled.
873type Mark = (Option<Inst>, Option<mir::Inst>);
874
875/// One function being lowered.
876struct Lowering<'a> {
877 source: &'a Func,
878 names: &'a mut Interner,
879 out: mir::Func,
880 /// The machine register each IR value is in, once it has one.
881 regs: Vec<Option<mir::Reg>>,
882 /// For a constant that has been written into a register, the block it was written into,
883 /// which is the only block that register is any good in.
884 written: Vec<Option<mir::Block>>,
885 /// How many times each IR value is read, which is what says whether an instruction may be
886 /// folded into the one that reads it.
887 uses: Vec<u32>,
888 /// The block being filled.
889 at: Option<mir::Block>,
890 /// The machine IR block each IR block became.
891 blocks: Vec<Option<mir::Block>>,
892 /// The class an address is in, which is the general purpose one and is not a question: every
893 /// register an addressing mode names holds part of an address, and there is no machine here
894 /// that computes an address anywhere but in this file. Which class a *value* is in is
895 /// [`Lowering::class_of`], and it is a question, because a float is in the other one.
896 gpr: RegClass,
897 /// The machine this selects for.
898 selector: &'static Selector,
899 /// Where the convention this function is compiled for puts things, which is read for the
900 /// arguments and for the calls.
901 conv: &'static CallRegs,
902 /// Which names this function may not work an address out for itself, which is a fact about the
903 /// module and so is worked out before any of this and handed in.
904 elsewhere: &'a Elsewhere,
905 /// What the function wants its stack to look like, filled in as the walk finds out.
906 stack: Stack,
907 /// What a `va_start` in this function has to write, or nothing for a function that takes no
908 /// arguments its signature does not name.
909 ///
910 /// Worked out once, when the entry block binds the parameters, because every number in it is
911 /// about where those parameters left the walk over the argument registers and there is nowhere
912 /// else that knows.
913 varargs: Option<Varargs>,
914 /// Which of the function's stack objects each eighty bit value lives in, once it has asked
915 /// for one.
916 ///
917 /// One slot per value and it is never given back, which is what makes an eighty bit value
918 /// behave like every other one: it is written once and read wherever it is read, and no two
919 /// of them share a slot the way two of them would share a register. What is in a register is
920 /// the address, and that is worked out again at every use rather than kept, so nothing here
921 /// holds a general purpose register open across a whole function.
922 slots: Vec<Option<usize>>,
923 /// The eight bytes a value passes through between a register and the x87 stack, once
924 /// something has wanted them.
925 ///
926 /// One for the whole function, because every group that uses it is a handful of instructions
927 /// with nothing in between: the bytes are written, read straight back and never looked at
928 /// again, so a second slot would be a second slot holding the same nothing.
929 crossing: Option<usize>,
930 /// The four bytes the control word is saved in and the changed copy written to, once
931 /// something has wanted them.
932 ///
933 /// One for the whole function for the reason above, and four rather than two because it is
934 /// two words: the one the unit had and the one with the rounding field turned to truncate.
935 control: Option<usize>,
936 /// The word a `__builtin_setjmp` in this function answers with, once one has asked for it.
937 ///
938 /// One for the whole function however many saves there are in it, because the word is written
939 /// and read back with nothing in between: the save writes a zero into it and the instruction
940 /// straight after reads it, and the only other thing that ever writes it is a restore arriving
941 /// between those two. Two saves sharing it is two pairs each doing that, and neither can be
942 /// inside the other.
943 answer: Option<usize>,
944 /// The block `__builtin_apply_args` answers the address of, or nothing in a function that holds
945 /// none.
946 ///
947 /// Written once, in the prologue, because what it holds is every argument register as it was
948 /// on the way in, and by the time the walk reaches the call the registers hold whatever the
949 /// function has done since. Every `__builtin_apply_args` in the function answers the same one.
950 applied: Option<usize>,
951 /// Which rules have fired so far.
952 fired: Fired,
953 /// Where each assignment that starts a declaration on a value part of the way through is, by
954 /// the IR block it is in and the instruction in front of it, and which machine instruction
955 /// is the first one after it once the block has been filled. See
956 /// [`rucc_ir::Func::declare_value_from`].
957 marks: HashMap<Block, Vec<Mark>>,
958 /// The frame slot each fixed size `alloca` was given, which a landing pad writes the address
959 /// of again rather than reading the register the rest of the function has it in. See
960 /// [`Self::pad`].
961 frame_slots: HashMap<Value, usize>,
962 /// The machine call each IR call with an unwind edge became, which [`Self::edges`] pairs with
963 /// the pad the edge went to. See [`rucc_ir::Opcode::Unwound`].
964 unwinding: HashMap<Inst, mir::Inst>,
965}
966
967/// What a `va_start` in a variadic function writes into the list it is given.
968///
969/// Two shapes, because two conventions describe a list two ways, and [`crate::varargs`] is where
970/// both are written down. Neither is a set of numbers on its own: where the save area is and where
971/// the caller's argument area is are distances into a frame that does not exist until after
972/// allocation, so each is a `lea` [`crate::finish`] fills in.
973#[derive(Debug, Clone, Copy, PartialEq, Eq)]
974enum Varargs {
975 /// The four field list, whose two offsets are settled here and whose two addresses are not.
976 Fields {
977 /// Which of the function's stack objects is the register save area.
978 save: usize,
979 /// How far up the caller's argument area the first argument the signature does not name is,
980 /// which is the whole of that area the named ones did not take.
981 incoming: u32,
982 /// What `gp_offset` starts at, which is past the general purpose registers the named
983 /// arguments took.
984 integers: u32,
985 /// What `fp_offset` starts at, which is past the vector ones.
986 floats: u32,
987 },
988 /// The AAPCS64 list, whose two offsets count up to zero from the top of each half of the save
989 /// area. The two tops are addresses in the frame and so is the first field, like the SysV list.
990 Aapcs {
991 /// Which of the function's stack objects is the register save area.
992 save: usize,
993 /// How far up the caller's argument area the first argument the signature does not name is.
994 incoming: u32,
995 /// Where the general purpose half of the save area ends.
996 integers_end: u32,
997 /// Where the vector half ends, which is the end of the area.
998 floats_end: u32,
999 /// What `__gr_offs` starts at, which is minus the general purpose half the named arguments
1000 /// did not take.
1001 integers: i32,
1002 /// What `__vr_offs` starts at.
1003 floats: i32,
1004 },
1005 /// The list that is a pointer, which is the one address and nothing else.
1006 Pointer {
1007 /// How far up the caller's argument area the first argument the signature does not name is,
1008 /// which on this convention is the word belonging to the position the named ones stopped
1009 /// at.
1010 incoming: u32,
1011 },
1012}
1013
1014/// How far a function's name reaches, narrowed from the linkage the IR gave it.
1015///
1016/// The IR has five and an object file says three, and the two the linker cannot tell apart are
1017/// the two weak ones: which of them a symbol had is a fact the optimizer reads and the linker has
1018/// no way to record. A function is never `Common`, since that is what a tentative definition of an
1019/// object is and there is no tentative definition of a function, and it is written here rather
1020/// than left out so that a linkage added later has to come past this.
1021const fn binding(linkage: Linkage) -> mir::Binding {
1022 match linkage {
1023 Linkage::Internal => mir::Binding::Local,
1024 Linkage::Weak | Linkage::LinkOnce => mir::Binding::Weak,
1025 Linkage::External | Linkage::Common => mir::Binding::Global,
1026 }
1027}
1028
1029/// How far a function's name reaches outside a shared library, carried across unchanged.
1030///
1031/// Nothing is narrowed here the way [`binding`] narrows the linkage, because ELF records all
1032/// three of these and the two enumerations are the same three answers written twice: once in a
1033/// crate that is not allowed to know what an object file is and once in one that is.
1034const fn visibility(visibility: Visibility) -> mir::Visibility {
1035 match visibility {
1036 Visibility::Default => mir::Visibility::Default,
1037 Visibility::Hidden => mir::Visibility::Hidden,
1038 Visibility::Protected => mir::Visibility::Protected,
1039 }
1040}
1041
1042impl<'a> Lowering<'a> {
1043 fn new(
1044 source: &'a Func,
1045 names: &'a mut Interner,
1046 selector: &'static Selector,
1047 conv: &'static CallRegs,
1048 elsewhere: &'a Elsewhere,
1049 ) -> Self {
1050 let counts = source.counts();
1051 let name = source.name;
1052 let mut uses = vec![0; counts.values];
1053 for block in source.blocks() {
1054 for inst in source.insts(block) {
1055 for &arg in &source[source[inst].args] {
1056 uses[arg.index()] += 1;
1057 }
1058 for call in source.successors(inst) {
1059 for &arg in &source[call.args] {
1060 uses[arg.index()] += 1;
1061 }
1062 }
1063 }
1064 }
1065 let mut out = mir::Func::new(name);
1066 out.align = source.align;
1067 // Carried rather than worked out here, because where a function was declared is a fact
1068 // about the source and this is a long way past it. What wants it is the line table.
1069 out.declared = source.declared;
1070 out.binding = binding(source.linkage);
1071 out.visibility = visibility(source.visibility);
1072 Self {
1073 source,
1074 names,
1075 out,
1076 regs: vec![None; counts.values],
1077 written: vec![None; counts.values],
1078 blocks: vec![None; counts.blocks],
1079 uses,
1080 at: None,
1081 gpr: selector.gpr,
1082 selector,
1083 conv,
1084 elsewhere,
1085 stack: Stack::default(),
1086 varargs: None,
1087 slots: vec![None; counts.values],
1088 crossing: None,
1089 control: None,
1090 answer: None,
1091 applied: None,
1092 fired: Fired::new(),
1093 marks: HashMap::new(),
1094 frame_slots: HashMap::new(),
1095 unwinding: HashMap::new(),
1096 }
1097 }
1098
1099 fn run(mut self) -> Result<Lowered, Unsupported> {
1100 for value in self.source.values() {
1101 for start in self.source.value_starts(value) {
1102 let Some((block, after)) = self.source.start_place(start) else { continue };
1103 let marks = self.marks.entry(block).or_default();
1104 if !marks.iter().any(|&(have, _)| have == after) {
1105 marks.push((after, None));
1106 }
1107 }
1108 }
1109 // Every block before any of them is filled, because a block that jumps forward has to
1110 // name the block it jumps to and a machine IR block is named by a handle rather than by
1111 // the IR block it came from.
1112 for block in self.source.blocks() {
1113 let out = self.out.create_block();
1114 self.blocks[block.index()] = Some(out);
1115 }
1116 for block in self.order() {
1117 self.block(block)?;
1118 }
1119 // And the name each block an image holds the address of was given, which nothing in the
1120 // walk above would ask for: the `lea` a label address is inside the function needs no
1121 // symbol, and the one thing that does is a relocation in another section.
1122 let named: Vec<(Block, Symbol)> = self.source.named_blocks().collect();
1123 let labels: Vec<(mir::Block, Symbol)> =
1124 named.into_iter().map(|(block, name)| (self.out_block(block), name)).collect();
1125 self.out.labels = labels;
1126 self.naming();
1127 Ok(Lowered { func: self.out, stack: self.stack, fired: self.fired, blocks: self.blocks })
1128 }
1129
1130 /// Which register each declaration the front end kept in a value ended up in, as far as this
1131 /// walk can say, which is the other half of what [`Lowering::new_reg`] writes down as it goes.
1132 ///
1133 /// Two halves because there are two ways a value gets a register here. Most of them ask for a
1134 /// fresh one and that is where `new_reg` catches them, and the rest are put in a register
1135 /// something else chose: a parameter arrives in whichever one the convention handed it, a block
1136 /// parameter in whichever one the edge agreed on, and a result of a rule that names its own
1137 /// registers in the one the rule named. None of those goes past the mint, so this is the map at
1138 /// the end read off the other side, and the two together are every value a declaration is
1139 /// behind.
1140 ///
1141 /// The map on its own would not do, which is why `new_reg` writes down what it writes down: the
1142 /// entry for a constant is cleared every time the walk leaves the block that wrote it, so a
1143 /// local a constant holds is in the map for one block of the function and nowhere else.
1144 fn naming(&mut self) {
1145 let mut named = std::mem::take(&mut self.out.named);
1146 for value in self.source.values() {
1147 let Some(reg) = self.regs[value.index()] else { continue };
1148 named.extend(self.source.value_decls(value).map(|decl| (decl, reg)));
1149 // A start in a block a pass took out was never reached above, and it says nothing
1150 // rather than something about another place.
1151 for start in self.source.value_starts(value) {
1152 let Some((block, after)) = self.source.start_place(start) else { continue };
1153 let first = self.marks.get(&block).and_then(|marks| {
1154 marks.iter().find(|&&(have, _)| have == after).and_then(|&(_, at)| at)
1155 });
1156 if let Some(first) = first {
1157 self.out.starts.push((start.decl, reg, first));
1158 }
1159 }
1160 }
1161 named.sort_unstable();
1162 named.dedup();
1163 self.out.named = named;
1164 self.out.starts.sort_unstable();
1165 self.out.starts.dedup();
1166 // Which of its values a declaration holds on the way into a block, for the blocks where
1167 // two of them are live at once. A block a pass took out says nothing, and neither does a
1168 // value the map above has lost the register of, since that is not the same as having none.
1169 let mut entries = Vec::new();
1170 for (decl, block, value) in crate::holding::on_entry(self.source) {
1171 if let (Some(block), Some(reg)) = (self.blocks[block.index()], self.regs[value.index()])
1172 {
1173 entries.push((decl, block, reg));
1174 }
1175 }
1176 entries.sort_unstable();
1177 entries.dedup();
1178 self.out.entries = entries;
1179 }
1180
1181 /// The order the blocks are filled in, which is not the order they are written in.
1182 ///
1183 /// Reverse postorder, because a value is written in a block that dominates every block that
1184 /// reads it and a block in reverse postorder comes before every block it dominates. The order
1185 /// the blocks are written in does not have that property: a block written early can read a
1186 /// value a block below it writes, and reading a value with no register yet mints one, so the
1187 /// register the definition writes later is not the register the read named. Nothing writes the
1188 /// one the read named, and what comes out is a function that loads a stack slot no store ever
1189 /// reached. It is the order this walk goes in rather than the order the blocks come out in,
1190 /// which is what the loop above fixes, so the machine function is still written the way the IR
1191 /// function was.
1192 ///
1193 /// Blocks the entry does not reach come last, in the order they are written in. Nothing runs
1194 /// them and nothing they name is read by anything that does, but they still have to be filled,
1195 /// because a machine block with no terminator is not one the passes below can read.
1196 fn order(&self) -> Vec<Block> {
1197 let Some(entry) = self.source.entry() else { return self.source.blocks().collect() };
1198 let count = self.blocks.len();
1199 let mut succs: Vec<Vec<Block>> = vec![Vec::new(); count];
1200 for block in self.source.blocks() {
1201 let Some(term) = self.source.terminator(block) else { continue };
1202 succs[block.index()] = self.source.successors(term).map(|call| call.block).collect();
1203 }
1204 // An explicit stack, because the depth of the walk is the number of blocks and a function
1205 // built by a generator has as many of those as it likes.
1206 let mut seen = vec![false; count];
1207 let mut order = Vec::with_capacity(count);
1208 let mut stack = vec![(entry, 0usize)];
1209 seen[entry.index()] = true;
1210 while let Some((block, at)) = stack.pop() {
1211 let Some(&next) = succs[block.index()].get(at) else {
1212 order.push(block);
1213 continue;
1214 };
1215 stack.push((block, at + 1));
1216 if !seen[next.index()] {
1217 seen[next.index()] = true;
1218 stack.push((next, 0));
1219 }
1220 }
1221 order.reverse();
1222 order.extend(self.source.blocks().filter(|block| !seen[block.index()]));
1223 order
1224 }
1225
1226 /// One block: its parameters, then every instruction in it that is not folded into another.
1227 fn block(&mut self, block: Block) -> Result<(), Unsupported> {
1228 let out = self.out_block(block);
1229 self.at = Some(out);
1230 if self.source.entry() == Some(block) {
1231 self.arrive(block, out)?;
1232 } else {
1233 let mut arriving = Vec::new();
1234 for ¶m in &self.source[block].params {
1235 // A value with no register to arrive in, which the class would not say, since
1236 // `class_of` puts one of these in the general purpose file on purpose and what it
1237 // means by that is that nothing there can hold it. What crosses the edge for one
1238 // of those is the address of where the value already is, so the parameter is a
1239 // pointer here and the bytes it points at are copied below.
1240 let ty = self.source[param].ty;
1241 let reg = self.out.append_param(out, self.class_of(ty));
1242 self.regs[param.index()] = Some(reg);
1243 if on_x87(ty) {
1244 arriving.push((param, reg));
1245 }
1246 }
1247 self.settle(block, &arriving)?;
1248 }
1249 let kept = self.pad(block)?;
1250
1251 // What each instruction matched, and which instructions were folded into another. The
1252 // decision is made for the whole block before any of it is written, and it is made more
1253 // than once: a value that only some of its readers took has to be put back in a register
1254 // for all of them, and taking it away from those readers changes what they match.
1255 let insts: Vec<Inst> = self.source.insts(block).collect();
1256 let mut refused: HashSet<Value> = HashSet::new();
1257 let mut decided = self.decide(&insts, &refused);
1258 while let Some(value) = self.left_alive(&insts, &decided.plans) {
1259 refused.insert(value);
1260 decided = self.decide(&insts, &refused);
1261 }
1262 let Decided { found, folded, .. } = decided;
1263
1264 // Where each assignment in this block that starts a declaration on a value is, as the
1265 // machine instruction in front of the place its IR instruction left off, or the block
1266 // for one where nothing has been written yet. What comes after it is not known until the
1267 // block is filled, so that is read below.
1268 let wanted: HashSet<Option<Inst>> =
1269 self.marks.get(&block).into_iter().flatten().map(|&(after, _)| after).collect();
1270 let mut reached: Vec<(Option<Inst>, mir::Block, Option<mir::Inst>)> = Vec::new();
1271 for (index, (&inst, matched)) in insts.iter().zip(found).enumerate() {
1272 let before = index.checked_sub(1).map(|index| insts[index]);
1273 if wanted.contains(&before) {
1274 let at = self.at.unwrap_or(out);
1275 reached.push((before, at, self.out.terminator(at)));
1276 }
1277 if folded.contains(&inst) || self.writes_nothing(inst) {
1278 continue;
1279 }
1280 // A call is built from the convention rather than matched, which is why it is the one
1281 // opcode looked at by name here. Through an address it is a different instruction and
1282 // the same convention, so the two arrive at the same place and differ in one line of
1283 // it.
1284 match self.source[inst].opcode {
1285 Opcode::Call | Opcode::CallIndirect => {
1286 self.called(inst)?;
1287 continue;
1288 }
1289 // The exception a landing pad was entered with, which the unwinder left in the
1290 // first return register. Built by name for the reason a named register is.
1291 Opcode::Landing => {
1292 self.landing(inst)?;
1293 continue;
1294 }
1295 // A call and the return behind it, which is what `crate::tail::mark` made it out
1296 // of, and both are built the way they would have been. What makes it a jump is
1297 // written at the very end, once the epilogue is there to jump from.
1298 Opcode::TailCall => {
1299 self.tail_called(inst)?;
1300 continue;
1301 }
1302 // Built from the frame rather than matched, for the same shape of reason a call
1303 // is built from the convention: what a rule replaces a term with is instructions,
1304 // and what an `alloca` needs first is bytes, which the rule language has no way
1305 // to ask for.
1306 Opcode::Alloca => {
1307 self.reserve(inst)?;
1308 continue;
1309 }
1310 // Reading the stack pointer and writing it back, which are the two ends of a scope
1311 // holding a variable length array. Built here for the reason an `alloca` is: the
1312 // value is a register the rule language has no way to name, because what it holds
1313 // is not a value the program computed but where the machine's stack had got to.
1314 // The arguments the function was handed, saved in the prologue, and a call made
1315 // out of them. Built here because neither is a value a rule could say anything
1316 // about: the first is a place in the frame and the second is a call, whose
1317 // arguments are a block of registers rather than values.
1318 Opcode::ApplyArgs => {
1319 self.apply_args(inst)?;
1320 continue;
1321 }
1322 Opcode::Apply => {
1323 self.apply(inst)?;
1324 continue;
1325 }
1326 Opcode::StackSave => {
1327 self.stack_pointer(inst, false)?;
1328 continue;
1329 }
1330 Opcode::StackRestore => {
1331 self.stack_pointer(inst, true)?;
1332 continue;
1333 }
1334 // The address of a name, built here for the same reason an `alloca` is: what a
1335 // rule replaces a term with is instructions over values, and the operand of this
1336 // one is a symbol, which is a thing the rule language has no way to bind and the
1337 // solver has no way to say anything about. There is nothing in `lea sym(%rip)` a
1338 // proof over bitvectors could discharge, because what makes it the right answer
1339 // is the relocation and what the linker does with it.
1340 Opcode::GlobalAddr => {
1341 self.address_of(inst)?;
1342 continue;
1343 }
1344 // The address of a label and the branch that reads one, built here for the same
1345 // reason and for one more. The reason is the same: what the first of them names is
1346 // a block, which is not a value a rule pattern can bind, and there is nothing in
1347 // the distance between two places in one function that a proof over bitvectors
1348 // could discharge. The extra one is that the second is a terminator whose arms are
1349 // not two and not fixed, and a rule says what an instruction reads rather than
1350 // where a block goes.
1351 Opcode::BlockAddr => {
1352 self.block_address(inst)?;
1353 continue;
1354 }
1355 Opcode::IndirectBr => {
1356 self.indirect_branch(inst)?;
1357 continue;
1358 }
1359 // A `switch` that `crate::switch` found dense enough for a table, which is a load
1360 // out of the table and the same jump. Built here for the reasons the jump above
1361 // is, and because what the load reads is a place in this function.
1362 Opcode::Switch => {
1363 self.jump_table(inst)?;
1364 continue;
1365 }
1366 // The pair that saves a place in this function and comes back to it. Built here
1367 // for the reason the address of a label is, and for two more. The reason is the
1368 // same: the first of them writes down where control comes back to, which is a
1369 // place in this function and not a value a rule pattern can bind. The extra ones
1370 // are that each of them is a group of instructions over a buffer the program owns
1371 // rather than one instruction, and that the first of them leaves the block it was
1372 // written in and carries on in a new one, which is a thing no rule can do.
1373 Opcode::SetjmpMarker => {
1374 self.saves_place(inst)?;
1375 continue;
1376 }
1377 Opcode::LongjmpMarker => {
1378 self.comes_back(inst)?;
1379 continue;
1380 }
1381 // Where this thread's own storage starts, built here for a reason of the same
1382 // shape: what it reads is `%fs`, which is not a register the rule language can
1383 // bind and not one a proof over bitvectors could say anything about, because what
1384 // makes the load the right answer is an agreement between the loader and the C
1385 // library rather than any arithmetic.
1386 Opcode::ThreadPointer => {
1387 self.thread_pointer(inst)?;
1388 continue;
1389 }
1390 // What a named machine register holds, built here for the reason above written
1391 // about any register rather than about one: which register it is is a string
1392 // beside the instruction, and a rule matches on an opcode and a type and could
1393 // not see it. There is nothing to prove either, since the answer is the register
1394 // and the instruction is the move that reads it.
1395 Opcode::RegisterValue => {
1396 self.register_value(inst)?;
1397 continue;
1398 }
1399 // Where a frame is and what it returns to, built here for the same reason and one
1400 // more. The reason is the same: what the walk starts from is the frame pointer,
1401 // which is not a register a rule pattern can bind, and there is nothing in reading
1402 // the link the prologue saved that a proof over bitvectors could discharge. The
1403 // extra one is that how long the walk is comes out of a number beside the
1404 // instruction, so one of these is not one instruction but however many the depth
1405 // says, and a rule replaces a term with a term.
1406 Opcode::FrameAddress | Opcode::ReturnAddress => {
1407 self.frames(inst)?;
1408 continue;
1409 }
1410 // Built from the frame for the reason an `alloca` is, and from the convention for
1411 // the reason a call is: three of the four fields it writes are distances that do
1412 // not exist until the frame does, and the fourth is where the walk over the
1413 // argument registers stopped. A function that is not variadic has no such walk to
1414 // report, so it has nothing here and is refused below, which is the right answer
1415 // for a `va_start` in one.
1416 Opcode::VaStart if self.varargs.is_some() => {
1417 self.va_start(inst)?;
1418 continue;
1419 }
1420 // A return of more than one value, which is a structure small enough to come
1421 // back in a pair of registers. Built from the convention for the reason a call
1422 // is: which register each half goes in depends on the halves in front of it,
1423 // because the two register files are walked separately, and a pattern over a term
1424 // cannot see them. A return of one value is a term with a name and a rule, and it
1425 // stays one.
1426 //
1427 // A return of none in a function whose answer went through memory is here too,
1428 // and for a different reason: what it gives back is not written in the IR at all.
1429 // The convention says the address the caller handed over comes back, and only the
1430 // signature says this function was handed one.
1431 //
1432 // And a return of one eighty bit value, for a third reason: what a rule would
1433 // write is an instruction leaving the value in a register, and this one is left on
1434 // the x87 stack instead. A rule could not name that stack any more than any other
1435 // rule about this type could.
1436 //
1437 // And a return the convention asks this side to extend, which a rule has no way to
1438 // know about since the signature is what says so and not the value.
1439 Opcode::Return
1440 if self.source[self.source[inst].args].len() > 1
1441 || self.sret().is_some()
1442 || self.gives_back_x87(inst)
1443 || self.widens_return() =>
1444 {
1445 let values = self.source[self.source[inst].args].to_vec();
1446 self.returned(inst, values)?;
1447 continue;
1448 }
1449 // A cast between a pointer and an integer of the same width, which on this
1450 // machine is every one the front end writes. No instruction at all, so no rule
1451 // could name one.
1452 Opcode::PtrToInt | Opcode::IntToPtr => {
1453 self.rename(inst)?;
1454 continue;
1455 }
1456 // A barrier, which is one instruction or none depending on the ordering. Written
1457 // by name because there is nothing about it a rule could be proved against, the
1458 // way there is nothing to prove about the address of a symbol.
1459 Opcode::Fence => {
1460 self.barrier(inst)?;
1461 continue;
1462 }
1463 // An ordered load or store that `crate::expand::orderings` left alone, which on a
1464 // machine that is not total store order is every one stronger than relaxed. Written
1465 // by name for the barrier's reason: what it adds to the plain access is an ordering.
1466 Opcode::AtomicLoad | Opcode::AtomicStore if self.on_aarch64() => {
1467 self.ordered(inst)?;
1468 continue;
1469 }
1470 // A hint, written by name for the reason a barrier is and one step further: not
1471 // only is there no equality for a proof to discharge, there is nothing about the
1472 // program around it either. Which of the four instructions it is comes out of the
1473 // number the builtin was given, which is beside the instruction rather than in it.
1474 Opcode::Prefetch => {
1475 self.hint(inst)?;
1476 continue;
1477 }
1478 // Stopping, written by name for the first half of the barrier's reason: it
1479 // computes nothing, so there is no term for a rule to replace, and what makes it
1480 // right is what the operating system does with the fault rather than anything a
1481 // proof over bitvectors could discharge.
1482 Opcode::Trap => {
1483 self.trap(inst);
1484 continue;
1485 }
1486 // A compare and exchange, which is written by name because it produces two values
1487 // and a rule produces one. The replacement of a rule is one term, a term names the
1488 // value an instruction computes, and there is no way in that language to say that
1489 // an instruction leaves an answer in one place and a yes or no in another.
1490 Opcode::Cmpxchg => {
1491 self.exchange(inst)?;
1492 continue;
1493 }
1494 // A read modify write, which is written by name for a different reason: it produces
1495 // one value, so a rule could name it, and what it does is not in the head a rule
1496 // matches on. Every one of the thirteen operations is the same opcode at the same
1497 // type and differs only in what is carried beside it, so one pattern would be all
1498 // thirteen patterns. Of the thirteen only the three with an instruction reach here,
1499 // since `crate::retry` turned the rest into loops a long way above this.
1500 Opcode::AtomicRmw => {
1501 self.modify(inst)?;
1502 continue;
1503 }
1504 // An `asm` statement, whose lowering is its template and there is no term for a
1505 // string. Written by name for the reason a barrier is, and before the x87 arm
1506 // below so that an `asm` holding a `long double` is refused as the `asm` it is
1507 // rather than as an instruction nothing computes.
1508 Opcode::InlineAsm => {
1509 // The template is read as x86 assembly, and that reader is the only one there
1510 // is. AArch64 keeps every template as text, and any other machine's `asm` is
1511 // refused here rather than read as the wrong language.
1512 if self.on_aarch64() {
1513 self.spelled(inst)?;
1514 continue;
1515 }
1516 if !std::ptr::eq(self.selector.shapes, &x86_64::MACHINE) {
1517 return Err(self.unsupported(inst));
1518 }
1519 if self.touches_x87(inst) {
1520 self.x87_assembly(inst)?;
1521 continue;
1522 }
1523 self.assembly(inst)?;
1524 continue;
1525 }
1526 // Anything at all with an eighty bit float in it, which is the one arm here
1527 // chosen by a type rather than by an opcode, because what makes these different
1528 // is not what they do but where the value is. A `long double` has no register,
1529 // so it has no name in `crate::term` and no rule could bind one: every one of
1530 // these is a group of instructions over a frame slot, written out below.
1531 //
1532 // Last of the arms, so that a call and a return with one of these in them reach
1533 // the convention first and are refused by it, which is the truer answer: what is
1534 // wrong there is where the value has to travel and not that nothing can compute
1535 // it.
1536 _ if self.touches_x87(inst) => {
1537 self.x87(inst)?;
1538 continue;
1539 }
1540 _ => {}
1541 }
1542 let matched = matched.ok_or_else(|| self.unsupported(inst))?;
1543 self.emit(inst, &matched)?;
1544 // After it is built rather than when it matched, so that what is recorded is the rules
1545 // this function was lowered by and not the rules something was tried with.
1546 self.fired.mark(matched.rule);
1547 }
1548 // Whichever block the walk ended in rather than the one it started in. The two are the
1549 // same block for every function that does not save a place for a `__builtin_longjmp`, and
1550 // where they differ it is the last of them that the terminator and the arms belong to.
1551 // See [`Self::saves_place`].
1552 let last = self.at.expect("a block is being filled");
1553 self.edges(block, last)?;
1554 for (value, reg) in kept {
1555 self.regs[value.index()] = reg;
1556 }
1557 // Now that the block is filled, the instruction after each place an assignment was is the
1558 // first one it holds its value at. One with nothing after it, which a block ending in the
1559 // assignment would be, stays unanswered.
1560 if let Some(marks) = self.marks.get_mut(&block) {
1561 for &(before, at, last) in &reached {
1562 let first = match last {
1563 Some(last) => self.out.next_inst(last),
1564 None => self.out.insts(at).next(),
1565 };
1566 for mark in marks.iter_mut().filter(|(after, _)| *after == before) {
1567 mark.1 = first;
1568 }
1569 }
1570 }
1571 Ok(())
1572 }
1573
1574 /// One call, which is built from the convention rather than matched against the table for the
1575 /// same reason the arguments of the function itself are.
1576 ///
1577 /// The arguments are read before the call is built, which is what materializes a constant
1578 /// argument into a register, since no call passes an immediate.
1579 ///
1580 /// A call to a name and a call through an address are both here, and what tells them apart is
1581 /// the opcode rather than whether a callee was recorded, which is the same thing the verifier
1582 /// reads. Through an address the first operand is the address and the arguments are the ones
1583 /// behind it, and everything after that is the same: where each argument goes, where the value
1584 /// comes back and which registers are gone across it are the convention's answers and the
1585 /// convention does not ask what is being called.
1586 fn called(&mut self, inst: Inst) -> Result<u32, Unsupported> {
1587 let data = &self.source[inst];
1588 let Extra::Call(info) = data.extra else { return Err(self.unsupported(inst)) };
1589 let info = self.source[info];
1590 let indirect = data.opcode == Opcode::CallIndirect;
1591
1592 let values: Vec<Value> = self.source[data.args].to_vec();
1593 let callee = if indirect {
1594 let &address = values.first().ok_or_else(|| self.unsupported(inst))?;
1595 abi::Callee::Through(self.reg_of(address)?)
1596 } else {
1597 abi::Callee::Named(info.callee.ok_or_else(|| self.unsupported(inst))?)
1598 };
1599
1600 // What the ABI asks of each argument, read out before any of them is, because reading one
1601 // borrows the function this is a table in. The ones the signature names are the signature's
1602 // answer and the ones behind them are the call's, which is where a structure passed to a
1603 // variadic callee by value says that its bytes travel: there is no parameter to say it on.
1604 let signature = &self.source[info.signature];
1605 let variadic = signature.variadic;
1606 let named: Vec<Abi> = signature.params.iter().map(|param| param.abi).collect();
1607 let beyond: Vec<Abi> = self.source[info.varargs].to_vec();
1608 // Every value that comes back and not only the first. A structure small enough to travel
1609 // in registers comes back in up to two of them, and which register each half is in is the
1610 // convention's answer, which is why the whole list goes to the same place the arguments do
1611 // rather than to a rule.
1612 let returns: Vec<Type> = signature.return_types().collect();
1613
1614 let mut args = Vec::with_capacity(values.len());
1615 for (index, value) in values.into_iter().skip(usize::from(indirect)).enumerate() {
1616 let abi = named.get(index).or_else(|| beyond.get(index - named.len()));
1617 let abi = abi.copied().unwrap_or_default();
1618 let ty = self.source[value].ty;
1619 // What travels for an eighty bit value is its bytes, so what the call is handed is
1620 // where they are rather than a register they are in, and there is no register they
1621 // could be in. Everything else about it is a sixteen byte object passed by value and
1622 // is built by the same code.
1623 let reg =
1624 if abi::on_the_stack(ty) { self.x87_slot(value) } else { self.reg_of(value)? };
1625 args.push(abi::Passing { ty, reg, abi });
1626 }
1627 let block = self.at.expect("a block is being filled");
1628 let what = abi::Calling {
1629 callee,
1630 args: &args,
1631 returns: &returns,
1632 variadic,
1633 named: named.len(),
1634 at: self.source.span(inst),
1635 };
1636 let made = abi::call(&mut self.out, block, &what, self.conv, self.selector.abi, self.names)
1637 .map_err(|refused| Unsupported::Call { inst, refused })?;
1638 if self.source.unwinds_to_pad(inst) {
1639 let call = self.out.insts(block).last().expect("the call just built");
1640 self.unwinding.insert(inst, call);
1641 }
1642 let calls = &mut self.stack.calls;
1643 *calls = Some(calls.unwrap_or(0).max(made.outgoing));
1644 // An eighty bit value came back on the x87 stack, and the one thing that has to happen
1645 // before anything else touches that stack is taking it off. So the `fstp` goes here, in
1646 // front of everything the block does next, and after it the value is in its slot and is
1647 // read the way every other one is. A complex one is two of them, the real half on top, so
1648 // taking them off in order leaves each in its own slot and the stack empty.
1649 let results: Vec<Value> = self.source[inst].results().collect();
1650 let types: Vec<Type> = results.iter().map(|&result| self.source[result].ty).collect();
1651 if abi::back_on_x87(&types) {
1652 let span = self.source.span(inst);
1653 for result in results {
1654 let into = self.x87_slot(result);
1655 let into = self.through(into);
1656 self.x87_at("fstp_t", span, into);
1657 }
1658 return Ok(made.outgoing);
1659 }
1660 for (result, ®) in results.into_iter().zip(&made.results) {
1661 self.regs[result.index()] = Some(reg);
1662 }
1663 Ok(made.outgoing)
1664 }
1665
1666 /// One `tail_call`, as the call and a return of what it gave back.
1667 ///
1668 /// The call is written down for [`crate::tail::jumps`] when it can be made after the frame is
1669 /// gone. That is when it put nothing in the argument area, which is the bottom of this frame,
1670 /// and when the answer comes back in registers, since one on the x87 stack is taken off and put
1671 /// back by instructions after the call. A call that is not written down stays a call and a
1672 /// return, which is what the IR said before `crate::tail::mark` read it.
1673 fn tail_called(&mut self, inst: Inst) -> Result<(), Unsupported> {
1674 let outgoing = self.called(inst)?;
1675 let block = self.at.expect("a block is being filled");
1676 let call = self.out.insts(block).last().expect("the call just built");
1677 let values: Vec<Value> = self.source[inst].results().collect();
1678 let x87 = self.x87_values(&values);
1679 self.returned(inst, values)?;
1680 if outgoing == 0 && !x87 && self.sret().is_none() {
1681 let returns = self.out.insts(block).skip_while(|&at| at != call).skip(1).collect();
1682 self.stack.tails.push(crate::tail::Tail { call, returns });
1683 }
1684 Ok(())
1685 }
1686
1687 /// The pointer a function returning through memory was handed, or nothing in a function that
1688 /// was not.
1689 ///
1690 /// It is the first parameter and the signature is what says so, since in the IR it is an
1691 /// ordinary pointer and reads like one everywhere in the body. A function with a signature
1692 /// like that and no entry block has nothing to give back and no body to give it back from.
1693 fn sret(&self) -> Option<Value> {
1694 let first = self.source.signature().params.first()?;
1695 if !matches!(first.abi, Abi::Sret { .. }) {
1696 return None;
1697 }
1698 self.source[self.source.entry()?].params.first().copied()
1699 }
1700
1701 /// One `return` the convention has to write, as the place each value has to be in by the end.
1702 ///
1703 /// One pseudo per value, each a read constrained to a return register, which is what a return
1704 /// of one value already is and is the whole of what either does. The `ret` itself comes from
1705 /// the epilogue for both, long after this, because the frame has to be given back first.
1706 ///
1707 /// The two register files are counted separately, so a structure of a `double` and a `long`
1708 /// leaves the `double` in the first vector register and the `long` in the first integer one
1709 /// rather than in the second of either. That is the same walk `rucc_codegen::abi` makes on
1710 /// the other side of the call, which is what makes the two ends agree.
1711 ///
1712 /// A function whose answer went through memory gives back the address it was handed, in front
1713 /// of nothing else, because a signature that returns that way returns nothing else. That the
1714 /// caller already knows the address is not enough: it is allowed to read the register instead,
1715 /// and a caller that does gets whatever the allocator last left there. In a leaf function that
1716 /// is usually the right answer by accident, and one call in the body is enough to make it a
1717 /// wild pointer, which is why this is written rather than left to luck.
1718 ///
1719 /// Where everything goes is worked out before anything is written, so a return this cannot
1720 /// make leaves no half of one behind.
1721 /// Whether a value this function gives back has to be extended first, which is Apple's arm64
1722 /// asking the callee to fill the 32 bits above a `char` or a `short` by its sign.
1723 fn widens_return(&self) -> bool {
1724 let returns = &self.source.signature().returns;
1725 returns.iter().any(|it| (self.selector.abi.extend)(it.ty, it.abi).is_some())
1726 }
1727
1728 /// Whether what a `return` gives back goes back on the x87 stack, per [`abi::back_on_x87`].
1729 fn gives_back_x87(&self, inst: Inst) -> bool {
1730 self.x87_values(&self.source[self.source[inst].args])
1731 }
1732
1733 /// Whether those values go back on the x87 stack, per [`abi::back_on_x87`].
1734 fn x87_values(&self, values: &[Value]) -> bool {
1735 let types: Vec<Type> = values.iter().map(|&value| self.source[value].ty).collect();
1736 abi::back_on_x87(&types)
1737 }
1738
1739 fn returned(&mut self, inst: Inst, values: Vec<Value>) -> Result<(), Unsupported> {
1740 let (mut ints, mut floats) = (0usize, 0usize);
1741 let mut parts = Vec::with_capacity(values.len() + 1);
1742 // An eighty bit value goes back on the x87 stack, which is where the convention says it is
1743 // and is the one place a value is left rather than put in a register. So the whole of the
1744 // return is an `fld` of its slot, and the stack it leaves the value on is not empty at the
1745 // `ret`, which is the one time in this file that is true and is what the convention asks
1746 // for. What comes after is the epilogue, which gives the frame back and touches nothing in
1747 // the unit. A complex one loads its imaginary half first so that the real half ends up on
1748 // top of it, in `st(0)`, with the imaginary half under it in `st(1)`.
1749 if self.x87_values(&values) && self.sret().is_none() {
1750 let span = self.source.span(inst);
1751 for &value in values.iter().rev() {
1752 let from = self.x87_slot(value);
1753 let from = self.through(from);
1754 self.x87_at("fld_t", span, from);
1755 }
1756 return Ok(());
1757 }
1758 // What the signature says about the bits above a narrow one, which on an ABI that extends
1759 // it is an obligation of this side: the caller reads the whole of the 32 bit register.
1760 let asked: Vec<Abi> = self.source.signature().returns.iter().map(|it| it.abi).collect();
1761 let asked = asked.into_iter().chain(std::iter::repeat(Abi::Plain));
1762 let sret = self.sret().map(|value| (value, Abi::Plain));
1763 for (value, abi) in sret.into_iter().chain(values.into_iter().zip(asked)) {
1764 let ty = self.source[value].ty;
1765 let at = if crate::term::in_vector_file(ty) { &mut floats } else { &mut ints };
1766 // Why it cannot come back, and not only that it cannot. A type that travels nowhere
1767 // says so itself, and a type that travels perfectly well ran out of registers.
1768 let missing = abi::refuses(ty, self.selector.abi).unwrap_or(Missing::NoRoom);
1769 let name =
1770 (self.selector.abi.ret)(ty, *at).ok_or(Unsupported::Returned { inst, missing })?;
1771 *at += 1;
1772 // The register is the target's answer and not one worked out here, the same as it is
1773 // for a return of one value, so that both halves of a pair and every rule that writes
1774 // half of one are reading the same table.
1775 let opcode =
1776 name.strip_prefix(self.selector.prefix()).ok_or_else(|| self.unsupported(inst))?;
1777 let descs = self.selector.operands(opcode).ok_or_else(|| self.unsupported(inst))?;
1778 let [desc] = descs else { return Err(self.unsupported(inst)) };
1779 let widen = (self.selector.abi.extend)(ty, abi).map(|name| self.names.intern(name));
1780 parts.push((self.names.intern(name), self.reg_of(value)?, *desc, widen));
1781 }
1782
1783 let block = self.at.expect("a block is being filled");
1784 let span = self.source.span(inst);
1785 for (opcode, mut reg, desc, widen) in parts {
1786 if let Some(widen) = widen {
1787 let wide = self.out.new_vreg(desc.class);
1788 let build = self.out.build(block, mir::Opcode::new(widen)).at(span);
1789 build.def(wide, desc.class).uses(reg, desc.class).finish();
1790 reg = wide;
1791 }
1792 let operand = mir::Operand {
1793 reg,
1794 class: desc.class,
1795 role: desc.role,
1796 constraint: desc.constraint,
1797 };
1798 self.out.build(block, mir::Opcode::new(opcode)).at(span).operand(operand).finish();
1799 }
1800 Ok(())
1801 }
1802
1803 /// One `alloca`: the bytes it asks for go on the list the frame is laid out from, and the
1804 /// address of them is one instruction.
1805 ///
1806 /// The instruction is a `lea` off the stack pointer, which is the one register that reaches
1807 /// the frame in every function, and its displacement is left at nothing because there is no
1808 /// frame yet. Which instruction is waiting for which local is remembered, and
1809 /// [`crate::finish`] fills the numbers in after [`crate::frame::Frame`] has placed them.
1810 ///
1811 /// There is deliberately no rule for `alloca` and no name for one in [`crate::term`], and
1812 /// that is what stops it being folded into something else. An operand shown as the
1813 /// instruction that computed it is offered to the matcher by its name, so an `alloca` with no
1814 /// name is one no pattern can reach past, and the address it computes is always in a register
1815 /// by the time anything reads it.
1816 fn reserve(&mut self, inst: Inst) -> Result<(), Unsupported> {
1817 let data = &self.source[inst];
1818 // A variable length array carries the size it wants as an operand rather than in the
1819 // instruction, which is the whole of what tells the two apart here.
1820 if let Some(&size) = self.source[data.args].first() {
1821 return self.grow(inst, size);
1822 }
1823 let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
1824 let info = self.source[mem];
1825 let size = u32::try_from(info.size)
1826 .map_err(|_| Unsupported::Dynamic { inst, growing: Growing::Huge })?;
1827 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1828
1829 // At least one, because the frame divides by the alignment and an object with no
1830 // alignment at all is one the front end had nothing to say about rather than one that may
1831 // go anywhere.
1832 let index = self.stack.locals.len();
1833 self.stack.locals.push(Local { size, align: info.align.max(1) });
1834 if let Some(decl) = self.source.mem_decl(mem) {
1835 self.stack.declared.push((index, decl));
1836 }
1837
1838 let block = self.at.expect("a block is being filled");
1839 let reg = self.new_reg(result);
1840 let span = self.source.span(inst);
1841 let lea = self.named(self.selector.frame.lea);
1842 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
1843 let made =
1844 self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
1845 self.stack.addresses.push((made, index));
1846 self.frame_slots.insert(result, index);
1847 Ok(())
1848 }
1849
1850 /// The other kind of `alloca`: one whose size the function does not know until it runs, which
1851 /// is what a variable length array is.
1852 ///
1853 /// Nothing about it is a slot the frame laid out, because the frame is laid out once and this
1854 /// happens as often as control reaches the declaration. The bytes come off the stack pointer
1855 /// where the declaration stands, which is two instructions:
1856 ///
1857 /// ```text
1858 /// sub sp, bytes the stack pointer moves down over the memory, which is what takes it
1859 /// lea reg, [sp+n] where the memory starts, which is above the outgoing argument area
1860 /// ```
1861 ///
1862 /// The displacement is left at nothing for the reason the constant kind leaves its own at
1863 /// nothing, and for a different number: that area belongs to the arguments of whatever this
1864 /// function calls, it stays at the bottom of the frame wherever the bottom has moved to, and
1865 /// how big it is is not known until every call in the function has been seen.
1866 ///
1867 /// The bytes are already a multiple of the stack pointer's alignment by the time they arrive,
1868 /// because [`crate::expand::rounds`] rounded them up in the IR, so nothing here has to mask the
1869 /// stack pointer afterwards and the stack pointer stays somewhere a call can be made from.
1870 ///
1871 /// Two instructions here and not always two in the finished function. On a command line that
1872 /// asked for the stack to be touched a page at a time, the subtraction becomes a loop that
1873 /// walks the same distance a page at a time, which [`crate::finish`] writes. That is why the
1874 /// instruction is written down in [`Stack::grown`] as well as left where it is.
1875 ///
1876 /// An array wanting more alignment than the convention leaves the stack pointer with does not
1877 /// reach here asking for it: [`crate::expand::rounds`] gives it the alignment in extra bytes
1878 /// and turns the array into a `ptr_add` of the offset that lands inside them, so what arrives
1879 /// is a block asking for the convention's alignment like any other. The refusal below is what
1880 /// answers IR that came from somewhere other than that pass, since forcing the alignment here
1881 /// would be a second rounding of a register the frame already rounded, and after it no
1882 /// constant reaches the rest of the frame from anywhere. See `Growing` in [`crate::frame`].
1883 fn grow(&mut self, inst: Inst, size: Value) -> Result<(), Unsupported> {
1884 let data = &self.source[inst];
1885 let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
1886 let info = self.source[mem];
1887 if info.align > self.conv.stack_align {
1888 return Err(Unsupported::Dynamic { inst, growing: Growing::Aligned });
1889 }
1890 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1891 let bytes = self.reg_of(size)?;
1892
1893 let block = self.at.expect("a block is being filled");
1894 let span = self.source.span(inst);
1895 let stack = mir::Reg::physical(self.conv.stack_pointer);
1896 let grow = self.named(self.selector.frame.grow);
1897 let took = self
1898 .out
1899 .build(block, grow)
1900 .at(span)
1901 .operand(mir::Operand::write(stack, self.gpr))
1902 .operand(mir::Operand::read(stack, self.gpr))
1903 .operand(mir::Operand::read(bytes, self.gpr))
1904 .finish();
1905 self.stack.grown.push(took);
1906
1907 let reg = self.new_reg(result);
1908 let lea = self.named(self.selector.frame.lea);
1909 let sp = mir::Operand::read(stack, self.gpr);
1910 let made =
1911 self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
1912 self.stack.dynamic.push(made);
1913 self.stack.grown_at.get_or_insert(inst);
1914 Ok(())
1915 }
1916
1917 /// Where the stack pointer is, kept so that something later can put it back.
1918 ///
1919 /// One move out of the stack pointer and one move into it, which is the whole of what the two
1920 /// halves are. What makes them worth writing is where the front end puts them: a scope holding
1921 /// a variable length array saves the stack pointer as it opens and puts it back as it closes,
1922 /// so a loop declaring one takes its bytes once round rather than once per iteration, and a
1923 /// jump out of the scope gives the bytes back on the way out.
1924 ///
1925 /// The value travels in an ordinary register the allocator hands out, so it may be spilled like
1926 /// any other, and a spill slot in a frame that grows is reached through the frame pointer,
1927 /// which is exactly the register that still means something after the stack pointer has moved.
1928 fn stack_pointer(&mut self, inst: Inst, into: bool) -> Result<(), Unsupported> {
1929 let data = &self.source[inst];
1930 let block = self.at.expect("a block is being filled");
1931 let span = self.source.span(inst);
1932 let stack = mir::Reg::physical(self.conv.stack_pointer);
1933 let mov =
1934 self.selector.frame.moves(self.gpr).expect("a class the target says how to move").mov;
1935 let mov = self.named(mov);
1936 let (write, read) = if into {
1937 let &saved = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
1938 (stack, self.reg_of(saved)?)
1939 } else {
1940 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1941 (self.new_reg(result), stack)
1942 };
1943 self.out
1944 .build(block, mov)
1945 .at(span)
1946 .operand(mir::Operand::write(write, self.gpr))
1947 .operand(mir::Operand::read(read, self.gpr))
1948 .finish();
1949 // Only the write is a move of the stack pointer, and it is the one that makes the frame a
1950 // growing one. A read of it in a function that never writes it back is a function that
1951 // asked where the stack was and did nothing with the answer.
1952 if into {
1953 self.stack.grown_at.get_or_insert(inst);
1954 }
1955 Ok(())
1956 }
1957
1958 /// Whether an instruction has an eighty bit float anywhere in it.
1959 ///
1960 /// Producing one and reading one are the same question here, because what makes one of these
1961 /// different from every other instruction is not the operation but where the value is. A
1962 /// `long double` is on the x87 stack while it is being worked on and in a frame slot the rest
1963 /// of the time, and neither of those is somewhere the operand of a rule could point.
1964 fn touches_x87(&self, inst: Inst) -> bool {
1965 let data = &self.source[inst];
1966 data.results().any(|value| on_x87(self.source[value].ty))
1967 || self.source[data.args].iter().any(|&arg| on_x87(self.source[arg].ty))
1968 }
1969
1970 /// Everything that happens to an eighty bit float, as the group of instructions it is.
1971 ///
1972 /// The first six move one, and every one of those is a load, a store, or a load and a store at
1973 /// two different formats, because that is the whole of what this machine converts with: the
1974 /// x87 has no instruction that turns one thing on its stack into another, so a widening is
1975 /// `fld` of the narrow format and a narrowing is `fstp` of it.
1976 ///
1977 /// The rest work on one, and they are here rather than in a rule for the same reason the six
1978 /// are. An add is a push, a push, the add and a pop, and what passes between those four is the
1979 /// top of a stack nothing allocates from, so there is no value in the middle of the group for
1980 /// a pattern to bind or a replacement to name. The comparison is the same shape with its last
1981 /// two instructions folded into one opcode, which is where the byte it produces comes from.
1982 ///
1983 /// Every group leaves the stack as empty as it found it, which is what `spec/10-backend.md`
1984 /// section 10.8 asks of one and is why nothing in this file has to track a depth: each push
1985 /// below is answered by a pop a line or two later, so no two groups can ever be looking at
1986 /// the same eight registers.
1987 fn x87(&mut self, inst: Inst) -> Result<(), Unsupported> {
1988 match self.source[inst].opcode {
1989 Opcode::Load => self.x87_load(inst),
1990 Opcode::Store => self.x87_store(inst),
1991 Opcode::FPExt => self.x87_widen(inst),
1992 Opcode::FPTrunc => self.x87_narrow(inst),
1993 Opcode::SIToFP => self.x87_from_signed(inst),
1994 Opcode::FPToSI => self.x87_to_signed(inst),
1995 Opcode::FAdd => self.x87_arith(inst, "fadd_p"),
1996 Opcode::FSub => self.x87_arith(inst, "fsubr_p"),
1997 Opcode::FMul => self.x87_arith(inst, "fmul_p"),
1998 Opcode::FDiv => self.x87_arith(inst, "fdivr_p"),
1999 Opcode::FNeg => self.x87_flip(inst),
2000 Opcode::FCmp => self.x87_compare(inst),
2001 Opcode::FConst => self.x87_const(inst),
2002 _ => Err(self.unsupported(inst)),
2003 }
2004 }
2005
2006 /// The eighty bit parameters of a block, copied out of the addresses an edge handed over and
2007 /// into slots of the block's own.
2008 ///
2009 /// What crosses an edge for a value of this type is an address, because the value is sixteen
2010 /// bytes of the frame and no register holds any of it. The block cannot keep that address: a
2011 /// second edge into the same block hands over a second one, and a read after the block would
2012 /// then be a read of whichever edge was taken rather than of one place. So the block has a
2013 /// slot per parameter and the bytes are copied into it here, which is the move on an edge that
2014 /// every other type gets from the allocator.
2015 ///
2016 /// Every load runs before every store and the stores run backwards, so all of the values are
2017 /// on the x87 stack at once and nothing reads a slot another one has already written. That
2018 /// costs nothing in the ordinary case of one parameter and is what makes the back edge of a
2019 /// loop that swaps two of these work. It is also the reason for the limit: the stack is eight
2020 /// deep, and a block with more of these than that is refused rather than copied in an order
2021 /// that could be wrong.
2022 fn settle(&mut self, block: Block, arriving: &[(Value, mir::Reg)]) -> Result<(), Unsupported> {
2023 let Some(&(first, _)) = arriving.first() else { return Ok(()) };
2024 if arriving.len() > X87_DEPTH {
2025 let ty = self.source[first].ty;
2026 return Err(Unsupported::Phi { block, count: arriving.len(), ty });
2027 }
2028 // A block parameter comes from no instruction, so what this points at is the first thing
2029 // in the block, which is where a reader looking for the copy would look.
2030 let first_inst = self.source.insts(block).next();
2031 let span = first_inst.map_or(Span::DUMMY, |it| self.source.span(it));
2032 for &(_, reg) in arriving {
2033 let from = self.through(reg);
2034 self.x87_at("fld_t", span, from);
2035 }
2036 for &(param, _) in arriving.iter().rev() {
2037 let into = self.x87_slot(param);
2038 let into = self.through(into);
2039 self.x87_at("fstp_t", span, into);
2040 }
2041 Ok(())
2042 }
2043
2044 /// The frame slot an eighty bit value lives in, as its address in a fresh register.
2045 ///
2046 /// The slot is the value's for the whole function and is taken the first time somebody asks.
2047 /// The address is worked out again every time, which is a `lea` per use and is deliberate: one
2048 /// address kept in a register from the definition to the last use would hold a general purpose
2049 /// register open across everything in between, and a function with a handful of these in it
2050 /// would spend its registers on addresses of things rather than on things.
2051 fn x87_slot(&mut self, value: Value) -> mir::Reg {
2052 // An argument of the function has a slot already and it is the caller's. The convention
2053 // puts the bytes in the argument area and hands over where they are, so the address that
2054 // arrived is the answer and no second copy of the value is made. Nothing ever writes to a
2055 // value of this type once it exists, so nothing writes to the caller's copy either. A
2056 // parameter of any other block is not this: what arrived there is an address a predecessor
2057 // chose, [`Lowering::settle`] has already copied the bytes out of it, and the slot those
2058 // bytes landed in is the one below.
2059 let entry = self.source.entry();
2060 if let (Def::Param { block, .. }, Some(reg)) =
2061 (self.source[value].def, self.regs[value.index()])
2062 {
2063 if entry == Some(block) {
2064 return reg;
2065 }
2066 }
2067 let index = match self.slots[value.index()] {
2068 Some(index) => index,
2069 None => {
2070 let index = self.stack.locals.len();
2071 self.stack.locals.push(Local { size: X87_BYTES, align: X87_BYTES });
2072 self.slots[value.index()] = Some(index);
2073 index
2074 }
2075 };
2076 let block = self.at.expect("a block is being filled");
2077 self.frame_address(block, index)
2078 }
2079
2080 /// The bytes a value crosses between a register and the x87 stack through, as their address
2081 /// in a fresh register.
2082 fn x87_crossing(&mut self) -> mir::Reg {
2083 let index = match self.crossing {
2084 Some(index) => index,
2085 None => {
2086 let index = self.stack.locals.len();
2087 self.stack.locals.push(Local { size: X87_CROSSING, align: X87_CROSSING });
2088 self.crossing = Some(index);
2089 index
2090 }
2091 };
2092 let block = self.at.expect("a block is being filled");
2093 self.frame_address(block, index)
2094 }
2095
2096 /// The two control words, as the address of the first of them in a fresh register.
2097 fn x87_control(&mut self) -> mir::Reg {
2098 let index = match self.control {
2099 Some(index) => index,
2100 None => {
2101 let index = self.stack.locals.len();
2102 self.stack.locals.push(Local { size: 4, align: 4 });
2103 self.control = Some(index);
2104 index
2105 }
2106 };
2107 let block = self.at.expect("a block is being filled");
2108 self.frame_address(block, index)
2109 }
2110
2111 /// An address held in a register, as the addressing mode that reaches it.
2112 fn through(&self, reg: mir::Reg) -> mir::Mem {
2113 mir::Mem::at(mir::Operand::read(reg, self.gpr))
2114 }
2115
2116 /// One instruction of a group, which names an address and nothing else.
2117 ///
2118 /// Every x87 instruction that moves a value is one of these. What it does to the stack is in
2119 /// the mnemonic rather than in an operand, so there is no register to write down and no
2120 /// register the allocator gets a say in.
2121 fn x87_at(&mut self, name: &str, span: Span, at: mir::Mem) {
2122 let block = self.at.expect("a block is being filled");
2123 let opcode = self.named(name);
2124 self.out.build(block, opcode).at(span).mem(at).finish();
2125 }
2126
2127 /// The one instruction of a group that reaches the program's own memory.
2128 ///
2129 /// A `long double` moves in two instructions with a frame slot at one end of them, and the
2130 /// other end is the address the program wrote. That end is the access, so it is the one that
2131 /// carries what the program said about it, and the trip through the slot is this compiler's
2132 /// own business the way a spill is. See [`Self::carried`].
2133 fn x87_touching(&mut self, name: &str, inst: Inst, at: mir::Mem) {
2134 let block = self.at.expect("a block is being filled");
2135 let opcode = self.named(name);
2136 let (span, flags) = (self.source.span(inst), self.carried(inst));
2137 self.out.build(block, opcode).at(span).flags(flags).mem(at).finish();
2138 }
2139
2140 /// One instruction of a group that names nothing at all.
2141 ///
2142 /// The arithmetic is these. Both of an add's operands are already on the stack when it runs
2143 /// and so is where the answer goes, and the stack is not somewhere an instruction says, so
2144 /// `faddp` has an argument in the assembler's syntax and nothing here for the argument to come
2145 /// from. What it works on is which two pushes came before it, which is a fact about the order
2146 /// of the group and is why the group is written in one place.
2147 fn x87_only(&mut self, name: &str, span: Span) {
2148 let block = self.at.expect("a block is being filled");
2149 let opcode = self.named(name);
2150 self.out.build(block, opcode).at(span).finish();
2151 }
2152
2153 /// A `load` of a `long double`: onto the stack from where it was, and off it into the slot.
2154 ///
2155 /// Two instructions rather than the two general purpose moves the same sixteen bytes would
2156 /// take, because `fld` and `fstp` at this format neither convert nor look: the value goes on
2157 /// in the format it was already in and comes back off in it, so a signalling NaN stays one
2158 /// and nothing is raised. Which is what makes this a copy at all.
2159 fn x87_load(&mut self, inst: Inst) -> Result<(), Unsupported> {
2160 let (args, result) = self.ends(inst)?;
2161 let &address = args.first().ok_or_else(|| self.unsupported(inst))?;
2162 let span = self.source.span(inst);
2163 let from = self.reg_of(address)?;
2164 let from = self.through(from);
2165 let into = self.x87_slot(result);
2166 let into = self.through(into);
2167 self.x87_touching("fld_t", inst, from);
2168 self.x87_at("fstp_t", span, into);
2169 Ok(())
2170 }
2171
2172 /// A `store` of a `long double`: the same pair the other way round.
2173 fn x87_store(&mut self, inst: Inst) -> Result<(), Unsupported> {
2174 let args = self.source[self.source[inst].args].to_vec();
2175 let [value, address] = args[..] else { return Err(self.unsupported(inst)) };
2176 let span = self.source.span(inst);
2177 let from = self.x87_slot(value);
2178 let from = self.through(from);
2179 let into = self.reg_of(address)?;
2180 let into = self.through(into);
2181 self.x87_at("fld_t", span, from);
2182 self.x87_touching("fstp_t", inst, into);
2183 Ok(())
2184 }
2185
2186 /// A `float`, a `double` or an integer becoming a `long double`.
2187 ///
2188 /// Through memory, because the x87 reads memory and nothing else: the value is in a register
2189 /// the machine has and the unit has no way to be handed one, so it is written to the crossing
2190 /// bytes and loaded back at the format that widens it. Every one of these is exact. Sixty four
2191 /// bits of significand and fifteen of exponent hold every `float`, every `double` and every
2192 /// sixty four bit integer outright, so none of the four can round and none can raise.
2193 fn x87_across(
2194 &mut self,
2195 inst: Inst,
2196 put: &'static str,
2197 class: RegClass,
2198 get: &'static str,
2199 ) -> Result<(), Unsupported> {
2200 let (args, result) = self.ends(inst)?;
2201 let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2202 let span = self.source.span(inst);
2203 let value = self.reg_of(source)?;
2204 let across = self.x87_crossing();
2205 let across = self.through(across);
2206 let into = self.x87_slot(result);
2207 let into = self.through(into);
2208
2209 let block = self.at.expect("a block is being filled");
2210 let store = self.named(put);
2211 self.out.build(block, store).at(span).uses(value, class).mem(across).finish();
2212 self.x87_at(get, span, across);
2213 self.x87_at("fstp_t", span, into);
2214 Ok(())
2215 }
2216
2217 /// A `long double` becoming a `float`, a `double` or an integer.
2218 ///
2219 /// Through memory for the reason above and in the same three instructions backwards. The two
2220 /// that go to a float round to nearest, which is what the control word says unless somebody
2221 /// has changed it and is what C wants. The two that go to an integer do not, which is why they
2222 /// do not come here.
2223 fn x87_back(
2224 &mut self,
2225 inst: Inst,
2226 put: &'static str,
2227 get: &'static str,
2228 class: RegClass,
2229 ) -> Result<(), Unsupported> {
2230 let (args, result) = self.ends(inst)?;
2231 let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2232 let span = self.source.span(inst);
2233 let from = self.x87_slot(source);
2234 let from = self.through(from);
2235 let across = self.x87_crossing();
2236 let across = self.through(across);
2237
2238 self.x87_at("fld_t", span, from);
2239 self.x87_at(put, span, across);
2240 let block = self.at.expect("a block is being filled");
2241 let reg = self.new_reg(result);
2242 let load = self.named(get);
2243 self.out.build(block, load).at(span).def(reg, class).mem(across).finish();
2244 Ok(())
2245 }
2246
2247 /// An `fpext` up to a `long double`, which is the only direction this machine has one in.
2248 fn x87_widen(&mut self, inst: Inst) -> Result<(), Unsupported> {
2249 let sse = self.conv.sse_class;
2250 match self.source[self.narrow(inst)?].ty.bits() {
2251 32 => self.x87_across(inst, "movss_mr", sse, "fld_s"),
2252 64 => self.x87_across(inst, "movsd_mr", sse, "fld_l"),
2253 _ => Err(self.unsupported(inst)),
2254 }
2255 }
2256
2257 /// An `fptrunc` down from a `long double`, which is the other direction of the same.
2258 fn x87_narrow(&mut self, inst: Inst) -> Result<(), Unsupported> {
2259 let sse = self.conv.sse_class;
2260 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2261 match self.source[result].ty.bits() {
2262 32 => self.x87_back(inst, "fstp_s", "movss_rm", sse),
2263 64 => self.x87_back(inst, "fstp_l", "movsd_rm", sse),
2264 _ => Err(self.unsupported(inst)),
2265 }
2266 }
2267
2268 /// A `sitofp` up to a `long double`.
2269 ///
2270 /// Thirty two bits and sixty four, and nothing narrower, because C widens an integer to `int`
2271 /// before it converts one and the front end writes that widening down. An unsigned integer is
2272 /// not here at all: `fild` reads its operand as signed, so a value above the signed range
2273 /// comes back short by two to the sixty fourth and has to be added back, which is arithmetic
2274 /// rather than a move and waits with the rest of it.
2275 fn x87_from_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
2276 let gpr = self.gpr;
2277 match self.source[self.narrow(inst)?].ty.bits() {
2278 32 => self.x87_across(inst, "mov_mr_32", gpr, "fild_l"),
2279 64 => self.x87_across(inst, "mov_mr_64", gpr, "fild_ll"),
2280 _ => Err(self.unsupported(inst)),
2281 }
2282 }
2283
2284 /// An `fptosi` down from a `long double`, which is the one conversion here with no single
2285 /// instruction behind it.
2286 ///
2287 /// C cuts towards zero and the unit rounds the way its control word says, so the store that
2288 /// takes the value off the stack is wrapped in the control word being saved, changed and put
2289 /// back. Five instructions around the one that does the work, and three more moving the word
2290 /// through a register, because this machine has no way to OR a constant into memory at this
2291 /// width. The unit has a shorter answer in `fisttp`, and `spec/10-backend.md` section 10.8
2292 /// says why it is not used: it is SSE3, the x86-64 baseline is not, and there is nothing here
2293 /// that can gate an instruction on a feature yet.
2294 fn x87_to_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
2295 let (args, result) = self.ends(inst)?;
2296 let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2297 let (put, get) = match self.source[result].ty.bits() {
2298 32 => ("fistp_l", "mov_rm_32"),
2299 64 => ("fistp_ll", "mov_rm_64"),
2300 _ => return Err(self.unsupported(inst)),
2301 };
2302 let span = self.source.span(inst);
2303 let gpr = self.gpr;
2304 let from = self.x87_slot(source);
2305 let from = self.through(from);
2306 let across = self.x87_crossing();
2307 let across = self.through(across);
2308 let control = self.x87_control();
2309 let saved = self.through(control).plus(0);
2310 let cut = self.through(control).plus(2);
2311
2312 // The word the unit has now, into the first of the two slots and into a register, with the
2313 // rounding field turned to truncate on the way to the second.
2314 self.x87_at("fnstcw", span, saved);
2315 let block = self.at.expect("a block is being filled");
2316 let was = self.out.new_vreg(gpr);
2317 let read = self.named("mov_rm_16");
2318 self.out.build(block, read).at(span).def(was, gpr).mem(saved).finish();
2319 let now = self.out.new_vreg(gpr);
2320 let set = self.named("or_ri_16");
2321 // Two address, which is written out here rather than taken from the two shorthands
2322 // because the shorthands leave an operand unconstrained: this machine ORs into the
2323 // register it read, so the two have to be the same one and only the constraint says so.
2324 self.out
2325 .build(block, set)
2326 .at(span)
2327 .operand(mir::Operand::write(now, gpr).with(Constraint::Reuse(1)))
2328 .operand(mir::Operand::read(was, gpr))
2329 .imm(X87_TRUNCATE)
2330 .finish();
2331 let write = self.named("mov_mr_16");
2332 self.out.build(block, write).at(span).uses(now, gpr).mem(cut).finish();
2333
2334 // The conversion itself, under the changed word, and then the word the unit had put back
2335 // before anything else runs.
2336 self.x87_at("fldcw", span, cut);
2337 self.x87_at("fld_t", span, from);
2338 self.x87_at(put, span, across);
2339 self.x87_at("fldcw", span, saved);
2340
2341 let block = self.at.expect("a block is being filled");
2342 let reg = self.new_reg(result);
2343 let load = self.named(get);
2344 self.out.build(block, load).at(span).def(reg, gpr).mem(across).finish();
2345 Ok(())
2346 }
2347
2348 /// A constant of this type, as the bits of it written into its slot.
2349 ///
2350 /// No x87 instruction at all, which is the surprise here. A slot holding an eighty bit value is
2351 /// the value, so a constant is ten bytes put where the value lives, and the unit never has to
2352 /// see it: whatever reads it will `fld` it out of the slot the way it reads any other one.
2353 ///
2354 /// Ten bytes in two goes, because the machine stores eight at a time and there is no store of
2355 /// an immediate to memory, so each half is put in a register first. The six bytes above the ten
2356 /// are left alone, since nothing reads them: they are the padding that makes the type sixteen
2357 /// wide and they are unspecified in the psABI rather than zero.
2358 ///
2359 /// The other way is a constant pool, an `fldt` of a symbol, and a relocation, which is what a
2360 /// compiler with somewhere to put a literal does. This back end has nowhere to put one yet, and
2361 /// four instructions in the frame is what that costs until it does.
2362 fn x87_const(&mut self, inst: Inst) -> Result<(), Unsupported> {
2363 let Extra::Imm(imm) = self.source[inst].extra else { return Err(self.unsupported(inst)) };
2364 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2365 let bits = self.source[imm].bits();
2366 let span = self.source.span(inst);
2367 let gpr = self.gpr;
2368 let slot = self.x87_slot(result);
2369 let low = self.through(slot).plus(0);
2370 let high = self.through(slot).plus(8);
2371
2372 let block = self.at.expect("a block is being filled");
2373 for (bytes, at, into) in
2374 [(bits as u64 as i64, low, "64"), (((bits >> 64) & 0xffff) as i64, high, "16")]
2375 {
2376 let held = self.out.new_vreg(gpr);
2377 let put = self.named(&format!("mov_ri_{into}"));
2378 self.out.build(block, put).at(span).def(held, gpr).imm(bytes).finish();
2379 let store = self.named(&format!("mov_mr_{into}"));
2380 self.out.build(block, store).at(span).uses(held, gpr).mem(at).finish();
2381 }
2382 Ok(())
2383 }
2384
2385 /// One arithmetic instruction on two eighty bit values, as the four it takes.
2386 ///
2387 /// The left operand is pushed first and the right one on top of it, so the left ends up
2388 /// underneath and the answer wanted is the one below against the top in that order. Which of
2389 /// the two mnemonics computes that is a question about the spelling rather than about the
2390 /// machine, and the two spellings disagree. Intel's `FSUBP ST(i), ST(0)` is `ST(i) - ST(0)`
2391 /// and is `DE E8+i`, and AT&T's `fsubp` is `DE E0+i`, which is the other subtraction. This
2392 /// compiler writes AT&T and encodes what gas encodes, so what it asks for here is `fsubr_p`
2393 /// and `fdivr_p`, and the `r` is not a reversal of anything the code generator decided.
2394 ///
2395 /// An addition and a multiplication have one form each and do not care, which is why a test
2396 /// that reads the mnemonic back would not have caught this and one that computes a subtraction
2397 /// and checks the answer does.
2398 ///
2399 /// The answer is left where the deeper of the two was and the shallower is gone, which is what
2400 /// the `p` on the mnemonic means, so one push has already been paid back by the time the
2401 /// `fstp` runs and the stack is level again after it.
2402 ///
2403 /// Nothing here is folded and nothing is reused. Two values that are the same value get two
2404 /// pushes of the same slot, and an operand that was just computed is read back out of the slot
2405 /// it was written to rather than left on the stack, which costs a store and a load per
2406 /// instruction in an expression. Keeping a partial result on the stack across the next
2407 /// instruction's operands means knowing how deep the stack is at every point in the block, and
2408 /// that is a different thing from writing a group.
2409 fn x87_arith(&mut self, inst: Inst, with: &'static str) -> Result<(), Unsupported> {
2410 let (args, result) = self.ends(inst)?;
2411 let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
2412 let span = self.source.span(inst);
2413 let left = self.x87_slot(left);
2414 let left = self.through(left);
2415 let right = self.x87_slot(right);
2416 let right = self.through(right);
2417 let into = self.x87_slot(result);
2418 let into = self.through(into);
2419 self.x87_at("fld_t", span, left);
2420 self.x87_at("fld_t", span, right);
2421 self.x87_only(with, span);
2422 self.x87_at("fstp_t", span, into);
2423 Ok(())
2424 }
2425
2426 /// A negation, which is a push, the sign bit turned over and a pop.
2427 ///
2428 /// `fchs` does not read the value as a number, so this is right for a zero, for an infinity
2429 /// and for a NaN, and it raises nothing on any of them. Which is what C asks of a negation and
2430 /// is not what subtracting from zero would give: `0.0L - x` is a different answer at a
2431 /// negative zero and a signalling one at a NaN.
2432 fn x87_flip(&mut self, inst: Inst) -> Result<(), Unsupported> {
2433 let (args, result) = self.ends(inst)?;
2434 let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2435 let span = self.source.span(inst);
2436 let from = self.x87_slot(source);
2437 let from = self.through(from);
2438 let into = self.x87_slot(result);
2439 let into = self.through(into);
2440 self.x87_at("fld_t", span, from);
2441 self.x87_only("fchs", span);
2442 self.x87_at("fstp_t", span, into);
2443 Ok(())
2444 }
2445
2446 /// A comparison of two eighty bit values, as the two pushes and the one opcode that reads them.
2447 ///
2448 /// The right operand is pushed first and the left one on top of it, which is the other way
2449 /// round from the arithmetic and is because `fucomip` asks about the top against what is under
2450 /// it: the comparison this machine can do is the top's, so the value the predicate is about
2451 /// has to be the top. The pop that gets the loser off the stack and the byte that reads the
2452 /// flags are both inside the opcode, since what passes between those and the comparison is the
2453 /// flags and the flags are not something anything here can name.
2454 ///
2455 /// Which of the ten opcodes, and which way round, is the same table the vector comparisons
2456 /// match against in `rules/x86-64.rules`, and it has to stay the same table: a predicate that
2457 /// picked a different condition here than there would be a `long double` comparison that
2458 /// disagreed with the `double` comparison of the same two numbers, which is the one thing a
2459 /// wider format is not allowed to do.
2460 ///
2461 /// The always false and the always true are refused rather than folded into a constant,
2462 /// because a comparison this machine never has to do is one the optimizer should have removed
2463 /// and an instruction here that quietly agreed with it would hide that it did not.
2464 fn x87_compare(&mut self, inst: Inst) -> Result<(), Unsupported> {
2465 let Extra::FloatPred(pred) = self.source[inst].extra else {
2466 return Err(self.unsupported(inst));
2467 };
2468 let (args, result) = self.ends(inst)?;
2469 let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
2470 // Two of the fourteen need a second byte and an instruction to put the two together,
2471 // because they are two conditions at once: an ordered equal is equal and not unordered,
2472 // and an unordered not equal is either. The opcode carries all of that and says here only
2473 // that it writes somewhere else as well.
2474 let (name, reversed, both) = match pred {
2475 FloatPred::Ogt => ("fucomip_set_a", false, false),
2476 FloatPred::Oge => ("fucomip_set_ae", false, false),
2477 FloatPred::Olt => ("fucomip_set_a", true, false),
2478 FloatPred::Ole => ("fucomip_set_ae", true, false),
2479 FloatPred::One => ("fucomip_set_ne", false, false),
2480 FloatPred::Ord => ("fucomip_set_np", false, false),
2481 FloatPred::Uno => ("fucomip_set_p", false, false),
2482 FloatPred::Ueq => ("fucomip_set_e", false, false),
2483 FloatPred::Ult => ("fucomip_set_b", false, false),
2484 FloatPred::Ule => ("fucomip_set_be", false, false),
2485 FloatPred::Ugt => ("fucomip_set_b", true, false),
2486 FloatPred::Uge => ("fucomip_set_be", true, false),
2487 FloatPred::Oeq => ("fucomip_set_e_and_np", false, true),
2488 FloatPred::Une => ("fucomip_set_ne_or_p", false, true),
2489 FloatPred::False | FloatPred::True => return Err(self.unsupported(inst)),
2490 };
2491 let (top, under) = if reversed { (right, left) } else { (left, right) };
2492
2493 let span = self.source.span(inst);
2494 let gpr = self.gpr;
2495 let under = self.x87_slot(under);
2496 let under = self.through(under);
2497 let top = self.x87_slot(top);
2498 let top = self.through(top);
2499 self.x87_at("fld_t", span, under);
2500 self.x87_at("fld_t", span, top);
2501
2502 let block = self.at.expect("a block is being filled");
2503 let reg = self.new_reg(result);
2504 // Taken before the instruction is started rather than inside it, since both come from the
2505 // same function being built and only one thing at a time may be adding to it.
2506 let spare = both.then(|| self.out.new_vreg(gpr));
2507 let opcode = self.named(name);
2508 let mut build = self.out.build(block, opcode).at(span).def(reg, gpr);
2509 if let Some(spare) = spare {
2510 build = build.def(spare, gpr);
2511 }
2512 build.finish();
2513 Ok(())
2514 }
2515
2516 /// The operands and the one result of an instruction that has exactly one.
2517 fn ends(&self, inst: Inst) -> Result<(&'a [Value], Value), Unsupported> {
2518 let data = &self.source[inst];
2519 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2520 Ok((&self.source[data.args], result))
2521 }
2522
2523 /// The operand of a conversion, which is the end of it that is not the `long double`.
2524 fn narrow(&self, inst: Inst) -> Result<Value, Unsupported> {
2525 let args = &self.source[self.source[inst].args];
2526 args.first().copied().ok_or_else(|| self.unsupported(inst))
2527 }
2528
2529 /// One `va_start`, as the fields of the list it was handed.
2530 ///
2531 /// On the four field list, two of them are numbers this already knows, and each costs an
2532 /// instruction to put in a register before it can be stored, because the machine here has no
2533 /// store of an immediate to memory. The other two are addresses in the frame, and each is a
2534 /// `lea` [`crate::finish`] finishes: the save area is one of the function's own stack objects,
2535 /// and the caller's argument area is where the parameters that had no register came from, which
2536 /// is the same place and the same fixup a parameter past the sixth already uses.
2537 ///
2538 /// On the list that is a pointer it is the second of those four and nothing else, since the
2539 /// whole of what that list says is where the walk is and the walk starts at the first argument
2540 /// the signature does not name. One `lea` and one store.
2541 ///
2542 /// What is written is exactly the fields [`crate::varargs`] describes, in the order they are
2543 /// laid out, so that reading this beside that table is the whole of the check.
2544 fn va_start(&mut self, inst: Inst) -> Result<(), Unsupported> {
2545 let Some(&list) = self.source[self.source[inst].args].first() else {
2546 return Err(self.unsupported(inst));
2547 };
2548 let started = self.varargs.ok_or_else(|| self.unsupported(inst))?;
2549 let list = self.reg_of(list)?;
2550 let block = self.at.expect("a block is being filled");
2551 let span = self.source.span(inst);
2552
2553 let (save, incoming) = match started {
2554 Varargs::Pointer { incoming } => (None, incoming),
2555 Varargs::Fields { save, incoming, integers, floats } => {
2556 let counts = [(varargs::GP_OFFSET, integers), (varargs::FP_OFFSET, floats)];
2557 for (at, count) in counts {
2558 self.store_small(list, at, i64::from(count), span);
2559 }
2560 (Some(save), incoming)
2561 }
2562 Varargs::Aapcs { save, incoming, integers_end, floats_end, integers, floats } => {
2563 let counts =
2564 [(varargs::aapcs::GR_OFFS, integers), (varargs::aapcs::VR_OFFS, floats)];
2565 for (at, count) in counts {
2566 self.store_small(list, at, i64::from(count), span);
2567 }
2568 let overflow = self.overflow(block, incoming, span);
2569 let integers_top = self.frame_address_plus(block, save, integers_end);
2570 let floats_top = self.frame_address_plus(block, save, floats_end);
2571 let fields = [
2572 (varargs::aapcs::STACK, overflow),
2573 (varargs::aapcs::GR_TOP, integers_top),
2574 (varargs::aapcs::VR_TOP, floats_top),
2575 ];
2576 for (at, held) in fields {
2577 self.store_word(list, at, held, span);
2578 }
2579 return Ok(());
2580 }
2581 };
2582
2583 // At the front of the list when that address is the whole of it, and at the field the
2584 // layout gives it when there are four, with the save area behind it.
2585 let overflow = self.overflow(block, incoming, span);
2586 let fields = match save {
2587 None => vec![(0, overflow)],
2588 Some(save) => {
2589 let save = self.frame_address(block, save);
2590 vec![(varargs::OVERFLOW, overflow), (varargs::SAVE_AREA, save)]
2591 }
2592 };
2593 for (at, held) in fields {
2594 self.store_word(list, at, held, span);
2595 }
2596 Ok(())
2597 }
2598
2599 /// The first argument the signature did not name, which is as far up the caller's argument
2600 /// area as the ones it did name reached. Nothing here knows where that area is, so the distance
2601 /// is recorded the way a parameter read out of it is and finished with it.
2602 fn overflow(&mut self, block: mir::Block, incoming: u32, span: Span) -> mir::Reg {
2603 let overflow = self.out.new_vreg(self.gpr);
2604 let lea = self.named(self.selector.frame.lea);
2605 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
2606 let made = self
2607 .out
2608 .build(block, lea)
2609 .at(span)
2610 .def(overflow, self.gpr)
2611 .mem(mir::Mem::at(sp))
2612 .finish();
2613 self.stack.arguments.push((made, incoming));
2614 overflow
2615 }
2616
2617 /// Writes a small constant into a 32 bit field of a list.
2618 fn store_small(&mut self, list: mir::Reg, at: i64, value: i64, span: Span) {
2619 let block = self.at.expect("a block is being filled");
2620 let held = self.out.new_vreg(self.gpr);
2621 let load = mir::Opcode::new(self.names.intern(self.selector.abi.small));
2622 self.out.build(block, load).at(span).def(held, self.gpr).imm(value).finish();
2623
2624 let head = (self.selector.abi.store)(Type::int(32)).expect("a store of a word");
2625 let store = mir::Opcode::new(self.names.intern(head));
2626 let mem = self.field(list, at);
2627 self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
2628 }
2629
2630 /// Writes an address into a pointer field of a list.
2631 fn store_word(&mut self, list: mir::Reg, at: i64, held: mir::Reg, span: Span) {
2632 let block = self.at.expect("a block is being filled");
2633 let head = (self.selector.abi.store)(Type::int(64)).expect("a store of an address");
2634 let store = mir::Opcode::new(self.names.intern(head));
2635 let mem = self.field(list, at);
2636 self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
2637 }
2638
2639 /// One field of a list, as the addressing mode that reaches it.
2640 fn field(&self, list: mir::Reg, at: i64) -> mir::Mem {
2641 let base = mir::Operand::read(list, self.gpr);
2642 mir::Mem::at(base).plus(i32::try_from(at).expect("a field of a list is a small offset"))
2643 }
2644
2645 /// The address of a name: one `lea` off the instruction pointer, with the name on it.
2646 ///
2647 /// That is x86-64, and [`Selector::symbols`] is what says so. AArch64 writes the same thing as
2648 /// an `adrp` of the page and an `add` of the low twelve bits, which is one opcode with the name
2649 /// as its own symbol and no addressing mode, and the table read is an `adrp` and an `ldr`.
2650 ///
2651 /// The same instruction an `alloca` gets and for a related reason. An address that is not in
2652 /// the program is a `lea` of an addressing mode that names no register, and the mode carries
2653 /// the symbol so that [`rucc_asm`] can write it relative to `%rip` and leave the relocation
2654 /// for the assembler. Both halves of that already existed: the printer writes `sym(%rip)` and
2655 /// the encoder emits the relocation, because a call to a name the file does not define needed
2656 /// them first.
2657 ///
2658 /// One `mov` and not one `lea` when the name is one [`Elsewhere`] holds, because the distance
2659 /// the `lea` adds to the instruction pointer is a number only a link that puts the name in
2660 /// this program can work out, and the address of a function this file merely declares is not
2661 /// such a number. The load reads the address out of the slot the linker fills in instead. The
2662 /// linker turns it back into the `lea` when the name turns out to have been here all along,
2663 /// so this is not slower in the case that was already right.
2664 ///
2665 /// There is deliberately no name for this in [`crate::term`], which is what stops the address
2666 /// being folded into the instruction that reads it. Folding it is the right thing to do and
2667 /// is what turns a load of a global from two instructions into one, but it is a separate
2668 /// question about addressing modes and issue #282 is it. Until then the address is in a
2669 /// register before anything uses it, which is correct and one instruction longer.
2670 ///
2671 /// What this does not do is give the name anything to refer to. A module carries its globals
2672 /// and nothing writes them out, so a file that defines the variable it reads compiles to a
2673 /// reference the linker cannot resolve. Issue #293 is the other half.
2674 ///
2675 /// A thread-local variable is neither of the two above and is [`Self::thread_address`].
2676 fn address_of(&mut self, inst: Inst) -> Result<(), Unsupported> {
2677 let data = &self.source[inst];
2678 let Extra::Symbol(symbol) = data.extra else { return Err(self.unsupported(inst)) };
2679 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2680 if self.elsewhere.thread(symbol) {
2681 return self.thread_address(inst, symbol, result);
2682 }
2683
2684 let block = self.at.expect("a block is being filled");
2685 let reg = self.new_reg(result);
2686 let span = self.source.span(inst);
2687 let far = self.elsewhere.holds(symbol);
2688 let symbols = self.selector.symbols;
2689 match if far { symbols.far } else { symbols.near } {
2690 Reach::Mode(name) => {
2691 let mem = if far { mir::Mem::got(symbol) } else { mir::Mem::of(symbol) };
2692 let opcode = self.named(name);
2693 self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
2694 }
2695 Reach::Own(name) => {
2696 let opcode = self.named(name);
2697 self.out.build(block, opcode).at(span).def(reg, self.gpr).symbol(symbol).finish();
2698 }
2699 }
2700 Ok(())
2701 }
2702
2703 /// The address of a thread-local variable, which is this thread's copy of it.
2704 ///
2705 /// Neither instruction the ordinary case writes would mean anything here. There is no distance
2706 /// to the variable for a `lea` to add, because there is no variable: there is one copy of it per
2707 /// thread and they are at different addresses, so a link asked for the distance to the name
2708 /// refuses rather than picking one. And there is no address for a table slot to hold either, for
2709 /// the same reason.
2710 ///
2711 /// What is the same in every thread is where the variable sits inside the block of storage a
2712 /// thread gets, so that offset is what the link writes down, and the address of the running
2713 /// thread's block is what turns it into an address. x86-64 keeps that address in `%fs`, at the
2714 /// front of the block, so the whole of this is three instructions:
2715 ///
2716 /// ```text
2717 /// movq x@gottpoff(%rip), %off # how far into the block x sits, which the link fills in
2718 /// movq %fs:0, %tp # where this thread's block is, which only the machine knows
2719 /// addq %tp, %off # this thread's copy of x
2720 /// ```
2721 ///
2722 /// That is the initial exec model. It is one instruction longer than what gcc writes at `-O2`
2723 /// in an executable, which folds the addition into the instruction that uses the address, and
2724 /// the difference is issue #282 rather than anything about threads: nothing here folds an
2725 /// address into its reader yet. The link relaxes the first instruction into an immediate when it
2726 /// is making an executable, since it lays the blocks out and therefore knows the number, so the
2727 /// table slot costs nothing in the case that is common.
2728 ///
2729 /// It is not the most general model. A library loaded by `dlopen` gets its storage after the
2730 /// program is already running, and the block this reaches was laid out before it started, so
2731 /// the loader has to find room in that block for the library's variables. glibc keeps a little
2732 /// spare room for exactly this and a library that fits in it loads and runs; one that does not
2733 /// fails to load, with a message saying so. The model with no such limit calls `__tls_get_addr`
2734 /// and is what gcc writes under `-fPIC` by default, and it is issue #1104.
2735 ///
2736 /// So this is the model gcc writes under `-ftls-model=initial-exec`: right for an executable,
2737 /// right for a library the program is linked against, and a load that either works or is
2738 /// refused out loud for a library something opens later. What it is never is quietly wrong.
2739 ///
2740 /// AArch64 Linux is the same three steps. The slot is reached with `adrp` and `ldr` against
2741 /// `:gottprel:`, the thread pointer is `tpidr_el0` read with `mrs`, and the add has three
2742 /// operands. Apple's platforms reach a thread-local variable through a descriptor call instead,
2743 /// which is [`Self::thread_descriptor`].
2744 fn thread_address(
2745 &mut self,
2746 inst: Inst,
2747 symbol: Symbol,
2748 result: Value,
2749 ) -> Result<(), Unsupported> {
2750 if self.elsewhere.described() {
2751 return self.thread_descriptor(inst, symbol, result);
2752 }
2753 let block = self.at.expect("a block is being filled");
2754 let span = self.source.span(inst);
2755 let gpr = self.gpr;
2756
2757 let offset = self.out.new_vreg(gpr);
2758 match self.selector.symbols.thread {
2759 Reach::Mode(name) => {
2760 let load = self.named(name);
2761 let mem = mir::Mem::thread(symbol);
2762 self.out.build(block, load).at(span).def(offset, gpr).mem(mem).finish();
2763 }
2764 Reach::Own(name) => {
2765 let load = self.named(name);
2766 self.out.build(block, load).at(span).def(offset, gpr).symbol(symbol).finish();
2767 }
2768 }
2769 let pointer = self.out.new_vreg(gpr);
2770 self.read_thread_pointer(block, span, pointer);
2771
2772 // Two address on x86-64, for the reason `x87_to_int` gives: that machine adds into the
2773 // register it read, and only the constraint says the two are the same one.
2774 let reg = self.new_reg(result);
2775 let jumps = self.selector.jumps;
2776 let add = self.named(jumps.add);
2777 let written = mir::Operand::write(reg, gpr);
2778 let written = if jumps.two_address { written.with(Constraint::Reuse(1)) } else { written };
2779 self.out
2780 .build(block, add)
2781 .at(span)
2782 .operand(written)
2783 .operand(mir::Operand::read(offset, gpr))
2784 .operand(mir::Operand::read(pointer, gpr))
2785 .finish();
2786 Ok(())
2787 }
2788
2789 /// A thread-local variable on Mach-O, which is a call.
2790 ///
2791 /// The slot the machine's thread load reads holds the address of the variable's descriptor
2792 /// there, `_v@TLVP` on x86-64 and `_v@TLVPPAGE` with `_v@TLVPPAGEOFF` on AArch64. The first
2793 /// word of the descriptor is the function that finds this thread's copy, and it takes the
2794 /// descriptor's address as its one argument and gives back the copy's address. That is the
2795 /// sequence clang writes on both machines.
2796 ///
2797 /// The call is built as an ordinary call through an address, so it costs what any call costs:
2798 /// everything the convention does not preserve is taken to be gone across it. Apple's function
2799 /// keeps more than that, all but the result and the two scratch registers on AArch64, and
2800 /// taking the fewer registers as gone would be faster. What this gives up is speed, and a
2801 /// function that reads a thread-local is no longer a leaf.
2802 fn thread_descriptor(
2803 &mut self,
2804 inst: Inst,
2805 symbol: Symbol,
2806 result: Value,
2807 ) -> Result<(), Unsupported> {
2808 let block = self.at.expect("a block is being filled");
2809 let span = self.source.span(inst);
2810 let gpr = self.gpr;
2811
2812 let descriptor = self.out.new_vreg(gpr);
2813 match self.selector.symbols.thread {
2814 Reach::Mode(name) => {
2815 let load = self.named(name);
2816 let mem = mir::Mem::thread(symbol);
2817 self.out.build(block, load).at(span).def(descriptor, gpr).mem(mem).finish();
2818 }
2819 Reach::Own(name) => {
2820 let load = self.named(name);
2821 let build = self.out.build(block, load).at(span);
2822 build.def(descriptor, gpr).symbol(symbol).finish();
2823 }
2824 }
2825 let finder = self.out.new_vreg(gpr);
2826 let word = (self.selector.abi.load)(Type::PTR).ok_or_else(|| self.unsupported(inst))?;
2827 let word = mir::Opcode::new(self.names.intern(word));
2828 let mem = mir::Mem::at(mir::Operand::read(descriptor, gpr));
2829 self.out.build(block, word).at(span).def(finder, gpr).mem(mem).finish();
2830
2831 let args = [abi::Passing { ty: Type::PTR, reg: descriptor, abi: Abi::default() }];
2832 let what = abi::Calling {
2833 callee: abi::Callee::Through(finder),
2834 args: &args,
2835 returns: &[Type::PTR],
2836 variadic: false,
2837 named: 1,
2838 at: span,
2839 };
2840 let made = abi::call(&mut self.out, block, &what, self.conv, self.selector.abi, self.names)
2841 .map_err(|refused| Unsupported::Call { inst, refused })?;
2842 let calls = &mut self.stack.calls;
2843 *calls = Some(calls.unwrap_or(0).max(made.outgoing));
2844 let &[reg] = &made.results[..] else { return Err(self.unsupported(inst)) };
2845 self.regs[result.index()] = Some(reg);
2846 Ok(())
2847 }
2848
2849 /// Refuses the thread pointer where it is not written, which is Mach-O. Apple keeps it in a
2850 /// different register from the one Linux does on both machines, and nothing written for it
2851 /// has been checked on one.
2852 fn threads_written(&self, inst: Inst) -> Result<(), Unsupported> {
2853 if self.elsewhere.described() {
2854 return Err(Unsupported::Unported { inst: Some(inst), what: Unported::Thread });
2855 }
2856 Ok(())
2857 }
2858
2859 /// The front of this thread's block into `reg`.
2860 ///
2861 /// On x86-64 that is the one thing no instruction can work out: `%fs` is not a register a
2862 /// program can read, and what it points at is a word holding its own address, so reading
2863 /// through it at zero is how the address is come by. AArch64 keeps it in `tpidr_el0`, which
2864 /// `mrs` reads.
2865 fn read_thread_pointer(&mut self, block: mir::Block, span: Span, reg: mir::Reg) {
2866 let gpr = self.gpr;
2867 match self.selector.symbols.pointer {
2868 Pointer::Segment(name, segment) => {
2869 let load = self.named(name);
2870 let at = mir::Mem::in_segment(segment, 0);
2871 self.out.build(block, load).at(span).def(reg, gpr).mem(at).finish();
2872 }
2873 Pointer::Own(name) => {
2874 let read = self.named(name);
2875 self.out.build(block, read).at(span).def(reg, gpr).finish();
2876 }
2877 }
2878 }
2879
2880 /// `&&label`, GNU's address of a label, which is the same `lea` a global gets against a place
2881 /// in this same function.
2882 ///
2883 /// What the two have in common is the whole of the instruction: an address worked out from
2884 /// where the instruction is, which is what `(%rip)` means and is the only way this compiler
2885 /// reaches anything. What they do not have in common is what fills the four bytes in. A
2886 /// global is a name, so the number is a relocation and the linker writes it. A block is a
2887 /// place in this function, so both ends are in one section and the number is known as soon as
2888 /// the blocks have been laid out, which is why `rucc_asm` fills it in the way it fills in a
2889 /// jump rather than leaving a relocation behind.
2890 ///
2891 /// Nothing here says the block is one control can arrive at. That is said by the
2892 /// [`Opcode::IndirectBr`] that reads the address, which lists every block it can arrive at,
2893 /// and by nothing else: an address on its own is a number.
2894 fn block_address(&mut self, inst: Inst) -> Result<(), Unsupported> {
2895 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2896 let Some(call) = self.source.successors(inst).next() else {
2897 return Err(self.unsupported(inst));
2898 };
2899 let block = self.at.expect("a block is being filled");
2900 let reg = self.new_reg(result);
2901 let span = self.source.span(inst);
2902 let opcode = self.named(self.selector.jumps.near);
2903 let mem = mir::Mem::block(self.out_block(call.block));
2904 self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
2905 Ok(())
2906 }
2907
2908 /// `goto *p`, GNU's computed goto, which is a jump through a register.
2909 ///
2910 /// Where it goes is not written here and cannot be. Every block it can arrive at is on the
2911 /// block this ends, the way every other arm is, and which of them the address holds is decided
2912 /// while the program runs. So this is one instruction with one operand, and the arms are
2913 /// copied across by [`Self::edges`] like anybody else's.
2914 fn indirect_branch(&mut self, inst: Inst) -> Result<(), Unsupported> {
2915 let data = &self.source[inst];
2916 let &address = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
2917 let reg = self.reg_of(address)?;
2918 let block = self.at.expect("a block is being filled");
2919 let span = self.source.span(inst);
2920 let name = self.selector.branch.indirect;
2921 let opcode = self.named(name);
2922 self.out.build(block, opcode).at(span).operand(mir::Operand::read(reg, self.gpr)).finish();
2923 Ok(())
2924 }
2925
2926 /// A `switch` on an index from zero up, as a jump through a table of this function.
2927 ///
2928 /// Every `switch` that reaches here is one `crate::switch` left behind on purpose: it has
2929 /// already checked the value is inside the table and taken the lowest case off it, so the
2930 /// operand is a 64 bit index, the cases are the values from zero up with gaps where the
2931 /// program had no case, and the default is only where those gaps go. What is written is the
2932 /// shape gcc writes for the same statement in position independent code:
2933 ///
2934 /// ```text
2935 /// leaq table(%rip), %base
2936 /// movslq (%base,%index,4), %offset
2937 /// addq %base, %offset
2938 /// jmp *%offset
2939 /// ```
2940 ///
2941 /// The table holds distances from itself to each arm rather than addresses, which is what
2942 /// lets it be filled in by the assembler with nothing left for a linker to do. Each cell is
2943 /// stored as the place of an arm among this block's successors, which [`Self::edges`] copies
2944 /// across in the IR's own order, the default first and then one per case. See
2945 /// [`mir::Table`] for why a place and not a block.
2946 fn jump_table(&mut self, inst: Inst) -> Result<(), Unsupported> {
2947 let data = &self.source[inst];
2948 let Extra::Switch(info) = data.extra else { return Err(self.unsupported(inst)) };
2949 let &index = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
2950 let ty = self.source[index].ty;
2951 if ty != Type::int(u64::BITS) {
2952 return Err(self.unsupported(inst));
2953 }
2954 let cases = self.source[self.source[info].cases].to_vec();
2955 let mut cells: Vec<u32> = Vec::new();
2956 for (arm, case) in cases.iter().enumerate() {
2957 let at = usize::try_from(case.signed(ty)).map_err(|_| self.unsupported(inst))?;
2958 if at >= cells.len() {
2959 cells.resize(at + 1, 0);
2960 }
2961 cells[at] = u32::try_from(arm + 1).map_err(|_| self.unsupported(inst))?;
2962 }
2963 let reg = self.reg_of(index)?;
2964 let block = self.at.expect("a block is being filled");
2965 let span = self.source.span(inst);
2966 let gpr = self.gpr;
2967 let table = u32::try_from(self.out.tables.len()).expect("fewer tables than that");
2968
2969 let jumps = self.selector.jumps;
2970
2971 let base = self.out.new_vreg(gpr);
2972 let near = self.named(jumps.near);
2973 self.out.build(block, near).at(span).def(base, gpr).mem(mir::Mem::table(table)).finish();
2974 let offset = self.out.new_vreg(gpr);
2975 let cell =
2976 mir::Mem::at(mir::Operand::read(base, gpr)).indexed(mir::Operand::read(reg, gpr), 4);
2977 let load = self.named(jumps.cell);
2978 self.out.build(block, load).at(span).def(offset, gpr).mem(cell).finish();
2979 // Two address on x86-64, for the reason `thread_pointer` gives.
2980 let to = self.out.new_vreg(gpr);
2981 let add = self.named(jumps.add);
2982 let written = mir::Operand::write(to, gpr);
2983 let written = if jumps.two_address { written.with(Constraint::Reuse(1)) } else { written };
2984 self.out
2985 .build(block, add)
2986 .at(span)
2987 .operand(written)
2988 .operand(mir::Operand::read(offset, gpr))
2989 .operand(mir::Operand::read(base, gpr))
2990 .finish();
2991 let jump = self.named(self.selector.branch.indirect);
2992 let jump =
2993 self.out.build(block, jump).at(span).operand(mir::Operand::read(to, gpr)).finish();
2994 self.out.tables.push(mir::Table { jump, cells });
2995 Ok(())
2996 }
2997
2998 /// `__builtin_setjmp`, which writes down where the function is so that a `__builtin_longjmp`
2999 /// somewhere else can bring control back here, and answers zero on the way past.
3000 ///
3001 /// Four words of the buffer, the three gcc writes and one of this compiler's own, and then the
3002 /// block ends: everything after the save in the IR block is put into a new machine IR block,
3003 /// and the address of that block is what went into the buffer. That is the whole reason the
3004 /// block is split here. An address points at a label, a machine IR block is the only thing in
3005 /// this representation that has one, and a save is in the middle of a block rather than at the
3006 /// end of one.
3007 ///
3008 /// # How the answer gets back
3009 ///
3010 /// Through the frame rather than through a register. The save writes a zero into a word of its
3011 /// own frame, puts the address of that word in the buffer, and the new block reads the word
3012 /// back. The restore writes a one through the address it finds in the buffer before it goes.
3013 /// So one load answers zero on the way past and one on the way back, and neither path has to
3014 /// agree with the other about a register.
3015 ///
3016 /// gcc does it the other way round, with a second block that sets the answer to one and is
3017 /// what the restore arrives at. That block is one nothing in the function jumps to, and a
3018 /// machine IR whose blocks are walked from the entry has nowhere to put such a thing: the
3019 /// allocator lays a function out in the line it is going to be emitted in, and a block no edge
3020 /// reaches is not in that line. The word in the frame costs eight bytes of stack and one load,
3021 /// and it needs nothing said anywhere about a block arrived at from outside.
3022 ///
3023 /// # What the allocator is told
3024 ///
3025 /// That every register it hands out is gone at the end of the first block. That is what makes
3026 /// the rest of the function right on the way back: control arrives from a `__builtin_longjmp`
3027 /// in some other function, and the only two registers that puts back are the stack pointer and
3028 /// the frame pointer, so anything this function still wants has to be in the frame those two
3029 /// reach. It is said with a write of every one of those registers, which is the same thing a
3030 /// call says about the registers a callee may destroy, on an instruction with nothing else on
3031 /// it so that the stores above are not caught up in it.
3032 fn saves_place(&mut self, inst: Inst) -> Result<(), Unsupported> {
3033 let data = &self.source[inst];
3034 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
3035 let &buffer = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
3036 let span = self.source.span(inst);
3037 let buf = self.reg_of(buffer)?;
3038 let at = self.at.expect("a block is being filled");
3039 let gpr = self.gpr;
3040 let moves = self.selector.frame.moves(gpr).expect("a class the target says how to move");
3041 let store = self.named(moves.store);
3042 let load = self.named(moves.load);
3043 let lea = self.named(self.selector.frame.lea);
3044 let put = self.named(self.selector.frame.imm);
3045 let nothing =
3046 self.selector.frame.pad.expect("a target with an instruction that does nothing");
3047 let nothing = self.named(nothing);
3048 self.stack.saves_place = true;
3049 let answer = self.answer_slot();
3050 let back = self.out.create_block();
3051
3052 // The zero this answers with, into the word a restore writes a one into.
3053 let zero = self.out.new_vreg(gpr);
3054 self.out.build(at, put).at(span).def(zero, gpr).imm(0).finish();
3055 let mem = self.frame_mem();
3056 let made = self.out.build(at, store).at(span).uses(zero, gpr).mem(mem).finish();
3057 self.stack.addresses.push((made, answer));
3058
3059 // The four words: where that word is, where control comes back to, and the two registers
3060 // the restore puts back.
3061 let found = self.frame_address(at, answer);
3062 self.write_word(at, span, store, found, buf, JUMP_ANSWER);
3063 let pc = self.out.new_vreg(gpr);
3064 self.out.build(at, lea).at(span).def(pc, gpr).mem(mir::Mem::block(back)).finish();
3065 self.write_word(at, span, store, pc, buf, JUMP_PC);
3066 let frame = mir::Reg::physical(self.conv.frame_pointer);
3067 self.write_word(at, span, store, frame, buf, JUMP_FRAME);
3068 let stack = mir::Reg::physical(self.conv.stack_pointer);
3069 self.write_word(at, span, store, stack, buf, JUMP_STACK);
3070
3071 // Nothing is in a register past this point, which is what the rest of the function is
3072 // allowed to assume about the way back in.
3073 let gone = self.across_jump();
3074 let mut build = self.out.build(at, nothing).at(span);
3075 for (reg, class) in gone {
3076 build = build.operand(mir::Operand::write(reg, class));
3077 }
3078 build.finish();
3079
3080 // And the rest of the block, which is the block the address above was of.
3081 *self.out.succs_mut(at) = vec![mir::BlockCall::to(back)];
3082 self.at = Some(back);
3083 let reg = self.new_reg(result);
3084 let mem = self.frame_mem();
3085 let made = self.out.build(back, load).at(span).def(reg, gpr).mem(mem).finish();
3086 self.stack.addresses.push((made, answer));
3087 Ok(())
3088 }
3089
3090 /// `__builtin_longjmp`, which reads a buffer a `__builtin_setjmp` filled in and goes there.
3091 ///
3092 /// Everything comes out of the buffer before anything is put back, and the four registers it
3093 /// comes out into are physical ones rather than values the allocator places. Both of those are
3094 /// about the same moment. The stack pointer is one of the things being put back, a value the
3095 /// allocator sent to the stack is reached through the stack pointer, and between the
3096 /// instruction that moves it and the jump there is no stack this function owns any more. A
3097 /// register named outright is a register nothing reloads into and nothing else is in, which is
3098 /// the only way to hold something across that moment.
3099 ///
3100 /// Four of them because that is how many things are in the air at once: where to go, the frame
3101 /// pointer to put back, the one the matching save is to answer with, and one register used
3102 /// twice, first for the address that one is written through and then for the stack pointer.
3103 ///
3104 /// Nothing after this in the block is reached. The marker is not a terminator, for the reason
3105 /// `spec/08-ir.md` gives, so the block goes on and whatever the front end wrote after it is
3106 /// written out and never run.
3107 fn comes_back(&mut self, inst: Inst) -> Result<(), Unsupported> {
3108 let data = &self.source[inst];
3109 let &buffer = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
3110 let span = self.source.span(inst);
3111 let buf = self.reg_of(buffer)?;
3112 let at = self.at.expect("a block is being filled");
3113 let gpr = self.gpr;
3114 let moves = self.selector.frame.moves(gpr).expect("a class the target says how to move");
3115 let load = self.named(moves.load);
3116 let store = self.named(moves.store);
3117 let mov = self.named(moves.mov);
3118 let put = self.named(self.selector.frame.imm);
3119 let jump = self.named(self.selector.branch.indirect);
3120
3121 let held = self.jump_regs();
3122 if held.len() < JUMP_REGS {
3123 return Err(self.unsupported(inst));
3124 }
3125 let pc = mir::Reg::physical(held[0]);
3126 let frame = mir::Reg::physical(held[1]);
3127 let spare = mir::Reg::physical(held[2]);
3128 let one = mir::Reg::physical(held[3]);
3129
3130 self.read_word(at, span, load, pc, buf, JUMP_PC);
3131 self.read_word(at, span, load, frame, buf, JUMP_FRAME);
3132 self.read_word(at, span, load, spare, buf, JUMP_ANSWER);
3133
3134 // What the matching save answers with, written through the address that came out of the
3135 // buffer, because the word it goes in is in the other function's frame and this one has no
3136 // way of knowing where that is.
3137 self.out.build(at, put).at(span).def(one, gpr).imm(1).finish();
3138 let mem = mir::Mem::at(mir::Operand::read(spare, gpr));
3139 self.out.build(at, store).at(span).uses(one, gpr).mem(mem).finish();
3140
3141 // The stack last of the four, so that the register the buffer is reached through is done
3142 // with before the stack it may have been spilled to stops being this function's.
3143 self.read_word(at, span, load, spare, buf, JUMP_STACK);
3144 let stack = mir::Reg::physical(self.conv.stack_pointer);
3145 self.copy(at, span, mov, stack, spare);
3146 let base = mir::Reg::physical(self.conv.frame_pointer);
3147 self.copy(at, span, mov, base, frame);
3148
3149 // And the jump, which reads the two registers just put back as well as the address it
3150 // goes through. Neither of those is printed, because the target's spelling of an indirect
3151 // jump has one argument and it is the first one read. They are there because the code
3152 // control arrives at reaches its frame through them, and because without them the two
3153 // instructions above write registers nothing reads: a scheduler is then free to put the
3154 // jump in front of them, and at `-O2` it does.
3155 self.out
3156 .build(at, jump)
3157 .at(span)
3158 .operand(mir::Operand::read(pc, gpr))
3159 .operand(mir::Operand::read(stack, gpr))
3160 .operand(mir::Operand::read(base, gpr))
3161 .finish();
3162 Ok(())
3163 }
3164
3165 /// One word of the buffer of a `__builtin_setjmp`, written from a register.
3166 fn write_word(
3167 &mut self,
3168 at: mir::Block,
3169 span: Span,
3170 store: mir::Opcode,
3171 from: mir::Reg,
3172 buf: mir::Reg,
3173 word: i32,
3174 ) {
3175 let mem = mir::Mem::at(mir::Operand::read(buf, self.gpr)).plus(word);
3176 self.out.build(at, store).at(span).uses(from, self.gpr).mem(mem).finish();
3177 }
3178
3179 /// One word of that buffer, read back into a register.
3180 fn read_word(
3181 &mut self,
3182 at: mir::Block,
3183 span: Span,
3184 load: mir::Opcode,
3185 into: mir::Reg,
3186 buf: mir::Reg,
3187 word: i32,
3188 ) {
3189 let mem = mir::Mem::at(mir::Operand::read(buf, self.gpr)).plus(word);
3190 self.out.build(at, load).at(span).def(into, self.gpr).mem(mem).finish();
3191 }
3192
3193 /// One register into another, which is the one shape of instruction the builder has no word
3194 /// for because neither operand is a definition of a value or a read of memory.
3195 fn copy(
3196 &mut self,
3197 at: mir::Block,
3198 span: Span,
3199 mov: mir::Opcode,
3200 into: mir::Reg,
3201 from: mir::Reg,
3202 ) {
3203 self.out
3204 .build(at, mov)
3205 .at(span)
3206 .operand(mir::Operand::write(into, self.gpr))
3207 .operand(mir::Operand::read(from, self.gpr))
3208 .finish();
3209 }
3210
3211 /// The word a `__builtin_setjmp` in this function answers with, asked for once and kept.
3212 fn answer_slot(&mut self) -> usize {
3213 match self.answer {
3214 Some(index) => index,
3215 None => {
3216 let index = self.stack.locals.len();
3217 self.stack.locals.push(Local { size: JUMP_WORD, align: JUMP_WORD });
3218 self.answer = Some(index);
3219 index
3220 }
3221 }
3222 }
3223
3224 /// An address in this function's frame with nothing in its displacement, which is what an
3225 /// instruction reaching one of its stack objects is written with until [`crate::finish`] knows
3226 /// where the object is.
3227 fn frame_mem(&self) -> mir::Mem {
3228 mir::Mem::at(mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr))
3229 }
3230
3231 /// Every register the allocator hands out, which is what a `__builtin_setjmp` destroys.
3232 ///
3233 /// Both files, since a `double` live across a save has the same problem an integer does. The
3234 /// two registers a frame is reached through are not here: the restore puts both of them back,
3235 /// which is the whole of what it puts back, and a function whose frame pointer was destroyed
3236 /// by its own save would have nothing left to find its caller with.
3237 fn across_jump(&self) -> Vec<(mir::Reg, RegClass)> {
3238 let mut gone = Vec::new();
3239 for ® in self.conv.int_order {
3240 if reg == self.conv.stack_pointer || reg == self.conv.frame_pointer {
3241 continue;
3242 }
3243 gone.push((mir::Reg::physical(reg), self.gpr));
3244 }
3245 for ® in self.conv.sse_order {
3246 gone.push((mir::Reg::physical(reg), self.conv.sse_class));
3247 }
3248 gone
3249 }
3250
3251 /// The registers a `__builtin_longjmp` may hold things in while it puts a frame back.
3252 ///
3253 /// The ones the allocator hands out, less the two a frame is reached through. The scratch
3254 /// registers are not among them on purpose: the rewriter writes a reload into one of those
3255 /// wherever it likes, and one of these has to survive from the load that fills it to the
3256 /// instruction that reads it however many instructions apart those are.
3257 fn jump_regs(&self) -> Vec<PhysReg> {
3258 self.conv
3259 .int_order
3260 .iter()
3261 .copied()
3262 .filter(|®| {
3263 reg != self.conv.stack_pointer
3264 && reg != self.conv.frame_pointer
3265 && !self.selector.scratch.contains(®)
3266 })
3267 .collect()
3268 }
3269
3270 /// A machine opcode of this target from the name the target gives it.
3271 fn named(&mut self, name: &str) -> mir::Opcode {
3272 mir::Opcode::new(self.names.intern(&format!("{}{name}", self.selector.prefix())))
3273 }
3274
3275 /// `__builtin_frame_address` and `__builtin_return_address`, which are a walk up the chain of
3276 /// saved frame pointers and then one thing read at the end of it.
3277 ///
3278 /// Every frame that kept a frame pointer holds the caller's at the address the register points
3279 /// at, and the address that frame returns to one word above that, which is where the call
3280 /// instruction put it and where the prologue's push left it. So the walk is a load through the
3281 /// register for each link, the frame address is wherever the walk stopped, and the return
3282 /// address is one more load from a word above it. gcc 16.2.0 writes exactly this, measured on
3283 /// x86-64 at `-O2` for depths zero to three of both builtins.
3284 ///
3285 /// The function is given a frame pointer because of this, which is what [`Stack::walks_frames`]
3286 /// carries out to the layout. A depth of zero needs it as the answer and every depth above zero
3287 /// needs it as the start, so there is no case here where it is not wanted.
3288 ///
3289 /// How far the chain actually reaches is the program's business and not this one's. A caller
3290 /// compiled without a frame pointer has no link in it for the walk to follow, so a depth above
3291 /// zero is a promise about how the whole program was built. That is why gcc documents a nonzero
3292 /// depth as unsafe rather than as an answer, and why the depth is refused above a limit in
3293 /// `check/builtin/frame.rs` rather than walked as far as it says.
3294 fn frames(&mut self, inst: Inst) -> Result<(), Unsupported> {
3295 let data = &self.source[inst];
3296 let Extra::Depth(depth) = data.extra else { return Err(self.unsupported(inst)) };
3297 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
3298 let returning = data.opcode == Opcode::ReturnAddress;
3299 let block = self.at.expect("a block is being filled");
3300 let span = self.source.span(inst);
3301 let moves =
3302 self.selector.frame.moves(self.gpr).expect("a class the target says how to move");
3303 let load = self.named(moves.load);
3304 self.stack.walks_frames = true;
3305
3306 // Where the walk is up to. The frame pointer to begin with, and the register the last load
3307 // wrote after that.
3308 let reg = self.new_reg(result);
3309 let mut base = mir::Reg::physical(self.conv.frame_pointer);
3310 for link in 0..depth {
3311 // The last load of a walk that is looking for a frame writes the answer itself, which
3312 // is what keeps a walk of so many links that many instructions and not one more.
3313 let ends_here = link + 1 == depth && !returning;
3314 let next = if ends_here { reg } else { self.out.new_vreg(self.gpr) };
3315 let at = mir::Mem::at(mir::Operand::read(base, self.gpr));
3316 self.out.build(block, load).at(span).def(next, self.gpr).mem(at).finish();
3317 base = next;
3318 }
3319
3320 if returning {
3321 let up = i32::try_from(self.conv.return_address).expect("a word above the frame");
3322 let at = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
3323 self.out.build(block, load).at(span).def(reg, self.gpr).mem(at).finish();
3324 } else if depth == 0 {
3325 // The one case with no load in it at all: the frame this function is running in is the
3326 // register itself, and a physical register is not one the allocator hands out, so the
3327 // answer is a copy of it.
3328 let mov = self.named(moves.mov);
3329 self.out
3330 .build(block, mov)
3331 .at(span)
3332 .operand(mir::Operand::write(reg, self.gpr))
3333 .operand(mir::Operand::read(base, self.gpr))
3334 .finish();
3335 }
3336 Ok(())
3337 }
3338
3339 /// `__builtin_thread_pointer`, which is the front of the block [`Self::thread_address`] adds
3340 /// an offset to.
3341 ///
3342 /// The same one instruction, on its own this time and with nothing to add to it. A program
3343 /// writes this when what it wants is a number that is different in every thread and cheap to
3344 /// come by, rather than a variable of its own in the block, so there is no relocation here and
3345 /// no name for the link to resolve.
3346 fn thread_pointer(&mut self, inst: Inst) -> Result<(), Unsupported> {
3347 self.threads_written(inst)?;
3348 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3349 let block = self.at.expect("a block is being filled");
3350 let span = self.source.span(inst);
3351 let reg = self.new_reg(result);
3352 self.read_thread_pointer(block, span, reg);
3353 Ok(())
3354 }
3355
3356 /// What a named machine register holds, which is `register long x asm ("rbx");`.
3357 ///
3358 /// One move out of that register, with the register named as itself the way a register a
3359 /// template wrote is named, which is [`Self::itself`] and is the thing #1653 built. What it
3360 /// buys here is what it buys there: the register is part of the instruction the allocator
3361 /// sees, so it is a use the allocator will not have written over first, and the value goes
3362 /// into an ordinary one of its own that everything downstream reads.
3363 ///
3364 /// The whole sixty four bits are moved whatever the type is, because the register is that
3365 /// wide and a narrower type reads the low end of the copy, which is the same low end. A type
3366 /// wider than the register is refused, since there is no register holding it to read. On
3367 /// AArch64 a float may be kept in a vector register, `register double x asm ("d8");`, and it is
3368 /// moved out of that file the same way.
3369 ///
3370 /// A name the machine has not got is refused too, and is the only thing that can be wrong
3371 /// with the string: which register a name means is this machine's question and this is where
3372 /// the question is asked, at the same table `asm` asks about clobbers at. The sigil gcc
3373 /// allows in front of it is taken off here, because what the name is written with is syntax.
3374 fn register_value(&mut self, inst: Inst) -> Result<(), Unsupported> {
3375 let Extra::Symbol(symbol) = self.source[inst].extra else {
3376 return Err(self.unsupported(inst));
3377 };
3378 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3379 let ty = self.source[result].ty;
3380 let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
3381 if bits > ADDRESS_BITS {
3382 return Err(self.unsupported(inst));
3383 }
3384 let spelled = self.names.resolve(symbol).to_owned();
3385 let bare = spelled.strip_prefix('%').unwrap_or(&spelled);
3386 let named = if self.on_aarch64() {
3387 aarch64::named(bare)
3388 } else if self.class_of(ty) != self.gpr {
3389 return Err(self.unsupported(inst));
3390 } else {
3391 x86_64::gpr_named(bare).map(|(reg, _)| (reg, self.gpr))
3392 };
3393 let Some((held, file)) = named else {
3394 return Err(Unsupported::Register { inst, name: spelled });
3395 };
3396 // A float in a general purpose register, or a number in a vector one, is a register the
3397 // machine has holding a type that is not kept there, and would need a move between the
3398 // files that nothing here makes yet.
3399 if on_x87(ty) || self.class_of(ty) != file {
3400 return Err(self.unsupported(inst));
3401 }
3402 let block = self.at.expect("a block is being filled");
3403 let span = self.source.span(inst);
3404 let mov = self.selector.frame.moves(file).expect("a class the target says how to move").mov;
3405 let mov = self.named(mov);
3406 let into = self.new_reg(result);
3407 self.out
3408 .build(block, mov)
3409 .at(span)
3410 .operand(mir::Operand::write(into, file))
3411 .operand(
3412 mir::Operand::read(mir::Reg::physical(held), file).with(Constraint::Fixed(held)),
3413 )
3414 .finish();
3415 Ok(())
3416 }
3417
3418 /// A conversion that converts nothing: the result is the operand under another type.
3419 ///
3420 /// `ptrtoint` and `inttoptr` at one width are the whole of this. An address on this machine is
3421 /// an integer as wide as the machine addresses, so a cast between the two changes what the
3422 /// type system calls the value and changes nothing about the value, and the register holding
3423 /// it is the register that already held it. The front end never writes either of them at any
3424 /// other width, because it widens or narrows around the cast rather than through it, so the
3425 /// two widths disagreeing here means the IR came from somewhere else and is refused rather
3426 /// than guessed at.
3427 ///
3428 /// Reading the operand first is what materializes it when it is a constant, which is the case
3429 /// that matters: a null pointer is an `inttoptr` of zero, and that zero has to reach a
3430 /// register before anything can call it an address.
3431 fn rename(&mut self, inst: Inst) -> Result<(), Unsupported> {
3432 let data = &self.source[inst];
3433 let [arg] = self.source[data.args] else { return Err(self.unsupported(inst)) };
3434 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
3435 if !self.is_address_width(self.source[arg].ty)
3436 || !self.is_address_width(self.source[result].ty)
3437 {
3438 return Err(self.unsupported(inst));
3439 }
3440 let reg = self.reg_of(arg)?;
3441 self.regs[result.index()] = Some(reg);
3442 Ok(())
3443 }
3444
3445 /// One barrier, which on this machine is one instruction at the strongest ordering and no
3446 /// instruction at all at every other one.
3447 ///
3448 /// x86-64 is total store order, so the only reordering the machine does is a store followed by
3449 /// a load of a different address, and the only ordering that forbids that is sequential
3450 /// consistency. An acquire, a release and an acquire release fence are therefore already true
3451 /// of every program running here, and what a program wanted from writing one is that the
3452 /// compiler not move memory accesses across it. The optimizer has finished by the time this
3453 /// runs and nothing below reorders one access past another, so the constraint is already
3454 /// discharged and there is nothing to write.
3455 ///
3456 /// The strongest one is `mfence`, which is what gcc 16.2.0 writes for
3457 /// `__atomic_thread_fence(__ATOMIC_SEQ_CST)` and for `__sync_synchronize`. A locked instruction
3458 /// on the stack is faster on most parts and is what some compilers write instead; it is also a
3459 /// write to memory the program did not ask for, and the plain barrier is the one that says what
3460 /// it means.
3461 ///
3462 /// Written here by name rather than by a rule, for the same reason a `lea` of a symbol is:
3463 /// there is nothing in a barrier that a proof over bitvectors could discharge. It computes
3464 /// nothing, so there is no equality to state, and what makes it the right answer is the memory
3465 /// model, which the rule language cannot talk about.
3466 fn barrier(&mut self, inst: Inst) -> Result<(), Unsupported> {
3467 let Extra::Order(order) = self.source[inst].extra else {
3468 return Err(self.unsupported(inst));
3469 };
3470 // AArch64 is not total store order, so every ordering above relaxed is an instruction
3471 // there. An acquire fence only has to keep later accesses after earlier loads, which is
3472 // `dmb ishld`, and everything stronger is the full `dmb ish` gcc writes for it.
3473 let name = match order {
3474 MemOrder::NotAtomic | MemOrder::Relaxed => return Ok(()),
3475 MemOrder::Acquire if self.on_aarch64() => "fence_acquire",
3476 _ if self.on_aarch64() => self.selector.fence,
3477 MemOrder::SeqCst => self.selector.fence,
3478 _ => return Ok(()),
3479 };
3480 let block = self.at.expect("a block is being filled");
3481 let span = self.source.span(inst);
3482 let fence = self.named(name);
3483 self.out.build(block, fence).at(span).finish();
3484 Ok(())
3485 }
3486
3487 /// The instruction a program stops on, which is one byte pair and no operands.
3488 ///
3489 /// `ud2` is an opcode the manual promises will never be given a meaning, so a processor that
3490 /// reaches it raises the fault for an instruction it does not know, and on Linux that arrives
3491 /// at the program as `SIGILL`. That is what `__builtin_trap` is for: a stop that cannot be
3492 /// caught by anything the program installed for an ordinary error, cannot be returned from,
3493 /// and leaves the address of the fault in the core file.
3494 ///
3495 /// Why not a call to `abort`. It is two bytes against a call and a relocation, it needs no
3496 /// library, and it works in the places this one is written most, which are a kernel and a
3497 /// freestanding program that has no `abort` to call. gcc 16.2.0 writes `ud2` here too.
3498 fn trap(&mut self, inst: Inst) {
3499 let block = self.at.expect("a block is being filled");
3500 let span = self.source.span(inst);
3501 let stop = self.named(self.selector.trap);
3502 self.out.build(block, stop).at(span).finish();
3503 }
3504
3505 /// One hint that an address is about to be used, which is one instruction and no promise.
3506 ///
3507 /// Four instructions on this machine and the locality picks between them, which is what the
3508 /// number means: how much of the data will still be wanted after the access. None of it wanted
3509 /// is `prefetchnta`, which brings the line in without keeping it, and all of it wanted is
3510 /// `prefetcht0`, which brings it as close as the machine can. The two in between are the levels
3511 /// between those. Measured against gcc 16.2.0 on x86-64 rather than read off the manual: zero
3512 /// gives `prefetchnta`, one `prefetcht2`, two `prefetcht1` and three `prefetcht0`.
3513 ///
3514 /// Whether the access will write is not read on x86-64, and that is the machine rather than an
3515 /// omission. The write hint is `prefetchw`, which is not in the base instruction set, and gcc
3516 /// writes it only when the command line said the part has it. So a prefetch for a write is the
3517 /// same instruction as a prefetch for a read, which is what gcc 16.2.0 writes without
3518 /// `-mprfchw`. AArch64 has it in the base set, so there a write picks the four `pst` forms of
3519 /// `prfm` in place of the `pld` ones, at the same levels.
3520 ///
3521 /// The address goes in the addressing mode rather than in an operand, the way a store's does.
3522 /// It is built here as the plainest one there is, a register and nothing else, because what
3523 /// arrives is a value and folding an addition into the mode is a rule's job and no rule reaches
3524 /// this instruction. An address the program computed is therefore one `lea` or one add in front
3525 /// of this, which is what it would have been for the load the hint is about anyway.
3526 fn hint(&mut self, inst: Inst) -> Result<(), Unsupported> {
3527 let Extra::Prefetch(hint) = self.source[inst].extra else {
3528 return Err(self.unsupported(inst));
3529 };
3530 let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3531 let [address] = args[..] else { return Err(self.unsupported(inst)) };
3532 // AArch64 has the write hint in the base instruction set, and gcc 16.2.0 writes it there.
3533 let write = hint.write && self.on_aarch64();
3534 let name = match (hint.locality, write) {
3535 (0, false) => "prefetch_nta",
3536 (1, false) => "prefetch_t2",
3537 (2, false) => "prefetch_t1",
3538 (PrefetchHint::MOST, false) => "prefetch_t0",
3539 (0, true) => "prefetch_w_nta",
3540 (1, true) => "prefetch_w_t2",
3541 (2, true) => "prefetch_w_t1",
3542 (PrefetchHint::MOST, true) => "prefetch_w_t0",
3543 // Nothing else exists. The checker reads a locality outside the range as zero and the
3544 // verifier refuses one that got here another way, so this is a hint that was built
3545 // rather than checked, and the safe answer for a hint is to write no instruction.
3546 _ => return Err(self.unsupported(inst)),
3547 };
3548 let base = self.reg_of(address)?;
3549 let block = self.at.expect("a block is being filled");
3550 let opcode = self.named(name);
3551 self.out
3552 .build(block, opcode)
3553 .at(self.source.span(inst))
3554 .mem(mir::Mem::at(mir::Operand::read(base, self.gpr)))
3555 .finish();
3556 Ok(())
3557 }
3558
3559 /// One compare and exchange, which is the instruction every other atomic on this machine is
3560 /// built out of.
3561 ///
3562 /// What the IR asks for is: read what is at an address, compare it against a value the program
3563 /// expected, put a second value there if the two were equal, and say both what was read and
3564 /// whether the exchange happened. The machine has exactly that instruction, and the `lock` in
3565 /// front of it is what makes the whole of it one step as far as every other processor is
3566 /// concerned.
3567 ///
3568 /// The ordering is not read here, and that is the memory model rather than an omission. A
3569 /// locked instruction on x86-64 is a full barrier whatever the program asked for, so a relaxed
3570 /// compare and exchange and a sequentially consistent one are the same instruction, and there
3571 /// is nothing weaker to emit for the weaker orderings. The failure ordering is not read for the
3572 /// same reason.
3573 ///
3574 /// The two values it produces are why this is written by name. The one the program compares
3575 /// against and the one it gets back are both `rax`, which the instruction reads and writes
3576 /// without being told, and the table says so with a fixed constraint at each end rather than
3577 /// leaving the allocator to find out. The second value is the byte behind it, which is the zero
3578 /// flag read out by a `sete`, and it is a definition of the same instruction so that the
3579 /// allocator knows the two are live together and never gives the byte the register the answer
3580 /// is in.
3581 fn exchange(&mut self, inst: Inst) -> Result<(), Unsupported> {
3582 let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3583 let results: Vec<Value> = self.source[inst].results().collect();
3584 let [addr, expected, desired] = args[..] else { return Err(self.unsupported(inst)) };
3585 let [old, exchanged] = results[..] else { return Err(self.unsupported(inst)) };
3586 if self.on_aarch64() {
3587 return self.exchange_a64(inst, [addr, expected, desired], [old, exchanged]);
3588 }
3589
3590 // A value the machine can compare in one instruction, which is an integer or an address at
3591 // one of the four widths it has a compare and exchange for. Anything else is a type this
3592 // has no instruction for rather than a program that is wrong, and the front end refuses it
3593 // before ever getting here.
3594 let ty = self.source[old].ty;
3595 let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
3596 if (!ty.is_int() && !ty.is_ptr()) || !matches!(bits, 8 | 16 | 32 | 64) {
3597 return Err(self.unsupported(inst));
3598 }
3599
3600 let base = self.reg_of(addr)?;
3601 let want = self.reg_of(expected)?;
3602 let put = self.reg_of(desired)?;
3603 let got = self.new_reg(old);
3604 let flag = self.new_reg(exchanged);
3605
3606 let name = format!("cmpxchg_{bits}");
3607 let descs = self.selector.operands(&name).ok_or_else(|| self.unsupported(inst))?;
3608 let block = self.at.expect("a block is being filled");
3609 let opcode = self.named(&name);
3610 let (span, flags) = (self.source.span(inst), self.carried(inst));
3611 let mut build = self.out.build(block, opcode).at(span).flags(flags);
3612 for (desc, reg) in descs.iter().zip([got, flag, want, put]) {
3613 let operand = mir::Operand {
3614 reg,
3615 class: desc.class,
3616 role: desc.role,
3617 constraint: desc.constraint,
3618 };
3619 build = build.operand(operand);
3620 }
3621 build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
3622 Ok(())
3623 }
3624
3625 /// One read modify write, for the three operations this machine does in a single instruction.
3626 ///
3627 /// What the IR asks for is: read what is at an address, do something to it, put the answer back,
3628 /// say what was there before, and let nothing get between the three steps. The machine has
3629 /// `xchg` for putting a value there and `lock xadd` for adding one, and both leave what they
3630 /// found in the register the operand arrived in, which is why the value that comes back and the
3631 /// value that went in are one register here.
3632 ///
3633 /// A subtraction is the add over the negated operand, which is right at every width because the
3634 /// machine's arithmetic wraps and negating then adding is subtracting in two's complement
3635 /// whatever the operands were. The negate is a separate instruction in front, over a register of
3636 /// its own, so that the value the program handed over is not the one written on: an operand may
3637 /// be live after this and a program that read it again would read the negation.
3638 ///
3639 /// The ordering is not read, for the reason the compare and exchange beside this does not read
3640 /// it. `xchg` with memory locks the bus whether it is asked to or not and `lock xadd` is asked
3641 /// to, so both are full barriers on this machine and there is nothing weaker to fall to.
3642 ///
3643 /// Eight of the other ten never arrive, because `crate::retry` turned each of them into a loop
3644 /// around a compare and exchange before anything here saw it. The two that do arrive are the
3645 /// ones on floating values, and they are refused: a compare and exchange of a float wants the
3646 /// value carried through an integer of the same width, and an eighty bit float has no such
3647 /// width. Neither family of builtins can write one yet either, so a program that reaches this
3648 /// refusal is a program that reached an unimplemented builtin first.
3649 fn modify(&mut self, inst: Inst) -> Result<(), Unsupported> {
3650 let Extra::Rmw(op, _) = self.source[inst].extra else {
3651 return Err(self.unsupported(inst));
3652 };
3653 let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3654 let [addr, operand] = args[..] else { return Err(self.unsupported(inst)) };
3655 let old = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3656
3657 // A value the machine can exchange in one instruction, which is an integer at one of the
3658 // four widths it has these for. A pointer arrives as an address, so it is an integer by the
3659 // time it is here, and anything else is a type this has no instruction for.
3660 let ty = self.source[old].ty;
3661 if !ty.is_int() || !matches!(ty.bits(), 8 | 16 | 32 | 64) {
3662 return Err(self.unsupported(inst));
3663 }
3664 if self.on_aarch64() {
3665 return self.modify_a64(inst, op, [addr, operand], old);
3666 }
3667 let name = match op {
3668 RmwOp::Xchg => format!("xchg_{}", ty.bits()),
3669 RmwOp::Add | RmwOp::Sub => format!("xadd_{}", ty.bits()),
3670 _ => return Err(self.unsupported(inst)),
3671 };
3672
3673 let base = self.reg_of(addr)?;
3674 let mut put = self.reg_of(operand)?;
3675 let block = self.at.expect("a block is being filled");
3676 let span = self.source.span(inst);
3677 if op == RmwOp::Sub {
3678 let negated = self.out.new_vreg(self.gpr);
3679 let negate = self.named(&format!("neg_r_{}", ty.bits()));
3680 let descs = self
3681 .selector
3682 .operands(&format!("neg_r_{}", ty.bits()))
3683 .ok_or_else(|| self.unsupported(inst))?;
3684 let mut build = self.out.build(block, negate).at(span);
3685 for (desc, reg) in descs.iter().zip([negated, put]) {
3686 build = build.operand(mir::Operand {
3687 reg,
3688 class: desc.class,
3689 role: desc.role,
3690 constraint: desc.constraint,
3691 });
3692 }
3693 build.finish();
3694 put = negated;
3695 }
3696
3697 let got = self.new_reg(old);
3698 let descs = self.selector.operands(&name).ok_or_else(|| self.unsupported(inst))?;
3699 let opcode = self.named(&name);
3700 let flags = self.carried(inst);
3701 let mut build = self.out.build(block, opcode).at(span).flags(flags);
3702 for (desc, reg) in descs.iter().zip([got, put]) {
3703 build = build.operand(mir::Operand {
3704 reg,
3705 class: desc.class,
3706 role: desc.role,
3707 constraint: desc.constraint,
3708 });
3709 }
3710 build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
3711 Ok(())
3712 }
3713
3714 /// The width an AArch64 atomic works at, which is an integer or an address of one of the four
3715 /// widths the exclusive loads and stores have. Anything else is refused.
3716 fn atomic_bits(&self, inst: Inst, ty: Type) -> Result<u32, Unsupported> {
3717 let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
3718 if (!ty.is_int() && !ty.is_ptr()) || !matches!(bits, 8 | 16 | 32 | 64) {
3719 return Err(self.unsupported(inst));
3720 }
3721 Ok(bits)
3722 }
3723
3724 /// One instruction by name, with its operands in the order the table lists them.
3725 fn written_as(&mut self, inst: Inst, name: &str, regs: &[mir::Reg]) -> Result<(), Unsupported> {
3726 let descs = self.selector.operands(name).ok_or_else(|| self.unsupported(inst))?;
3727 if descs.len() != regs.len() {
3728 return Err(self.unsupported(inst));
3729 }
3730 let block = self.at.expect("a block is being filled");
3731 let opcode = self.named(name);
3732 let (span, flags) = (self.source.span(inst), self.carried(inst));
3733 let mut build = self.out.build(block, opcode).at(span).flags(flags);
3734 for (desc, ®) in descs.iter().zip(regs) {
3735 build = build.operand(mir::Operand {
3736 reg,
3737 class: desc.class,
3738 role: desc.role,
3739 constraint: desc.constraint,
3740 });
3741 }
3742 build.finish();
3743 Ok(())
3744 }
3745
3746 /// An acquiring load or a releasing store on AArch64, which is `ldar` or `stlr`.
3747 ///
3748 /// Only a relaxed access became the plain one above this, so what arrives is acquire or
3749 /// stronger for a load and release or stronger for a store. `ldar` and `stlr` are also
3750 /// sequentially consistent with each other, which is why the strongest ordering needs no fence
3751 /// on either side, and is what gcc 16.2.0 writes for all of them.
3752 fn ordered(&mut self, inst: Inst) -> Result<(), Unsupported> {
3753 let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3754 if self.source[inst].opcode == Opcode::AtomicLoad {
3755 let [addr] = args[..] else { return Err(self.unsupported(inst)) };
3756 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3757 let bits = self.atomic_bits(inst, self.source[result].ty)?;
3758 let base = self.reg_of(addr)?;
3759 let got = self.new_reg(result);
3760 return self.written_as(inst, &format!("ldar_{bits}"), &[got, base]);
3761 }
3762 let [value, addr] = args[..] else { return Err(self.unsupported(inst)) };
3763 let bits = self.atomic_bits(inst, self.source[value].ty)?;
3764 let put = self.reg_of(value)?;
3765 let base = self.reg_of(addr)?;
3766 self.written_as(inst, &format!("stlr_{bits}"), &[put, base])
3767 }
3768
3769 /// A compare and exchange on AArch64, which is a loop of an exclusive load and store.
3770 ///
3771 /// The loop is one instruction as far as everything below is concerned, so that nothing can
3772 /// be spilled or reloaded between the two exclusive accesses, which would lose the reservation
3773 /// on some parts every time. Its definitions are all early, since they are written before the
3774 /// last read. The acquiring and releasing forms are used whatever the ordering, which is what
3775 /// gcc writes at the strongest one and is never wrong at a weaker one. The yes or no comes out
3776 /// of the status register the store wrote, read as a flag after the loop.
3777 fn exchange_a64(
3778 &mut self,
3779 inst: Inst,
3780 [addr, expected, desired]: [Value; 3],
3781 [old, exchanged]: [Value; 2],
3782 ) -> Result<(), Unsupported> {
3783 let bits = self.atomic_bits(inst, self.source[old].ty)?;
3784 let base = self.reg_of(addr)?;
3785 let want = self.reg_of(expected)?;
3786 let put = self.reg_of(desired)?;
3787 let got = self.new_reg(old);
3788 let flag = self.new_reg(exchanged);
3789 self.written_as(inst, &format!("cmpxchg_{bits}"), &[got, flag, base, want, put])
3790 }
3791
3792 /// A read modify write on AArch64, for the three operations that reach here, each a loop of
3793 /// an exclusive load and store for the reason the compare and exchange above is.
3794 fn modify_a64(
3795 &mut self,
3796 inst: Inst,
3797 op: RmwOp,
3798 [addr, operand]: [Value; 2],
3799 old: Value,
3800 ) -> Result<(), Unsupported> {
3801 let bits = self.atomic_bits(inst, self.source[old].ty)?;
3802 let base = self.reg_of(addr)?;
3803 let put = self.reg_of(operand)?;
3804 let got = self.new_reg(old);
3805 let status = self.out.new_vreg(self.gpr);
3806 match op {
3807 RmwOp::Xchg => {
3808 self.written_as(inst, &format!("xchg_{bits}"), &[got, status, base, put])
3809 }
3810 RmwOp::Add | RmwOp::Sub => {
3811 let name = if op == RmwOp::Add { "xadd" } else { "xsub" };
3812 let new = self.out.new_vreg(self.gpr);
3813 self.written_as(inst, &format!("{name}_{bits}"), &[got, new, status, base, put])
3814 }
3815 _ => Err(self.unsupported(inst)),
3816 }
3817 }
3818
3819 /// One `asm` statement.
3820 ///
3821 /// An empty template is most of the inline assembly in a test suite, and it is not a corner
3822 /// case somebody wrote by accident. A program that wants a value computed where it stands, or a
3823 /// loop the optimizer must not touch, writes `asm volatile ("" : : : "memory")`, and forty
3824 /// years of bug reports about optimizers are full of them. What such a statement asks for is
3825 /// the barrier and the operand places, and no instructions at all.
3826 ///
3827 /// So the operands are the half that is always real: a constraint says where a value has to be,
3828 /// and where it has to be is still true when the template between them is empty.
3829 ///
3830 /// What the constraints ask for, on an empty template, is only ever that two operands share a
3831 /// place. Nothing reads a register no text names, so `"r"` on its own asks for a register and
3832 /// no particular one, and any register at all answers it. A matching constraint is different,
3833 /// because it says the output the assembly leaves is the place the input arrived in, and with
3834 /// no instructions between them that is the input unchanged. So it is a rename and not a move:
3835 /// the value is already in a register and the result is that register.
3836 ///
3837 /// An output nothing is tied to and no instruction writes is whatever the assembly left there,
3838 /// which for a template that writes nothing is whatever was in the register. That is a value
3839 /// the program is not entitled to, and this writes a zero rather than reading one, because the
3840 /// allocator has to be given a definition before a use whatever the program is entitled to.
3841 ///
3842 /// # A template with instructions in it
3843 ///
3844 /// [`x86_64::read`] turns the text into the opcodes this backend already has, which is what
3845 /// `spec/11-asm-objects-debug.md` section 11.1 asks for: the machine is described once, and an
3846 /// instruction a program wrote is looked up in that description rather than copied through to
3847 /// an assembler that has one of its own. So nothing here assembles anything. What it does is
3848 /// put the statement's operands where the opcode holds them, and from there an `asm` statement
3849 /// is ordinary machine code: the allocator picks the registers, the listing and the object file
3850 /// are written from the same table as every other instruction, and a spill around one works
3851 /// because there is nothing left about it for a spill to get wrong.
3852 ///
3853 /// A register the template named in its own text is the one thing in there that is nobody's
3854 /// operand, and it is placed as itself. See [`Self::itself`] for why that is safer here than
3855 /// the thing gcc does, which is to copy the name out and leave the allocator none the wiser.
3856 ///
3857 /// Two things are refused, both for one reason, which is that placing them by a guess gives a
3858 /// program that assembles into something other than what it says.
3859 ///
3860 /// An output the template writes more than once, which is one place with two definitions in it,
3861 /// and the machine IR between here and the allocator has one definition per register by
3862 /// construction. An output tied to an input and written once is not that: it is two registers
3863 /// the description ties together, which is what [`Place`] is about.
3864 ///
3865 /// An operand read where the opcode writes, or written where it reads. An output that has not
3866 /// been written yet is not a value, and an input the assembly writes over is a value something
3867 /// else may still be using.
3868 ///
3869 /// # A register the instruction uses without being told
3870 ///
3871 /// An instruction may reach a register its text does not name, and `cpuid` is all of them at
3872 /// once: the leaf goes in `eax`, the subleaf in `ecx`, and the answer comes back in all four
3873 /// registers. The description holds every bit of that already, so what is left is to say which
3874 /// of the statement's operands is in each of those registers, and the constraint letter is the
3875 /// one thing in an assembly statement that says it. `"=a"` is an output in `rax` and `"c"` is
3876 /// an input in `rcx`, which is why a program writing `cpuid` writes its constraints that way
3877 /// and has no choice about it.
3878 ///
3879 /// A register no letter named is one the statement put nothing in, and that is the usual case
3880 /// rather than an unusual one, since an instruction that answers four questions is written by
3881 /// programs that asked one. A write of one is the register being destroyed and gets a register
3882 /// of its own, which is what tells the allocator to keep everything else out of it. A read of
3883 /// one is a register the instruction looks at and the program never filled, which gets a zero
3884 /// for the reason [`Self::undefined`] gives.
3885 ///
3886 /// # The clobber list
3887 ///
3888 /// Read now, as the registers it names being written by every instruction of the template. By
3889 /// every one rather than by one of them, because the list says the assembly as a whole leaves
3890 /// them ruined and nothing here knows which line did it. Every entry has to be a register this
3891 /// machine has a name for or the statement is refused, since a name nobody read is a register
3892 /// nobody is keeping out of.
3893 ///
3894 /// `memory` and `cc` are the two entries that are not registers and both are skipped. `memory`
3895 /// says the assembly touches storage, which is already true of every `asm` this writes and is
3896 /// nothing a register list could hold. `cc` says it ruins the condition flags, and the flag
3897 /// tracking already has that from the instructions the template was read into, since it takes
3898 /// every instruction it does not recognize as writing them and every instruction here is one
3899 /// this machine describes. `flags` is the name gcc's own register table gives the same thing on
3900 /// this machine, so a program writing it has written `cc` and is read that way: tcc's
3901 /// `tests/tcctest.c` lists both on one statement.
3902 ///
3903 /// A clobber the instruction already writes is left off it. `cpuid` writes all four registers
3904 /// by description, and a statement listing three of them as clobbers as well is saying the
3905 /// same thing twice, which the allocator would read as one register with two definitions.
3906 ///
3907 /// On a template with nothing in it the list is ignored, as it was before, since a template
3908 /// with no instructions ruins nothing whatever it said about what it ruins.
3909 fn assembly(&mut self, inst: Inst) -> Result<(), Unsupported> {
3910 let data = &self.source[inst];
3911 let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
3912 let info = self.source[asm];
3913 if self.jumps_from_text(inst) {
3914 return Err(Unsupported::Assembly { inst, refused: Written::Goto });
3915 }
3916 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
3917
3918 let constraints = self.names.resolve(info.constraints).to_string();
3919 let results: Vec<Value> = data.results().collect();
3920 let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
3921 .ok_or_else(refused)?;
3922 let list: Vec<AsmOperand<'_>> = operands.iter().copied().collect();
3923
3924 // Read after the constraints and not before them, because a mnemonic whose suffix the
3925 // program left off is read at the width of the operands it names, and the operands are
3926 // what the constraints are a list of.
3927 let widths: Vec<Option<x86_64::Width>> = list
3928 .iter()
3929 .map(|operand| {
3930 let ty = self.source[operand.result.or(operand.value)?].ty;
3931 if !ty.is_scalar() {
3932 return None;
3933 }
3934 x86_64::Width::of_bits(held_bits(ty))
3935 })
3936 .collect();
3937 // An operand in memory is an address the statement holds and an object the template names,
3938 // so the reader is told which ones those are and spells `%0` for one as the object.
3939 let memory: Vec<bool> = list.iter().map(|operand| operand.memory).collect();
3940 let template = self.names.resolve(info.template).to_string();
3941 // A clobber list naming a vector register goes the way a template this cannot read does.
3942 // The instructions read here are all in the general purpose file, and what keeps the text
3943 // already takes every vector register a call may use away from the allocator across it.
3944 let clobbers = self.names.resolve(info.clobbers);
3945 if clobbers.split(',').any(|entry| vector_named(entry).is_some()) {
3946 return self.kept(inst, &template, &list, &widths, &memory);
3947 }
3948 let steps = if template.trim().is_empty() {
3949 Vec::new()
3950 } else {
3951 match x86_64::read_in(&template, &widths, &memory) {
3952 Some(steps) => steps,
3953 None => return self.kept(inst, &template, &list, &widths, &memory),
3954 }
3955 };
3956
3957 // Which operands the template writes, counted before anything is placed, because the answer
3958 // decides where each of the three below comes from and one instruction may name an operand
3959 // that a later one writes. Which of them any instruction puts in a register at all is
3960 // counted in the same walk, since an operand no instruction reaches that way is one nothing
3961 // has to put anywhere: a constant a template names only as the distance into an address is
3962 // written into the instruction, and a register holding a copy of it would be one nobody
3963 // reads. An operand the address is counted from is reached that way and is counted here for
3964 // that reason, because the walk below it is over the opcode's operands and an address is
3965 // not one of those.
3966 //
3967 // Whether any instruction reads an operand an instruction above it wrote is counted in the
3968 // same walk too. Such a template is one whose instructions have to be written in order with
3969 // each read taken from wherever the last write left the operand, which is what
3970 // [`Self::woven`] does, and so is one that writes an operand twice.
3971 let mut writes = vec![0usize; list.len()];
3972 let mut reads = vec![false; list.len()];
3973 let mut held = vec![false; list.len()];
3974 let mut after = false;
3975 for step in &steps {
3976 // A call out of the template writes every register the convention lets the callee
3977 // leave anything in, and an output pinned to one of those is written by it.
3978 if let x86_64::Step::Call { .. } = step {
3979 for index in self.lost(&list).into_iter().filter_map(|(_, _, index)| index) {
3980 *writes.get_mut(index).ok_or_else(refused)? += 1;
3981 }
3982 continue;
3983 }
3984 let x86_64::Step::Line(line) = step else { continue };
3985 match line.at.and_then(|at| at.base) {
3986 Some(x86_64::Piece::Operand { index, .. }) => {
3987 *held.get_mut(index).ok_or_else(refused)? = true;
3988 after |= writes[index] > 0;
3989 }
3990 Some(x86_64::Piece::Reg { reg, .. }) => {
3991 if let Some(index) = bound(&list, reg, Role::Use) {
3992 *held.get_mut(index).ok_or_else(refused)? = true;
3993 after |= writes[index] > 0;
3994 }
3995 }
3996 _ => {}
3997 }
3998 let mut written = Vec::new();
3999 let form = x86_64::form(line.opcode).ok_or_else(refused)?;
4000 // Which registers the instruction reaches, asked the same way it is asked again when
4001 // the instruction is written. See [`Self::lettered`] for the one opcode whose answer
4002 // comes from the constraint letters rather than from the description.
4003 let lettered = (line.opcode == x86_64::LITERAL).then(|| self.lettered(&list));
4004 let (described, pieces) = match &lettered {
4005 Some((described, pieces)) => (described.as_slice(), pieces.as_slice()),
4006 None => (form.operands(), line.operands.as_slice()),
4007 };
4008 for (desc, piece) in described.iter().zip(pieces) {
4009 // An operand the instruction reaches without its text saying so is the statement's
4010 // only when a constraint letter put something there. One that is nobody's writes
4011 // nothing of the program's, so it is counted nowhere and is dealt with where it is
4012 // placed.
4013 let index = match *piece {
4014 x86_64::Piece::Operand { index, .. } => index,
4015 x86_64::Piece::Implicit { reg } => match bound(&list, reg, desc.role) {
4016 Some(index) => index,
4017 None => continue,
4018 },
4019 x86_64::Piece::Reg { reg, .. } => match bound(&list, reg, desc.role) {
4020 Some(index) => index,
4021 None => continue,
4022 },
4023 };
4024 *held.get_mut(index).ok_or_else(refused)? = true;
4025 if matches!(desc.role, Role::Def | Role::EarlyDef) {
4026 written.push(index);
4027 } else {
4028 *reads.get_mut(index).ok_or_else(refused)? = true;
4029 after |= writes[index] > 0;
4030 }
4031 }
4032 for index in written {
4033 *writes.get_mut(index).ok_or_else(refused)? += 1;
4034 }
4035 }
4036 let woven = after
4037 || writes.iter().any(|&count| count > 1)
4038 || steps.iter().any(|step| !matches!(step, x86_64::Step::Line(_)));
4039
4040 // Where every operand is. Worked out in full before the first instruction is written, since
4041 // reading a value may be what puts it in a register in the first place, and that has to
4042 // happen in front of the assembly rather than in the middle of it.
4043 let mut places: Vec<Place> = vec![Place::default(); list.len()];
4044 for (index, operand) in list.iter().copied().enumerate() {
4045 let Some(result) = operand.result else {
4046 // An input, or an output the assembly was handed the address of, and both are a
4047 // value that arrives in a register and is read out of it, unless no instruction of
4048 // the template reads it out of one.
4049 let value = operand.value.ok_or_else(refused)?;
4050 if held[index] {
4051 places[index].read = Some(self.reg_of(value)?);
4052 }
4053 continue;
4054 };
4055 let ty = self.source[result].ty;
4056 if on_x87(ty) {
4057 return Err(refused());
4058 }
4059 let tied = operands.tied_to(index);
4060 if let Some(from) = tied {
4061 if self.class_of(self.source[from].ty) != self.class_of(ty) {
4062 return Err(refused());
4063 }
4064 places[index].read = Some(self.reg_of(from)?);
4065 }
4066 if writes[index] > 0 {
4067 places[index].write = Some(self.new_reg(result));
4068 continue;
4069 }
4070 match tied {
4071 // The place the input arrived in, which the assembly wrote nothing over. One
4072 // register, so this is a rename rather than a move.
4073 Some(_) => {
4074 let reg = places[index].read.ok_or_else(refused)?;
4075 self.regs[result.index()] = Some(reg);
4076 places[index].write = Some(reg);
4077 }
4078 None => {
4079 self.undefined(inst, result)?;
4080 places[index].write = self.regs[result.index()];
4081 }
4082 }
4083 }
4084
4085 // An output an instruction of the template also reads, which the statement said nothing
4086 // about because an output is what a statement says the other thing about. What it holds
4087 // there is undefined, and a program writing one means it: `sbb %0, %0` in libgmp's
4088 // `add_mssaaaa` subtracts a register from itself and is asking for the borrow bit rather
4089 // than for the number, so whatever the register held, the answer is the same. Undefined is
4090 // not the same as absent though, since the allocator is owed a definition in front of every
4091 // use, so it gets the zero an output nothing wrote gets and for the same reason.
4092 //
4093 // Unless an input could have been in the same register, in which case gcc's allocator puts
4094 // it there whenever it can and a program may have been written against that. tcc's test of
4095 // a call from a template reads its output `"=a" (s)` to pass `"r" (str)` to `getenv`, which
4096 // is only the string because gcc gave the two of them `rax`. So an output nothing has
4097 // written yet reads the one input that could share its place, when there is exactly one.
4098 // One written `&` is written before the inputs are read and shares nothing.
4099 for index in 0..list.len() {
4100 if !reads[index] || places[index].read.is_some() || places[index].write.is_none() {
4101 continue;
4102 }
4103 let reg = match self.shared(&list, index) {
4104 Some(value) => self.reg_of(value)?,
4105 None => self.seeded(inst, list[index])?,
4106 };
4107 places[index].read = Some(reg);
4108 }
4109
4110 // Worked out once for the whole template, since the list is one list and every instruction
4111 // of the template gets it. Not worked out at all for a template with no instructions, which
4112 // is where there is nothing for it to go on.
4113 let clobbers = self.names.resolve(info.clobbers).to_string();
4114 let clobbered =
4115 if steps.is_empty() { Vec::new() } else { Self::clobbered(inst, &clobbers)? };
4116
4117 // A template with a label in it is not one run of instructions, and what it is instead is
4118 // in [`Self::woven`], which is also where a template goes whose instructions read what the
4119 // ones above them wrote. Every other template is what it has always been, which is every
4120 // instruction of it written into the block the statement stands in.
4121 if woven {
4122 return self.woven(inst, &steps, &mut places, &list, &clobbered, &writes);
4123 }
4124 for step in &steps {
4125 let x86_64::Step::Line(line) = step else { continue };
4126 self.instruction(inst, line, &places, &list, &clobbered)?;
4127 }
4128 Ok(())
4129 }
4130
4131 /// A template the reader could not take apart, kept as its text. See [`x86_64::Form::Template`].
4132 ///
4133 /// What the text names is spelled into it here, the way gcc prints it into its listing: a
4134 /// constant as `$5`, or as `5` under the `c` modifier, and the address of a name as the name.
4135 /// An object in memory is the one thing that cannot be spelled yet, since where it is depends on
4136 /// registers nothing has chosen, so it is left as a hole the writer fills and its address is the
4137 /// instruction's memory operand. One is all an instruction has room for, and every template this
4138 /// has met names one at most. A template that names an operand by name rather than by number is
4139 /// refused for now.
4140 ///
4141 /// # An operand in a register
4142 ///
4143 /// Which register is not known until the allocator has run, and the text is written down before
4144 /// then, so an operand in a register is a hole too. It names the instruction's own operand and
4145 /// the width the modifier asked for, or the width of the operand's type when there was none,
4146 /// and the writer spells whatever register the operand ended up in. What the text writes goes
4147 /// in first as definitions and what it reads goes in last as uses, with the registers below in
4148 /// between, so the allocator sees the statement as one instruction with every operand said. An
4149 /// output tied to an input, by `+` or by a number, reuses the input's register, and one written
4150 /// `&` is written early. Anything wider than a general purpose register is refused.
4151 ///
4152 /// A statement written with no colons is basic assembly, where `%` is a character like any
4153 /// other and a register is written `%eax`. The front end keeps no mark of which kind a statement
4154 /// was, so one with no operands and no clobbers is read as basic, which is what gcc would do for
4155 /// every such template but one written with empty colons around it.
4156 ///
4157 /// The registers a call may write are taken as written, see below for why.
4158 fn kept(
4159 &mut self,
4160 inst: Inst,
4161 template: &str,
4162 list: &[AsmOperand<'_>],
4163 widths: &[Option<x86_64::Width>],
4164 memory: &[bool],
4165 ) -> Result<(), Unsupported> {
4166 // Refused as the template it is, since keeping it is what was tried after reading it
4167 // failed, and what could not be kept is what it names rather than any one operand.
4168 let refused = || Unsupported::Assembly { inst, refused: Written::Template };
4169 let data = &self.source[inst];
4170 let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
4171 let clobbers = self.names.resolve(self.source[asm].clobbers).to_string();
4172 let basic = list.is_empty() && clobbers.trim().is_empty();
4173
4174 // Every register a call may leave anything in, as well as the ones the list names. The
4175 // text can write any register it likes without saying so, and tcc's tests do: gcc gets
4176 // away with that at `-O0` because nothing lives in a register between two statements
4177 // there, and taking these away from the allocator across the template is what gives the
4178 // same answer here. Nothing is written to them by this, so a register one template leaves
4179 // a value in is still holding it when the next template reads it.
4180 let a64 = self.on_aarch64();
4181 let mut clobbered: Vec<(PhysReg, RegClass)> =
4182 self.lost(list).into_iter().map(|(reg, class, _)| (reg, class)).collect();
4183 let named = if a64 {
4184 Self::clobbered_a64(inst, &clobbers)?
4185 } else {
4186 Self::clobbered_x86(inst, &clobbers, self.gpr, self.conv.sse_class)?
4187 };
4188 for &(reg, class) in &named {
4189 if !clobbered.iter().any(|&(had, of)| had == reg && of == class) {
4190 clobbered.push((reg, class));
4191 }
4192 }
4193
4194 // The file each operand is in. On AArch64 `w` is a floating point or vector register and an
4195 // input tied to an output is in that output's file. A value whose type puts it in the other
4196 // file would need a move into this one first, which gcc makes and this does not yet, so
4197 // that is refused below.
4198 let mut files = vec![self.gpr; list.len()];
4199 if a64 {
4200 let constraints = self.names.resolve(self.source[asm].constraints);
4201 for (file, entry) in files.iter_mut().zip(constraints.split(',')) {
4202 if vector_letter(entry) {
4203 *file = self.conv.sse_class;
4204 }
4205 }
4206 for index in 0..list.len() {
4207 if let Some(&file) = list[index].tied.and_then(|output| files.get(output)) {
4208 files[index] = file;
4209 }
4210 }
4211 }
4212 let pins: Vec<_> = list.iter().map(|operand| self.pinned_here(operand)).collect();
4213 let pin = |index: usize, file: RegClass| match pins[index] {
4214 Some((at, class)) if class == file => Ok(Some(Constraint::Fixed(at))),
4215 Some(_) => Err(refused()),
4216 None => Ok(None),
4217 };
4218
4219 // The operands in a register, as the instruction's own. An input the text is handed as a
4220 // constant or as the address of a name is spelled into the text instead, when its
4221 // constraint allows a constant at all and no output is tied to it. `"a" (0x1234)` is a
4222 // register holding the number, the way gcc loads it, since the text may ask for `%h0`.
4223 let mut defs: Vec<mir::Operand> = Vec::new();
4224 let mut uses: Vec<mir::Operand> = Vec::new();
4225 let mut def_of: Vec<Option<usize>> = vec![None; list.len()];
4226 let mut use_of: Vec<Option<usize>> = vec![None; list.len()];
4227 if !basic {
4228 for (index, operand) in list.iter().enumerate() {
4229 let Some(result) = operand.result else { continue };
4230 let (ty, file) = (self.source[result].ty, files[index]);
4231 if on_x87(ty) || self.class_of(ty) != file {
4232 return Err(refused());
4233 }
4234 let reg = self.new_reg(result);
4235 let written = if operand.early {
4236 mir::Operand::write_early(reg, file)
4237 } else {
4238 mir::Operand::write(reg, file)
4239 };
4240 def_of[index] = Some(defs.len());
4241 defs.push(match pin(index, file)? {
4242 Some(fixed) => written.with(fixed),
4243 None => written,
4244 });
4245 }
4246 for (index, operand) in list.iter().enumerate() {
4247 let Some(value) = operand.value else { continue };
4248 let spelled = operand.result.is_none()
4249 && operand.tied.is_none()
4250 && operand.immediate
4251 && (self.number(value).is_some() || self.named_address(value).is_some());
4252 // An operand in memory is spelled on AArch64 as the register its address is in,
4253 // which is `[x3]` and is an address every instruction that takes one reads.
4254 if (operand.memory && !a64) || spelled {
4255 continue;
4256 }
4257 let (ty, file) = (self.source[value].ty, files[index]);
4258 if on_x87(ty) || self.class_of(ty) != file {
4259 return Err(refused());
4260 }
4261 let read = mir::Operand::read(self.reg_of(value)?, file);
4262 use_of[index] = Some(uses.len());
4263 uses.push(match pin(index, file)? {
4264 Some(fixed) => read.with(fixed),
4265 None => read,
4266 });
4267 }
4268 }
4269 // Every register a call may write is more than a template can give up when it has more
4270 // operands in registers than the convention keeps across a call. `sodium_sub` in
4271 // libsodium's `utils.c` is one: eight outputs written early and two inputs pinned, against
4272 // the five registers SysV preserves, so an output has nowhere to go and nothing is left to
4273 // carry one to its slot either. gcc gives that template ten registers, and a program that
4274 // writes a register it did not name is only owed what gcc would have done, which here is
4275 // one of the ten. So the registers taken as written without being named are handed back,
4276 // from the end of the convention's order, until the operands fit in what is left. One the
4277 // list names or an operand is pinned to stays where it is.
4278 let fixed_to: Vec<PhysReg> = defs
4279 .iter()
4280 .chain(&uses)
4281 .filter_map(|operand| match operand.constraint {
4282 Constraint::Fixed(at) => Some(at),
4283 _ => None,
4284 })
4285 .collect();
4286 let wanted = defs.iter().chain(&uses).count() - fixed_to.len();
4287 let int = self.conv.int_class;
4288 let free = |clobbered: &[(PhysReg, RegClass)]| {
4289 self.conv
4290 .int_order
4291 .iter()
4292 .filter(|&®| !fixed_to.contains(®) && !clobbered.contains(&(reg, int)))
4293 .count()
4294 };
4295 while free(&clobbered) < wanted {
4296 let Some(at) = clobbered.iter().rposition(|&(reg, class)| {
4297 class == int && !named.contains(&(reg, class)) && !fixed_to.contains(®)
4298 }) else {
4299 break;
4300 };
4301 clobbered.remove(at);
4302 }
4303
4304 // A register an output is pinned to is that output's definition and not a clobber as well.
4305 // One an input is pinned to is written as the instruction finishes, the way a call writes
4306 // the register its argument came in, and every other one is written early, since the text
4307 // may write it before it has read its inputs and an input must not be in it.
4308 let mut written: Vec<mir::Operand> = Vec::new();
4309 for (reg, class) in clobbered {
4310 let fixed = |operand: &mir::Operand| {
4311 operand.class == class && operand.constraint == Constraint::Fixed(reg)
4312 };
4313 if defs.iter().any(fixed) {
4314 continue;
4315 }
4316 let reg = mir::Reg::physical(reg);
4317 written.push(if uses.iter().any(fixed) {
4318 mir::Operand::write(reg, class)
4319 } else {
4320 mir::Operand::write_early(reg, class)
4321 });
4322 }
4323 // An output tied to an input is one register, which the definition says by reusing the
4324 // use, or by both being fixed to the same one when the output was pinned.
4325 //
4326 // A reused register is kept from every other input already, since the allocator counts the
4327 // output as taken from where the instruction reads. So `+&` asks for nothing more than `+`,
4328 // and saying it as an early write as well costs a register: the allocator only hands an
4329 // output the register of the input it reuses when the output starts at the instruction, and
4330 // an early one starts a point sooner, so it gets one of its own and a copy in front. Eleven
4331 // operands written that way in xz's range decoder need seventeen registers and run out. The
4332 // one case where `&` still means something is an input reading the same value as the one
4333 // tied, which would be in the same register and read after the output was written.
4334 let first_use = defs.len() + written.len();
4335 for (output, operand) in list.iter().enumerate() {
4336 let Some(def) = def_of[output] else { continue };
4337 let input = if operand.value.is_some() {
4338 Some(output)
4339 } else {
4340 list.iter().position(|entry| entry.tied == Some(output))
4341 };
4342 let Some(read) = input.and_then(|input| use_of[input]) else { continue };
4343 match defs[def].constraint {
4344 Constraint::Fixed(_) => uses[read].constraint = defs[def].constraint,
4345 _ => {
4346 let at = u8::try_from(first_use + read).map_err(|_| refused())?;
4347 defs[def].constraint = Constraint::Reuse(at);
4348 let source = uses[read].reg;
4349 let shared = uses
4350 .iter()
4351 .enumerate()
4352 .any(|(other, operand)| other != read && operand.reg == source);
4353 if defs[def].role == Role::EarlyDef && !shared {
4354 defs[def].role = Role::Def;
4355 }
4356 }
4357 }
4358 }
4359
4360 // A line naming an operand in a register, with an instruction on it the reader knows, is
4361 // one the reader refused for a reason of its own, and keeping it as text would hand the
4362 // assembler what the reader already said no to. `addq %1, %k0` is that: a quadword add
4363 // into half a register. What is kept is a line with an instruction nothing here knows.
4364 let registered = |index: usize| def_of[index].is_some() || use_of[index].is_some();
4365 if !a64 && (0..list.len()).any(registered) {
4366 for line in template.split(['\n', ';']) {
4367 if names_one(line, registered)
4368 && x86_64::known(line, widths, memory)
4369 && x86_64::read_in(line, widths, memory).is_none()
4370 {
4371 return Err(refused());
4372 }
4373 }
4374 }
4375
4376 let mut text = String::with_capacity(template.len());
4377 let mut memory: Option<usize> = None;
4378 if basic {
4379 text.push_str(template);
4380 } else {
4381 let mut chars = template.chars().peekable();
4382 // Inside `{att|intel}`, and past the `|` in it, which is the half nobody reads. AArch64
4383 // has one dialect, and a brace there is a list of vector registers.
4384 let mut dialect = false;
4385 let mut skipped = false;
4386 while let Some(c) = chars.next() {
4387 match c {
4388 '{' if !a64 => {
4389 dialect = true;
4390 continue;
4391 }
4392 '|' if dialect => {
4393 skipped = true;
4394 continue;
4395 }
4396 '}' if dialect => {
4397 dialect = false;
4398 skipped = false;
4399 continue;
4400 }
4401 _ if skipped => continue,
4402 '%' => {}
4403 _ => {
4404 text.push(c);
4405 continue;
4406 }
4407 }
4408 match chars.peek().copied() {
4409 Some(c @ ('%' | '{' | '|' | '}')) => {
4410 chars.next();
4411 text.push(c);
4412 continue;
4413 }
4414 Some('=') => {
4415 chars.next();
4416 text.push_str(&inst.index().to_string());
4417 continue;
4418 }
4419 _ => {}
4420 }
4421 let modifier = match chars.peek().copied() {
4422 Some(c) if c.is_ascii_alphabetic() => {
4423 chars.next();
4424 Some(c)
4425 }
4426 _ => None,
4427 };
4428 let mut digits = String::new();
4429 while let Some(c) = chars.peek().copied().filter(char::is_ascii_digit) {
4430 digits.push(c);
4431 chars.next();
4432 }
4433 let index: usize = digits.parse().map_err(|_| refused())?;
4434 let operand = list.get(index).ok_or_else(refused)?;
4435 if operand.memory && a64 {
4436 let at = use_of[index].map(|at| first_use + at).ok_or_else(refused)?;
4437 if modifier.is_some() {
4438 return Err(refused());
4439 }
4440 text.push('[');
4441 text.push_str(&template_reg(at, 'x'));
4442 text.push(']');
4443 continue;
4444 }
4445 if operand.memory {
4446 if modifier.is_some() || memory.is_some_and(|had| had != index) {
4447 return Err(refused());
4448 }
4449 memory = Some(index);
4450 text.push_str(x86_64::TEMPLATE_MEM);
4451 continue;
4452 }
4453 let placed = def_of[index].or(use_of[index].map(|at| first_use + at));
4454 if let Some(at) = placed {
4455 let value = operand.result.or(operand.value).ok_or_else(refused)?;
4456 let bits = held_bits(self.source[value].ty);
4457 // `w` and `x` are the two names every general purpose register has, and one
4458 // with no modifier is named at the width of its type, as gcc names it. A
4459 // vector register with no modifier is `v`, which is what gcc writes for one
4460 // whatever is in it, and the modifiers name the scalar views of it.
4461 let width = if a64 && files[index] != self.gpr {
4462 match modifier {
4463 None => 'v',
4464 Some(view @ ('b' | 'h' | 's' | 'd' | 'q')) => view,
4465 Some(_) => return Err(refused()),
4466 }
4467 } else if a64 {
4468 match (modifier, bits) {
4469 (None, 8 | 16 | 32) | (Some('w'), _) => 'w',
4470 (None, 64) | (Some('x'), _) => 'x',
4471 _ => return Err(refused()),
4472 }
4473 } else {
4474 match modifier {
4475 None => match held_bits(self.source[value].ty) {
4476 8 => 'b',
4477 16 => 'w',
4478 32 => 'k',
4479 64 => 'q',
4480 _ => return Err(refused()),
4481 },
4482 Some(width @ ('b' | 'w' | 'k' | 'q')) => width,
4483 // The second byte is a name only four registers have, so it is taken for
4484 // an operand pinned to one of them and for nothing the allocator chose.
4485 Some('h') if pinned(operand).and_then(x86_64::gpr_high).is_some() => {
4486 'h'
4487 }
4488 Some(_) => return Err(refused()),
4489 }
4490 };
4491 text.push_str(&template_reg(at, width));
4492 continue;
4493 }
4494 let value = operand.value.ok_or_else(refused)?;
4495 let bare = match modifier {
4496 None => false,
4497 Some('c' | 'P' | 'p') => true,
4498 Some(_) => return Err(refused()),
4499 };
4500 // A constant is bare on AArch64 whatever the modifier, which is how gcc prints one
4501 // there and a form GNU as takes wherever `#` would go.
4502 if !bare && !a64 {
4503 text.push('$');
4504 }
4505 if let Some(number) = self.number(value) {
4506 text.push_str(&number.to_string());
4507 } else if let Some(symbol) = self.named_address(value) {
4508 text.push_str(&template_name(self.names.resolve(symbol)));
4509 } else {
4510 return Err(refused());
4511 }
4512 }
4513 }
4514
4515 // An object in this function's frame is named by where it is in the frame, the way gcc
4516 // names it, rather than by a register its address was put in first. The text may write
4517 // registers it does not declare, and tcc's tests do: one that writes `%ecx` behind the
4518 // compiler's back would otherwise take the address with it.
4519 let mut local = None;
4520 let at = match memory.filter(|_| !a64) {
4521 Some(index) => {
4522 let value = list[index].value.ok_or_else(refused)?;
4523 local = self.local_of(value);
4524 let base = match local {
4525 Some(_) => mir::Reg::physical(self.conv.stack_pointer),
4526 None => self.reg_of(value)?,
4527 };
4528 Some(mir::Mem::at(mir::Operand::read(base, self.gpr)))
4529 }
4530 None => None,
4531 };
4532 let symbol = self.names.intern(&text);
4533 let opcode = self.named(if a64 { aarch64::TEMPLATE } else { x86_64::TEMPLATE });
4534 let block = self.at.expect("a block is being filled");
4535 let span = self.source.span(inst);
4536 let mut build = self.out.build(block, opcode).at(span).symbol(symbol);
4537 for operand in defs.into_iter().chain(written).chain(uses) {
4538 build = build.operand(operand);
4539 }
4540 if let Some(mem) = at {
4541 build = build.mem(mem);
4542 }
4543 let made = build.finish();
4544 if let Some(local) = local {
4545 self.stack.addresses.push((made, local));
4546 }
4547 Ok(())
4548 }
4549
4550 /// The object in this function's frame a value is the address of, for one an `alloca` of a
4551 /// size known here made. See [`Self::reserve`], which is where the `lea` it is found by came
4552 /// from.
4553 fn local_of(&self, value: Value) -> Option<usize> {
4554 let Def::Result { inst, .. } = self.source[value].def else { return None };
4555 if self.source[inst].opcode != Opcode::Alloca
4556 || !self.source[self.source[inst].args].is_empty()
4557 {
4558 return None;
4559 }
4560 let reg = self.regs[value.index()]?;
4561 self.stack.addresses.iter().find_map(|&(made, local)| {
4562 let data = &self.out[made];
4563 let defined = self.out[data.operands].first()?;
4564 (defined.reg == reg).then_some(local)
4565 })
4566 }
4567
4568 /// The name a value is the address of, for one a `global_addr` defined.
4569 fn named_address(&self, value: Value) -> Option<Symbol> {
4570 let Def::Result { inst, .. } = self.source[value].def else { return None };
4571 if self.source[inst].opcode != Opcode::GlobalAddr {
4572 return None;
4573 }
4574 let Extra::Symbol(symbol) = self.source[inst].extra else { return None };
4575 Some(symbol)
4576 }
4577
4578 /// A register holding a zero, for an operand of a template that is read before anything filled
4579 /// it.
4580 ///
4581 /// Two things ask for this and they are the same thing twice. An output the template reads has
4582 /// nothing to be read out of until the instruction that writes it has run, and a loop carries
4583 /// an operand into a block before the instruction that fills it, so both are a use in front of
4584 /// every definition. What the program is owed there is nothing, since the value is undefined
4585 /// either way, and what the allocator is owed is a register something wrote.
4586 fn seeded(&mut self, inst: Inst, operand: AsmOperand<'_>) -> Result<mir::Reg, Unsupported> {
4587 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4588 let value = operand.result.or(operand.value).ok_or_else(refused)?;
4589 let class = self.class_of(self.source[value].ty);
4590 if class != self.gpr {
4591 return Err(refused());
4592 }
4593 let block = self.at.expect("a block is being filled");
4594 let reg = self.out.new_vreg(class);
4595 let put = self.named("mov_ri_64");
4596 self.out.build(block, put).at(self.source.span(inst)).def(reg, class).imm(0).finish();
4597 Ok(reg)
4598 }
4599
4600 /// A template with labels in it, as the blocks its jumps leave and arrive at.
4601 ///
4602 /// A statement is an instruction of the IR and stands inside one block, so a template that
4603 /// jumps has to stop being one thing. Each label becomes a block, each jump ends the block it
4604 /// stands in and gives it two arms, and whatever follows the statement goes into whichever
4605 /// block the walk finished in, which is what [`Self::block`] already reads off `self.at` and
4606 /// what [`Self::saves_place`] already does for the same reason.
4607 ///
4608 /// # What is carried between them
4609 ///
4610 /// The machine IR here is in the form where a register is written once, so an operand written
4611 /// inside a loop and read again at the top of it cannot be one register. What arrives at the
4612 /// top is a parameter of that block, and every jump to it carries whichever register held the
4613 /// operand where the jump stands. That is the whole of the bookkeeping: every block a label
4614 /// made takes one parameter for each operand that is in a register at all, in one order, so an
4615 /// arm's arguments and a block's parameters are the same list read twice.
4616 ///
4617 /// Which register an operand is in at each point is kept in the read half of its place, since
4618 /// that is what the instructions below read it out of. An instruction that writes an operand
4619 /// leaves it in the register it wrote, and a jump below carries that one. The block an
4620 /// untaken jump falls into is arrived at one way only and so takes no parameters, and nothing
4621 /// about where the operands are changes there.
4622 ///
4623 /// An operand written by the template and filled by nothing is written as a zero first, for
4624 /// the reason [`Self::undefined`] gives and one more: a jump may carry it before the
4625 /// instruction that fills it has run, and an argument has to be a register something wrote.
4626 ///
4627 /// # The condition state
4628 ///
4629 /// Nothing carries it and nothing has to. The instruction that sets it and the jump that reads
4630 /// it are both written here, next to each other in one block, and what the allocator may put
4631 /// between them is a move, which on this machine leaves the condition state alone. The edge
4632 /// into a block a loop goes back to is a critical edge and `crate::split` gives it a block of
4633 /// its own, so the moves an arm turns into land behind the jump rather than in front of it.
4634 fn woven(
4635 &mut self,
4636 inst: Inst,
4637 steps: &[x86_64::Step],
4638 places: &mut [Place],
4639 list: &[AsmOperand<'_>],
4640 clobbered: &[PhysReg],
4641 writes: &[usize],
4642 ) -> Result<(), Unsupported> {
4643 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4644 let span = self.source.span(inst);
4645
4646 // Which operands are carried, which is every one that is in a register at all. An operand
4647 // the template never puts in one, such as a constant it names only as the distance into an
4648 // address, is in the instruction and has nowhere to be carried from.
4649 let mut carried: Vec<(usize, RegClass)> = Vec::new();
4650 for (index, operand) in list.iter().enumerate() {
4651 if places[index].read.is_none() && places[index].write.is_none() {
4652 continue;
4653 }
4654 let value = operand.result.or(operand.value).ok_or_else(refused)?;
4655 let ty = self.source[value].ty;
4656 if on_x87(ty) {
4657 return Err(refused());
4658 }
4659 carried.push((index, self.class_of(ty)));
4660 }
4661
4662 // What each of them holds where the template starts.
4663 for &(index, _) in &carried {
4664 if places[index].read.is_some() {
4665 continue;
4666 }
4667 if writes[index] == 0 {
4668 places[index].read = places[index].write;
4669 continue;
4670 }
4671 places[index].read = Some(self.seeded(inst, list[index])?);
4672 }
4673
4674 // The blocks, made before the walk because a jump forwards names a label the walk has not
4675 // reached yet.
4676 let mut labels: Vec<(&str, mir::Block, Vec<mir::Reg>)> = Vec::new();
4677 for step in steps {
4678 let x86_64::Step::Label(name) = step else { continue };
4679 let block = self.out.create_block();
4680 let mut params = Vec::with_capacity(carried.len());
4681 for &(_, class) in &carried {
4682 params.push(self.out.append_param(block, class));
4683 }
4684 labels.push((name.as_str(), block, params));
4685 }
4686
4687 let mut wrote: Vec<usize> = Vec::new();
4688 for step in steps {
4689 match step {
4690 x86_64::Step::Label(name) => {
4691 let (block, params) = Self::went(&labels, name).ok_or_else(refused)?;
4692 let from = self.at.expect("a block is being filled");
4693 let args = Self::held(places, &carried).ok_or_else(refused)?;
4694 *self.out.succs_mut(from) = vec![mir::BlockCall::with(block, args)];
4695 self.at = Some(block);
4696 for (at, &(index, _)) in carried.iter().enumerate() {
4697 places[index].read = params.get(at).copied();
4698 }
4699 }
4700 x86_64::Step::Jump { opcode, to } => {
4701 let (block, _) = Self::went(&labels, to).ok_or_else(refused)?;
4702 let from = self.at.expect("a block is being filled");
4703 let args = Self::held(places, &carried).ok_or_else(refused)?;
4704 let opcode = self.named(opcode);
4705 self.out.build(from, opcode).at(span).finish();
4706 let next = self.out.create_block();
4707 *self.out.succs_mut(from) =
4708 vec![mir::BlockCall::with(block, args), mir::BlockCall::to(next)];
4709 self.at = Some(next);
4710 }
4711 x86_64::Step::Away { symbol } => {
4712 // Only in a function that is written without a prologue, which is the one
4713 // place the jump means what it says. Anywhere else there is an epilogue behind
4714 // the statement that puts the registers back and gives the frame up, and a
4715 // jump over it goes to the next function with this function's frame still
4716 // taken. The reader already made sure it is the last step of the template, so
4717 // what is left to ask is about the function around it.
4718 if !self.source.attrs.set.contains(AttrSet::NAKED) {
4719 return Err(Unsupported::Assembly { inst, refused: Written::Away });
4720 }
4721 let from = self.at.expect("a block is being filled");
4722 let opcode = self.named(AWAY);
4723 let symbol = self.names.intern(symbol);
4724 self.out.build(from, opcode).at(span).symbol(symbol).finish();
4725 // Nowhere, which is what a jump out of the function leaves behind it and is
4726 // the same list a `ret` leaves. The block after it is made for the walk above
4727 // rather than for the program: the statement may be in the middle of a body
4728 // that goes on being lowered, and what that lowering writes is reached by
4729 // nothing and thrown away with the block.
4730 *self.out.succs_mut(from) = Vec::new();
4731 self.at = Some(self.out.create_block());
4732 }
4733 x86_64::Step::Call { symbol } => {
4734 self.call_out(inst, symbol, places, list, clobbered, &carried, &mut wrote)?;
4735 }
4736 x86_64::Step::Line(line) => {
4737 let form = x86_64::form(line.opcode).ok_or_else(refused)?;
4738 let mut written = Vec::new();
4739 for (desc, piece) in form.operands().iter().zip(&line.operands) {
4740 if !desc.role.is_def() {
4741 continue;
4742 }
4743 let index = match *piece {
4744 x86_64::Piece::Operand { index, .. } => index,
4745 x86_64::Piece::Implicit { reg } => match bound(list, reg, desc.role) {
4746 Some(index) => index,
4747 None => continue,
4748 },
4749 x86_64::Piece::Reg { reg, .. } => match bound(list, reg, desc.role) {
4750 Some(index) => index,
4751 None => continue,
4752 },
4753 };
4754 written.push(index);
4755 }
4756 // A register is written once in this form of the machine IR, so an operand
4757 // an instruction above already wrote is written into a new one here, and what
4758 // reads it below reads that one.
4759 for &index in &written {
4760 if !wrote.contains(&index) {
4761 wrote.push(index);
4762 continue;
4763 }
4764 let &(_, class) =
4765 carried.iter().find(|&&(at, _)| at == index).ok_or_else(refused)?;
4766 let place = places.get_mut(index).ok_or_else(refused)?;
4767 place.write = Some(self.out.new_vreg(class));
4768 }
4769 self.instruction(inst, line, places, list, clobbered)?;
4770 for index in written {
4771 let place = places.get_mut(index).ok_or_else(refused)?;
4772 if place.write.is_some() {
4773 place.read = place.write;
4774 }
4775 }
4776 }
4777 }
4778 }
4779
4780 // Where the walk left each output, which is the parameter of the block a label made when
4781 // the template ends in one and the register an instruction wrote when it does not.
4782 for (index, operand) in list.iter().enumerate() {
4783 let Some(result) = operand.result else { continue };
4784 if let Some(reg) = places[index].read {
4785 self.regs[result.index()] = Some(reg);
4786 }
4787 }
4788 Ok(())
4789 }
4790
4791 /// A template's call to a function somewhere else, as the call the convention makes.
4792 ///
4793 /// The opcode is the one a call written in C becomes, so everything that asks whether a
4794 /// function calls anything gets the answer it would for one: the stack pointer is left aligned
4795 /// at the statement and nothing is kept in the red zone. What is not the same is the operands.
4796 /// Nothing is passed by the convention, since the template put the arguments where it wanted
4797 /// them, and what comes back is whatever an output is pinned to, since that is the only thing
4798 /// the template says about it. Every other register the callee may leave anything in is
4799 /// written here, which is what a program that calls from a template never says and always
4800 /// means.
4801 #[allow(clippy::too_many_arguments)]
4802 fn call_out(
4803 &mut self,
4804 inst: Inst,
4805 symbol: &str,
4806 places: &mut [Place],
4807 list: &[AsmOperand<'_>],
4808 clobbered: &[PhysReg],
4809 carried: &[(usize, RegClass)],
4810 wrote: &mut Vec<usize>,
4811 ) -> Result<(), Unsupported> {
4812 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4813 let mut operands = Vec::new();
4814 let mut written = Vec::new();
4815 let lost = self.lost(list);
4816 for &(reg, class, index) in &lost {
4817 let Some(index) = index else {
4818 operands.push(mir::Operand::write(mir::Reg::physical(reg), class));
4819 continue;
4820 };
4821 // Written once in this form of the machine IR, so a second write is a new register,
4822 // the same as for an instruction in [`Self::woven`].
4823 if wrote.contains(&index) {
4824 let &(_, class) =
4825 carried.iter().find(|&&(at, _)| at == index).ok_or_else(refused)?;
4826 places.get_mut(index).ok_or_else(refused)?.write = Some(self.out.new_vreg(class));
4827 } else {
4828 wrote.push(index);
4829 }
4830 let place = places.get(index).ok_or_else(refused)?.write.ok_or_else(refused)?;
4831 operands.push(mir::Operand::write(place, class).with(Constraint::Fixed(reg)));
4832 written.push(index);
4833 }
4834 for ® in clobbered {
4835 if lost.iter().all(|&(gone, class, _)| gone != reg || class != self.gpr) {
4836 operands.push(mir::Operand::write(mir::Reg::physical(reg), self.gpr));
4837 }
4838 }
4839 let block = self.at.expect("a block is being filled");
4840 let span = self.source.span(inst);
4841 let opcode = mir::Opcode::new(self.names.intern(abi::CALL));
4842 let symbol = self.names.intern(symbol);
4843 let mut build = self.out.build(block, opcode).at(span).symbol(symbol);
4844 for operand in operands {
4845 build = build.operand(operand);
4846 }
4847 build.finish();
4848 let calls = &mut self.stack.calls;
4849 *calls = Some(calls.unwrap_or(0));
4850 for index in written {
4851 let place = places.get_mut(index).ok_or_else(refused)?;
4852 place.read = place.write;
4853 }
4854 Ok(())
4855 }
4856
4857 /// Every register a call may leave anything in, with its file and the output pinned to it if
4858 /// one is.
4859 ///
4860 /// A register is asked about with its file, since the two files are numbered from nought alike
4861 /// and a question about `v8` alone would find an output pinned to `x8`.
4862 fn lost(&self, list: &[AsmOperand<'_>]) -> Vec<(PhysReg, RegClass, Option<usize>)> {
4863 let conv = self.conv;
4864 let ints = conv.int_order.iter().filter(|&®| !conv.preserves_int(reg));
4865 let sses = conv.sse_order.iter().filter(|&®| !conv.preserves_sse(reg));
4866 let written = |reg, class| {
4867 list.iter().position(|operand| {
4868 operand.result.is_some() && self.pinned_here(operand) == Some((reg, class))
4869 })
4870 };
4871 ints.map(|®| (reg, conv.int_class, written(reg, conv.int_class)))
4872 .chain(sses.map(|®| (reg, conv.sse_class, written(reg, conv.sse_class))))
4873 .collect()
4874 }
4875
4876 /// The input an output read before anything wrote it shares its register with, which is the
4877 /// one input that could be in that register, or nothing when there is none or more than one.
4878 ///
4879 /// Could be means nothing ties it elsewhere: it is in a register rather than in memory, no
4880 /// constraint pins it anywhere the output is not, and it is not tied to another output. An
4881 /// output written `&` shares nothing, since the assembly writes it before it reads the inputs.
4882 fn shared(&self, list: &[AsmOperand<'_>], index: usize) -> Option<Value> {
4883 let output = list.get(index)?;
4884 if output.early || output.tied.is_some() {
4885 return None;
4886 }
4887 let class = self.class_of(self.source[output.result?].ty);
4888 let mut fits = list.iter().filter(|operand| {
4889 operand.result.is_none()
4890 && !operand.memory
4891 && operand.tied.is_none()
4892 && operand.value.is_some_and(|value| self.class_of(self.source[value].ty) == class)
4893 && pinned(operand).is_none_or(|reg| pinned(output) == Some(reg))
4894 });
4895 let value = fits.next()?.value;
4896 if fits.next().is_some() {
4897 return None;
4898 }
4899 value
4900 }
4901
4902 /// The block one of the template's labels made, and the parameters it takes.
4903 fn went<'b>(
4904 labels: &'b [(&str, mir::Block, Vec<mir::Reg>)],
4905 name: &str,
4906 ) -> Option<(mir::Block, &'b [mir::Reg])> {
4907 labels
4908 .iter()
4909 .find(|(had, ..)| *had == name)
4910 .map(|(_, block, params)| (*block, params.as_slice()))
4911 }
4912
4913 /// The register each carried operand is in, which is what an arm to a label carries.
4914 fn held(places: &[Place], carried: &[(usize, RegClass)]) -> Option<Vec<mir::Reg>> {
4915 carried.iter().map(|&(index, _)| places.get(index)?.read).collect()
4916 }
4917
4918 /// The registers a clobber list names, in the order it named them.
4919 ///
4920 /// Nothing is dropped. A name this has no register for is refused, because the list is the
4921 /// program telling the compiler which registers it may not leave anything in, and an entry
4922 /// nobody read is a register something may still be left in. See [`Self::assembly`] for the
4923 /// two entries that are not registers and for why they are skipped rather than refused.
4924 fn clobbered(inst: Inst, clobbers: &str) -> Result<Vec<PhysReg>, Unsupported> {
4925 let refused = || Unsupported::Assembly { inst, refused: Written::Clobber };
4926 let mut named = Vec::new();
4927 for entry in clobbers.split(',') {
4928 let entry = entry.trim().trim_matches('"');
4929 // The sigil is optional in a clobber list and means nothing when it is there, unlike
4930 // in a template, where it is what tells a register from an operand.
4931 let entry = entry.strip_prefix('%').unwrap_or(entry);
4932 if entry.is_empty() || matches!(entry, "memory" | "cc" | "flags") {
4933 continue;
4934 }
4935 let (reg, _) = x86_64::gpr_named(entry).ok_or_else(refused)?;
4936 if !named.contains(®) {
4937 named.push(reg);
4938 }
4939 }
4940 Ok(named)
4941 }
4942
4943 /// [`Self::clobbered`] for a template kept as text, where a clobber may also name a vector
4944 /// register, `xmm0` or its wider spelling `ymm0`, which busybox's `xorbuf16_aligned_long` does.
4945 /// Each comes back with the file it is in, since `xmm0` and `rax` are both register nought.
4946 fn clobbered_x86(
4947 inst: Inst,
4948 clobbers: &str,
4949 gpr: RegClass,
4950 sse: RegClass,
4951 ) -> Result<Vec<(PhysReg, RegClass)>, Unsupported> {
4952 let mut named = Vec::new();
4953 let mut general = Vec::new();
4954 for entry in clobbers.split(',') {
4955 match vector_named(entry) {
4956 Some(reg) => {
4957 if !named.contains(&(reg, sse)) {
4958 named.push((reg, sse));
4959 }
4960 }
4961 None => general.push(entry),
4962 }
4963 }
4964 for reg in Self::clobbered(inst, &general.join(","))? {
4965 named.push((reg, gpr));
4966 }
4967 Ok(named)
4968 }
4969
4970 /// [`Self::clobbered`] on AArch64, where a clobber may name a vector register as well as a
4971 /// general purpose one, so each comes back with the file it is in. See [`aarch64::named`].
4972 fn clobbered_a64(inst: Inst, clobbers: &str) -> Result<Vec<(PhysReg, RegClass)>, Unsupported> {
4973 let refused = || Unsupported::Assembly { inst, refused: Written::Clobber };
4974 let mut named = Vec::new();
4975 for entry in clobbers.split(',') {
4976 let entry = entry.trim().trim_matches('"');
4977 if entry.is_empty() || matches!(entry, "memory" | "cc") {
4978 continue;
4979 }
4980 let reg = aarch64::named(entry).ok_or_else(refused)?;
4981 if !named.contains(®) {
4982 named.push(reg);
4983 }
4984 }
4985 Ok(named)
4986 }
4987
4988 /// Whether the machine being lowered for is AArch64.
4989 fn on_aarch64(&self) -> bool {
4990 std::ptr::eq(self.selector.shapes, &aarch64::MACHINE)
4991 }
4992
4993 /// The register an operand is pinned to on the machine being lowered for.
4994 ///
4995 /// [`pinned`] on x86, where it is always a general purpose register. AArch64 has no constraint
4996 /// letter for one register, so there only a local register variable pins anything, and its name
4997 /// is read against [`aarch64::named`], which may put it in either file. The file comes back with
4998 /// the register because the two are numbered from nought alike, and `x8` is not `v8`.
4999 fn pinned_here(&self, operand: &AsmOperand<'_>) -> Option<(PhysReg, RegClass)> {
5000 if !self.on_aarch64() {
5001 return pinned(operand).map(|reg| (reg, self.gpr));
5002 }
5003 let name = operand.named?;
5004 aarch64::named(name.strip_prefix('%').unwrap_or(name))
5005 }
5006
5007 /// An `asm` statement whose operands are `long double` values on the x87 stack.
5008 ///
5009 /// `t` is the top of the stack and `u` is the register under it, and those two letters, or a
5010 /// number tying an input to an output in one of them, are the only places taken here. That is
5011 /// what glibc's old `<bits/mathinline.h>` writes, `fpatan` with `=t`, `0` and `u` and `st(1)`
5012 /// in the clobber list, and it is gcc-torture `execute/990413-2.c`.
5013 ///
5014 /// The group is the shape every other one in [`Self::x87`] has. The inputs are pushed from the
5015 /// deepest up, so the `t` one is pushed last and ends up on top, then the template runs, then
5016 /// the outputs are popped into their slots from the top down. That leaves the stack as empty
5017 /// as it was found only when the template popped every input it was handed and pushed every
5018 /// output it says it leaves, and gcc's rule for these statements says when that is: an input
5019 /// tied to an output or named in the clobber list is one the template pops. So a statement
5020 /// with an input it leaves behind is refused, as is one with an operand anywhere other than
5021 /// `st(0)` and `st(1)`, since nothing here would know what to do with the stack after it.
5022 fn x87_assembly(&mut self, inst: Inst) -> Result<(), Unsupported> {
5023 let data = &self.source[inst];
5024 let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
5025 let info = self.source[asm];
5026 if !self.source[info.targets].is_empty() {
5027 return Err(Unsupported::Assembly { inst, refused: Written::Goto });
5028 }
5029 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5030 let constraints = self.names.resolve(info.constraints).to_string();
5031 let results: Vec<Value> = data.results().collect();
5032 let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
5033 .ok_or_else(refused)?;
5034 let list: Vec<AsmOperand<'_>> = operands.iter().copied().collect();
5035
5036 // Where on the stack each operand is, as a depth from the top.
5037 let letters: Vec<&str> = constraints.split(',').collect();
5038 let mut depths = Vec::with_capacity(list.len());
5039 for (operand, letter) in list.iter().zip(&letters) {
5040 let value = operand.result.or(operand.value).ok_or_else(refused)?;
5041 if operand.memory || !on_x87(self.source[value].ty) {
5042 return Err(refused());
5043 }
5044 let depth = match operand.tied {
5045 Some(output) => *depths.get(output).ok_or_else(refused)?,
5046 None => match letter.trim_start_matches(['=', '+', '&']) {
5047 "t" => 0,
5048 "u" => 1,
5049 _ => return Err(refused()),
5050 },
5051 };
5052 depths.push(depth);
5053 }
5054
5055 // Which depths the clobber list says the template pops.
5056 let clobbers = self.names.resolve(info.clobbers).to_string();
5057 let mut popped = [false; 2];
5058 for entry in clobbers.split(',') {
5059 let entry = entry.trim().trim_matches('"');
5060 let entry = entry.strip_prefix('%').unwrap_or(entry);
5061 match entry {
5062 "" | "memory" | "cc" | "flags" => {}
5063 "st" | "st(0)" => popped[0] = true,
5064 "st(1)" => popped[1] = true,
5065 _ => return Err(Unsupported::Assembly { inst, refused: Written::Clobber }),
5066 }
5067 }
5068
5069 // The inputs, one per depth and from the top down with no gap, and each one popped.
5070 let mut inputs: Vec<Option<Value>> = vec![None; 2];
5071 let mut outputs: Vec<Option<Value>> = vec![None; 2];
5072 for (index, operand) in list.iter().enumerate() {
5073 let depth = depths[index];
5074 if let Some(result) = operand.result {
5075 if outputs[depth].replace(result).is_some() {
5076 return Err(refused());
5077 }
5078 }
5079 let Some(value) = operand.value else { continue };
5080 // An output written `+` is an input tied to itself.
5081 let consumed = operand.result.is_some() || operand.tied.is_some() || popped[depth];
5082 if !consumed {
5083 return Err(refused());
5084 }
5085 if inputs[depth].replace(value).is_some() {
5086 return Err(refused());
5087 }
5088 }
5089 let gapless =
5090 |held: &[Option<Value>]| held.iter().skip_while(|it| it.is_some()).all(Option::is_none);
5091 if !gapless(&inputs) || !gapless(&outputs) {
5092 return Err(refused());
5093 }
5094
5095 // The text, with an operand spelled as the register it is in.
5096 let template = self.names.resolve(info.template).to_string();
5097 let mut text = String::with_capacity(template.len());
5098 let mut chars = template.chars().peekable();
5099 while let Some(c) = chars.next() {
5100 if c != '%' {
5101 text.push(c);
5102 continue;
5103 }
5104 match chars.peek().copied() {
5105 Some('%') => {
5106 chars.next();
5107 text.push('%');
5108 }
5109 Some('=') => {
5110 chars.next();
5111 text.push_str(&inst.index().to_string());
5112 }
5113 Some(digit) if digit.is_ascii_digit() => {
5114 chars.next();
5115 if chars.peek().is_some_and(char::is_ascii_digit) {
5116 return Err(refused());
5117 }
5118 let index = digit.to_digit(10).map_or(usize::MAX, |it| it as usize);
5119 match depths.get(index).ok_or_else(refused)? {
5120 0 => text.push_str("%st"),
5121 depth => text.push_str(&format!("%st({depth})")),
5122 }
5123 }
5124 _ => return Err(refused()),
5125 }
5126 }
5127
5128 let span = self.source.span(inst);
5129 for value in inputs.iter().rev().flatten() {
5130 let from = self.x87_slot(*value);
5131 let from = self.through(from);
5132 self.x87_at("fld_t", span, from);
5133 }
5134 let symbol = self.names.intern(&text);
5135 let opcode = self.named(x86_64::TEMPLATE);
5136 let block = self.at.expect("a block is being filled");
5137 self.out.build(block, opcode).at(span).symbol(symbol).finish();
5138 for value in outputs.iter().flatten() {
5139 let into = self.x87_slot(*value);
5140 let into = self.through(into);
5141 self.x87_at("fstp_t", span, into);
5142 }
5143 Ok(())
5144 }
5145
5146 /// An `asm` statement on AArch64, which is kept as text whatever is in it.
5147 ///
5148 /// Nothing reads AArch64 assembly back into instructions yet, so every template goes the way
5149 /// one the x86 reader could not take apart goes, which is [`Self::kept`]: the text is carried
5150 /// to the listing with a hole for each operand, and the operands are the instruction's own. A
5151 /// constraint with a letter whose meaning differs between the two machines is refused first.
5152 /// See [`shared_letters`].
5153 fn spelled(&mut self, inst: Inst) -> Result<(), Unsupported> {
5154 let data = &self.source[inst];
5155 let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
5156 let info = self.source[asm];
5157 if self.jumps_from_text(inst) {
5158 return Err(Unsupported::Assembly { inst, refused: Written::Goto });
5159 }
5160 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5161 let constraints = self.names.resolve(info.constraints).to_string();
5162 if !constraints.split(',').all(shared_letters) {
5163 return Err(refused());
5164 }
5165 // `Q` is memory addressed by one register and nothing else, which is how every operand in
5166 // memory is spelled here already, so it is read as `m`. See [`shared_letters`].
5167 let constraints = letters_outside(&constraints, |c| if c == 'Q' { 'm' } else { c });
5168 let results: Vec<Value> = data.results().collect();
5169 let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
5170 .ok_or_else(refused)?;
5171 let list: Vec<AsmOperand<'_>> = operands.iter().copied().collect();
5172 let widths = vec![None; list.len()];
5173 let memory: Vec<bool> = list.iter().map(|operand| operand.memory).collect();
5174 let template = self.names.resolve(info.template).to_string();
5175 self.kept(inst, &template, &list, &widths, &memory)
5176 }
5177
5178 /// One instruction of a template, as the machine instruction it was read back into.
5179 fn instruction(
5180 &mut self,
5181 inst: Inst,
5182 line: &x86_64::Line,
5183 places: &[Place],
5184 list: &[AsmOperand<'_>],
5185 clobbered: &[PhysReg],
5186 ) -> Result<(), Unsupported> {
5187 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5188 let form = x86_64::form(line.opcode).ok_or_else(refused)?;
5189 // What the instruction reaches and what is in each of them. The description answers the
5190 // first for every opcode but one, and the pieces the template was read into answer the
5191 // second. Bytes a program wrote out itself are the one, since nothing in a number is a
5192 // register anybody could read, so the constraint letters answer both. See
5193 // [`Self::lettered`].
5194 let lettered = (line.opcode == x86_64::LITERAL).then(|| self.lettered(list));
5195 let (described, pieces) = match &lettered {
5196 Some((described, pieces)) => (described.as_slice(), pieces.as_slice()),
5197 None => (form.operands(), line.operands.as_slice()),
5198 };
5199 let mut built = Vec::with_capacity(pieces.len() + clobbered.len());
5200 for (desc, piece) in described.iter().zip(pieces) {
5201 built.push(self.placed(inst, *desc, *piece, places, list)?);
5202 }
5203 // The clobbers go in among the definitions rather than behind the reads, because an operand
5204 // vector in the machine IR is every definition and then every use and what counts them
5205 // reads that order rather than each operand's role.
5206 let defs = built.iter().take_while(|operand| operand.role.is_def()).count();
5207 let mut added = 0usize;
5208 for ® in clobbered {
5209 if described.iter().any(|desc| desc.constraint == Constraint::Fixed(reg)) {
5210 continue;
5211 }
5212 built.insert(defs, mir::Operand::write(mir::Reg::physical(reg), self.gpr));
5213 added += 1;
5214 }
5215 // A constraint tying one operand to another names it by its place in this vector, and the
5216 // clobbers were put in the middle of the vector, so everything behind them moved. The
5217 // description is written against an instruction with no clobbers in it and cannot know
5218 // that, which makes this the one place the two numberings have to be reconciled.
5219 for operand in &mut built {
5220 if let Constraint::Reuse(at) = operand.constraint {
5221 if usize::from(at) >= defs {
5222 let moved = usize::from(at) + added;
5223 operand.constraint =
5224 Constraint::Reuse(u8::try_from(moved).map_err(|_| refused())?);
5225 }
5226 }
5227 }
5228 let at = match line.at {
5229 Some(at) => Some(self.addressed(inst, at, places, list)?),
5230 None => None,
5231 };
5232
5233 let block = self.at.expect("a block is being filled");
5234 let span = self.source.span(inst);
5235 let opcode = self.named(line.opcode);
5236 let mut build = self.out.build(block, opcode).at(span);
5237 for operand in built {
5238 build = build.operand(operand);
5239 }
5240 if let Some(value) = line.imm {
5241 build = build.imm(value);
5242 }
5243 if let Some(mem) = at {
5244 build = build.mem(mem);
5245 }
5246 build.finish();
5247 Ok(())
5248 }
5249
5250 /// The registers a run of bytes reaches, taken from the constraint letters rather than from the
5251 /// description of an opcode.
5252 ///
5253 /// Every other instruction of a template has a description saying which registers it reaches
5254 /// without naming them, and [`Self::assembly`] matches the letters against that. Bytes a program
5255 /// wrote out itself have no such description and could not have one: what the instruction is, is
5256 /// a number, and nothing in a number is a register anything could read. So the letters are the
5257 /// whole of what is known, and they are enough, because a program writing an instruction this
5258 /// way has to say where its operands go for exactly the reason a program writing `cpuid` does.
5259 ///
5260 /// Each register named by a letter gets one entry for the write and one for the read, the same
5261 /// two `cpuid` has, and only the half the statement asked for: a register no output names is not
5262 /// written here and one no input names is not read. The writes come first because that is the
5263 /// order an operand vector in the machine IR is counted in. A register named by nothing is left
5264 /// out rather than given a spare one, which is the difference from `cpuid` and is right for the
5265 /// same reason: `cpuid` writes four registers whatever the program said, and what these bytes
5266 /// touch is known only from what the program said.
5267 fn lettered(&self, list: &[AsmOperand<'_>]) -> (Vec<OperandDesc>, Vec<x86_64::Piece>) {
5268 let mut named: Vec<PhysReg> = Vec::new();
5269 for operand in list {
5270 if let Some(reg) = pinned(operand) {
5271 if !named.contains(®) {
5272 named.push(reg);
5273 }
5274 }
5275 }
5276 let mut described = Vec::with_capacity(named.len() * 2);
5277 let mut pieces = Vec::with_capacity(named.len() * 2);
5278 for role in [Role::Def, Role::Use] {
5279 for ® in &named {
5280 if bound(list, reg, role).is_none() {
5281 continue;
5282 }
5283 let desc = if role.is_def() {
5284 OperandDesc::write(self.gpr)
5285 } else {
5286 OperandDesc::read(self.gpr)
5287 };
5288 described.push(desc.with(Constraint::Fixed(reg)));
5289 pieces.push(x86_64::Piece::Implicit { reg });
5290 }
5291 }
5292 (described, pieces)
5293 }
5294
5295 /// One operand of one instruction of a template, in the register the statement put it in.
5296 fn placed(
5297 &mut self,
5298 inst: Inst,
5299 desc: OperandDesc,
5300 piece: x86_64::Piece,
5301 places: &[Place],
5302 list: &[AsmOperand<'_>],
5303 ) -> Result<mir::Operand, Unsupported> {
5304 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5305 // A register the instruction reaches without its text naming it belongs to whichever of the
5306 // statement's operands a constraint letter put there, and to nobody when no letter did.
5307 // There is no width to check in that case: the operand is the register the letter named and
5308 // the instruction does what it does to it, which is what a program writing `"=a"` asked for.
5309 let (index, spelled) = match piece {
5310 x86_64::Piece::Operand { index, width, stated } => (index, Some((width, stated))),
5311 x86_64::Piece::Implicit { reg } => match bound(list, reg, desc.role) {
5312 Some(index) => (index, None),
5313 None => return self.spare(inst, desc),
5314 },
5315 // A register the template named, which belongs to one of the statement's operands when
5316 // a constraint letter put that operand there and to nobody otherwise. Asked in that
5317 // order rather than placed straight away, because `"D" (p)` with `%rdi` in the text is
5318 // the program saying one thing twice, and answering it twice would hand the allocator
5319 // one register holding two values.
5320 x86_64::Piece::Reg { reg, .. } => match bound(list, reg, desc.role) {
5321 Some(index) => (index, None),
5322 None => return self.itself(inst, desc, reg),
5323 },
5324 };
5325 let operand = list.get(index).copied().ok_or_else(refused)?;
5326 // The two halves of an operand written `+`, which arrives in one register and leaves in
5327 // another with the allocator told to make them the same one. Everything else has one of
5328 // the two and asking for the other is the refusal below.
5329 let place = places.get(index).copied().ok_or_else(refused)?;
5330 let reg = match desc.role {
5331 Role::Use => place.read,
5332 Role::Def | Role::EarlyDef => place.write,
5333 }
5334 .ok_or_else(refused)?;
5335
5336 // Read where the opcode reads and written where it writes, which is what the first half of
5337 // this asks. An output has a result and an input has a value, an output written `+` has
5338 // both because it is read before it is written, and an output a matching constraint names
5339 // is read as the input that named it. See [`read_as`].
5340 // An output with neither is read as well, and what it holds there is undefined, which
5341 // [`Self::assembly`] says why and puts a zero in a register for.
5342 let placeable = match desc.role {
5343 Role::Use => read_as(list, index).is_some() || operand.result.is_some(),
5344 Role::Def | Role::EarlyDef => operand.result.is_some(),
5345 };
5346 let ty = match (operand.result, operand.value) {
5347 (Some(result), _) => self.source[result].ty,
5348 (None, Some(value)) => self.source[value].ty,
5349 (None, None) => return Err(refused()),
5350 };
5351 let bits = held_bits(ty);
5352 if !placeable || self.class_of(ty) != desc.class {
5353 return Err(refused());
5354 }
5355 if let Some((width, stated)) = spelled {
5356 // An operand the template wrote a width on may be written by an instruction that fills
5357 // more of the register than the object in it does, and the object is then the low part
5358 // of what was written. That is what gmp asks for when it counts the low zero bits of a
5359 // limb into an `unsigned` and spells the count `%q0`: one quadword instruction writes
5360 // the whole register and the `unsigned` is the bottom of it, which is every bit of an
5361 // answer that cannot exceed sixty four anyway.
5362 //
5363 // An operand read at a width the template wrote is the other way round: the object is
5364 // in the register and the instruction looks at the bottom of it. tcc tests the low bits
5365 // of a `size_t` count with `testb $2,%b4`, and every bit that test reads is one the
5366 // object put there.
5367 //
5368 // A write of less of a register than the object fills is right in one case, which is
5369 // an instruction that reads the register it writes and an operand that arrives with
5370 // the object in it. The top of the register is then the top of the object, and the
5371 // instruction leaves it alone. tcc swaps the bytes of an `unsigned` with `xchgb
5372 // %b0,%h0` and a rotate between two of them, and the swap only ever touches the low
5373 // half.
5374 //
5375 // The two that stay refused are a read of more of a register than its type fills,
5376 // which hands an instruction bits nothing ever put there, and a write of less of one
5377 // that nothing carried the object into, which leaves the top of the object holding
5378 // whatever the register held before. An operand the template left plain is refused
5379 // either way, because what gets spelled for that one is the register at the width of
5380 // its type and no other instruction is the one written down.
5381 let carried = matches!(desc.constraint, Constraint::Reuse(_) | Constraint::Fixed(_))
5382 && read_as(list, index).is_some();
5383 // The other case is the one the machine settles by itself: a write of the low four
5384 // bytes of a register clears the four above them, so a sixty four bit object written
5385 // that way holds the thirty two bit answer and nothing else. tcc loads a word through
5386 // `movl 4(%0),%k0` into a `long` and means exactly that.
5387 let cleared = desc.class == self.gpr && width == x86_64::Width::Long && bits == 64;
5388 let widened = stated && desc.role.is_def() && width.bits() > bits;
5389 let narrowed =
5390 stated && width.bits() < bits && (!desc.role.is_def() || carried || cleared);
5391 if bits != width.bits() && !widened && !narrowed {
5392 return Err(refused());
5393 }
5394 }
5395 // An operand the program pinned is in that register and nowhere else, whatever the opcode
5396 // would have allowed it. That is the whole of what a local register variable asks for, and
5397 // it is the same shape a division already has: the allocator is told the register, puts a
5398 // move in front or behind where it has to, and leaves it out where it does not.
5399 let constraint = match pinned(&operand) {
5400 Some(reg) => Constraint::Fixed(reg),
5401 None => desc.constraint,
5402 };
5403 Ok(mir::Operand { reg, class: desc.class, role: desc.role, constraint })
5404 }
5405
5406 /// A register the template named in its own text.
5407 ///
5408 /// Not one of the statement's operands and not something the allocator handed out. The program
5409 /// wrote `%rbx` in the middle of a template and meant that register, which is what code doing
5410 /// something the constraint letters cannot say is made of: micropython saves the callee-saved
5411 /// registers into a buffer by name because the whole point of the buffer is that those exact
5412 /// registers are in it, and there is no constraint letter for `%rsp`.
5413 ///
5414 /// So it is placed as itself, fixed to the register the template named. What that buys is the
5415 /// thing gcc does not do: the register becomes part of the instruction the allocator sees, so a
5416 /// write of one is a definition it knows about and will not leave anything of the program's
5417 /// across, and a read of one is a use it will not have put something else in first. gcc copies
5418 /// the text out and a register two things believe they own is a wrong program nothing reports.
5419 /// Here the allocator is told, and a program that also named the register in its clobber list
5420 /// says the same thing twice rather than something new.
5421 fn itself(
5422 &mut self,
5423 inst: Inst,
5424 desc: OperandDesc,
5425 reg: PhysReg,
5426 ) -> Result<mir::Operand, Unsupported> {
5427 let refused = Unsupported::Assembly { inst, refused: Written::Operand };
5428 if desc.class != self.gpr {
5429 return Err(refused);
5430 }
5431 Ok(mir::Operand {
5432 reg: mir::Reg::physical(reg),
5433 class: self.gpr,
5434 role: desc.role,
5435 constraint: Constraint::Fixed(reg),
5436 })
5437 }
5438
5439 /// A register an instruction of a template uses and the statement put nothing in.
5440 ///
5441 /// A write of one is the register being destroyed, which is what a clobber list is usually
5442 /// written to say and what an instruction with more answers than the program asked for does
5443 /// anyway: `cpuid` writes all four registers whether or not the statement wanted all four. A
5444 /// register of its own is the whole of what that needs, since a value nothing reads is one the
5445 /// allocator may put anywhere and is told about so that nothing else is put there.
5446 ///
5447 /// A read of one is a register the instruction looks at and the program never filled, which
5448 /// gcc leaves as whatever happened to be there. A zero is written instead, for the reason
5449 /// [`Self::undefined`] gives: the allocator has to be given a definition before a use, and a
5450 /// zero is the one answer that reads the same on every run.
5451 fn spare(&mut self, inst: Inst, desc: OperandDesc) -> Result<mir::Operand, Unsupported> {
5452 let refused = Unsupported::Assembly { inst, refused: Written::Operand };
5453 if desc.class != self.gpr {
5454 return Err(refused);
5455 }
5456 let reg = self.out.new_vreg(desc.class);
5457 if !desc.role.is_def() {
5458 let block = self.at.expect("a block is being filled");
5459 let span = self.source.span(inst);
5460 let put = self.named("mov_ri_64");
5461 self.out.build(block, put).at(span).def(reg, desc.class).imm(0).finish();
5462 }
5463 Ok(mir::Operand { reg, class: desc.class, role: desc.role, constraint: desc.constraint })
5464 }
5465
5466 /// The address one instruction of a template reads or writes.
5467 fn addressed(
5468 &mut self,
5469 inst: Inst,
5470 at: x86_64::At,
5471 places: &[Place],
5472 list: &[AsmOperand<'_>],
5473 ) -> Result<mir::Mem, Unsupported> {
5474 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5475 let base = match at.base {
5476 None => None,
5477 Some(x86_64::Piece::Operand { index, .. }) => {
5478 // The register an address is counted from is read and never written, whatever the
5479 // instruction does to what it finds there.
5480 let reg = places.get(index).and_then(|place| place.read).ok_or_else(refused)?;
5481 Some(mir::Operand::read(reg, self.gpr))
5482 }
5483 // A register the template named, counted from as itself. See [`Self::itself`], and note
5484 // that this is the half of it every one of these templates needs: `movq %rax, 16(%rdi)`
5485 // names one register as the thing being stored and another as where to store it. An
5486 // operand a constraint letter put in that register is that operand, for the reason
5487 // [`Self::placed`] gives.
5488 Some(x86_64::Piece::Reg { reg, .. }) => match bound(list, reg, Role::Use) {
5489 Some(index) => {
5490 let reg = places.get(index).and_then(|place| place.read).ok_or_else(refused)?;
5491 Some(mir::Operand::read(reg, self.gpr))
5492 }
5493 None => Some(
5494 mir::Operand::read(mir::Reg::physical(reg), self.gpr)
5495 .with(Constraint::Fixed(reg)),
5496 ),
5497 },
5498 // An address counted from a register the instruction reaches without being told is
5499 // not something this machine has: every addressing mode is written out in the text it
5500 // is part of, so a base that got here another way is a base nothing wrote down.
5501 Some(x86_64::Piece::Implicit { .. }) => return Err(refused()),
5502 };
5503 // A distance the template wrote, or the one in an operand the template pointed at, which is
5504 // the same distance said by something that knows how big a thing is. It has to be a number
5505 // the compiler can read at translation time, since it goes in the instruction rather than
5506 // in a register, and an operand holding anything else is refused rather than put somewhere.
5507 let disp = match at.disp {
5508 x86_64::Disp::Number(disp) => disp,
5509 x86_64::Disp::Operand(index) => {
5510 let value =
5511 list.get(index).and_then(|operand| operand.value).ok_or_else(refused)?;
5512 let number = self.number(value).ok_or_else(refused)?;
5513 i32::try_from(number).map_err(|_| refused())?
5514 }
5515 };
5516 Ok(mir::Mem { base, scale: 1, disp, segment: at.segment, ..mir::Mem::default() })
5517 }
5518
5519 /// The number in that value, for one an `iconst` defined, read at the width of its own type.
5520 ///
5521 /// Signed, because the two things a template asks this for are a distance into an address and
5522 /// the number on an instruction, and both of those are signed wherever they land. A constant
5523 /// whose type is unsigned and whose top bit is set therefore reads as a negative number here,
5524 /// which is the same number and is the reading that fits in the thirty two bits an addressing
5525 /// mode has room for.
5526 fn number(&self, value: Value) -> Option<i128> {
5527 let Def::Result { inst, .. } = self.source[value].def else { return None };
5528 if self.source[inst].opcode != Opcode::IConst {
5529 return None;
5530 }
5531 let Extra::Imm(imm) = self.source[inst].extra else { return None };
5532 let bits = self.source[imm].bits();
5533 let width = self.source[value].ty.bits();
5534 if width == 0 || width > 128 {
5535 return None;
5536 }
5537 let spare = 128 - width;
5538 Some(((bits << spare) as i128) >> spare)
5539 }
5540
5541 /// A register holding a value the program has no claim on, written as a zero.
5542 ///
5543 /// Every other way of saying it costs the same instruction or needs a word the machine IR does
5544 /// not have, and a zero is the one that reads the same on every run.
5545 fn undefined(&mut self, inst: Inst, result: Value) -> Result<(), Unsupported> {
5546 let ty = self.source[result].ty;
5547 let refused = Unsupported::Assembly { inst, refused: Written::Operand };
5548 let bits = held_bits(ty);
5549 if self.class_of(ty) != self.gpr || !matches!(bits, 8 | 16 | 32 | 64) {
5550 return Err(refused);
5551 }
5552 let block = self.at.expect("a block is being filled");
5553 let span = self.source.span(inst);
5554 let reg = self.new_reg(result);
5555 let put = self.named(&format!("mov_ri_{bits}"));
5556 self.out.build(block, put).at(span).def(reg, self.gpr).imm(0).finish();
5557 Ok(())
5558 }
5559
5560 /// Whether a type is the width an address is, which is what makes a cast to or from one free.
5561 fn is_address_width(&self, ty: Type) -> bool {
5562 ty.is_ptr() || (ty.is_int() && ty.bits() == ADDRESS_BITS)
5563 }
5564
5565 /// Where a block goes, which in machine IR is on the block rather than on its terminator.
5566 ///
5567 /// That is why no rule ever names a block: a branch is selected for what it reads and the
5568 /// edges are copied across here, arguments and all. The arguments are read last, after every
5569 /// instruction of the block is written, because an argument that is a constant is
5570 /// materialized where it is first wanted and the end of the block is where an edge wants it.
5571 ///
5572 /// Which is not quite the end. A block that leaves two ways has the branch as its last
5573 /// instruction, and a block that leaves through a register has the indirect jump as its last,
5574 /// and anything appended after either is something it has already jumped past, so a constant
5575 /// materialized here would be a register the block below reads and nothing ever writes. The
5576 /// one that was there is put back on the end when that happened, which is the only reordering
5577 /// anything in this crate does and is why it is remembered before a single argument is read.
5578 fn edges(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
5579 let Some(term) = self.source.terminator(block) else { return Ok(()) };
5580 // An `asm goto` whose template has nothing in it can only fall through, since there is no
5581 // instruction in it to jump with, so the only edge the machine block gets is the first
5582 // one. The labels it names are still arms in the IR, which is what kept the passes above
5583 // from assuming anything about the way into them, and here they are blocks nothing jumps
5584 // to, the same as a label no `goto` names. One that does have instructions was refused by
5585 // [`Self::jumps_from_text`] before this.
5586 if self.source[term].opcode == Opcode::InlineAsm {
5587 let Some(call) = self.source.successors(term).next() else { return Ok(()) };
5588 let args: Vec<Value> = self.source[call.args].to_vec();
5589 let regs =
5590 args.into_iter().map(|value| self.reg_of(value)).collect::<Result<_, _>>()?;
5591 *self.out.succs_mut(out) = vec![mir::BlockCall::with(self.out_block(call.block), regs)];
5592 return Ok(());
5593 }
5594 // A call's unwind edge, which is not an edge of the machine function at all. The branch was
5595 // never written, so what the block has is the arm control takes when the call returns, and
5596 // the pad is a block with nothing in front of it that the call site table is what reaches.
5597 // See [`Self::pad`] for why that is a block the allocator can be handed.
5598 if let Some(unwound) = self.unwind_edge(term) {
5599 let arms: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
5600 let next = arms[1];
5601 let args: Vec<Value> = self.source[next.args].to_vec();
5602 let regs =
5603 args.into_iter().map(|value| self.reg_of(value)).collect::<Result<_, _>>()?;
5604 *self.out.succs_mut(out) = vec![mir::BlockCall::with(self.out_block(next.block), regs)];
5605 let call = self.source.prev_inst(unwound).and_then(|call| self.unwinding.get(&call));
5606 if let Some(&call) = call {
5607 let pad = self.out_block(arms[0].block);
5608 self.out.landings.push((call, pad));
5609 }
5610 return Ok(());
5611 }
5612 let leaves =
5613 matches!(self.source[term].opcode, Opcode::BrIf | Opcode::IndirectBr | Opcode::Switch);
5614 let branch = if leaves { self.out.terminator(out) } else { None };
5615
5616 let calls: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
5617 let mut succs = Vec::with_capacity(calls.len());
5618 for call in calls {
5619 let args: Vec<Value> = self.source[call.args].to_vec();
5620 let mut regs = Vec::with_capacity(args.len());
5621 for value in args {
5622 // The address of where the value is rather than the value, for the one type a
5623 // register holds none of. The block on the other side copies the bytes out of it
5624 // into a slot of its own, which is what makes a second edge into the same block
5625 // safe.
5626 let reg = if on_x87(self.source[value].ty) {
5627 self.x87_slot(value)
5628 } else {
5629 self.reg_of(value)?
5630 };
5631 regs.push(reg);
5632 }
5633 succs.push(mir::BlockCall::with(self.out_block(call.block), regs));
5634 }
5635 if let Some(branch) = branch {
5636 if self.out.terminator(out) != Some(branch) {
5637 self.out.remove_inst(branch);
5638 self.out.append_inst(out, branch);
5639 }
5640 }
5641 *self.out.succs_mut(out) = succs;
5642 Ok(())
5643 }
5644
5645 /// The `unwound` a branch reads, when the branch is a call's unwind edge.
5646 fn unwind_edge(&self, inst: Inst) -> Option<Inst> {
5647 let data = &self.source[inst];
5648 if data.opcode != Opcode::BrIf {
5649 return None;
5650 }
5651 let &cond = self.source[data.args].first()?;
5652 match self.source[cond].def {
5653 Def::Result { inst, .. } if self.source[inst].opcode == Opcode::Unwound => Some(inst),
5654 _ => None,
5655 }
5656 }
5657
5658 /// The exception a landing pad was entered with, as a copy out of the register the unwinder
5659 /// left it in, which is the first register a value comes back in.
5660 fn landing(&mut self, inst: Inst) -> Result<(), Unsupported> {
5661 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
5662 let held = *self.conv.int_returns.first().ok_or_else(|| self.unsupported(inst))?;
5663 let block = self.at.expect("a block is being filled");
5664 let span = self.source.span(inst);
5665 let mov = self.selector.frame.moves(self.gpr).expect("a class the target says how to move");
5666 let mov = self.named(mov.mov);
5667 let into = self.new_reg(result);
5668 self.out
5669 .build(block, mov)
5670 .at(span)
5671 .operand(mir::Operand::write(into, self.gpr))
5672 .operand(
5673 mir::Operand::read(mir::Reg::physical(held), self.gpr)
5674 .with(Constraint::Fixed(held)),
5675 )
5676 .finish();
5677 Ok(())
5678 }
5679
5680 /// Makes a landing pad a block that reads nothing from the blocks around it, and says what to
5681 /// put back once it has been filled.
5682 ///
5683 /// The pad has no machine block in front of it, because the edge into it is not one the machine
5684 /// takes: control arrives from the unwinder, with the registers the frame rules at the call put
5685 /// back. So nothing the allocator keeps in a register can reach it, and a value it reads from
5686 /// elsewhere is made again inside it. What a pad reads is the address of each object a handler
5687 /// is owed, which is a slot of the frame, the address of a name, or a constant, and each of
5688 /// those can be written a second time from nothing. Anything else is refused.
5689 ///
5690 /// The registers the rest of the function knows those values by are put back afterwards,
5691 /// which is what the answer is for: the pad's copies are its own.
5692 fn pad(&mut self, block: Block) -> Result<Vec<(Value, Option<mir::Reg>)>, Unsupported> {
5693 let mut kept = Vec::new();
5694 let first = self.source.insts(block).next();
5695 if !first.is_some_and(|inst| self.source[inst].opcode == Opcode::Landing) {
5696 return Ok(kept);
5697 }
5698 let out = self.at.expect("a block is being filled");
5699 let insts: Vec<Inst> = self.source.insts(block).collect();
5700 for inst in insts {
5701 let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
5702 for value in args {
5703 let Def::Result { inst: def, .. } = self.source[value].def else {
5704 return Err(self.unsupported(inst));
5705 };
5706 if self.source.block_of(def) == Some(block)
5707 || kept.iter().any(|&(done, _)| done == value)
5708 {
5709 continue;
5710 }
5711 match self.source[def].opcode {
5712 Opcode::IConst => {}
5713 Opcode::Alloca => {
5714 let &index =
5715 self.frame_slots.get(&value).ok_or_else(|| self.unsupported(def))?;
5716 kept.push((value, self.regs[value.index()]));
5717 let reg = self.out.new_vreg(self.gpr);
5718 self.regs[value.index()] = Some(reg);
5719 let lea = self.named(self.selector.frame.lea);
5720 let sp = mir::Reg::physical(self.conv.stack_pointer);
5721 let sp = mir::Operand::read(sp, self.gpr);
5722 let span = self.source.span(def);
5723 let made = self
5724 .out
5725 .build(out, lea)
5726 .at(span)
5727 .def(reg, self.gpr)
5728 .mem(mir::Mem::at(sp))
5729 .finish();
5730 self.stack.addresses.push((made, index));
5731 }
5732 Opcode::GlobalAddr => {
5733 kept.push((value, self.regs[value.index()]));
5734 self.regs[value.index()] = None;
5735 self.address_of(def)?;
5736 }
5737 _ => return Err(self.unsupported(def)),
5738 }
5739 }
5740 }
5741 Ok(kept)
5742 }
5743
5744 /// Whether an `asm goto` has instructions in its template, which is what it would jump with.
5745 ///
5746 /// One with an empty template is what a program writes to tell the optimizer that control may
5747 /// arrive at a label without saying how, and the torture suite has several of them. It never
5748 /// jumps, so it is written as the statement it would be without its labels and a fall through
5749 /// into its first arm. See [`Self::edges`]. One with anything in it needs the labels it names
5750 /// written into the text and an edge for each of them the allocator knows about, and that is
5751 /// still refused.
5752 fn jumps_from_text(&self, inst: Inst) -> bool {
5753 let Extra::Asm(asm) = self.source[inst].extra else { return false };
5754 let info = self.source[asm];
5755 !self.source[info.targets].is_empty()
5756 && !self.names.resolve(info.template).trim().is_empty()
5757 }
5758
5759 /// The machine IR block an IR block became.
5760 fn out_block(&self, block: Block) -> mir::Block {
5761 self.blocks[block.index()].expect("every block was created before any was filled")
5762 }
5763
5764 /// The parameters of the entry block, which are the function's arguments.
5765 ///
5766 /// They are not block parameters in the machine IR and they cannot be. A block parameter is
5767 /// given its value by a move on the edge into the block, and there is no edge into an entry
5768 /// block, so what arrives in a function is the convention's to say. [`crate::abi`] is what
5769 /// says it.
5770 ///
5771 /// The ones past the last register arrived in the caller's memory and are read out of it, and
5772 /// the loads that read them come back here so that the frame can finish them the way it
5773 /// finishes an `alloca`.
5774 fn arrive(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
5775 let params = self.source[block].params.clone();
5776 // The type of each is the block's answer and what the ABI asks of it is the signature's,
5777 // and the two lists are the same list: a parameter the classification turned into a
5778 // pointer is a pointer in the block too. A block with more parameters than the signature
5779 // names is not one the front end writes, and each of those is taken as a plain value.
5780 let asked: Vec<Abi> = self.source.signature().params.iter().map(|it| it.abi).collect();
5781 let types: Vec<Param> = params
5782 .iter()
5783 .enumerate()
5784 .map(|(index, &value)| {
5785 let abi = asked.get(index).copied().unwrap_or_default();
5786 Param { ty: self.source[value].ty, abi }
5787 })
5788 .collect();
5789 // A save area for a function that takes arguments its signature does not name, which is a
5790 // block of this function's frame on one convention and the shadow space the caller already
5791 // reserved on the other. Which of the two it is is [`varargs::Area::of`]'s answer and
5792 // [`Self::save_area`] is where the difference is spent.
5793 //
5794 // Apple's AArch64 is neither. Every argument a signature does not name is in the caller's
5795 // memory, so there is nothing to save and the list starts at the first word past the named
5796 // ones.
5797 //
5798 // A function holding `__builtin_apply_args` asks for the same area whether it is variadic
5799 // or not, because what it saves is every argument register, and the area is where the
5800 // walk that binds them says where each one goes.
5801 let variadic = self.source.signature().variadic;
5802 let in_memory = self.conv.abi.variadic == Variadic::AlwaysMemory;
5803 let applies = self.saves_arguments();
5804 let area = (variadic && !in_memory || applies).then(|| varargs::Area::of(self.conv));
5805 let arrived =
5806 abi::entry(&mut self.out, out, &types, self.conv, self.selector.abi, self.names, area)
5807 .map_err(|(index, missing)| Unsupported::Argument { index, missing })?;
5808 for (¶m, reg) in params.iter().zip(&arrived.regs) {
5809 self.regs[param.index()] = Some(*reg);
5810 }
5811 if applies {
5812 self.save_arguments(out, &arrived);
5813 }
5814 if let (true, Some(area)) = (variadic && !in_memory, area) {
5815 self.save_area(out, &arrived, area);
5816 } else if variadic {
5817 let incoming = arrived.beyond.next_multiple_of(self.conv.word);
5818 self.varargs = Some(Varargs::Pointer { incoming });
5819 }
5820 self.stack.arguments.extend(arrived.stack);
5821 Ok(())
5822 }
5823
5824 /// The prologue of a variadic function, which is every argument register it was handed written
5825 /// into the frame.
5826 ///
5827 /// Every one the signature did not name, that is. Which of those hold anything is a thing only
5828 /// the caller knew and there is nothing here to ask, so all of them are written, and the ones a
5829 /// named parameter took are not, because `va_start` sets the two offsets past them and nothing
5830 /// ever reads their slots.
5831 ///
5832 /// What that costs is up to fourteen stores in the prologue of a function that may read none of
5833 /// them, and the convention's answer to that is the count of vector registers in `%al`, which
5834 /// lets a callee skip the eight vector stores when the call passed no floats. Skipping them is a
5835 /// branch in a prologue, and a prologue is written long after this by [`crate::finish`], which
5836 /// has no blocks to branch between. So they are all written every time, which is correct and is
5837 /// what `-O0` costs. Issue #323 is the branch.
5838 ///
5839 /// A vector register is written all sixteen bytes at a time, because a `_Float128` fills one and
5840 /// a `va_arg` of a quad reads the slot back whole. gcc writes the same sixteen with the same
5841 /// instruction, which is what [`crate::varargs`] says a list has to be built out of.
5842 ///
5843 /// The address is computed once into a register rather than written as a displacement off the
5844 /// stack pointer, because a displacement into a frame is not known until after allocation and
5845 /// one `lea` costs less than a fixup list for a dozen stores. It is the same `lea` an `alloca`
5846 /// gets and [`crate::finish`] fills it in the same way.
5847 ///
5848 /// A convention that homes its register arguments has none of that. Its area is the shadow
5849 /// space the caller reserved above the return address, so there is no object to make and no
5850 /// address to work out: each store reaches into the caller's argument area the way the load of
5851 /// a parameter the registers ran out before does, which is the same waiting list and the same
5852 /// fixup. There are at most four of them and none is a vector register, since a float the
5853 /// signature does not name arrived in a general purpose register too and that is the copy the
5854 /// walk reads.
5855 fn save_area(&mut self, out: mir::Block, arrived: &abi::Arrived, area: varargs::Area) {
5856 if self.conv.shared_positions {
5857 self.varargs = Some(Varargs::Pointer { incoming: arrived.beyond });
5858 let store = self.named("mov_mr_64");
5859 for &(reg, class, at) in &arrived.spare {
5860 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
5861 let made =
5862 self.out.build(out, store).uses(reg, class).mem(mir::Mem::at(sp)).finish();
5863 self.stack.arguments.push((made, at));
5864 }
5865 return;
5866 }
5867
5868 let save = self.stack.locals.len();
5869 self.stack.locals.push(Local { size: area.size, align: varargs::VECTOR_SLOT });
5870 let took = |count: usize, float: bool| {
5871 let count = u32::try_from(count).unwrap_or(0).min(area.holds(float));
5872 area.starts_at(float) + count * area.stride(float)
5873 };
5874 let integers = took(arrived.took.0, false);
5875 let floats = took(arrived.took.1, true);
5876 self.varargs = Some(if self.conv.list == VaList::Aapcs {
5877 // Minus what is left of each half, since the two offsets count up to its top.
5878 let left = |at: u32, float: bool| {
5879 i32::try_from(at).unwrap_or(0) - i32::try_from(area.ends_at(float)).unwrap_or(0)
5880 };
5881 Varargs::Aapcs {
5882 save,
5883 incoming: arrived.beyond,
5884 integers_end: area.ends_at(false),
5885 floats_end: area.ends_at(true),
5886 integers: left(integers, false),
5887 floats: left(floats, true),
5888 }
5889 } else {
5890 Varargs::Fields { save, incoming: arrived.beyond, integers, floats }
5891 });
5892
5893 // A vector register is saved all sixteen bytes wide, as a quad is, whatever it held.
5894 let base = self.frame_address(out, save);
5895 for &(reg, class, at) in &arrived.spare {
5896 let ty =
5897 if class == self.gpr { Type::int(64) } else { Type::float(rucc_ir::Float::F128) };
5898 let head = (self.selector.abi.store)(ty).expect("a store of a whole register");
5899 let store = mir::Opcode::new(self.names.intern(head));
5900 let up = i32::try_from(at).expect("a register save area under two gigabytes");
5901 let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
5902 self.out.build(out, store).uses(reg, class).mem(mem).finish();
5903 }
5904 }
5905
5906 /// Whether the function holds a `__builtin_apply_args`, on a convention this can save the
5907 /// arguments of.
5908 ///
5909 /// Only the one that keeps the two register files apart and saves them the way a SysV list
5910 /// does, since the block is that layout with one word in front of it. On any other the call is
5911 /// refused where it stands, which is [`Self::apply_args`] finding nothing saved.
5912 fn saves_arguments(&self) -> bool {
5913 if self.conv.list != VaList::SysV || self.conv.shared_positions {
5914 return false;
5915 }
5916 let source = self.source;
5917 source
5918 .blocks()
5919 .any(|block| source.insts(block).any(|inst| source[inst].opcode == Opcode::ApplyArgs))
5920 }
5921
5922 /// The prologue of a function holding `__builtin_apply_args`, which is every argument register
5923 /// it was handed and where the arguments in memory start, written into a block of its frame.
5924 ///
5925 /// The block is the one gcc lays out on this convention, so that a program reading it the way
5926 /// gcc's manual says reads the same bytes:
5927 ///
5928 /// ```text
5929 /// 0 where the arguments that came in memory are
5930 /// 8 nothing, so that what follows is sixteen byte aligned
5931 /// 16..64 the six general purpose argument registers, a word each
5932 /// 64..192 the eight vector argument registers, sixteen bytes each
5933 /// ```
5934 ///
5935 /// Which is the register save area of a variadic function with a word and a pad in front, so
5936 /// the offsets are that area's plus sixteen. What is different is that every register is
5937 /// written and not only the ones no parameter took: the one a parameter arrived in is written
5938 /// from the register the parameter was bound to, which holds it untouched because nothing has
5939 /// run yet, and the rest from the pseudos the walk made for them.
5940 fn save_arguments(&mut self, out: mir::Block, arrived: &abi::Arrived) {
5941 let applied = self.stack.locals.len();
5942 self.stack.locals.push(Local { size: APPLY_ARGS, align: varargs::VECTOR_SLOT });
5943 self.applied = Some(applied);
5944 let base = self.frame_address(out, applied);
5945 let overflow = self.overflow(out, 0, Span::DUMMY);
5946 let head = (self.selector.abi.store)(Type::int(64)).expect("a store of an address");
5947 let store = mir::Opcode::new(self.names.intern(head));
5948 let mem = mir::Mem::at(mir::Operand::read(base, self.gpr));
5949 self.out.build(out, store).uses(overflow, self.gpr).mem(mem).finish();
5950
5951 let named = arrived.named.iter().map(|&(index, at)| {
5952 let reg = arrived.regs[index];
5953 let class = self.out.class_of(reg).unwrap_or(self.gpr);
5954 (reg, class, at)
5955 });
5956 let every: Vec<_> = named.chain(arrived.spare.iter().copied()).collect();
5957 for (reg, class, at) in every {
5958 let ty =
5959 if class == self.gpr { Type::int(64) } else { Type::float(rucc_ir::Float::F128) };
5960 let head = (self.selector.abi.store)(ty).expect("a store of a whole register");
5961 let store = mir::Opcode::new(self.names.intern(head));
5962 let up = i32::try_from(at + APPLY_REGS).expect("a block of under two gigabytes");
5963 let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
5964 self.out.build(out, store).uses(reg, class).mem(mem).finish();
5965 }
5966 }
5967
5968 /// One `__builtin_apply_args`, which is the address of the block the prologue wrote.
5969 fn apply_args(&mut self, inst: Inst) -> Result<(), Unsupported> {
5970 let Some(applied) = self.applied else { return Err(self.unsupported(inst)) };
5971 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
5972 let block = self.at.expect("a block is being filled");
5973 let reg = self.frame_address(block, applied);
5974 self.regs[result.index()] = Some(reg);
5975 Ok(())
5976 }
5977
5978 /// One `__builtin_apply`, which is a call whose arguments are every register in a block
5979 /// `__builtin_apply_args` answered and some bytes of the memory it says the arguments in
5980 /// memory were in.
5981 ///
5982 /// Built as a call of fourteen arguments, six words and eight vectors, which puts each in the
5983 /// register it came out of, and one object of the size the program gave, which is copied into
5984 /// the bottom of the outgoing area the way a structure passed by value is. The call is made as
5985 /// to a variadic function, so the count of vector registers is eight and a variadic callee
5986 /// saves all of them.
5987 ///
5988 /// What comes back is every register a value can come back in, which is two of each file, and
5989 /// they are written into a block of this function's frame whose address is the answer: the two
5990 /// words at 0 and 8 and the two vectors at 16 and 32. An eighty bit value comes back on the x87
5991 /// stack and is not in it, which is the one thing gcc's block holds that this one does not.
5992 fn apply(&mut self, inst: Inst) -> Result<(), Unsupported> {
5993 if self.conv.list != VaList::SysV || self.conv.shared_positions {
5994 return Err(self.unsupported(inst));
5995 }
5996 let values: Vec<Value> = self.source[self.source[inst].args].to_vec();
5997 let [function, saved, size] = values[..] else { return Err(self.unsupported(inst)) };
5998 let size = self.number(size).ok_or_else(|| self.unsupported(inst))?;
5999 let size = u32::try_from(size).map_err(|_| self.unsupported(inst))?;
6000 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
6001 let function = self.reg_of(function)?;
6002 let saved = self.reg_of(saved)?;
6003 let block = self.at.expect("a block is being filled");
6004 let span = self.source.span(inst);
6005
6006 let word = Type::int(64);
6007 let vector = Type::float(rucc_ir::Float::F128);
6008 let area = varargs::Area::of(self.conv);
6009 let load = |ty: Type| (self.selector.abi.load)(ty).expect("a load of a whole register");
6010 let (load_word, load_vector) = (load(word), load(vector));
6011 let mut read = |ty: Type, head: &str, class: RegClass, at: u32| {
6012 let reg = self.out.new_vreg(class);
6013 let opcode = mir::Opcode::new(self.names.intern(head));
6014 let at = i32::try_from(at).expect("a block of under two gigabytes");
6015 let mem = mir::Mem::at(mir::Operand::read(saved, self.gpr)).plus(at);
6016 self.out.build(block, opcode).at(span).def(reg, class).mem(mem).finish();
6017 abi::Passing { ty, reg, abi: Abi::Plain }
6018 };
6019 let sse = self.conv.sse_class;
6020 let gpr = self.gpr;
6021 let mut args = Vec::with_capacity(15);
6022 for (float, ty, head, class) in
6023 [(false, word, load_word, gpr), (true, vector, load_vector, sse)]
6024 {
6025 for index in 0..area.holds(float) {
6026 let at = APPLY_REGS + area.starts_at(float) + index * area.stride(float);
6027 args.push(read(ty, head, class, at));
6028 }
6029 }
6030 if size > 0 {
6031 let memory = read(word, load_word, gpr, 0);
6032 let object =
6033 Abi::ByVal { size: u64::from(size), align: 8, drains: rucc_ir::Drains::Nothing };
6034 args.push(abi::Passing { abi: object, ..memory });
6035 }
6036 let returns = [word, word, vector, vector];
6037 let what = abi::Calling {
6038 callee: abi::Callee::Through(function),
6039 args: &args,
6040 returns: &returns,
6041 variadic: true,
6042 named: args.len(),
6043 at: span,
6044 };
6045 let made = abi::call(&mut self.out, block, &what, self.conv, self.selector.abi, self.names)
6046 .map_err(|refused| Unsupported::Call { inst, refused })?;
6047 let calls = &mut self.stack.calls;
6048 *calls = Some(calls.unwrap_or(0).max(made.outgoing));
6049
6050 let back = self.stack.locals.len();
6051 self.stack.locals.push(Local { size: APPLY_BACK, align: varargs::VECTOR_SLOT });
6052 let base = self.frame_address(block, back);
6053 for ((®, ty), at) in made.results.iter().zip(returns).zip([0, 8, 16, 32]) {
6054 let class = if ty == word { gpr } else { sse };
6055 let head = (self.selector.abi.store)(ty).expect("a store of a whole register");
6056 let store = mir::Opcode::new(self.names.intern(head));
6057 let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(at);
6058 self.out.build(block, store).at(span).uses(reg, class).mem(mem).finish();
6059 }
6060 let answer = self.frame_address(block, back);
6061 self.regs[result.index()] = Some(answer);
6062 Ok(())
6063 }
6064
6065 /// The address of one of the function's stack objects, in a fresh register.
6066 ///
6067 /// Written with nothing in its displacement, because where an object is in a frame is not known
6068 /// until after allocation, and given to [`crate::finish`] to fill in the way an `alloca` is.
6069 fn frame_address(&mut self, out: mir::Block, local: usize) -> mir::Reg {
6070 self.frame_address_plus(out, local, 0)
6071 }
6072
6073 /// The address some way into a local, which the frame finishes the same way, adding where the
6074 /// local is to what is already there.
6075 fn frame_address_plus(&mut self, out: mir::Block, local: usize, plus: u32) -> mir::Reg {
6076 let reg = self.out.new_vreg(self.gpr);
6077 let lea = self.named(self.selector.frame.lea);
6078 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
6079 let plus = i32::try_from(plus).expect("an offset into a local under two gigabytes");
6080 let mem = mir::Mem::at(sp).plus(plus);
6081 let made = self.out.build(out, lea).def(reg, self.gpr).mem(mem).finish();
6082 self.stack.addresses.push((made, local));
6083 reg
6084 }
6085
6086 /// Whether an instruction is one no machine instruction is written for where it stands.
6087 ///
6088 /// Four of them, and none is a lowering decision, which is why none is a rule. A constant is
6089 /// written where a register for it is first wanted rather than where the IR put it, and every
6090 /// reader of one may have folded it into an immediate, in which case nowhere is the right
6091 /// place. A return of nothing has nothing to put anywhere: the epilogue gives the frame back
6092 /// and leaves, and it is appended to every block with no successors long after this has
6093 /// finished, so a return with a value is one instruction here and a return without one is
6094 /// none. Unless the value went back through memory, in which case there is something to put
6095 /// somewhere after all and the IR does not carry it: the address the caller handed over has
6096 /// to be in `rax` on the way out, and [`Lowering::returned`] is what writes that.
6097 ///
6098 /// An unconditional jump is the third, and there is even less of it: the edge is on the
6099 /// block, and whether the block it goes to is the next one and needs no jump at all is the
6100 /// block layout's answer rather than this one's.
6101 ///
6102 /// The fourth is a point control does not arrive at, in both of the forms the IR has for it:
6103 /// the `unreachable` terminator the front end puts at the end of a function whose body can run
6104 /// off the bottom, and the `unreachable_hint` a call to `__builtin_unreachable` becomes. What
6105 /// to write for a place nothing reaches is a question with no wrong answer, and nothing is the
6106 /// smallest one and the one gcc 16.2.0 gives at `-O0`. The terminator leaves the block with no
6107 /// successors, so the epilogue lands at the end of it the way it does on any other block that
6108 /// goes nowhere, and the function cannot fall out of its own last instruction into whatever
6109 /// the assembler puts next.
6110 fn writes_nothing(&self, inst: Inst) -> bool {
6111 let data = &self.source[inst];
6112 match data.opcode {
6113 Opcode::IConst | Opcode::Jump | Opcode::Unreachable | Opcode::UnreachableHint => true,
6114 // The question of whether a call unwound and the branch on its answer, neither of which
6115 // is an instruction. See [`Self::edges`].
6116 Opcode::Unwound => true,
6117 Opcode::BrIf => self.unwind_edge(inst).is_some(),
6118 Opcode::Return => self.source[data.args].is_empty() && self.sret().is_none(),
6119 _ => false,
6120 }
6121 }
6122
6123 /// What every instruction in one block matched, with a set of values nobody may take.
6124 ///
6125 /// Backwards, because an instruction that has been folded into a later one does not get to
6126 /// fold anything into itself: the rule that took it only reached one level down, so what is
6127 /// under it is not in the term the matcher saw and cannot be replaced.
6128 fn decide(&self, insts: &[Inst], refused: &HashSet<Value>) -> Decided {
6129 let mut found: Vec<Option<Match<Term>>> = (0..insts.len()).map(|_| None).collect();
6130 let mut plans: Vec<Option<Plan>> = vec![None; insts.len()];
6131 let mut folded: Vec<Inst> = Vec::new();
6132 for (index, &inst) in insts.iter().enumerate().rev() {
6133 if folded.contains(&inst) {
6134 continue;
6135 }
6136 if let Some((plan, matched)) = self.select(inst, refused) {
6137 folded.extend(self.folds(inst, plan));
6138 found[index] = Some(matched);
6139 plans[index] = Some(plan);
6140 }
6141 }
6142 Decided { found, plans, folded }
6143 }
6144
6145 /// A value some of its readers took and some of them did not, which is the one case folding
6146 /// buys nothing.
6147 ///
6148 /// Folding does not delete the instruction that computed a value for anybody else, so a
6149 /// reader that did not take it still needs it in a register and the instruction stays. The
6150 /// reader that did take it now does that work again. Either all of them take it, in which
6151 /// case nothing is left to read it and the instruction goes, or none of them do.
6152 ///
6153 /// The count is over the whole function rather than over the block, since a value read from
6154 /// another block is read from a register there whatever this block decides. An instruction
6155 /// built by name rather than matched, a call being the one that matters, has no plan and so
6156 /// takes nothing, which is the right answer for it as well.
6157 ///
6158 /// The count is kept only for the values this block's instructions take. It used to be a slot
6159 /// for every value in the function, cleared for every block, and on a function of thirty
6160 /// thousand blocks and a hundred and seventy thousand values that clearing was four percent of
6161 /// an optimized compile.
6162 fn left_alive(&self, insts: &[Inst], plans: &[Option<Plan>]) -> Option<Value> {
6163 let mut taken: HashMap<Value, u32> = HashMap::new();
6164 for (&inst, plan) in insts.iter().zip(plans) {
6165 let Some(plan) = plan else { continue };
6166 let args = &self.source[self.source[inst].args];
6167 for (index, &arg) in args.iter().take(MAX_ARGS).enumerate() {
6168 if plan[index] == Shown::Expand {
6169 *taken.entry(arg).or_default() += 1;
6170 }
6171 }
6172 }
6173 for (&inst, plan) in insts.iter().zip(plans) {
6174 let Some(plan) = plan else { continue };
6175 let args = &self.source[self.source[inst].args];
6176 for (index, &arg) in args.iter().take(MAX_ARGS).enumerate() {
6177 if plan[index] == Shown::Expand && taken[&arg] < self.uses[arg.index()] {
6178 return Some(arg);
6179 }
6180 }
6181 }
6182 None
6183 }
6184
6185 /// The rule that fires on an instruction, and what it bound.
6186 ///
6187 /// The plans are tried in order and the first that matches wins, which is the maximal munch
6188 /// `spec/10-backend.md` asks for: a plan that offers more to the matcher is tried before one
6189 /// that offers less.
6190 fn select(&self, inst: Inst, refused: &HashSet<Value>) -> Option<(Plan, Match<Term>)> {
6191 for plan in self.plans(inst, refused) {
6192 let terms = Terms::new(self.source, inst, plan);
6193 if let Some(matched) = self.selector.table.find(&terms, Term::Root) {
6194 return Some((plan, matched));
6195 }
6196 }
6197 None
6198 }
6199
6200 /// Every way this instruction can be shown to the matcher, most offered first.
6201 fn plans(&self, inst: Inst, refused: &HashSet<Value>) -> Vec<Plan> {
6202 let args = &self.source[self.source[inst].args];
6203 let mut plans = vec![PLAIN];
6204 for (index, &arg) in args.iter().enumerate().take(MAX_ARGS) {
6205 let mut ways = Vec::new();
6206 if self.foldable(inst, arg, refused) {
6207 ways.push(Shown::Expand);
6208 }
6209 if Terms::new(self.source, inst, PLAIN).constant(arg).is_some() {
6210 ways.push(Shown::Const);
6211 }
6212 ways.push(Shown::Reg);
6213 plans = plans
6214 .into_iter()
6215 .flat_map(|plan| {
6216 ways.iter().map(move |&way| {
6217 let mut next = plan;
6218 next[index] = way;
6219 next
6220 })
6221 })
6222 .collect();
6223 }
6224 plans
6225 }
6226
6227 /// Whether an operand may be shown as the instruction that computed it.
6228 ///
6229 /// It has to be in the same block, because a rule that folds one instruction into another
6230 /// moves the work to where the second one is. It has to be something rather than a block
6231 /// parameter, and not a constant, which is shown as a constant instead. And it has to be a
6232 /// value [`Lowering::left_alive`] has not put back, which is how the one reader at a time
6233 /// question is asked here: this says yes to a value with any number of readers, and a value
6234 /// only some of them could take is refused after the fact and asked again.
6235 ///
6236 /// A value with several readers used to be refused outright, on the reasoning that folding
6237 /// does not delete the instruction for anybody else. That reasoning is about the set of
6238 /// readers and was being applied to one reader at a time, which is stricter than it needs to
6239 /// be: when every reader takes it there is nobody left to read it and the instruction goes.
6240 /// An address a store and a load share is the shape that matters, since a memory operand has
6241 /// room for the whole of it and both readers have a memory operand.
6242 fn foldable(&self, into: Inst, value: Value, refused: &HashSet<Value>) -> bool {
6243 let Def::Result { inst, .. } = self.source[value].def else { return false };
6244 if self.source[inst].opcode == Opcode::IConst || refused.contains(&value) {
6245 return false;
6246 }
6247 self.source.block_of(inst).is_some()
6248 && self.source.block_of(inst) == self.source.block_of(into)
6249 }
6250
6251 /// The instructions a match folded into the one it matched.
6252 ///
6253 /// The plan is what says this, not the bindings: a binding is a register or a number either
6254 /// way, and an operand shown as the instruction that computed it is one no rule could have
6255 /// matched without taking that instruction, because the plan offered the matcher nothing
6256 /// else to call it.
6257 fn folds(&self, inst: Inst, plan: Plan) -> Vec<Inst> {
6258 let args = &self.source[self.source[inst].args];
6259 args.iter()
6260 .take(MAX_ARGS)
6261 .enumerate()
6262 .filter(|&(index, _)| plan[index] == Shown::Expand)
6263 .filter_map(|(_, &arg)| match self.source[arg].def {
6264 Def::Result { inst, .. } => Some(inst),
6265 Def::Param { .. } => None,
6266 })
6267 .collect()
6268 }
6269
6270 /// What the IR instruction said about itself that the machine instruction has to keep saying.
6271 ///
6272 /// One flag today. `volatile` says the access happens exactly once and is never moved or
6273 /// merged, and nothing below here can work that out again: a `volatile` load and an ordinary
6274 /// one are the same instruction over the same address, so a pass that puts two accesses
6275 /// together would put these together too. Carried rather than checked here, because the pass
6276 /// that has to refuse is a long way down and this is the last place the answer is known.
6277 ///
6278 /// The instructions this compiler writes for itself get nothing, which is the right answer
6279 /// for all of them: a prologue, a spill and the moves around a call were asked for by the
6280 /// machine rather than by the program.
6281 ///
6282 /// Every access the flag is legal on carries it: the loads and the stores a rule matched,
6283 /// the two ends of a `long double` copy that are the program's own memory, and the compare
6284 /// and exchange and the read modify write. An `asm` statement does not, and it is the one
6285 /// exception on purpose. What the flag says there is that the statement stays even when
6286 /// nothing reads what it wrote, which is a different sentence about a different thing, and
6287 /// every `asm` is already fixed where it stands whether the word was written or not.
6288 fn carried(&self, inst: Inst) -> mir::Flags {
6289 if self.source[inst].flags.contains(Flags::VOLATILE) {
6290 mir::Flags::VOLATILE
6291 } else {
6292 mir::Flags::NONE
6293 }
6294 }
6295
6296 /// Build the machine instructions a match calls for.
6297 fn emit(&mut self, inst: Inst, matched: &Match<Term>) -> Result<(), Unsupported> {
6298 let rule: &Rule = self.selector.table.rule(matched);
6299 self.build(inst, rule.replacement, 0, &matched.bindings, true).map(|_| ())
6300 }
6301
6302 /// Build the machine term that starts at `at`, and give back the position after it and the
6303 /// register it wrote, if it wrote one.
6304 ///
6305 /// The outermost term computes what the IR instruction does, so what it writes is the
6306 /// register of the instruction's result. A term inside another is a step on the way and
6307 /// writes a register of its own, which the term around it then reads. Its operands are read
6308 /// before it is built and it is built before the term around it, so the instructions come
6309 /// out in the order the values are needed.
6310 fn build(
6311 &mut self,
6312 inst: Inst,
6313 pieces: &'static [Piece],
6314 at: usize,
6315 bindings: &[Term],
6316 outermost: bool,
6317 ) -> Result<(usize, Option<mir::Reg>), Unsupported> {
6318 let Some(Piece::App { head, arity }) = pieces.get(at) else {
6319 return Err(self.unsupported(inst));
6320 };
6321 let opcode =
6322 head.strip_prefix(self.selector.prefix()).ok_or_else(|| self.unsupported(inst))?;
6323 let descs = self.selector.operands(opcode).ok_or_else(|| self.unsupported(inst))?;
6324
6325 let mut read = Read::default();
6326 let mut at = at + 1;
6327 for _ in 0..*arity {
6328 at = self.read(inst, pieces, at, bindings, &mut read)?;
6329 }
6330
6331 let writes = descs.iter().take_while(|desc| desc.role.is_def()).count();
6332 if descs.len() - writes != read.regs.len() {
6333 return Err(self.unsupported(inst));
6334 }
6335
6336 // The first thing the instruction writes is what it computes, and any others are
6337 // registers the machine destroys on the way, which are fresh because nothing else is in
6338 // them and nothing reads them. An instruction that writes nothing at all is one whose
6339 // whole purpose is its effect, which is what a store is, and there is no result to put
6340 // anywhere.
6341 let mut regs = Vec::new();
6342 if writes > 0 {
6343 // A term inside another computes a step rather than the result, into a register only
6344 // the term around it reads.
6345 let first = match outermost {
6346 true => {
6347 let result =
6348 self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
6349 self.new_reg(result)
6350 }
6351 false => self.out.new_vreg(descs[0].class),
6352 };
6353 regs.push(first);
6354 // The rest are the registers the machine destroys on the way, and the class each is in
6355 // is the one the instruction's description gives it rather than a guess, so that an
6356 // instruction that wrecks a register in the other file says so.
6357 regs.extend(descs[1..writes].iter().map(|desc| self.out.new_vreg(desc.class)));
6358 } else if !outermost || self.source[inst].first_result.is_some() {
6359 // A rule that throws away a value the IR gave a name to would leave every reader of
6360 // that name with nothing to read, so it is a rule this and the target disagree about.
6361 // So is a term inside another that writes nothing for the one around it to read.
6362 return Err(self.unsupported(inst));
6363 }
6364 let written = regs.first().copied();
6365 regs.extend(read.regs.iter().copied());
6366
6367 let block = self.at.expect("a block is being filled");
6368 let opcode = mir::Opcode::new(self.names.intern(head));
6369 let (span, flags) = (self.source.span(inst), self.carried(inst));
6370 let mut build = self.out.build(block, opcode).at(span).flags(flags);
6371 for (desc, reg) in descs.iter().zip(regs) {
6372 let operand = mir::Operand {
6373 reg,
6374 class: desc.class,
6375 role: desc.role,
6376 constraint: desc.constraint,
6377 };
6378 build = build.operand(operand);
6379 }
6380 if let Some(mem) = read.mem {
6381 build = build.mem(mem);
6382 }
6383 if let Some(imm) = read.imm {
6384 build = build.imm(imm);
6385 }
6386 build.finish();
6387 Ok((at, written))
6388 }
6389
6390 /// Read one argument of a replacement, which is a register, a number, an address or another
6391 /// machine term.
6392 ///
6393 /// Gives back the position after it, because a replacement is flat and an address or a term
6394 /// takes arguments of its own. A machine term is built on the spot, and what is read is the
6395 /// register it wrote.
6396 fn read(
6397 &mut self,
6398 inst: Inst,
6399 pieces: &'static [Piece],
6400 at: usize,
6401 bindings: &[Term],
6402 out: &mut Read,
6403 ) -> Result<usize, Unsupported> {
6404 match pieces.get(at) {
6405 Some(Piece::Int(value)) => {
6406 out.imm = i64::try_from(*value).ok();
6407 Ok(at + 1)
6408 }
6409 // A number the rule worked out of the ones it matched rather than one it wrote down,
6410 // which is an immediate once it has been worked out and is read here as one. It gives
6411 // nothing back when a binding it reads is a register, and a replacement that cannot be
6412 // built is a rule this file and the matcher disagree about, which is what `unsupported`
6413 // is for.
6414 Some(Piece::Computed { work, .. }) => {
6415 let matched: Vec<Option<i128>> = bindings
6416 .iter()
6417 .map(|term| match *term {
6418 Term::Num(value) => Some(value),
6419 _ => None,
6420 })
6421 .collect();
6422 let number = work(&matched).ok_or_else(|| self.unsupported(inst))?;
6423 out.imm = i64::try_from(number).ok();
6424 Ok(at + 1)
6425 }
6426 Some(Piece::Var { index, .. }) => {
6427 match bindings.get(*index) {
6428 Some(&Term::Reg(value)) => {
6429 let reg = self.reg_of(value)?;
6430 out.regs.push(reg);
6431 }
6432 Some(&Term::Num(value)) => out.imm = i64::try_from(value).ok(),
6433 // A pattern binds a register or a number and nothing else, so this is a
6434 // rule the matcher and this file disagree about.
6435 _ => return Err(self.unsupported(inst)),
6436 }
6437 Ok(at + 1)
6438 }
6439 Some(Piece::App { head, .. }) if (self.selector.address)(head).is_none() => {
6440 let (next, reg) = self.build(inst, pieces, at, bindings, false)?;
6441 out.regs.push(reg.ok_or_else(|| self.unsupported(inst))?);
6442 Ok(next)
6443 }
6444 Some(Piece::App { head, arity }) => {
6445 let kind = (self.selector.address)(head).ok_or_else(|| self.unsupported(inst))?;
6446 let mut inner = Read::default();
6447 let mut next = at + 1;
6448 for _ in 0..*arity {
6449 next = self.read(inst, pieces, next, bindings, &mut inner)?;
6450 }
6451 let mem = address(kind, &inner, self.gpr).ok_or_else(|| self.unsupported(inst))?;
6452 out.mem = Some(mem);
6453 Ok(next)
6454 }
6455 None => Err(self.unsupported(inst)),
6456 }
6457 }
6458
6459 /// The register a value is in, materializing it if it is a constant that has not been put in
6460 /// one yet.
6461 ///
6462 /// A constant is written where it is wanted rather than where the IR defined it, and where it
6463 /// is wanted is a block that need not be the one the IR defined it in. So the register holding
6464 /// one is only good inside the block it was written into, and a second block that wants the
6465 /// same constant gets its own. Anything else is a register read where nothing wrote it: the
6466 /// IR guarantees a definition dominates its uses, and this moved the definition.
6467 ///
6468 /// Writing the number again is also the right answer and not merely the safe one. It is one
6469 /// instruction that reads nothing, which is cheaper than holding a register live across a
6470 /// branch for it, and it is what a rematerializing allocator would do with the value anyway.
6471 fn reg_of(&mut self, value: Value) -> Result<mir::Reg, Unsupported> {
6472 let constant = match self.source[value].def {
6473 Def::Result { inst, .. } => {
6474 (self.source[inst].opcode == Opcode::IConst).then_some(inst)
6475 }
6476 Def::Param { .. } => None,
6477 };
6478 let here = self.at.expect("a block is being filled");
6479 if let Some(reg) = self.regs[value.index()] {
6480 if constant.is_none() || self.written[value.index()] == Some(here) {
6481 return Ok(reg);
6482 }
6483 }
6484 if let Some(inst) = constant {
6485 // Cleared so that the register the constant is written into is a new one rather than
6486 // the one the block above wrote, which is still being read up there.
6487 self.regs[value.index()] = None;
6488 // Nothing is refused here. A constant is written on its own, out of the loop over the
6489 // block, and the operands of the rule that writes one are the number and nothing else.
6490 let matched = self
6491 .select(inst, &HashSet::new())
6492 .map(|(_, matched)| matched)
6493 .ok_or_else(|| self.unsupported(inst))?;
6494 self.emit(inst, &matched)?;
6495 // The same mark the loop over the instructions makes, and it has to be made here as
6496 // well because this is the only place a constant is ever selected: the loop skips one
6497 // where the IR wrote it, so a rule that lowers a constant fires from nowhere else and
6498 // would be reported as a rule nothing reaches.
6499 self.fired.mark(matched.rule);
6500 self.written[value.index()] = Some(here);
6501 return Ok(self.regs[value.index()].expect("a constant is written into a register"));
6502 }
6503 Ok(self.new_reg(value))
6504 }
6505
6506 /// Which register file a value of that type lives in.
6507 ///
6508 /// The vector one for the two float widths the machine has scalar instructions for and for the
6509 /// one it only moves, and the general purpose one for everything else. An eighty bit `long
6510 /// double` is in neither, and it is here rather than in the vector class on purpose: it would
6511 /// be put in a register that cannot hold it, and there is no rule that names one, so the
6512 /// instruction computing it is reported. The wrong class would make that a wrong program
6513 /// instead of a refused one.
6514 ///
6515 /// A hundred and twenty eight bit float is in the vector class and fits it exactly, which is
6516 /// the difference. Nothing computes in it, so every arithmetic on one is still reported, and
6517 /// what the class buys is the moves: a register that holds the whole value is a register a
6518 /// spill, a reload and a copy are each one instruction for.
6519 fn class_of(&self, ty: Type) -> RegClass {
6520 if crate::term::in_vector_file(ty) { self.conv.sse_class } else { self.gpr }
6521 }
6522
6523 /// A fresh register for a value, which is what the instruction computing it writes.
6524 ///
6525 /// Any declaration the value is a value of comes with it. Here rather than once at the end over
6526 /// the whole map, because a constant is written again in every block that wants one and the map
6527 /// only remembers the last of those registers, and a local held in a constant is a local that
6528 /// would otherwise be findable in one block of the function and nowhere else.
6529 fn new_reg(&mut self, value: Value) -> mir::Reg {
6530 if let Some(reg) = self.regs[value.index()] {
6531 return reg;
6532 }
6533 let reg = self.out.new_vreg(self.class_of(self.source[value].ty));
6534 self.regs[value.index()] = Some(reg);
6535 let source = self.source;
6536 for decl in source.value_decls(value) {
6537 self.out.named.push((decl, reg));
6538 }
6539 reg
6540 }
6541
6542 fn unsupported(&self, inst: Inst) -> Unsupported {
6543 let data = &self.source[inst];
6544 Unsupported::Inst {
6545 inst,
6546 term: Terms::new(self.source, inst, PLAIN).name(inst),
6547 opcode: data.opcode,
6548 ty: data.first_result.map(|result| self.source[result].ty),
6549 }
6550 }
6551}
6552
6553/// What the arguments of one replacement came to.
6554#[derive(Debug, Default)]
6555struct Read {
6556 regs: Vec<mir::Reg>,
6557 imm: Option<i64>,
6558 mem: Option<mir::Mem>,
6559}
6560
6561/// The addressing mode an address constructor's arguments make.
6562///
6563/// One arm per constructor rather than a question asked of the kind, because what the arguments
6564/// mean is the whole of what tells the four apart: the same register is a base in one and an
6565/// index in another, and the same constant is a scale in one and a displacement in another.
6566fn address(kind: Address, read: &Read, gpr: RegClass) -> Option<mir::Mem> {
6567 let mut regs = read.regs.iter().copied().map(|reg| mir::Operand::read(reg, gpr));
6568 match kind {
6569 Address::BaseIndexScale => {
6570 let base = regs.next()?;
6571 let index = regs.next()?;
6572 Some(mir::Mem::at(base).indexed(index, u8::try_from(read.imm?).ok()?))
6573 }
6574 Address::IndexScale => Some(mir::Mem {
6575 base: None,
6576 index: Some(regs.next()?),
6577 scale: u8::try_from(read.imm?).ok()?,
6578 disp: 0,
6579 symbol: None,
6580 block: None,
6581 table: None,
6582 reach: mir::Reach::Itself,
6583 segment: None,
6584 }),
6585 Address::Base => Some(mir::Mem::at(regs.next()?)),
6586 // The rule that writes this has a guard saying the constant fits, so a displacement that
6587 // does not is a rule and a target that disagree rather than a program this cannot compile.
6588 Address::BaseOffset => {
6589 Some(mir::Mem { disp: i32::try_from(read.imm?).ok()?, ..mir::Mem::at(regs.next()?) })
6590 }
6591 }
6592}
6593
6594#[cfg(test)]
6595mod tests {
6596 use rucc_ir::{
6597 AsmInfo, Builder, CallInfo, Flags, InstData, MemInfo, MemOrder, Restrict, Signature, Type,
6598 };
6599 use rucc_regalloc::assign::Env;
6600 use rucc_target::x86_64::{FRAME, REGS, SYSV};
6601
6602 use super::*;
6603 use crate::finish::{Convention, finish};
6604 use crate::frame::{Frame, Incoming, Layout};
6605 use crate::select::x86_64::SELECTOR;
6606
6607 /// A function of as many 64 bit parameters as the test wants, and the block they are in.
6608 fn blank(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
6609 let mut names = Interner::new();
6610 let mut func = Func::new(names.intern("f"), Signature::new());
6611 let block = func.create_block();
6612 let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
6613 (names, func, block, values)
6614 }
6615
6616 /// An ordinary access: not atomic, and aligned enough that nothing here has an opinion.
6617 /// Neither field reaches selection, which is the point of saying it once here.
6618 fn plain() -> MemInfo {
6619 MemInfo {
6620 size: 0,
6621 align: 1,
6622 order: MemOrder::NotAtomic,
6623 tbaa: None,
6624 owns: 0,
6625 restrict: Restrict::NONE,
6626 }
6627 }
6628
6629 /// What the allocator is given: every integer register the convention offers except two, held
6630 /// back so that a move on an edge has somewhere to break a cycle and a spilled value has
6631 /// somewhere to be read into. Which two does not matter, and holding back the last two the
6632 /// convention would reach for leaves every expectation below unchanged.
6633 fn env() -> Env {
6634 const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
6635 let order: Vec<PhysReg> =
6636 SYSV.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
6637 Env::new().with(x86_64::GPR, &order, &SCRATCH)
6638 }
6639
6640 /// The machine IR text a function lowers to.
6641 fn lower(names: &mut Interner, source: &Func) -> String {
6642 let out = func(source, names, &SELECTOR, &SYSV, &Elsewhere::default())
6643 .expect("every instruction has a rule");
6644 mir::print_func(&out.func, names, ®S)
6645 }
6646
6647 /// The same function lowered for AArch64, which is the first thing this file writes for a
6648 /// machine other than x86-64. Nothing past selection runs here, so what is checked is that the
6649 /// arguments, the rule and the return all come out named for the machine that was asked for.
6650 #[test]
6651 fn an_addition_lowers_for_aarch64_with_its_own_names() {
6652 let i32 = Type::int(32);
6653 let (mut names, mut func, block, args) = blank(&[i32, i32]);
6654 let mut build = Builder::new(&mut func, block);
6655 let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
6656 build.ret(&[sum]);
6657
6658 let conv = &aarch64::AAPCS64;
6659 let selector = &crate::select::aarch64::SELECTOR;
6660 let out = super::func(&func, &mut names, selector, conv, &Elsewhere::default())
6661 .expect("an addition and a return have AArch64 rules");
6662 let text = mir::print_func(&out.func, &names, &aarch64::REGS);
6663 assert!(!text.contains("x64."), "{text}");
6664 assert!(text.contains("= a64.arg_val_32"), "{text}");
6665 assert!(text.contains("= a64.add_rr_32 %0, %1"), "{text}");
6666 assert!(text.contains("a64.ret_val_32 %2"), "{text}");
6667 }
6668
6669 /// Lowers one function for AArch64 and prints it, or says why it could not.
6670 fn lower_a64(names: &mut Interner, func: &Func) -> Result<String, String> {
6671 let conv = &aarch64::AAPCS64;
6672 let selector = &crate::select::aarch64::SELECTOR;
6673 let out = super::func(func, names, selector, conv, &Elsewhere::default())
6674 .map_err(|why| why.to_string())?;
6675 Ok(mir::print_func(&out.func, names, &aarch64::REGS))
6676 }
6677
6678 /// Nothing reads AArch64 assembly back into instructions, so every template there is kept as
6679 /// its text. The operands are the instruction's own, with the output first and the inputs
6680 /// last, a hole in the text asks for the `w` or the `x` name of one, and a vector register the
6681 /// clobber list names is written by it as well as every register a call may leave anything in.
6682 #[test]
6683 fn a_template_on_aarch64_is_kept_as_text_with_its_operands_in_registers() {
6684 let (i32, i64) = (Type::int(32), Type::int(64));
6685 let (mut names, mut source, block, args) = blank(&[i32, i64]);
6686 let out = clobbering(
6687 &mut source,
6688 block,
6689 &mut names,
6690 "add %w0, %w1, #1\n\tstr %2, [sp]",
6691 "=r,r,r",
6692 "d8",
6693 &[args[0], args[1]],
6694 &[i32],
6695 );
6696 let produced = source[out].results().next().expect("one result");
6697 Builder::new(&mut source, block).ret(&[produced]);
6698
6699 // Forty one registers between the output and the inputs: `x0` to `x15`, the sixteen vector
6700 // registers a call does not keep, and `v8`, which is the one the program named.
6701 let text = lower_a64(&mut names, &source).expect("kept as text");
6702 assert!(text.contains("%2:gpr, early $x0, early $x1,"), "{text}");
6703 assert!(text.contains(
6704 "early $v31, early $v8 = a64.template %0, %1, \
6705 @add \u{1}r0w\u{2}, \u{1}r42w\u{2}, #1\n\tstr \u{1}r43x\u{2}, [sp]\n"
6706 ));
6707 }
6708
6709 /// A letter that means one thing on x86 and another on AArch64 is refused there rather than
6710 /// read as x86. `a` to `d` and `S` name one register each on x86 and nothing on AArch64.
6711 #[test]
6712 fn a_constraint_letter_the_two_machines_disagree_about_is_refused_on_aarch64() {
6713 let i64 = Type::int(64);
6714 for constraints in ["=a,r", "=r,S", "=r,c"] {
6715 let (mut names, mut source, block, args) = blank(&[i64]);
6716 let out = clobbering(
6717 &mut source,
6718 block,
6719 &mut names,
6720 "mov %0, %1",
6721 constraints,
6722 "",
6723 &[args[0]],
6724 &[i64],
6725 );
6726 let produced = source[out].results().next().expect("one result");
6727 Builder::new(&mut source, block).ret(&[produced]);
6728 let refused = lower_a64(&mut names, &source).expect_err(constraints);
6729 assert!(refused.contains("has an operand this cannot place"), "{refused}");
6730 }
6731 }
6732
6733 /// `Q` on AArch64 is memory addressed by one register, which is `[x3]` and is how an operand in
6734 /// memory is spelled there already.
6735 #[test]
6736 fn a_q_operand_on_aarch64_is_its_address_in_brackets() {
6737 let (i64, ptr) = (Type::int(64), Type::PTR);
6738 let (mut names, mut source, block, args) = blank(&[ptr]);
6739 let out =
6740 clobbering(&mut source, block, &mut names, "ldr %x0, %1", "=r,Q", "", &args, &[i64]);
6741 let produced = source[out].results().next().expect("one result");
6742 Builder::new(&mut source, block).ret(&[produced]);
6743 let text = lower_a64(&mut names, &source).expect("kept as text");
6744 assert!(text.contains("@ldr \u{1}r0x\u{2}, [\u{1}r"), "{text}");
6745 }
6746
6747 /// `w` on AArch64 is a vector register, named `v` with no modifier the way gcc names it and by
6748 /// its scalar view with one. An integer asked for in one is refused, since it would need a move
6749 /// into that file first.
6750 #[test]
6751 fn a_vector_operand_on_aarch64_is_in_the_vector_file() {
6752 let f64 = Type::float(rucc_ir::Float::F64);
6753 let (mut names, mut source, block, args) = blank(&[f64, f64]);
6754 let out = clobbering(
6755 &mut source,
6756 block,
6757 &mut names,
6758 "fadd %d0, %d1, %d2\n\tmov %0.16b, %0.16b",
6759 "=w,w,w",
6760 "",
6761 &[args[0], args[1]],
6762 &[f64],
6763 );
6764 let produced = source[out].results().next().expect("one result");
6765 Builder::new(&mut source, block).ret(&[produced]);
6766 let text = lower_a64(&mut names, &source).expect("kept as text");
6767 assert!(text.contains("%2:fpr, early $x0,"), "{text}");
6768 assert!(text.contains("@fadd \u{1}r0d\u{2}, \u{1}r"), "{text}");
6769 assert!(text.contains("\n\tmov \u{1}r0v\u{2}.16b, \u{1}r0v\u{2}.16b\n"), "{text}");
6770
6771 let i64 = Type::int(64);
6772 let (mut names, mut source, block, args) = blank(&[i64]);
6773 let out =
6774 clobbering(&mut source, block, &mut names, "fmov %d0, %d1", "=w,w", "", &args, &[i64]);
6775 let produced = source[out].results().next().expect("one result");
6776 Builder::new(&mut source, block).ret(&[produced]);
6777 assert!(lower_a64(&mut names, &source).is_err());
6778 }
6779
6780 #[test]
6781 fn an_addition_of_two_registers_is_one_instruction() {
6782 let i32 = Type::int(32);
6783 let (mut names, mut func, block, args) = blank(&[i32, i32]);
6784 let mut build = Builder::new(&mut func, block);
6785 build.binary(Opcode::Add, args[0], args[1], Flags::default());
6786
6787 assert_eq!(
6788 lower(&mut names, &func),
6789 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
6790 %1:gpr($rsi) = x64.arg_val_32\n %2:gpr(reuse 1) = x64.add_rr_32 %0, %1\n}\n"
6791 );
6792 }
6793
6794 #[test]
6795 fn a_constant_operand_becomes_an_immediate() {
6796 let i32 = Type::int(32);
6797 let (mut names, mut func, block, args) = blank(&[i32]);
6798 let mut build = Builder::new(&mut func, block);
6799 let seven = build.iconst(i32, 7);
6800 build.binary(Opcode::Add, args[0], seven, Flags::default());
6801
6802 // The constant is in the instruction and nothing was written to hold it, which is what
6803 // materializing one where a register for it is wanted buys.
6804 assert_eq!(
6805 lower(&mut names, &func),
6806 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
6807 %1:gpr(reuse 1) = x64.add_ri_32 %0, 7\n}\n"
6808 );
6809 }
6810
6811 #[test]
6812 fn a_constant_too_wide_for_an_immediate_goes_into_a_register() {
6813 let i64 = Type::int(64);
6814 let (mut names, mut func, block, args) = blank(&[i64]);
6815 let mut build = Builder::new(&mut func, block);
6816 let big = build.iconst(i64, i128::from(i32::MAX) + 1);
6817 build.binary(Opcode::Add, args[0], big, Flags::default());
6818
6819 // Nobody wrote this fallback down. The rule that takes an immediate has a guard that
6820 // turns a number this wide down, so it does not fire, and the next way of showing the
6821 // operand puts it in a register.
6822 assert_eq!(
6823 lower(&mut names, &func),
6824 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
6825 %1:gpr = x64.mov_ri_64 2147483648\n %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n}\n"
6826 );
6827 }
6828
6829 #[test]
6830 fn an_index_calculation_folds_into_an_address() {
6831 let i64 = Type::int(64);
6832 let (mut names, mut func, block, args) = blank(&[i64, i64]);
6833 let mut build = Builder::new(&mut func, block);
6834 let four = build.iconst(i64, 4);
6835 let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
6836 build.binary(Opcode::Add, args[0], scaled, Flags::default());
6837
6838 // Three IR instructions and one machine instruction. The multiply is gone because the
6839 // rule that matched reached down and took it.
6840 assert_eq!(
6841 lower(&mut names, &func),
6842 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
6843 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr = x64.lea_64 [%0 + %1*4]\n}\n"
6844 );
6845 }
6846
6847 #[test]
6848 fn an_instruction_every_reader_can_take_is_folded_into_all_of_them() {
6849 let i64 = Type::int(64);
6850 let (mut names, mut func, block, args) = blank(&[i64, i64]);
6851 let mut build = Builder::new(&mut func, block);
6852 let four = build.iconst(i64, 4);
6853 let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
6854 let first = build.binary(Opcode::Add, args[0], scaled, Flags::default());
6855 build.binary(Opcode::Add, first, scaled, Flags::default());
6856
6857 // Both readers have room for a scaled index, so both of them take it and nothing is left
6858 // to read the multiply. Three IR instructions become two machine ones, where refusing to
6859 // fold into either reader would have left three.
6860 assert_eq!(
6861 lower(&mut names, &func),
6862 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
6863 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr = x64.lea_64 [%0 + %1*4]\n \
6864 %3:gpr = x64.lea_64 [%2 + %1*4]\n}\n"
6865 );
6866 }
6867
6868 #[test]
6869 fn an_instruction_one_of_its_readers_cannot_take_is_folded_into_none_of_them() {
6870 let i64 = Type::int(64);
6871 let (mut names, mut func, block, args) = blank(&[i64, i64]);
6872 let mut build = Builder::new(&mut func, block);
6873 let four = build.iconst(i64, 4);
6874 let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
6875 build.binary(Opcode::Add, args[0], scaled, Flags::default());
6876 build.store(scaled, args[0], plain(), Flags::default());
6877
6878 // The addition has room for the multiply and the store does not: what a store writes is
6879 // a register, and no rule reaches through it. Folding into the addition alone would
6880 // leave the multiply where it is for the store to read and do the work twice, so the
6881 // multiply is put back and both readers read the register it wrote.
6882 let text = lower(&mut names, &func);
6883 assert!(text.contains("x64.lea_64 [%1*4]"), "{text}");
6884 assert!(text.contains("x64.add_rr_64"), "{text}");
6885 }
6886
6887 #[test]
6888 fn a_shift_by_a_register_asks_for_it_in_cl() {
6889 let i32 = Type::int(32);
6890 let (mut names, mut func, block, args) = blank(&[i32, i32]);
6891 let mut build = Builder::new(&mut func, block);
6892 build.binary(Opcode::Shl, args[0], args[1], Flags::default());
6893
6894 // The fixed register is not in the rule. It is what the target says the instruction does
6895 // with its operands, and the allocator is what will act on it.
6896 let text = lower(&mut names, &func);
6897 assert!(text.contains("x64.shl_rcl_32 %0, %1($rcx)"), "{text}");
6898 }
6899
6900 #[test]
6901 fn a_division_names_the_registers_and_the_register_it_destroys() {
6902 let i32 = Type::int(32);
6903 let (mut names, mut func, block, args) = blank(&[i32, i32]);
6904 let mut build = Builder::new(&mut func, block);
6905 build.binary(Opcode::SDiv, args[0], args[1], Flags::default());
6906
6907 // Two definitions, because a division writes the remainder whether anybody wanted it or
6908 // not, and the second one is early because it is destroyed before the operands are read.
6909 let text = lower(&mut names, &func);
6910 assert!(
6911 text.contains("%2:gpr($rax), early %3:gpr($rdx) = x64.idiv_quo_32 %0($rax), %1"),
6912 "{text}"
6913 );
6914 }
6915
6916 #[test]
6917 fn a_load_reads_through_the_register_the_address_is_in() {
6918 let i64 = Type::int(64);
6919 let (mut names, mut func, block, args) = blank(&[i64]);
6920 let mut build = Builder::new(&mut func, block);
6921 build.load(Type::int(32), args[0], plain(), Flags::default());
6922
6923 assert_eq!(
6924 lower(&mut names, &func),
6925 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
6926 %1:gpr = x64.mov_rm_32 [%0]\n}\n"
6927 );
6928 }
6929
6930 #[test]
6931 fn a_store_writes_no_register_and_the_value_it_writes_is_the_one_the_ir_gave_it() {
6932 let (mut names, mut func, block, args) = blank(&[Type::int(32), Type::int(64)]);
6933 let mut build = Builder::new(&mut func, block);
6934 build.store(args[0], args[1], plain(), Flags::default());
6935
6936 // The value is the first parameter and the address is the second, and the instruction
6937 // takes them the other way round. Getting that backwards would compile to a store of the
6938 // address into the value, which is a program that runs and does the wrong thing.
6939 assert_eq!(
6940 lower(&mut names, &func),
6941 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
6942 %1:gpr($rsi) = x64.arg_val_64\n x64.mov_mr_32 %0, [%1]\n}\n"
6943 );
6944 }
6945
6946 #[test]
6947 fn an_address_with_a_constant_added_folds_into_the_access() {
6948 let i64 = Type::int(64);
6949 let (mut names, mut func, block, args) = blank(&[i64]);
6950 let mut build = Builder::new(&mut func, block);
6951 let twelve = build.iconst(i64, 12);
6952 let field = build.binary(Opcode::Add, args[0], twelve, Flags::default());
6953 build.load(Type::int(64), field, plain(), Flags::default());
6954
6955 // Two IR instructions and one machine instruction, which is what every read of a field
6956 // of a structure comes to.
6957 assert_eq!(
6958 lower(&mut names, &func),
6959 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
6960 %1:gpr = x64.mov_rm_64 [%0 + 12]\n}\n"
6961 );
6962 }
6963
6964 #[test]
6965 fn a_displacement_too_wide_to_encode_leaves_the_addition_where_it_is() {
6966 let i64 = Type::int(64);
6967 let (mut names, mut func, block, args) = blank(&[i64]);
6968 let mut build = Builder::new(&mut func, block);
6969 let big = build.iconst(i64, i128::from(i32::MAX) + 1);
6970 let far = build.binary(Opcode::Add, args[0], big, Flags::default());
6971 build.load(Type::int(32), far, plain(), Flags::default());
6972
6973 // A displacement is signed and 32 bits. The rule that folds one has a guard that turns
6974 // this down, so the addition stays and the load reads through what it produced. Nobody
6975 // wrote that fallback: it is the next way of showing the operand.
6976 let text = lower(&mut names, &func);
6977 assert!(text.contains("x64.mov_rm_32 [%2]"), "{text}");
6978 assert!(text.contains("x64.add_rr_64"), "{text}");
6979 }
6980
6981 #[test]
6982 fn a_store_of_a_value_that_was_loaded_is_two_instructions_and_no_arithmetic() {
6983 let i64 = Type::int(64);
6984 let (mut names, mut func, block, args) = blank(&[i64, i64]);
6985 let mut build = Builder::new(&mut func, block);
6986 let got = build.load(Type::int(8), args[0], plain(), Flags::default());
6987 build.store(got, args[1], plain(), Flags::default());
6988
6989 // A load feeding a store is the one place folding would be wrong: an x86-64 `mov` has at
6990 // most one memory operand, and there is no rule that takes two, so the load is left where
6991 // it is and the store reads the register it wrote.
6992 assert_eq!(
6993 lower(&mut names, &func),
6994 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
6995 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr = x64.mov_rm_8 [%0]\n \
6996 x64.mov_mr_8 %2, [%1]\n}\n"
6997 );
6998 }
6999
7000 #[test]
7001 fn an_access_at_a_width_no_rule_is_written_at_is_reported() {
7002 let i64 = Type::int(64);
7003 let (mut names, mut source, block, args) = blank(&[i64]);
7004 let mut build = Builder::new(&mut source, block);
7005 build.load(Type::int(128), args[0], plain(), Flags::default());
7006
7007 // The width is the whole of what is wrong here, so the width is in the message: `load`
7008 // on its own is written about at every other width and would send a reader looking in
7009 // the wrong place.
7010 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7011 .expect_err("nothing loads 128 bits");
7012 assert_eq!(failed.to_string(), "no rule lowers a `load` producing a `i128`");
7013 }
7014
7015 #[test]
7016 fn a_return_asks_for_the_value_in_the_register_the_caller_reads() {
7017 let (mut names, mut func, block, args) = blank(&[Type::int(32)]);
7018 let mut build = Builder::new(&mut func, block);
7019 build.ret(&[args[0]]);
7020
7021 // The register is not in the rule, the same way `cl` is not in the rule for a shift. It
7022 // is what the target says the instruction does with its operand, and the allocator is
7023 // what will act on it. There is no `ret` here, because giving the frame back has to
7024 // happen between this and leaving and the frame is not worked out yet.
7025 assert_eq!(
7026 lower(&mut names, &func),
7027 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
7028 x64.ret_val_32 %0($rax)\n}\n"
7029 );
7030 }
7031
7032 #[test]
7033 fn a_return_of_two_values_asks_for_the_second_register_as_well() {
7034 let i64 = Type::int(64);
7035 let (mut names, mut func, block, args) = blank(&[i64, i64]);
7036 let mut build = Builder::new(&mut func, block);
7037 build.ret(&[args[0], args[1]]);
7038
7039 // `struct { long a, b; } f(long a, long b)`, after the front end has classified it. Both
7040 // halves are integers, so the second is in the second integer return register, and both
7041 // pseudos say so the same way the one for a single value does.
7042 assert_eq!(
7043 lower(&mut names, &func),
7044 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
7045 %1:gpr($rsi) = x64.arg_val_64\n x64.ret_val_64 %0($rax)\n \
7046 x64.ret_val2_64 %1($rdx)\n}\n"
7047 );
7048 }
7049
7050 #[test]
7051 fn two_values_back_in_different_files_are_both_the_first_of_their_own() {
7052 let f64 = Type::float(rucc_ir::Float::F64);
7053 let (mut names, mut func, block, args) = blank(&[f64, Type::int(64)]);
7054 let mut build = Builder::new(&mut func, block);
7055 build.ret(&[args[0], args[1]]);
7056
7057 // `struct { double a; long b; } f(double a, long b)`. The two files are counted apart, so
7058 // neither half is the second of anything and the `double` is in `xmm0` rather than in the
7059 // register a second `double` would have been in. Getting this wrong is not a crash: the
7060 // caller reads a register nobody wrote, and this is where that is ruled out.
7061 assert_eq!(
7062 lower(&mut names, &func),
7063 "mfunc @f {\nblock0:\n %0:xmm($xmm0) = x64.arg_val_f64\n \
7064 %1:gpr($rdi) = x64.arg_val_64\n x64.ret_val_f64 %0($xmm0)\n \
7065 x64.ret_val_64 %1($rax)\n}\n"
7066 );
7067 }
7068
7069 #[test]
7070 fn two_of_the_same_file_back_take_the_first_two_of_it() {
7071 let f64 = Type::float(rucc_ir::Float::F64);
7072 let (mut names, mut func, block, args) = blank(&[f64, f64]);
7073 let mut build = Builder::new(&mut func, block);
7074 build.ret(&[args[0], args[1]]);
7075
7076 // `struct { double x, y; } f(double x, double y)`, which is the vector half of the pair
7077 // above and counts in its own file the same way.
7078 assert_eq!(
7079 lower(&mut names, &func),
7080 "mfunc @f {\nblock0:\n %0:xmm($xmm0) = x64.arg_val_f64\n \
7081 %1:xmm($xmm1) = x64.arg_val_f64\n x64.ret_val_f64 %0($xmm0)\n \
7082 x64.ret_val2_f64 %1($xmm1)\n}\n"
7083 );
7084 }
7085
7086 /// A function whose answer goes back through memory, with the pointer to the space for it in
7087 /// front of whatever else it takes. Only the signature says it is one.
7088 fn returning_through_memory(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
7089 let mut names = Interner::new();
7090 let sret = Abi::Sret { size: 32, align: 8 };
7091 let mut signature = Signature::new().and_param(Param::with_abi(Type::PTR, sret));
7092 signature.params.extend(params.iter().copied().map(Param::new));
7093 let mut func = Func::new(names.intern("f"), signature);
7094 let block = func.create_block();
7095 let space = func.append_param(block, Type::PTR);
7096 let values = std::iter::once(space)
7097 .chain(params.iter().map(|&ty| func.append_param(block, ty)))
7098 .collect();
7099 (names, func, block, values)
7100 }
7101
7102 #[test]
7103 fn the_space_a_return_through_memory_was_given_goes_back_in_the_first_return_register() {
7104 let (mut names, mut func, block, _) = returning_through_memory(&[]);
7105 Builder::new(&mut func, block).ret(&[]);
7106
7107 // `struct big f(void)`, where `big` is too large to come back in registers. The `return`
7108 // carries nothing, because the value went into the space the caller handed over, and the
7109 // document still says that address comes back in `rax`. Nothing in the IR says it, so the
7110 // convention says it, and the pseudo is the one any other pointer return would use.
7111 assert_eq!(
7112 lower(&mut names, &func),
7113 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
7114 x64.ret_val_64 %0($rax)\n}\n"
7115 );
7116 }
7117
7118 #[test]
7119 fn what_the_function_did_in_between_does_not_take_the_register_off_it() {
7120 let (mut names, mut func, block, args) = returning_through_memory(&[Type::int(32)]);
7121 let mut build = Builder::new(&mut func, block);
7122 build.store(args[1], args[0], plain(), Flags::default());
7123 build.ret(&[]);
7124
7125 // The register is a read at the end and not a move at the start, so it is live across
7126 // everything between the two and the allocator has to keep it somewhere. In a function
7127 // with a call in it that somewhere is a callee saved register, and the address comes back
7128 // into `rax` here rather than whatever the last instruction happened to leave there. That
7129 // is issue #333, and a store is enough to show the value outlives the entry block.
7130 let text = lower(&mut names, &func);
7131 assert!(text.contains("x64.mov_mr_32 %1, [%0]"), "{text}");
7132 assert!(text.ends_with(" x64.ret_val_64 %0($rax)\n}\n"), "{text}");
7133 }
7134
7135 #[test]
7136 fn a_pointer_that_is_only_a_pointer_is_not_given_back() {
7137 let (mut names, mut func, block, args) = blank(&[Type::PTR]);
7138 let mut build = Builder::new(&mut func, block);
7139 build.store(args[0], args[0], plain(), Flags::default());
7140 build.ret(&[]);
7141
7142 // `void f(void **p)`. It takes a pointer first and returns nothing, which is the shape of
7143 // the one above and none of its meaning, and what tells them apart is the signature. A
7144 // `void` function leaves `rax` alone.
7145 assert!(!lower(&mut names, &func).contains("ret_val"));
7146 }
7147
7148 #[test]
7149 fn a_return_of_a_constant_puts_it_in_a_register_first() {
7150 let (mut names, mut func, block, _) = blank(&[]);
7151 let mut build = Builder::new(&mut func, block);
7152 let zero = build.iconst(Type::int(32), 0);
7153 build.ret(&[zero]);
7154
7155 // No rule returns an immediate, so the plan that offers one is turned down and the next
7156 // one materializes it. That is `int main(void) { return 0; }` in full, once the epilogue
7157 // is appended to it.
7158 assert_eq!(
7159 lower(&mut names, &func),
7160 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_32 0\n x64.ret_val_32 %0($rax)\n}\n"
7161 );
7162 }
7163
7164 #[test]
7165 fn the_rule_that_writes_a_constant_down_is_recorded_as_a_rule_that_fired() {
7166 let (mut names, mut func, block, _) = blank(&[]);
7167 let mut build = Builder::new(&mut func, block);
7168 let zero = build.iconst(Type::int(32), 0);
7169 build.ret(&[zero]);
7170
7171 // The loop over the instructions passes a constant by, because a constant is written where
7172 // a register for it is first wanted rather than where the IR put it. So the only place a
7173 // rule about one is ever selected is the materialization, and a mark made in the loop
7174 // alone would report every rule about a constant as a rule nothing reaches.
7175 let out = super::func(&func, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7176 .expect("every instruction has a rule");
7177 let rules = &crate::select::x86_64::TABLE.rules;
7178 let fired: Vec<&str> = rules
7179 .iter()
7180 .enumerate()
7181 .filter(|(index, _)| out.fired.has(*index))
7182 .map(|(_, rule)| rule.pattern)
7183 .collect();
7184 assert!(fired.contains(&"(iconst.i32 k)"), "{fired:?}");
7185 }
7186
7187 #[test]
7188 fn a_return_of_nothing_is_no_instruction_at_all() {
7189 let (mut names, mut func, block, _) = blank(&[]);
7190 let mut build = Builder::new(&mut func, block);
7191 build.ret(&[]);
7192
7193 // Every part of leaving a function that returns nothing is the epilogue's, and the
7194 // epilogue goes in after allocation. A block with nothing in it is the right answer here
7195 // rather than a function that could not be lowered.
7196 assert_eq!(lower(&mut names, &func), "mfunc @f {\nblock0:\n}\n");
7197 }
7198
7199 #[test]
7200 fn the_allocator_is_what_moves_the_answer_into_the_return_register() {
7201 let (mut names, mut source, block, _) = blank(&[]);
7202 let mut build = Builder::new(&mut source, block);
7203 let zero = build.iconst(Type::int(32), 0);
7204 build.ret(&[zero]);
7205
7206 let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7207 .expect("every instruction has a rule")
7208 .func;
7209 let env = env();
7210 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7211 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
7212 finish(
7213 &mut out,
7214 &allocation,
7215 &frame,
7216 &Stack::default(),
7217 Convention::new(&SYSV, &FRAME),
7218 &mut names,
7219 );
7220
7221 // `int main(void) { return 0; }` end to end. Nothing here asked for `rax`: the rule said
7222 // the value goes back, the target said where, and the allocator is what made it true. The
7223 // epilogue is what leaves, and this function needs no frame, so it is the return alone.
7224 //
7225 // Two instructions and no copy, which is what a hint buys. The return insists on `rax`,
7226 // so `rax` is the register the allocator tries first for the value the return reads, and
7227 // the constant is written straight into it.
7228 assert_eq!(
7229 mir::print_func(&out, &names, ®S),
7230 "mfunc @f {\nblock0:\n $rax = x64.mov_ri_32 0\n \
7231 x64.ret_val_32 $rax($rax)\n x64.ret\n}\n"
7232 );
7233 }
7234
7235 #[test]
7236 fn a_function_of_two_arguments_is_a_whole_function_now() {
7237 let i32 = Type::int(32);
7238 let (mut names, mut source, block, args) = blank(&[i32, i32]);
7239 let mut build = Builder::new(&mut source, block);
7240 let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
7241 build.ret(&[sum]);
7242
7243 let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7244 .expect("every instruction has a rule")
7245 .func;
7246 let env = env();
7247 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7248 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
7249 finish(
7250 &mut out,
7251 &allocation,
7252 &frame,
7253 &Stack::default(),
7254 Convention::new(&SYSV, &FRAME),
7255 &mut names,
7256 );
7257
7258 // `int f(int a, int b) { return a + b; }` end to end, and this is the test the argument
7259 // side exists for. Before it there was no way to write one: the allocator refuses a
7260 // function whose entry block takes parameters, because there is no edge into an entry
7261 // block for the moves that give a block parameter its value to go on.
7262 //
7263 // One move, and it is the one the machine's addition needs rather than one the allocator
7264 // owes anybody. Each argument stays in the register it arrived in, because the pseudo
7265 // that defines it insists on that register and the allocator now tries it first, and the
7266 // sum stays in the register the addition wrote it to until the return reads it out. The
7267 // copy in front of a two address instruction is what makes its destination one of the
7268 // registers it reads, and the source operand keeps its own name because the destination
7269 // is what the encoder writes.
7270 assert_eq!(
7271 mir::print_func(&out, &names, ®S),
7272 "mfunc @f {\nblock0:\n $rdi($rdi) = x64.arg_val_32\n \
7273 $rsi($rsi) = x64.arg_val_32\n \
7274 $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n $rax = x64.mov_rr_64 $rdi\n \
7275 x64.ret_val_32 $rax($rax)\n x64.ret\n}\n"
7276 );
7277 }
7278
7279 #[test]
7280 fn an_argument_with_no_register_left_for_it_is_read_out_of_the_caller_s_stack() {
7281 let i64 = Type::int(64);
7282 let (mut names, mut source, block, args) = blank(&[i64; 7]);
7283 let mut build = Builder::new(&mut source, block);
7284 build.ret(&[args[6]]);
7285
7286 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7287 .expect("the seventh is read from memory");
7288
7289 // SysV passes six integers in registers and the seventh in the caller's memory, so six of
7290 // these are pseudos that encode to nothing and the seventh is a load that encodes to real
7291 // bytes. Its displacement is nothing here for the reason a local's is: there is no frame
7292 // yet. What the walk hands on is which instruction is waiting, and for how far up the
7293 // caller's argument area, which is the bottom of it because it is the first one there.
7294 assert_eq!(lowered.stack.arguments.len(), 1);
7295 assert_eq!(lowered.stack.arguments[0].1, 0);
7296 let text = mir::print_func(&lowered.func, &names, ®S);
7297 assert!(text.contains("%6:gpr = x64.mov_rm_64 [$rsp]"), "{text}");
7298 assert_eq!(text.matches("x64.arg_val_64").count(), 6, "{text}");
7299 }
7300
7301 #[test]
7302 fn the_frame_is_what_says_how_far_up_the_caller_s_stack_an_argument_is() {
7303 let i64 = Type::int(64);
7304 let (mut names, mut source, block, args) = blank(&[i64; 8]);
7305 let mut build = Builder::new(&mut source, block);
7306 let sum = build.binary(Opcode::Add, args[6], args[7], Flags::default());
7307 build.ret(&[sum]);
7308
7309 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7310 .expect("both are read from memory");
7311 let stack = lowered.stack;
7312 let mut out = lowered.func;
7313 let env = env();
7314 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7315 let layout = stack.layout(Layout::new(&SYSV, REGS));
7316 let frame = Frame::of(&out, &allocation, &layout);
7317 finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
7318
7319 // A leaf that takes no frame, so the stack pointer never moves and the only thing between
7320 // it and the caller's arguments is the return address the call pushed. The seventh
7321 // parameter is at the bottom of the caller's argument area and the eighth is one word
7322 // further up, which is the eight bytes between the two offsets.
7323 let text = mir::print_func(&out, &names, ®S);
7324 assert_eq!(frame.size(), 0);
7325 assert_eq!(frame.incoming(), Incoming::from_stack(8));
7326 assert!(text.contains("x64.mov_rm_64 [$rsp + 8]"), "{text}");
7327 assert!(text.contains("x64.mov_rm_64 [$rsp + 16]"), "{text}");
7328 }
7329
7330 #[test]
7331 fn a_realigned_frame_reaches_the_caller_s_arguments_through_the_frame_pointer() {
7332 let i64 = Type::int(64);
7333 let (mut names, mut source, block, args) = blank(&[i64; 7]);
7334 let wide = slot(&mut source, block, 64, 32);
7335 let mut build = Builder::new(&mut source, block);
7336 build.store(args[6], wide, plain(), Flags::default());
7337 build.ret(&[args[6]]);
7338
7339 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7340 .expect("every instruction has a rule");
7341 let stack = lowered.stack;
7342 let mut out = lowered.func;
7343 let env = env();
7344 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7345 let layout = stack.layout(Layout::new(&SYSV, REGS));
7346 let frame = Frame::of(&out, &allocation, &layout);
7347 finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
7348
7349 // A local wanting thirty two byte alignment makes the prologue force the stack pointer,
7350 // which throws away how far the caller's stack was. So the load the lowering wrote off the
7351 // stack pointer is rewritten to read through the frame pointer, at the one distance that
7352 // survives: the word the prologue pushed the frame pointer into, and the return address
7353 // above it.
7354 let text = mir::print_func(&out, &names, ®S);
7355 assert_eq!(frame.realign(), Some(32));
7356 assert_eq!(frame.incoming(), Incoming::from_frame(16));
7357 assert!(text.contains("x64.mov_rm_64 [$rbp + 16]"), "{text}");
7358 assert!(!text.contains("x64.mov_rm_64 [$rsp"), "{text}");
7359 }
7360
7361 #[test]
7362 fn a_jump_is_the_edge_and_nothing_else() {
7363 let i32 = Type::int(32);
7364 let (mut names, mut source, entry, args) = blank(&[i32]);
7365 let next = source.create_block();
7366 let got = source.append_param(next, i32);
7367 Builder::new(&mut source, entry).jump(next, &[args[0]]);
7368 Builder::new(&mut source, next).ret(&[got]);
7369
7370 // Two blocks and two instructions, and the jump is neither of them. What it was is the
7371 // arm on the first block, and what the arm carries is the argument it was called with.
7372 assert_eq!(
7373 lower(&mut names, &source),
7374 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32 block1(%0)\n\n\
7375 block1(%1:gpr):\n x64.ret_val_32 %1($rax)\n}\n"
7376 );
7377 }
7378
7379 /// A block that reads what a block below it writes is filled after it, not before it.
7380 ///
7381 /// The blocks are written entry, `early`, `late`, `exit`, and the entry jumps straight past
7382 /// `early` to `late`, so `late` dominates `early` while sitting below it in the function.
7383 /// Filling them in the order they are written reaches the read in `early` first, and reading
7384 /// a value with no register yet mints one. The cast in `late` is no instruction at all, so
7385 /// what it does is give its answer the register its operand is already in, and that is not
7386 /// the register the read minted. Nothing writes the register the read minted. The printer
7387 /// says `%?` for a register nothing defines, which is what this looks for, and what came out
7388 /// of the real bug was SQLite loading a stack slot no store ever reached.
7389 #[test]
7390 fn a_block_that_reads_what_a_block_below_it_writes_is_filled_after_it() {
7391 let i64 = Type::int(64);
7392 let (mut names, mut source, entry, args) = blank(&[i64, i64]);
7393 let early = source.create_block();
7394 let late = source.create_block();
7395 let exit = source.create_block();
7396
7397 Builder::new(&mut source, entry).jump(late, &[]);
7398 let ptr = cast(&mut source, late, Opcode::IntToPtr, args[0], Type::PTR);
7399 Builder::new(&mut source, early).ret(&[ptr]);
7400 let mut build = Builder::new(&mut source, late);
7401 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7402 build.br_if(cond, early, &[], exit, &[]);
7403 Builder::new(&mut source, exit).ret(&[args[1]]);
7404
7405 let text = lower(&mut names, &source);
7406 assert!(!text.contains("%?"), "every register has something that writes it: {text}");
7407 }
7408
7409 /// A constant is written where it is wanted rather than where the IR defined it, and two
7410 /// blocks wanting the same one is two places. Writing it once and reading it in both is a
7411 /// register read where nothing wrote it, unless the block it was written in happens to
7412 /// dominate the other, which nothing here checks and which the second arm of a branch never
7413 /// does. Each block gets its own copy of the number instead.
7414 #[test]
7415 fn a_constant_two_blocks_want_is_written_in_both_of_them() {
7416 let i32 = Type::int(32);
7417 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7418 let then = source.create_block();
7419 let other = source.create_block();
7420 let join = source.create_block();
7421 let got = source.append_param(join, i32);
7422
7423 let mut build = Builder::new(&mut source, entry);
7424 let seven = build.iconst(i32, 7);
7425 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7426 build.br_if(cond, then, &[], other, &[]);
7427 // Both arms want the seven in a register, because a block argument is never an immediate,
7428 // and neither arm dominates the other.
7429 Builder::new(&mut source, then).jump(join, &[seven]);
7430 Builder::new(&mut source, other).jump(join, &[seven]);
7431 Builder::new(&mut source, join).ret(&[got]);
7432
7433 let text = lower(&mut names, &source);
7434 assert_eq!(text.matches("x64.mov_ri_32 7").count(), 2, "one seven per block: {text}");
7435 }
7436
7437 /// An argument on an edge out of a block that leaves two ways is read after every instruction
7438 /// of the block is written, and reading one can write an instruction, which would land after
7439 /// the branch that has already jumped past it. The branch goes back on the end.
7440 #[test]
7441 fn a_constant_an_edge_wants_is_written_before_the_branch_and_not_after_it() {
7442 let i32 = Type::int(32);
7443 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7444 let then = source.create_block();
7445 let join = source.create_block();
7446 let got = source.append_param(join, i32);
7447
7448 let mut build = Builder::new(&mut source, entry);
7449 let nine = build.iconst(i32, 9);
7450 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7451 build.br_if(cond, then, &[], join, &[nine]);
7452 Builder::new(&mut source, then).jump(join, &[args[0]]);
7453 Builder::new(&mut source, join).ret(&[got]);
7454
7455 let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7456 .expect("every instruction has a rule")
7457 .func;
7458 let entry = out.entry().expect("an entry block");
7459 let last = out.terminator(entry).expect("a block that leaves two ways has a branch");
7460 let branch = names.intern("x64.br_cond_8");
7461 assert_eq!(
7462 out[last].opcode,
7463 mir::Opcode::new(branch),
7464 "the branch is last: {}",
7465 mir::print_func(&out, &names, ®S)
7466 );
7467 }
7468
7469 #[test]
7470 fn a_conditional_branch_is_lowered_to_the_condition_and_nothing_about_where_it_goes() {
7471 let i32 = Type::int(32);
7472 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7473 let then = source.create_block();
7474 let other = source.create_block();
7475 let mut build = Builder::new(&mut source, entry);
7476 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7477 build.br_if(cond, then, &[], other, &[]);
7478 Builder::new(&mut source, then).ret(&[args[0]]);
7479 Builder::new(&mut source, other).ret(&[args[1]]);
7480
7481 // The comparison writes a byte and the branch reads it, and neither says a block. Both
7482 // arms are on the entry block, in the order the branch took them, so the arm that runs
7483 // when the condition holds is the first.
7484 assert_eq!(
7485 lower(&mut names, &source),
7486 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
7487 %1:gpr($rsi) = x64.arg_val_32\n %2:gpr = x64.cmp_set_l_32 %0, %1\n \
7488 x64.br_cond_8 %2, block1, block2\n\n\
7489 block1:\n x64.ret_val_32 %0($rax)\n\n\
7490 block2:\n x64.ret_val_32 %1($rax)\n}\n"
7491 );
7492 }
7493
7494 /// A choice between two values, which is one instruction and no blocks at all.
7495 ///
7496 /// The arms come out the other way round from the IR, because a conditional move overwrites its
7497 /// destination and the destination is the arm taken when the condition does not hold. The
7498 /// condition arrives last for the same reason: it is read by the test in front of the move
7499 /// rather than by the move.
7500 #[test]
7501 fn a_select_is_lowered_to_a_test_and_a_conditional_move() {
7502 let i32 = Type::int(32);
7503 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7504 let mut build = Builder::new(&mut source, entry);
7505 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7506 let picked = build.select(cond, args[0], args[1]);
7507 build.ret(&[picked]);
7508
7509 assert_eq!(
7510 lower(&mut names, &source),
7511 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
7512 %1:gpr($rsi) = x64.arg_val_32\n %2:gpr = x64.cmp_set_l_32 %0, %1\n \
7513 %3:gpr(reuse 1) = x64.test_cmov_ne_32 %1, %0, %2\n \
7514 x64.ret_val_32 %3($rax)\n}\n"
7515 );
7516 }
7517
7518 #[test]
7519 fn a_branch_over_a_block_is_a_whole_function_now() {
7520 let i32 = Type::int(32);
7521 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7522 let then = source.create_block();
7523 let other = source.create_block();
7524 let join = source.create_block();
7525 let got = source.append_param(join, i32);
7526 let mut build = Builder::new(&mut source, entry);
7527 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7528 build.br_if(cond, then, &[], other, &[]);
7529 let mut build = Builder::new(&mut source, then);
7530 let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
7531 build.jump(join, &[sum]);
7532 Builder::new(&mut source, other).jump(join, &[args[1]]);
7533 Builder::new(&mut source, join).ret(&[got]);
7534
7535 // `int f(int a, int b) { if (a < b) return a + b; else return b; }` end to end, written
7536 // the way a front end writes it: both arms of the branch are blocks of their own and the
7537 // return is the block they meet at. No edge here is critical, because the two arms out of
7538 // the entry carry nothing and the two arms into the join each leave a block that goes
7539 // nowhere else, so each has its own end to put its move at.
7540 let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7541 .expect("every instruction has a rule")
7542 .func;
7543 assert_eq!(crate::split::critical(&mut out), 0, "no edge here is critical");
7544 let env = env();
7545 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7546 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
7547 finish(
7548 &mut out,
7549 &allocation,
7550 &frame,
7551 &Stack::default(),
7552 Convention::new(&SYSV, &FRAME),
7553 &mut names,
7554 );
7555
7556 // One epilogue, on the join, which is the one block the function leaves from, and the
7557 // moves that give the join its parameter are at the end of each arm. Every register is
7558 // physical and the branch is still a branch on a register, because turning it into a
7559 // `test` and a `jcc` is the block layout's and there is no block layout yet.
7560 let text = mir::print_func(&out, &names, ®S);
7561 assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
7562 assert!(text.contains("x64.br_cond_8"), "{text}");
7563 assert!(text.contains("x64.add_rr_32"), "{text}");
7564 assert!(!text.contains('%'), "{text}");
7565 }
7566
7567 #[test]
7568 fn a_critical_edge_is_split_before_the_allocator_ever_sees_it() {
7569 let i32 = Type::int(32);
7570 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7571 let then = source.create_block();
7572 let join = source.create_block();
7573 let got = source.append_param(join, i32);
7574 let mut build = Builder::new(&mut source, entry);
7575 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7576 build.br_if(cond, then, &[], join, &[args[1]]);
7577 Builder::new(&mut source, then).jump(join, &[args[0]]);
7578 let mut build = Builder::new(&mut source, join);
7579 let twice = build.binary(Opcode::Add, got, got, Flags::default());
7580 build.ret(&[twice]);
7581
7582 // The else arm is critical: the entry block leaves two ways and the join is arrived at
7583 // two ways, and the arm carries a value. Without splitting it the allocator asserts,
7584 // because the move that gives the join its parameter would have to run at the end of a
7585 // block that also goes to the other arm.
7586 let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7587 .expect("every instruction has a rule")
7588 .func;
7589 assert_eq!(crate::split::critical(&mut out), 1);
7590 let env = env();
7591 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7592 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
7593 finish(
7594 &mut out,
7595 &allocation,
7596 &frame,
7597 &Stack::default(),
7598 Convention::new(&SYSV, &FRAME),
7599 &mut names,
7600 );
7601
7602 // The block the split added is where the move went, and it is the whole of that block.
7603 let text = mir::print_func(&out, &names, ®S);
7604 assert_eq!(out.block_count(), 4, "{text}");
7605 assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
7606 }
7607
7608 #[test]
7609 fn a_call_passes_what_the_convention_says_and_takes_back_what_it_says() {
7610 let i32 = Type::int(32);
7611 let (mut names, mut source, block, args) = blank(&[i32, i32]);
7612 let sig =
7613 source.add_signature(Signature::new().with_params(&[i32, i32]).with_returns(&[i32]));
7614 let callee = names.intern("g");
7615 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0], args[1]]);
7616 let got = source[call].first_result.expect("an integer comes back");
7617 Builder::new(&mut source, block).ret(&[got]);
7618
7619 // `int f(int a, int b) { return g(a, b); }`. The arguments arrived where the call wants
7620 // them, so what the call reads is what arrived, and the whole of the convention is in the
7621 // constraints rather than in a move.
7622 let text = lower(&mut names, &source);
7623 assert!(text.contains("= x64.call %0($rdi), %1($rsi), @g"), "{text}");
7624 assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
7625 // What the call writes is the value that comes back and then every register the callee is
7626 // free to destroy, in both classes, which is the whole of what stops the allocator from
7627 // leaving something in one of them.
7628 assert!(text.contains("%2:gpr($rax), $rcx, $rdx, $r8, $r9, $r10, $r11, $xmm0,"), "{text}");
7629 assert!(text.contains("$xmm15 = x64.call"), "{text}");
7630 }
7631
7632 #[test]
7633 fn what_the_frame_owes_a_call_comes_back_with_the_function() {
7634 let i32 = Type::int(32);
7635 let sig = |source: &mut Func| source.add_signature(Signature::new().with_params(&[i32]));
7636
7637 let (mut names, mut source, block, args) = blank(&[i32]);
7638 let sig = sig(&mut source);
7639 let callee = names.intern("g");
7640 Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
7641 let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7642 .expect("every instruction has a rule");
7643
7644 // Nothing on the stack, so nothing owed, but not a leaf either: a function that calls
7645 // owes the callee an aligned stack pointer and may not use the red zone.
7646 assert_eq!(out.stack.calls, Some(0));
7647 let layout = out.stack.layout(Layout::new(&SYSV, REGS));
7648 assert!(!layout.leaf);
7649 assert_eq!(layout.outgoing, 0);
7650
7651 // The same call under the other convention owes thirty two bytes for the callee to spill
7652 // its register arguments into, which is a fact about the convention and not about the call.
7653 let out = func(&source, &mut names, &SELECTOR, &x86_64::WIN64, &Elsewhere::default())
7654 .expect("every instruction has a rule");
7655 assert_eq!(out.stack.calls, Some(32));
7656
7657 // And a function that calls nothing is a leaf, which is what says it may use the red zone.
7658 let (mut names, mut source, block, args) = blank(&[i32]);
7659 Builder::new(&mut source, block).ret(&[args[0]]);
7660 let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7661 .expect("every instruction has a rule");
7662 assert_eq!(out.stack.calls, None);
7663 assert!(out.stack.layout(Layout::new(&SYSV, REGS)).leaf);
7664 }
7665
7666 /// A Windows variadic prologue writes the argument registers the signature did not name into
7667 /// the shadow space the caller already reserved, which makes every argument one run of words up
7668 /// there and a `va_start` the address of the first of them. One `lea` and one store, and no
7669 /// counts, because a list that is a pointer has nowhere to put one and nothing that reads one.
7670 #[test]
7671 fn a_windows_variadic_function_homes_its_spare_registers_in_the_callers_area() {
7672 let mut names = Interner::new();
7673 let params = [Type::int(32), Type::PTR];
7674 let signature = Signature::new().with_params(¶ms).variadic();
7675 let mut source = Func::new(names.intern("f"), signature);
7676 let block = source.create_block();
7677 let values: Vec<Value> = params.iter().map(|&ty| source.append_param(block, ty)).collect();
7678 let mut build = Builder::new(&mut source, block);
7679 let args = build.func().push_values(&values[1..]);
7680 build.inst(InstData { args, ..InstData::new(Opcode::VaStart) }, &[]);
7681 build.ret(&[]);
7682
7683 let out = func(&source, &mut names, &SELECTOR, &x86_64::WIN64, &Elsewhere::default())
7684 .expect("every instruction has a rule");
7685 let text = mir::print_func(&out.func, &names, ®S);
7686
7687 // Two named parameters, so the registers at the next two positions hold arguments nobody
7688 // named and both are written up into the caller's area. The displacement is empty here and
7689 // `finish` fills it in, the same way it does for a parameter the registers ran out before.
7690 assert!(text.contains("($r8) = x64.arg_val_64"), "{text}");
7691 assert!(text.contains("($r9) = x64.arg_val_64"), "{text}");
7692 assert_eq!(text.matches("x64.mov_mr_64").count(), 3, "two homed and one stored: {text}");
7693 assert!(!text.contains("x64.mov_ri_32"), "and no field holds a count: {text}");
7694
7695 // All three waiting on the same fixup, and the last of them is the `lea` the list is given,
7696 // sixteen bytes up, which is where the two arguments the signature does name stopped.
7697 assert_eq!(out.stack.arguments.len(), 3);
7698 assert_eq!(out.stack.arguments[2].1, 16);
7699 }
7700
7701 #[test]
7702 fn a_value_that_outlives_a_call_is_not_left_where_the_call_destroys_it() {
7703 let i32 = Type::int(32);
7704 let (mut names, mut source, block, args) = blank(&[i32]);
7705 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
7706 let callee = names.intern("g");
7707 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
7708 let got = source[call].first_result.expect("an integer comes back");
7709 let mut build = Builder::new(&mut source, block);
7710 let sum = build.binary(Opcode::Add, got, args[0], Flags::default());
7711 build.ret(&[sum]);
7712
7713 // `int f(int a) { return g(a) + a; }`, which is the smallest program that asks the
7714 // question: `a` is read after the call and `rdi` is a register the call destroys.
7715 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7716 .expect("every instruction has a rule");
7717 let layout = lowered.stack.layout(Layout::new(&SYSV, REGS));
7718 let mut out = lowered.func;
7719 let env = env();
7720 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7721 let frame = Frame::of(&out, &allocation, &layout);
7722 finish(
7723 &mut out,
7724 &allocation,
7725 &frame,
7726 &Stack::default(),
7727 Convention::new(&SYSV, &FRAME),
7728 &mut names,
7729 );
7730
7731 // It went to a register the callee has to put back, and the prologue and epilogue are what
7732 // put it back, which is the whole bargain the two halves of a convention make.
7733 let text = mir::print_func(&out, &names, ®S);
7734 assert!(text.contains("$rbx"), "{text}");
7735 assert!(!text.contains('%'), "{text}");
7736 assert_eq!(text.matches("x64.call").count(), 1, "{text}");
7737 }
7738
7739 #[test]
7740 fn a_call_with_more_arguments_than_registers_writes_the_rest_into_the_outgoing_area() {
7741 let i64 = Type::int(64);
7742 let (mut names, mut source, block, args) = blank(&[i64]);
7743 let seven = vec![i64; 7];
7744 let sig = source.add_signature(Signature::new().with_params(&seven));
7745 let callee = names.intern("g");
7746 let passed = vec![args[0]; 7];
7747 Builder::new(&mut source, block).call(callee, sig, &passed);
7748
7749 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7750 .expect("the seventh goes to memory");
7751 // The bytes the call needs are on the layout the frame is worked out from, so that the
7752 // frame reserves as many as the widest call in the function asked for.
7753 assert_eq!(lowered.stack.calls, Some(8));
7754 let text = mir::print_func(&lowered.func, &names, ®S);
7755 assert!(text.contains("x64.mov_mr_64 %0, [$rsp]\n"), "{text}");
7756 }
7757
7758 #[test]
7759 fn a_call_this_cannot_make_is_reported_rather_than_made() {
7760 let (mut names, mut source, block, _) = blank(&[]);
7761 let returns = [Type::float(rucc_ir::Float::F80), Type::int(64)];
7762 let sig = source.add_signature(Signature::new().with_returns(&returns));
7763 let callee = names.intern("g");
7764 Builder::new(&mut source, block).call(callee, sig, &[]);
7765 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7766 .expect_err("a long double is on the x87");
7767 assert_eq!(failed.to_string(), "what this call gives back is on the x87 stack");
7768 }
7769
7770 /// A `long double` on its own is a different answer, because on its own it comes back on the
7771 /// x87 stack rather than in a register, which is somewhere the call cannot be said to write.
7772 ///
7773 /// So the call gives back nothing at all and the value is taken off the stack by the `fstp`
7774 /// straight after it. That instruction has to be straight after it: the stack is one place and
7775 /// anything else that touched it before this ran would be looking at the value still on it.
7776 #[test]
7777 fn a_call_that_gives_back_a_long_double_takes_it_off_the_stack_at_once() {
7778 let (mut names, mut source, block, _) = blank(&[]);
7779 let long_double = Type::float(rucc_ir::Float::F80);
7780 let sig = source.add_signature(Signature::new().with_returns(&[long_double]));
7781 let callee = names.intern("g");
7782 Builder::new(&mut source, block).call(callee, sig, &[]);
7783
7784 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7785 .expect("the value comes back in st0");
7786 let text = mir::print_func(&lowered.func, &names, ®S);
7787 let after: Vec<&str> =
7788 text.lines().skip_while(|line| !line.contains("x64.call")).skip(1).collect();
7789 assert_eq!(after[0].trim(), "%0:gpr = x64.lea_64 [$rsp]", "{text}");
7790 assert_eq!(after[1].trim(), "x64.fstp_t [%0]", "{text}");
7791 // And the slot it went into is the sixteen bytes the type takes, like every other one.
7792 assert_eq!(lowered.stack.locals.len(), 1, "{text}");
7793 assert_eq!(lowered.stack.locals[0].size, X87_BYTES);
7794 }
7795
7796 #[test]
7797 fn a_call_through_an_address_goes_through_the_register_the_address_is_in() {
7798 let i32 = Type::int(32);
7799 let (mut names, mut source, block, args) = blank(&[Type::PTR, i32]);
7800 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
7801 let varargs = source.push_abis(&[]);
7802 let info = source.add_call(CallInfo { callee: None, signature: sig, varargs });
7803 let mut build = Builder::new(&mut source, block);
7804 let inst = InstData {
7805 args: build.func().push_values(&[args[0], args[1]]),
7806 extra: Extra::Call(info),
7807 ..InstData::new(Opcode::CallIndirect)
7808 };
7809 let called = build.inst(inst, &[i32]);
7810 let got = source[called].first_result.expect("an integer comes back");
7811 Builder::new(&mut source, block).ret(&[got]);
7812
7813 // `int f(int (*g)(int), int a) { return g(a); }`. The first operand is the address and
7814 // the arguments are the ones behind it, and everything else about the call is what a call
7815 // to a name would have been.
7816 let text = lower(&mut names, &source);
7817 assert!(text.contains("= x64.call_reg %0, %1($rdi)"), "{text}");
7818 assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
7819 assert!(!text.contains("@g"), "a call through an address names nobody: {text}");
7820 }
7821
7822 #[test]
7823 fn an_instruction_no_rule_covers_is_reported() {
7824 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
7825 let mut build = Builder::new(&mut source, block);
7826 let operands = build.func().push_values(&[args[0]]);
7827 build.inst(InstData { args: operands, ..InstData::new(Opcode::MetaBegin) }, &[]);
7828
7829 // The mark that an object has come into being, which nothing writes an instruction for
7830 // yet: what it needs is a write over a range of the lifetime plane, and that is
7831 // `tamnd/rucc#856`. Nothing about it is a width or a register, so there is nothing for the
7832 // message to add beyond the name.
7833 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7834 .expect_err("no rule writes the beginning of a lifetime");
7835 assert_eq!(failed.to_string(), "no rule lowers a `meta_begin`");
7836
7837 // It produces nothing, so there is no type in the message and nothing invents one, and the
7838 // instruction comes back so a caller can ask the function where it was.
7839 let inst = failed.inst().expect("the instruction it is about");
7840 assert_eq!(source[inst].opcode, Opcode::MetaBegin);
7841 }
7842
7843 /// A barrier is written by name here, and what it is depends on the ordering and on nothing
7844 /// else. `crate::expand` is where the reasoning about this machine's memory model lives.
7845 #[test]
7846 fn a_barrier_is_one_instruction_at_the_strongest_ordering_and_none_below_it() {
7847 for order in MemOrder::all().filter(|&order| order != MemOrder::NotAtomic) {
7848 let (mut names, mut source, block, _) = blank(&[]);
7849 let mut build = Builder::new(&mut source, block);
7850 build
7851 .inst(InstData { extra: Extra::Order(order), ..InstData::new(Opcode::Fence) }, &[]);
7852
7853 let text = lower(&mut names, &source);
7854 assert_eq!(text.contains("x64.mfence"), order == MemOrder::SeqCst, "{order:?}: {text}");
7855 }
7856 }
7857
7858 /// A compare and exchange is written by name too, and at the width of the value rather than at
7859 /// the width of the address, which is the mistake worth pinning: everything here is a pointer
7860 /// and only the value says how many bytes the instruction touches.
7861 #[test]
7862 fn a_compare_and_exchange_is_one_instruction_at_the_width_of_the_value() {
7863 for bits in [8, 16, 32, 64] {
7864 let ty = Type::int(bits);
7865 let (mut names, mut source, block, args) = blank(&[Type::PTR, ty, ty]);
7866 let mut build = Builder::new(&mut source, block);
7867 let mem = build.func().add_mem(MemInfo {
7868 size: u64::from(bits / 8),
7869 align: bits / 8,
7870 order: MemOrder::SeqCst,
7871 ..plain()
7872 });
7873 let operands = build.func().push_values(&[args[0], args[1], args[2]]);
7874 build.inst(
7875 InstData {
7876 args: operands,
7877 extra: Extra::Mem(mem),
7878 ..InstData::new(Opcode::Cmpxchg)
7879 },
7880 &[ty, Type::I1],
7881 );
7882
7883 // Two values out of one instruction, the first of them in the register the machine
7884 // reads the expected value out of, the second free for the allocator to place. The
7885 // address is the memory operand and neither of the two values is.
7886 let text = lower(&mut names, &source);
7887 let written = format!("%3:gpr($rax), %4:gpr = x64.cmpxchg_{bits} %1($rax), %2, [%0]");
7888 assert!(text.contains(&written), "{bits}: {text}");
7889 }
7890 }
7891
7892 #[test]
7893 fn more_values_back_than_the_convention_has_registers_for_is_reported() {
7894 let i64 = Type::int(64);
7895 let (mut names, mut source, block, args) = blank(&[i64, i64, i64]);
7896 let mut build = Builder::new(&mut source, block);
7897 build.ret(&[args[0], args[1], args[2]]);
7898
7899 // Two integers come back in `rax` and `rdx` and a third has nowhere to go, which is not a
7900 // gap in the rules but the convention saying no. The front end classifies before it gets
7901 // here, so this is the shape that would mean the classification went wrong.
7902 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7903 .expect_err("only two come back");
7904 assert_eq!(
7905 failed.to_string(),
7906 "what this function gives back takes more registers than this convention has for it"
7907 );
7908
7909 let inst = failed.inst().expect("the instruction it is about");
7910 assert_eq!(source[inst].opcode, Opcode::Return);
7911 }
7912
7913 /// A refusal about a signature has no instruction, which is what makes it the one arm apart.
7914 ///
7915 /// Everything else is about something written somewhere in the body and hands it back so a
7916 /// caller can ask the function where it came from. A parameter arrives before the first
7917 /// instruction runs, so there is nothing in the body to point at and the message is about
7918 /// the function.
7919 #[test]
7920 fn a_refusal_about_a_parameter_has_no_instruction_to_point_at() {
7921 let missing = Unsupported::Argument { index: 0, missing: Missing::OnX87 };
7922 assert_eq!(missing.inst(), None);
7923 }
7924
7925 /// An `alloca` of a fixed size, which is what every local whose address is taken becomes.
7926 fn slot(source: &mut Func, block: Block, size: u64, align: u32) -> Value {
7927 let info = MemInfo { size, align, ..plain() };
7928 let mut build = Builder::new(source, block);
7929 let mem = build.func().add_mem(info);
7930 build.value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR)
7931 }
7932
7933 #[test]
7934 fn a_local_is_memory_in_the_frame_and_one_instruction_that_says_where() {
7935 let (mut names, mut source, block, _) = blank(&[]);
7936 let slot = slot(&mut source, block, 4, 4);
7937 let mut build = Builder::new(&mut source, block);
7938 let nine = build.iconst(Type::int(32), 9);
7939 build.store(nine, slot, plain(), Flags::default());
7940 let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
7941 build.ret(&[loaded]);
7942
7943 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7944 .expect("every instruction has a rule");
7945
7946 // Four bytes on the list the frame is laid out from, and the one instruction that reads
7947 // where they went. Its displacement is nothing here because there is no frame yet, and
7948 // which instruction is waiting for which local is what `finish` is handed.
7949 assert_eq!(lowered.stack.locals, vec![Local { size: 4, align: 4 }]);
7950 assert_eq!(lowered.stack.addresses.len(), 1);
7951 assert_eq!(lowered.stack.addresses[0].1, 0);
7952 assert_eq!(
7953 mir::print_func(&lowered.func, &names, ®S),
7954 "mfunc @f {\nblock0:\n %0:gpr = x64.lea_64 [$rsp]\n \
7955 %1:gpr = x64.mov_ri_32 9\n x64.mov_mr_32 %1, [%0]\n \
7956 %2:gpr = x64.mov_rm_32 [%0]\n x64.ret_val_32 %2($rax)\n}\n"
7957 );
7958 }
7959
7960 #[test]
7961 fn a_local_the_program_declared_says_which_declaration_it_is_and_the_rest_say_nothing() {
7962 let (mut names, mut source, block, _) = blank(&[]);
7963 let scratch = slot(&mut source, block, 4, 4);
7964 let mut build = Builder::new(&mut source, block);
7965 let mem = build.func().add_mem(MemInfo { size: 8, align: 8, ..plain() });
7966 let declared = build
7967 .value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR);
7968 build.func().declare_mem(mem, 41);
7969 build.store(scratch, declared, MemInfo { size: 8, align: 8, ..plain() }, Flags::default());
7970 build.ret(&[]);
7971
7972 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7973 .expect("every instruction has a rule");
7974
7975 // Two locals and one declaration, held against the order the allocas were lowered in,
7976 // which is the only name a local has by the time the frame places it. The scratch one was
7977 // reached first and is local zero, so the declared one is local one.
7978 assert_eq!(lowered.stack.locals.len(), 2);
7979 assert_eq!(lowered.stack.declared, vec![(1, 41)]);
7980 }
7981
7982 /// A local the program kept in a value comes out saying which register holds it.
7983 ///
7984 /// The other half of the local above, which had a slot. This one has none, so what carries the
7985 /// declaration is the register the instruction computing it writes into.
7986 #[test]
7987 fn a_local_the_program_kept_in_a_value_says_which_register_holds_it() {
7988 let (mut names, mut source, block, _) = blank(&[]);
7989 let mut build = Builder::new(&mut source, block);
7990 let nine = build.iconst(Type::int(32), 9);
7991 let ten = build.iconst(Type::int(32), 10);
7992 let sum = build.binary(Opcode::Add, nine, ten, Flags::default());
7993 build.func().declare_value(sum, 41);
7994 build.ret(&[sum]);
7995
7996 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7997 .expect("every instruction has a rule");
7998
7999 // One pair and not three. The constants are values the program never declared, and a
8000 // register holding one of those is nobody's. The register is the one the addition writes,
8001 // which the listing under it is what pins down.
8002 assert_eq!(lowered.func.named, vec![(41, mir::Reg::virtual_reg(1))]);
8003 assert_eq!(
8004 mir::print_func(&lowered.func, &names, ®S),
8005 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_32 9\n \
8006 %1:gpr(reuse 1) = x64.add_ri_32 %0, 10\n x64.ret_val_32 %1($rax)\n}\n"
8007 );
8008 }
8009
8010 /// A local held in a constant two blocks want is two registers and both of them are it.
8011 ///
8012 /// Why the declaration is written down as each register is handed out rather than once at the
8013 /// end over the map from values to registers. That map remembers the last register a value was
8014 /// written into, and a constant is written again in every block that wants one, so a local held
8015 /// in one would come out findable in the last block of the function and nowhere else.
8016 #[test]
8017 fn a_local_held_in_a_constant_two_blocks_want_is_named_in_both_of_them() {
8018 let i32 = Type::int(32);
8019 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
8020 let then = source.create_block();
8021 let other = source.create_block();
8022 let join = source.create_block();
8023 let got = source.append_param(join, i32);
8024
8025 let mut build = Builder::new(&mut source, entry);
8026 let seven = build.iconst(i32, 7);
8027 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
8028 build.func().declare_value(seven, 41);
8029 build.br_if(cond, then, &[], other, &[]);
8030 Builder::new(&mut source, then).jump(join, &[seven]);
8031 Builder::new(&mut source, other).jump(join, &[seven]);
8032 Builder::new(&mut source, join).ret(&[got]);
8033
8034 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8035 .expect("every instruction has a rule");
8036
8037 let held = &lowered.func.named;
8038 assert_eq!(held.len(), 2, "one register per block that wanted the seven: {held:?}");
8039 assert!(held.iter().all(|&(decl, _)| decl == 41), "{held:?}");
8040 assert_ne!(held[0].1, held[1].1, "the same register in two blocks: {held:?}");
8041 }
8042
8043 /// A parameter the program declared comes out named too, in the register it arrived in.
8044 ///
8045 /// The case the walk over the map at the end is for. A parameter is put in a register the
8046 /// convention chose rather than in a fresh one, so nothing asks the mint for it and the pair
8047 /// would otherwise never be written down.
8048 #[test]
8049 fn a_parameter_the_program_declared_says_which_register_it_arrived_in() {
8050 let i32 = Type::int(32);
8051 let (mut names, mut source, block, args) = blank(&[i32]);
8052 let mut build = Builder::new(&mut source, block);
8053 build.func().declare_value(args[0], 41);
8054 build.ret(&[args[0]]);
8055
8056 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8057 .expect("every instruction has a rule");
8058
8059 let held = &lowered.func.named;
8060 assert_eq!(held.len(), 1, "one pair for the one parameter: {held:?}");
8061 assert_eq!(held[0].0, 41);
8062 }
8063
8064 /// A function with nothing declared in it says nothing, which is every function compiled
8065 /// without debugging information asked for.
8066 #[test]
8067 fn a_function_the_front_end_named_nothing_in_names_no_registers() {
8068 let (mut names, mut source, block, _) = blank(&[]);
8069 let mut build = Builder::new(&mut source, block);
8070 let nine = build.iconst(Type::int(32), 9);
8071 build.ret(&[nine]);
8072
8073 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8074 .expect("every instruction has a rule");
8075 assert!(lowered.func.named.is_empty(), "{:?}", lowered.func.named);
8076 }
8077
8078 #[test]
8079 fn the_frame_is_what_fills_the_address_of_a_local_in() {
8080 let (mut names, mut source, block, _) = blank(&[]);
8081 let slot = slot(&mut source, block, 4, 4);
8082 let mut build = Builder::new(&mut source, block);
8083 let nine = build.iconst(Type::int(32), 9);
8084 build.store(nine, slot, plain(), Flags::default());
8085 let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
8086 build.ret(&[loaded]);
8087
8088 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8089 .expect("every instruction has a rule");
8090 let stack = lowered.stack;
8091 let mut out = lowered.func;
8092 let env = env();
8093 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
8094 let layout = stack.layout(Layout::new(&SYSV, REGS));
8095 let frame = Frame::of(&out, &allocation, &layout);
8096 finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
8097
8098 // `int f(void) { int x; x = 9; return x; }` with the address of `x` taken, end to end.
8099 // A leaf small enough to live in the red zone takes no frame at all, so the stack pointer
8100 // never moves and the four bytes are below it, which is what the negative offset is. The
8101 // instruction the lowering left with nothing in its displacement now has the answer in it.
8102 let text = mir::print_func(&out, &names, ®S);
8103 assert!(text.contains("$rax = x64.lea_64 [$rsp - 8]"), "{text}");
8104 assert!(!text.contains("x64.sub_ri_64"), "{text}");
8105 assert_eq!(frame.size(), 0);
8106 assert_eq!(frame.local(0), Some(-8));
8107 }
8108
8109 /// An `alloca` whose size is an operand, which is a variable length array.
8110 fn growing(source: &mut Func, block: Block, size: Value, align: u32) -> Value {
8111 let info = MemInfo { size: 0, align, ..plain() };
8112 let mut build = Builder::new(source, block);
8113 let mem = build.func().add_mem(info);
8114 let args = build.func().push_values(&[size]);
8115 build.value(
8116 InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) },
8117 Type::PTR,
8118 )
8119 }
8120
8121 #[test]
8122 fn a_stack_slot_whose_size_is_not_known_until_it_runs_takes_the_bytes_off_the_stack_pointer() {
8123 let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
8124 let slot = growing(&mut source, block, args[0], 16);
8125 Builder::new(&mut source, block).ret(&[slot]);
8126
8127 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8128 .expect("every instruction has a rule");
8129
8130 // The bytes come off the stack pointer where the declaration stands and the address is
8131 // where the stack pointer then is, which is one subtraction and one `lea` rather than a
8132 // slot the frame laid out. Nothing is on the list of locals, because there is nothing
8133 // about this the frame could place.
8134 let text = mir::print_func(&lowered.func, &names, ®S);
8135 assert!(text.contains("$rsp = x64.sub_rr_64 $rsp, %0"), "{text}");
8136 assert!(text.contains("x64.lea_64 [$rsp]"), "{text}");
8137 assert!(lowered.stack.locals.is_empty(), "{text}");
8138 assert_eq!(lowered.stack.dynamic.len(), 1);
8139 assert!(lowered.stack.grown_at.is_some());
8140 }
8141
8142 #[test]
8143 fn a_growing_slot_wanting_more_alignment_than_the_stack_pointer_has_is_reported() {
8144 let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
8145 let slot = growing(&mut source, block, args[0], 32);
8146 Builder::new(&mut source, block).ret(&[slot]);
8147
8148 // Thirty two is more than a call leaves the stack pointer on, so giving it what it asked
8149 // for means masking the stack pointer after moving it, and after that no constant reaches
8150 // the rest of the frame from the frame pointer either. A second pointer held for the
8151 // purpose is what fixes it and there is not one yet.
8152 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8153 .expect_err("nothing realigns a frame that grows");
8154 assert_eq!(
8155 failed.to_string(),
8156 "this local wants more alignment than the stack pointer is left on, which needs a \
8157 base register nothing here keeps"
8158 );
8159 }
8160
8161 #[test]
8162 fn a_frame_that_grows_reaches_its_own_locals_through_the_frame_pointer() {
8163 let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
8164 let fixed = slot(&mut source, block, 4, 4);
8165 let mut build = Builder::new(&mut source, block);
8166 let nine = build.iconst(Type::int(32), 9);
8167 build.store(nine, fixed, plain(), Flags::default());
8168 let grown = growing(&mut source, block, args[0], 16);
8169 Builder::new(&mut source, block).ret(&[grown]);
8170
8171 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8172 .expect("every instruction has a rule");
8173 let stack = lowered.stack;
8174 let mut out = lowered.func;
8175 let env = env();
8176 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
8177 let layout = stack.layout(Layout::new(&SYSV, REGS));
8178 let frame = Frame::of(&out, &allocation, &layout);
8179 finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
8180
8181 // The stack pointer moves in the middle of the function, so the four bytes of the fixed
8182 // local are not a constant away from it any more and the frame pointer is what reaches
8183 // them. The frame keeps one whatever the flags asked for, takes its bytes rather than
8184 // living in the red zone, and the address of the growing slot is off the stack pointer as
8185 // it stands after the subtraction rather than off anything the prologue left.
8186 let text = mir::print_func(&out, &names, ®S);
8187 assert!(frame.grows());
8188 assert!(frame.frame_pointer());
8189 assert!(frame.size() > 0, "{text}");
8190 assert!(text.contains("x64.lea_64 [$rbp"), "{text}");
8191 assert!(text.contains("$rsp = x64.sub_rr_64 $rsp"), "{text}");
8192 assert!(text.contains("x64.lea_64 [$rsp]"), "{text}");
8193 }
8194
8195 #[test]
8196 fn an_address_is_read_written_and_added_to_like_the_integer_it_is() {
8197 let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
8198 let mut build = Builder::new(&mut source, block);
8199 let stepped = build.func().push_values(&[args[0], args[1]]);
8200 let next =
8201 build.value(InstData { args: stepped, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
8202 let loaded = build.load(Type::int(32), next, plain(), Flags::default());
8203 build.ret(&[loaded]);
8204
8205 // `int f(int *p, long i) { return *(int *)((char *)p + i); }`. Nothing about this is new
8206 // in the rule set, which is the point: the two addresses arrive in registers because an
8207 // address is an integer as wide as one, and the arithmetic on them is the add it always
8208 // was, so every rule written about an add reaches it.
8209 //
8210 // The add stays its own instruction here rather than folding into the address the load
8211 // reads from. Two registers with no scale on either is the one addressing mode the rules
8212 // have no load through, because the folds that exist are the displacement one and the
8213 // scaled ones, and this is neither. `crate::fold` is what puts the two together, after
8214 // selection, and this is the pair it is handed.
8215 assert_eq!(
8216 lower(&mut names, &source),
8217 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
8218 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n \
8219 %3:gpr = x64.mov_rm_32 [%2]\n x64.ret_val_32 %3($rax)\n}\n"
8220 );
8221 }
8222
8223 /// The address of a file scope name, which is what every use of a global and every string
8224 /// literal starts from.
8225 fn address_of(source: &mut Func, block: Block, names: &mut Interner, name: &str) -> Value {
8226 let symbol = names.intern(name);
8227 let mut build = Builder::new(source, block);
8228 build.value(
8229 InstData { extra: Extra::Symbol(symbol), ..InstData::new(Opcode::GlobalAddr) },
8230 Type::PTR,
8231 )
8232 }
8233
8234 #[test]
8235 fn the_address_of_a_name_is_one_instruction_carrying_the_name() {
8236 let (mut names, mut source, block, _) = blank(&[]);
8237 let counter = address_of(&mut source, block, &mut names, "counter");
8238 let mut build = Builder::new(&mut source, block);
8239 let loaded = build.load(Type::int(32), counter, plain(), Flags::default());
8240 build.ret(&[loaded]);
8241
8242 // `extern int counter; int f(void) { return counter; }`. The address is an addressing mode
8243 // that names no register and carries the symbol, which is what the assembler writes
8244 // relative to `%rip` and what the object writer leaves a relocation for.
8245 assert_eq!(
8246 lower(&mut names, &source),
8247 "mfunc @f {\nblock0:\n %0:gpr = x64.lea_64 [@counter]\n \
8248 %1:gpr = x64.mov_rm_32 [%0]\n x64.ret_val_32 %1($rax)\n}\n"
8249 );
8250 }
8251
8252 #[test]
8253 fn the_address_of_a_name_outside_the_file_is_read_out_of_the_offset_table() {
8254 let (mut names, mut source, block, _) = blank(&[]);
8255 let away = address_of(&mut source, block, &mut names, "away");
8256 Builder::new(&mut source, block).ret(&[away]);
8257 let elsewhere: Elsewhere = [names.intern("away")].into_iter().collect();
8258
8259 // `extern void away(void); void *f(void) { return away; }`. A load and not an address
8260 // computation, because the distance from here to a name a shared library may be the one
8261 // that defines is not a number any link can work out, and the slot the linker fills in is
8262 // in this program and so is a distance it has.
8263 let out = func(&source, &mut names, &SELECTOR, &SYSV, &elsewhere)
8264 .expect("every instruction has a rule");
8265 assert_eq!(
8266 mir::print_func(&out.func, &names, ®S),
8267 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rm_64 [got @away]\n \
8268 x64.ret_val_64 %0($rax)\n}\n"
8269 );
8270 }
8271
8272 #[test]
8273 fn the_address_of_a_thread_local_is_an_offset_out_of_the_table_plus_where_this_thread_starts() {
8274 let (mut names, mut source, block, _) = blank(&[]);
8275 let own = address_of(&mut source, block, &mut names, "own");
8276 Builder::new(&mut source, block).ret(&[own]);
8277 let elsewhere = Elsewhere::default().with_threads([names.intern("own")]);
8278
8279 // `extern _Thread_local int own; void *f(void) { return &own; }`. Three instructions where
8280 // the two cases above are one, because there is no address to load or to work out: the
8281 // slot holds how far into a thread's block the variable sits, `%fs:0` is where this
8282 // thread's block starts, and the sum of the two is this thread's copy.
8283 let out = func(&source, &mut names, &SELECTOR, &SYSV, &elsewhere)
8284 .expect("every instruction has a rule");
8285 assert_eq!(
8286 mir::print_func(&out.func, &names, ®S),
8287 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rm_64 [thread @own]\n \
8288 %1:gpr = x64.mov_rm_64 [fs:0]\n %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n \
8289 x64.ret_val_64 %2($rax)\n}\n"
8290 );
8291 }
8292
8293 /// The same load with nothing added to it, which is the whole of `__builtin_thread_pointer`.
8294 #[test]
8295 fn the_start_of_this_thread_s_own_storage_is_the_one_load_and_no_arithmetic() {
8296 let (mut names, mut source, block, _) = blank(&[]);
8297 let here =
8298 Builder::new(&mut source, block).value(InstData::new(Opcode::ThreadPointer), Type::PTR);
8299 Builder::new(&mut source, block).ret(&[here]);
8300
8301 let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8302 .expect("every instruction has a rule");
8303 assert_eq!(
8304 mir::print_func(&out.func, &names, ®S),
8305 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rm_64 [fs:0]\n \
8306 x64.ret_val_64 %0($rax)\n}\n"
8307 );
8308 }
8309
8310 /// One `asm` statement, with its template and its constraint list written as a program does.
8311 fn assembly(
8312 source: &mut Func,
8313 block: Block,
8314 names: &mut Interner,
8315 template: &str,
8316 constraints: &str,
8317 args: &[Value],
8318 results: &[Type],
8319 ) -> Inst {
8320 clobbering(source, block, names, template, constraints, "memory", args, results)
8321 }
8322
8323 /// The same with a clobber list of its own, for the statements that are about one.
8324 #[allow(clippy::too_many_arguments)]
8325 fn clobbering(
8326 source: &mut Func,
8327 block: Block,
8328 names: &mut Interner,
8329 template: &str,
8330 constraints: &str,
8331 clobbers: &str,
8332 args: &[Value],
8333 results: &[Type],
8334 ) -> Inst {
8335 let info = AsmInfo {
8336 template: names.intern(template),
8337 constraints: names.intern(constraints),
8338 clobbers: names.intern(clobbers),
8339 targets: rucc_ir::BlockCallList::EMPTY,
8340 };
8341 Builder::new(source, block).inline_asm(info, args, results, Flags::VOLATILE)
8342 }
8343
8344 /// What a program asking the processor what it can do writes, which is the instruction whose
8345 /// every operand is a register its text does not name.
8346 #[test]
8347 fn a_template_whose_registers_are_named_by_the_constraints_places_them_from_the_letters() {
8348 let u32 = Type::int(32);
8349 let (mut names, mut source, block, _) = blank(&[]);
8350 let zero = Builder::new(&mut source, block).iconst(u32, 0);
8351 let out = clobbering(
8352 &mut source,
8353 block,
8354 &mut names,
8355 "cpuid",
8356 "=a,a",
8357 "ebx,ecx,edx",
8358 &[zero],
8359 &[u32],
8360 );
8361 let produced = source[out].results().next().expect("one result");
8362 Builder::new(&mut source, block).ret(&[produced]);
8363
8364 // `asm ("cpuid" : "=a" (n) : "a" (0) : "ebx", "ecx", "edx")`, which is the first thing
8365 // every program that has a faster path on some machines writes. Four registers written and
8366 // two read, none of them in the template, all of them out of the description, and the two
8367 // that the letters named are the statement's own. The subleaf is a zero because the
8368 // instruction reads `ecx` and the program said nothing about what is in it. The three
8369 // clobbers are gone because `cpuid` writes those three anyway, and saying it twice is one
8370 // register with two definitions.
8371 assert_eq!(
8372 lower(&mut names, &source),
8373 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_32 0\n \
8374 %1:gpr = x64.mov_ri_64 0\n \
8375 %2:gpr($rax), %3:gpr($rbx), %4:gpr($rcx), %5:gpr($rdx) = x64.cpuid %0($rax), \
8376 %1($rcx)\n x64.ret_val_32 %2($rax)\n}\n"
8377 );
8378 }
8379
8380 /// An operand the program pinned, by declaring the object it comes from `register long x asm
8381 /// ("r12")`. The letter on its own leaves the allocator to pick, and a template that reads the
8382 /// register by name needs the two to be the same register, so the brace is what ties them
8383 /// together. That is the one use of a local register variable the GNU manual calls reliable,
8384 /// and it is what tcc's `tests/tcctest.c` counts on.
8385 #[test]
8386 fn an_operand_the_program_pinned_is_placed_in_the_register_it_named() {
8387 let u64 = Type::int(64);
8388 let (mut names, mut source, block, _) = blank(&[]);
8389 let out =
8390 assembly(&mut source, block, &mut names, "mov $0x4542, %r12", "=r{r12}", &[], &[u64]);
8391 let produced = source[out].results().next().expect("one result");
8392 Builder::new(&mut source, block).ret(&[produced]);
8393
8394 // The template is one instruction the table already has, so it lowers to that instruction
8395 // rather than to text nobody read, and the register it names is the statement's own output
8396 // because the brace put the output there. Without the brace the letter would have let the
8397 // allocator pick, the two `%r12` would have been different registers, and the program would
8398 // have come back with whatever was in the one it picked.
8399 assert_eq!(
8400 lower(&mut names, &source),
8401 "mfunc @f {\nblock0:\n %0:gpr($r12) = x64.mov_ri_64 17730\n \
8402 x64.ret_val_64 %0($rax)\n}\n"
8403 );
8404 }
8405
8406 /// A clobber the instruction does not write itself, which is the case the list is there for.
8407 /// It goes on as a definition of the register, in among the other definitions, because that is
8408 /// the whole of how a machine function says a register is not worth anything after this.
8409 #[test]
8410 fn a_clobber_the_instruction_does_not_write_itself_is_a_definition_of_that_register() {
8411 let (mut names, mut source, block, _) = blank(&[]);
8412 clobbering(&mut source, block, &mut names, "pause", "", "rsi,cc,memory", &[], &[]);
8413 Builder::new(&mut source, block).ret(&[]);
8414
8415 assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n $rsi = x64.pause\n}\n");
8416 }
8417
8418 /// A clobber naming something this has no register for. Refused rather than dropped, since the
8419 /// list is the program saying which registers it may not leave anything in, and an entry
8420 /// nobody read is a register something may still be left in.
8421 #[test]
8422 fn a_clobber_this_has_no_register_for_is_refused() {
8423 let (mut names, mut source, block, _) = blank(&[]);
8424 clobbering(&mut source, block, &mut names, "pause", "", "zmm0", &[], &[]);
8425 Builder::new(&mut source, block).ret(&[]);
8426
8427 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8428 .expect_err("there is no such register here");
8429 assert_eq!(
8430 failed.to_string(),
8431 "this `asm` says it destroys a register this has no name for"
8432 );
8433 }
8434
8435 #[test]
8436 fn an_asm_with_an_empty_template_and_no_operands_is_no_instructions() {
8437 let (mut names, mut source, block, _) = blank(&[]);
8438 assembly(&mut source, block, &mut names, "", "", &[], &[]);
8439 Builder::new(&mut source, block).ret(&[]);
8440
8441 // `asm volatile ("" : : : "memory")`, which is a barrier and nothing else. The barrier was
8442 // spent on the optimizer, which has finished by now, so what is left is nothing.
8443 assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n}\n");
8444 }
8445
8446 #[test]
8447 fn an_output_an_input_is_tied_to_is_the_register_that_input_arrived_in() {
8448 let i32 = Type::int(32);
8449 let (mut names, mut source, block, args) = blank(&[i32]);
8450 let out = assembly(&mut source, block, &mut names, "", "=r,0", &args, &[i32]);
8451 let produced = source[out].results().next().expect("one result");
8452 Builder::new(&mut source, block).ret(&[produced]);
8453
8454 // `asm ("" : "=r" (x) : "0" (x))`, which is how a program stops the optimizer following a
8455 // value without changing it. The two share a place and the template writes nothing over
8456 // it, so the value comes back out of the register it went in.
8457 assert_eq!(
8458 lower(&mut names, &source),
8459 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
8460 x64.ret_val_32 %0($rax)\n}\n"
8461 );
8462 }
8463
8464 #[test]
8465 fn an_output_written_plus_is_the_same_rename() {
8466 let i32 = Type::int(32);
8467 let (mut names, mut source, block, args) = blank(&[i32]);
8468 let out = assembly(&mut source, block, &mut names, "", "+r", &args, &[i32]);
8469 let produced = source[out].results().next().expect("one result");
8470 Builder::new(&mut source, block).ret(&[produced]);
8471
8472 // `asm ("" : "+r" (x))`, which says the same thing in one operand instead of two.
8473 assert_eq!(
8474 lower(&mut names, &source),
8475 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
8476 x64.ret_val_32 %0($rax)\n}\n"
8477 );
8478 }
8479
8480 #[test]
8481 fn an_output_nothing_is_tied_to_is_a_zero() {
8482 let i32 = Type::int(32);
8483 let (mut names, mut source, block, _) = blank(&[]);
8484 let out = assembly(&mut source, block, &mut names, "", "=r", &[], &[i32]);
8485 let produced = source[out].results().next().expect("one result");
8486 Builder::new(&mut source, block).ret(&[produced]);
8487
8488 // `asm ("" : "=r" (y))`, whose answer is whatever the assembly left in the register, and
8489 // an empty template leaves nothing. A definite value rather than a register nothing wrote,
8490 // because the allocator is owed a definition before the use however little the program is.
8491 assert_eq!(
8492 lower(&mut names, &source),
8493 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_32 0\n x64.ret_val_32 %0($rax)\n}\n"
8494 );
8495 }
8496
8497 #[test]
8498 fn a_template_that_is_one_instruction_becomes_that_instruction() {
8499 let (mut names, mut source, block, _) = blank(&[]);
8500 assembly(&mut source, block, &mut names, "pause", "", &[], &[]);
8501 Builder::new(&mut source, block).ret(&[]);
8502
8503 // `asm volatile ("pause")`, which is what every spin lock in every allocator writes. One
8504 // instruction, no operands, and nothing between the template and the machine but the table
8505 // that already says what a `pause` is.
8506 assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n x64.pause\n}\n");
8507 }
8508
8509 #[test]
8510 fn a_template_that_reads_a_segment_becomes_the_load_it_already_was() {
8511 let i64 = Type::int(64);
8512 let (mut names, mut source, block, _) = blank(&[]);
8513 let out = assembly(&mut source, block, &mut names, "movq %%fs:0, %0", "=r", &[], &[i64]);
8514 let produced = source[out].results().next().expect("one result");
8515 Builder::new(&mut source, block).ret(&[produced]);
8516
8517 // `asm ("movq %%fs:0, %0" : "=r" (tid))`, which is how a program finds the block its own
8518 // thread owns. The same instruction `crate::lower` already writes for a thread-local
8519 // variable, reached this time because a program wrote it out by hand.
8520 assert_eq!(
8521 lower(&mut names, &source),
8522 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rm_64 [fs:0]\n \
8523 x64.ret_val_64 %0($rax)\n}\n"
8524 );
8525 }
8526
8527 /// A template this cannot read is kept as its text, which is what gcc does with every template.
8528 /// Whether the text is an instruction is the assembler's question, asked when the unit is
8529 /// assembled from its listing.
8530 #[test]
8531 fn a_template_naming_an_instruction_this_machine_has_not_got_is_kept_as_text() {
8532 let (mut names, mut source, block, _) = blank(&[]);
8533 assembly(&mut source, block, &mut names, "hcf", "", &[], &[]);
8534 Builder::new(&mut source, block).ret(&[]);
8535
8536 let printed = lower(&mut names, &source);
8537 assert!(printed.contains("x64.template"), "{printed}");
8538 assert!(printed.contains("@hcf"), "{printed}");
8539 }
8540
8541 /// A template kept as text with an operand in a register reads the operand, and its text holds
8542 /// a hole naming that operand of the instruction, which the writer fills with the register the
8543 /// allocator chose. The input is the instruction's only use, behind every register a call may
8544 /// write.
8545 #[test]
8546 fn a_template_kept_as_text_reads_an_operand_in_a_register_through_a_hole() {
8547 let i32 = Type::int(32);
8548 let (mut names, mut source, block, args) = blank(&[i32]);
8549 assembly(&mut source, block, &mut names, "hcf %0", "r", &[args[0]], &[]);
8550 Builder::new(&mut source, block).ret(&[]);
8551
8552 let printed = lower(&mut names, &source);
8553 let line = printed.lines().find(|line| line.contains("x64.template")).unwrap_or_default();
8554 // Twenty five registers are written ahead of it, so the operand read is the twenty sixth,
8555 // spelled at the width of an `int`.
8556 assert!(line.contains("x64.template %0, @hcf \u{1}r25k\u{2}"), "{printed}");
8557 assert!(line.contains("early $rax"), "{printed}");
8558 }
8559
8560 /// A template kept as text with more outputs than the convention keeps registers across a call
8561 /// gets back as many of the registers a call may write as it needs, from the end of the order,
8562 /// and keeps the rest. Six outputs against five preserved registers is one handed back, which is
8563 /// `r11`. The shape is `sodium_sub` in libsodium, whose `sbbq` into memory the reader has no
8564 /// form for, and before this the allocator ran out of registers on it.
8565 #[test]
8566 fn a_template_kept_as_text_with_more_outputs_than_are_kept_gets_registers_back() {
8567 let i64 = Type::int(64);
8568 let (mut names, mut source, block, _) = blank(&[]);
8569 let outputs = [i64; 6];
8570 let asm = assembly(
8571 &mut source,
8572 block,
8573 &mut names,
8574 "hcf %0, %1, %2, %3, %4, %5",
8575 "=&r,=&r,=&r,=&r,=&r,=&r",
8576 &[],
8577 &outputs,
8578 );
8579 let produced: Vec<Value> = source[asm].results().collect();
8580 Builder::new(&mut source, block).ret(&produced[..1]);
8581
8582 let printed = lower(&mut names, &source);
8583 let line = printed.lines().find(|line| line.contains("x64.template")).unwrap_or_default();
8584 assert!(line.contains("early $r10"), "{printed}");
8585 assert!(!line.contains("early $r11"), "{printed}");
8586 }
8587
8588 /// A register the template named is placed as itself, fixed to the register the program wrote
8589 /// down. A register a constraint letter names is a different thing and is placed too, which the
8590 /// test above is about: there the statement said which of its own operands is in the register,
8591 /// and a name in the middle of a template says the register and nothing about any operand.
8592 #[test]
8593 fn a_template_naming_a_register_gets_that_register() {
8594 let i64 = Type::int(64);
8595 let (mut names, mut source, block, _) = blank(&[]);
8596 let out = assembly(&mut source, block, &mut names, "movq %%rax, %0", "=r", &[], &[i64]);
8597 let produced = source[out].results().next().expect("one result");
8598 Builder::new(&mut source, block).ret(&[produced]);
8599
8600 // `asm ("movq %%rax, %0" : "=r" (x))`, which is a program reading whatever is in `%rax`.
8601 // The source is the register itself and the destination is one the allocator picks.
8602 assert_eq!(
8603 lower(&mut names, &source),
8604 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rr_64 $rax($rax)\n \
8605 x64.ret_val_64 %0($rax)\n}\n"
8606 );
8607 }
8608
8609 /// The half of the same thing every register saving template needs. micropython writes the
8610 /// callee-saved registers into a buffer one `movq %%r12, 48(%%rdi)` at a time, and both halves
8611 /// of that line are a register the template named: the one being stored and the one the address
8612 /// is counted from.
8613 #[test]
8614 fn a_template_counting_an_address_from_a_register_it_named_gets_that_register() {
8615 let (mut names, mut source, block, _) = blank(&[]);
8616 assembly(&mut source, block, &mut names, "movq %%r12, 48(%%rdi)", "", &[], &[]);
8617 Builder::new(&mut source, block).ret(&[]);
8618
8619 assert_eq!(
8620 lower(&mut names, &source),
8621 "mfunc @f {\nblock0:\n x64.mov_mr_64 $r12($r12), [$rdi + 48]\n}\n"
8622 );
8623 }
8624
8625 /// A local kept in a named register, which is the same register named as itself and reached
8626 /// from the other side. micropython's collector writes six of these and reads them with
8627 /// ordinary C rather than with a template.
8628 #[test]
8629 fn a_local_kept_in_a_named_register_is_one_move_out_of_it() {
8630 let (mut names, mut source, block, _) = blank(&[]);
8631 let held = names.intern("rbx");
8632 let value = Builder::new(&mut source, block).value(
8633 InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
8634 Type::int(64),
8635 );
8636 Builder::new(&mut source, block).ret(&[value]);
8637
8638 assert_eq!(
8639 lower(&mut names, &source),
8640 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rr_64 $rbx($rbx)\n \
8641 x64.ret_val_64 %0($rax)\n}\n"
8642 );
8643 }
8644
8645 /// The sigil gcc allows in front of the name is syntax and comes off, and a name that is not
8646 /// a register of this machine is refused in words that say which name it was.
8647 #[test]
8648 fn a_register_name_is_read_with_or_without_its_sigil_and_refused_when_there_is_no_such_one() {
8649 for written in ["%r12", "r12"] {
8650 let (mut names, mut source, block, _) = blank(&[]);
8651 let held = names.intern(written);
8652 let value = Builder::new(&mut source, block).value(
8653 InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
8654 Type::int(64),
8655 );
8656 Builder::new(&mut source, block).ret(&[value]);
8657 assert!(lower(&mut names, &source).contains("$r12($r12)"), "{written} is not read");
8658 }
8659
8660 let (mut names, mut source, block, _) = blank(&[]);
8661 let held = names.intern("nowhere");
8662 let value = Builder::new(&mut source, block).value(
8663 InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
8664 Type::int(64),
8665 );
8666 Builder::new(&mut source, block).ret(&[value]);
8667
8668 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8669 .expect_err("there is no such register");
8670 assert_eq!(
8671 failed.to_string(),
8672 "this object is kept in `nowhere`, which is not a register this machine has"
8673 );
8674 }
8675
8676 #[test]
8677 fn a_constraint_list_that_does_not_describe_the_operands_is_refused() {
8678 let i32 = Type::int(32);
8679 let (mut names, mut source, block, args) = blank(&[i32]);
8680 assembly(&mut source, block, &mut names, "", "=r", &args, &[]);
8681 Builder::new(&mut source, block).ret(&[]);
8682
8683 // An output with no result to be, which is what the front end never writes and what a
8684 // hand written module can. Refused rather than placed by a guess.
8685 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8686 .expect_err("the list and the instruction disagree");
8687 assert_eq!(failed.to_string(), "this `asm` has an operand this cannot place");
8688 }
8689
8690 /// A cast between a pointer and an integer, at whatever width the result is asked for.
8691 fn cast(source: &mut Func, block: Block, opcode: Opcode, from: Value, to: Type) -> Value {
8692 let mut build = Builder::new(source, block);
8693 let args = build.func().push_values(&[from]);
8694 build.value(InstData { args, ..InstData::new(opcode) }, to)
8695 }
8696
8697 #[test]
8698 fn a_cast_between_a_pointer_and_an_integer_as_wide_is_no_instruction_at_all() {
8699 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
8700 let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(64));
8701 Builder::new(&mut source, block).ret(&[number]);
8702
8703 // `long f(void *p) { return (long)p; }`. An address on this machine is an integer as wide
8704 // as the machine addresses, so the cast changes what the type system calls the value and
8705 // changes nothing about the value, and the register holding it is the one that held it.
8706 assert_eq!(
8707 lower(&mut names, &source),
8708 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
8709 x64.ret_val_64 %0($rax)\n}\n"
8710 );
8711 }
8712
8713 #[test]
8714 fn a_null_pointer_is_a_constant_that_reaches_a_register_before_anything_reads_it() {
8715 let (mut names, mut source, block, _) = blank(&[]);
8716 let mut build = Builder::new(&mut source, block);
8717 let zero = build.iconst(Type::int(64), 0);
8718 let null = cast(&mut source, block, Opcode::IntToPtr, zero, Type::PTR);
8719 Builder::new(&mut source, block).ret(&[null]);
8720
8721 // `void *f(void) { return 0; }`. The cast is nothing, and reading its operand is what
8722 // writes the zero down: a constant is materialized where it is wanted rather than where
8723 // the IR defined it, and without the read there would be no instruction at all.
8724 assert_eq!(
8725 lower(&mut names, &source),
8726 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_64 0\n x64.ret_val_64 %0($rax)\n}\n"
8727 );
8728 }
8729
8730 #[test]
8731 fn the_five_linkages_the_ir_has_narrow_to_the_three_an_object_file_can_say() {
8732 let readings = [
8733 (Linkage::External, mir::Binding::Global),
8734 (Linkage::Common, mir::Binding::Global),
8735 (Linkage::Internal, mir::Binding::Local),
8736 (Linkage::Weak, mir::Binding::Weak),
8737 (Linkage::LinkOnce, mir::Binding::Weak),
8738 ];
8739 for (linkage, wanted) in readings {
8740 let (mut names, mut source, block, _) = blank(&[]);
8741 source.linkage = linkage;
8742 Builder::new(&mut source, block).ret(&[]);
8743 let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8744 .expect("a return");
8745 // The narrowing is done here rather than where the object is written, because a
8746 // machine function is all the assembler and the writer are ever handed.
8747 assert_eq!(out.func.binding, wanted, "{linkage:?}");
8748 }
8749 }
8750
8751 /// The visibility makes the same trip and is not narrowed on the way, because ELF says all
8752 /// three of them.
8753 ///
8754 /// Here for the reason the linkage above is here. A machine function is the whole of what the
8755 /// assembler and the object writer are handed, so a fact about the symbol that does not get
8756 /// onto one is a fact that is gone by the time anything could write it down, and the way that
8757 /// shows up is a shared library exporting the wrong set of names with nothing said anywhere.
8758 #[test]
8759 fn the_visibility_survives_the_trip_from_the_ir_to_a_machine_function() {
8760 let readings = [
8761 (Visibility::Default, mir::Visibility::Default),
8762 (Visibility::Hidden, mir::Visibility::Hidden),
8763 (Visibility::Protected, mir::Visibility::Protected),
8764 ];
8765 for (visibility, wanted) in readings {
8766 let (mut names, mut source, block, _) = blank(&[]);
8767 source.visibility = visibility;
8768 Builder::new(&mut source, block).ret(&[]);
8769 let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8770 .expect("a return");
8771 assert_eq!(out.func.visibility, wanted, "{visibility:?}");
8772 }
8773 }
8774
8775 #[test]
8776 fn a_cast_between_a_pointer_and_a_narrower_integer_is_reported() {
8777 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
8778 let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(32));
8779 Builder::new(&mut source, block).ret(&[number]);
8780
8781 // The front end never writes one: it casts at the address width and truncates or extends
8782 // around it, so both of those are the rules they always were. IR from somewhere else that
8783 // does write one is refused rather than compiled to a move that keeps the high half.
8784 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8785 .expect_err("no rule narrows an address");
8786 assert_eq!(failed.to_string(), "no rule lowers a `ptrtoint` producing a `i32`");
8787 }
8788
8789 /// The type this machine has no register for.
8790 fn long_double() -> Type {
8791 Type::float(rucc_ir::Float::F80)
8792 }
8793
8794 #[test]
8795 fn a_double_widened_and_narrowed_again_goes_out_through_the_frame_and_back() {
8796 let f64 = Type::float(rucc_ir::Float::F64);
8797 let (mut names, mut source, block, args) = blank(&[f64]);
8798 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
8799 let back = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
8800 Builder::new(&mut source, block).ret(&[back]);
8801
8802 // `double f(double d) { long double x = d; return x; }`. The x87 reads memory and nothing
8803 // else, so the value is written to the crossing slot, loaded at the format that widens it
8804 // and put in the slot the eighty bit value lives in. Coming back is the same three the
8805 // other way. Both slots are addressed by a `lea` with nothing in it yet, which is what
8806 // every address in a frame looks like here until `finish` has the numbers.
8807 assert_eq!(
8808 lower(&mut names, &source),
8809 "mfunc @f {\nblock0:\n \
8810 %0:xmm($xmm0) = x64.arg_val_f64\n \
8811 %1:gpr = x64.lea_64 [$rsp]\n \
8812 %2:gpr = x64.lea_64 [$rsp]\n \
8813 x64.movsd_mr %0, [%1]\n \
8814 x64.fld_l [%1]\n \
8815 x64.fstp_t [%2]\n \
8816 %3:gpr = x64.lea_64 [$rsp]\n \
8817 %4:gpr = x64.lea_64 [$rsp]\n \
8818 x64.fld_t [%3]\n \
8819 x64.fstp_l [%4]\n \
8820 %5:xmm = x64.movsd_rm [%4]\n \
8821 x64.ret_val_f64 %5($xmm0)\n}\n"
8822 );
8823 }
8824
8825 #[test]
8826 fn a_long_double_has_sixteen_bytes_of_its_own_and_keeps_them() {
8827 let f64 = Type::float(rucc_ir::Float::F64);
8828 let (mut names, mut source, block, args) = blank(&[f64]);
8829 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
8830 let once = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
8831 let twice = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
8832 let mut build = Builder::new(&mut source, block);
8833 let sum = build.binary(Opcode::FAdd, once, twice, Flags::default());
8834 build.ret(&[sum]);
8835
8836 let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8837 .expect("every instruction is written");
8838
8839 // Two slots and not four: sixteen bytes for the one eighty bit value, which is what the
8840 // psABI says one takes and is aligned to, and eight for the crossing, which every group
8841 // in the function shares because nothing is ever left in it. The value's slot is its own
8842 // for the whole function, so reading it twice reads the same sixteen bytes.
8843 assert_eq!(
8844 out.stack.locals,
8845 vec![Local { size: 8, align: 8 }, Local { size: 16, align: 16 }]
8846 );
8847 }
8848
8849 #[test]
8850 fn an_integer_becomes_a_long_double_by_being_loaded_as_one() {
8851 let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
8852 let wide = cast(&mut source, block, Opcode::SIToFP, args[0], long_double());
8853 let back =
8854 cast(&mut source, block, Opcode::FPTrunc, wide, Type::float(rucc_ir::Float::F64));
8855 Builder::new(&mut source, block).ret(&[back]);
8856
8857 // `double f(long n) { long double x = n; return x; }`. `fild` is the same push at another
8858 // format, so the conversion is the load and there is no instruction that converts.
8859 let text = lower(&mut names, &source);
8860 assert!(text.contains("x64.mov_mr_64 %0, [%1]"), "{text}");
8861 assert!(text.contains("x64.fild_ll [%1]"), "{text}");
8862 }
8863
8864 #[test]
8865 fn a_long_double_becoming_an_integer_cuts_towards_zero_with_the_control_word() {
8866 let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
8867 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
8868 let whole = cast(&mut source, block, Opcode::FPToSI, wide, Type::int(32));
8869 Builder::new(&mut source, block).ret(&[whole]);
8870
8871 // The one conversion here with no single instruction behind it. C cuts towards zero and
8872 // the unit rounds the way its control word says, so the word is saved, ORed with the two
8873 // bits that mean truncate, loaded, used and put back. Nine instructions for what `fisttp`
8874 // does in one, and `spec/10-backend.md` section 10.8 says why that one is not used.
8875 let text = lower(&mut names, &source);
8876 let group: Vec<&str> = text
8877 .lines()
8878 .map(str::trim)
8879 .filter(|line| line.starts_with("x64.f") || line.contains("_16"))
8880 .collect();
8881 assert_eq!(
8882 group,
8883 [
8884 "x64.fld_l [%1]",
8885 "x64.fstp_t [%2]",
8886 "x64.fnstcw [%5]",
8887 "%6:gpr = x64.mov_rm_16 [%5]",
8888 "%7:gpr(reuse 1) = x64.or_ri_16 %6, 3072",
8889 "x64.mov_mr_16 %7, [%5 + 2]",
8890 "x64.fldcw [%5 + 2]",
8891 "x64.fld_t [%3]",
8892 "x64.fistp_l [%4]",
8893 "x64.fldcw [%5]",
8894 ],
8895 "{text}"
8896 );
8897 }
8898
8899 #[test]
8900 fn a_long_double_is_read_and_written_as_the_bits_it_already_is() {
8901 let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::PTR]);
8902 let mut build = Builder::new(&mut source, block);
8903 let value = build.load(long_double(), args[0], plain(), Flags::default());
8904 build.store(value, args[1], plain(), Flags::default());
8905 build.ret(&[]);
8906
8907 // `void f(long double *a, long double *b) { *b = *a; }`. A copy is a push and a pop at the
8908 // format the value is already in, which neither converts nor looks: a signalling NaN stays
8909 // one and nothing is raised, which is the whole of what makes it a copy.
8910 let text = lower(&mut names, &source);
8911 let group: Vec<&str> =
8912 text.lines().map(str::trim).filter(|line| line.starts_with("x64.f")).collect();
8913 assert_eq!(
8914 group,
8915 ["x64.fld_t [%0]", "x64.fstp_t [%2]", "x64.fld_t [%3]", "x64.fstp_t [%1]"],
8916 "{text}"
8917 );
8918 }
8919
8920 /// Two `long double` values, from two `double` parameters, and the instructions that made
8921 /// them, which every test below this one throws away.
8922 fn two_long_doubles(source: &mut Func, block: Block, args: &[Value]) -> (Value, Value) {
8923 let left = cast(source, block, Opcode::FPExt, args[0], long_double());
8924 let right = cast(source, block, Opcode::FPExt, args[1], long_double());
8925 (left, right)
8926 }
8927
8928 /// The x87 instructions of a function, in order, with everything else dropped.
8929 fn stack_only(text: &str) -> Vec<&str> {
8930 text.lines().map(str::trim).filter(|line| line.contains("x64.f")).collect()
8931 }
8932
8933 /// The two frame slots the last two addresses of a function were taken of, which in a
8934 /// comparison are the two operands in the order they go on the stack.
8935 fn pushed(out: &Lowered) -> Vec<usize> {
8936 let taken: Vec<usize> = out.stack.addresses.iter().map(|&(_, local)| local).collect();
8937 taken[taken.len() - 2..].to_vec()
8938 }
8939
8940 #[test]
8941 fn adding_two_long_doubles_pushes_both_and_leaves_the_answer_in_a_slot() {
8942 let f64 = Type::float(rucc_ir::Float::F64);
8943 let (mut names, mut source, block, args) = blank(&[f64, f64]);
8944 let (left, right) = two_long_doubles(&mut source, block, &args);
8945 let sum =
8946 Builder::new(&mut source, block).binary(Opcode::FAdd, left, right, Flags::default());
8947 let back = cast(&mut source, block, Opcode::FPTrunc, sum, f64);
8948 Builder::new(&mut source, block).ret(&[back]);
8949
8950 // `double f(double a, double b) { return (long double) a + (long double) b; }`. The last
8951 // four lines are the add: both operands pushed, the instruction that names neither of
8952 // them because they are the top two of a stack, and the answer taken off into its slot.
8953 let text = lower(&mut names, &source);
8954 assert_eq!(
8955 stack_only(&text),
8956 [
8957 "x64.fld_l [%2]",
8958 "x64.fstp_t [%3]",
8959 "x64.fld_l [%4]",
8960 "x64.fstp_t [%5]",
8961 "x64.fld_t [%6]",
8962 "x64.fld_t [%7]",
8963 "x64.fadd_p",
8964 "x64.fstp_t [%8]",
8965 "x64.fld_t [%9]",
8966 "x64.fstp_l [%10]",
8967 ],
8968 "{text}"
8969 );
8970 }
8971
8972 #[test]
8973 fn a_subtraction_pushes_the_left_operand_first_and_asks_for_the_att_spelling() {
8974 let f64 = Type::float(rucc_ir::Float::F64);
8975 let (mut names, mut source, block, args) = blank(&[f64, f64]);
8976 let (left, right) = two_long_doubles(&mut source, block, &args);
8977 let less =
8978 Builder::new(&mut source, block).binary(Opcode::FSub, left, right, Flags::default());
8979 let back = cast(&mut source, block, Opcode::FPTrunc, less, f64);
8980 Builder::new(&mut source, block).ret(&[back]);
8981
8982 // The left one goes on first, so it ends up under the right one, and the answer wanted is
8983 // the one below minus the top. In AT&T that is `fsubrp`, since `fsubp` there is `DE E0+i`
8984 // and computes the other one. The `r` says which spelling this is and not which order the
8985 // pushes were in. `crates/rucc/tests/x87.rs` is what says the answer is right, because a
8986 // name is what got this wrong the first time.
8987 let text = lower(&mut names, &source);
8988 assert_eq!(
8989 &stack_only(&text)[4..8],
8990 ["x64.fld_t [%6]", "x64.fld_t [%7]", "x64.fsubr_p", "x64.fstp_t [%8]"],
8991 "{text}"
8992 );
8993 }
8994
8995 #[test]
8996 fn negating_a_long_double_turns_the_sign_over_and_reads_nothing() {
8997 let f64 = Type::float(rucc_ir::Float::F64);
8998 let (mut names, mut source, block, args) = blank(&[f64]);
8999 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
9000 let flipped = Builder::new(&mut source, block).unary(Opcode::FNeg, wide, long_double());
9001 let back = cast(&mut source, block, Opcode::FPTrunc, flipped, f64);
9002 Builder::new(&mut source, block).ret(&[back]);
9003
9004 // `fchs` and not a subtraction from zero, which would give a different answer at a negative
9005 // zero and would signal at a NaN. It does not read the value as a number at all.
9006 let text = lower(&mut names, &source);
9007 assert_eq!(
9008 &stack_only(&text)[2..5],
9009 ["x64.fld_t [%3]", "x64.fchs", "x64.fstp_t [%4]"],
9010 "{text}"
9011 );
9012 }
9013
9014 #[test]
9015 fn comparing_two_long_doubles_puts_the_left_one_on_top() {
9016 let f64 = Type::float(rucc_ir::Float::F64);
9017 let (mut names, mut source, block, args) = blank(&[f64, f64]);
9018 let (left, right) = two_long_doubles(&mut source, block, &args);
9019 let mut build = Builder::new(&mut source, block);
9020 build.fcmp(FloatPred::Ogt, left, right, Flags::default());
9021 build.ret(&[]);
9022
9023 // `a > b`. `fucomip` asks about the top of the stack against what is under it, so the
9024 // operand the predicate is about has to go on last, which is the other way round from the
9025 // arithmetic above. The pop that clears the loser and the byte that reads the flags are
9026 // both inside the one opcode.
9027 let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9028 .expect("every instruction is written");
9029 let slots = pushed(&out);
9030 assert_eq!(slots, [2, 1], "the right operand goes on first and the left one on top");
9031 let text = mir::print_func(&out.func, &names, ®S);
9032 assert_eq!(
9033 &stack_only(&text)[4..],
9034 ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
9035 "{text}"
9036 );
9037 }
9038
9039 #[test]
9040 fn a_comparison_that_the_machine_has_backwards_swaps_the_two_pushes() {
9041 let f64 = Type::float(rucc_ir::Float::F64);
9042 let (mut names, mut source, block, args) = blank(&[f64, f64]);
9043 let (left, right) = two_long_doubles(&mut source, block, &args);
9044 let mut build = Builder::new(&mut source, block);
9045 build.fcmp(FloatPred::Olt, left, right, Flags::default());
9046 build.ret(&[]);
9047
9048 // `a < b` is `b > a` and this machine has the one condition, so the same opcode runs with
9049 // the operands the other way round. The same trade the vector rules make, and it has to
9050 // be the same one: a `long double` comparison that picked a different condition from the
9051 // `double` comparison of the same two numbers would be wrong at exactly the unordered
9052 // cases the two conditions differ on.
9053 //
9054 // Which slot each push names is the whole of the difference from the test above, and the
9055 // text does not show it, since an address in a frame is a `lea` with nothing in it until
9056 // `finish` has the numbers. So the slots are what is read here.
9057 let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9058 .expect("every instruction is written");
9059 let slots = pushed(&out);
9060 assert_eq!(slots, [1, 2], "the left operand goes on first and the right one on top");
9061 let text = mir::print_func(&out.func, &names, ®S);
9062 assert_eq!(
9063 &stack_only(&text)[4..],
9064 ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
9065 "{text}"
9066 );
9067 }
9068
9069 #[test]
9070 fn an_ordered_equal_needs_a_second_byte_to_put_the_two_conditions_together() {
9071 let f64 = Type::float(rucc_ir::Float::F64);
9072 let (mut names, mut source, block, args) = blank(&[f64, f64]);
9073 let (left, right) = two_long_doubles(&mut source, block, &args);
9074 let mut build = Builder::new(&mut source, block);
9075 build.fcmp(FloatPred::Oeq, left, right, Flags::default());
9076 build.ret(&[]);
9077
9078 // Equal and ordered are two conditions and the flags carry both, so the opcode writes a
9079 // second register as well as the one the value is in and ANDs them together. Said here by
9080 // handing it a spare, since an instruction that wrote a register nothing knew about would
9081 // be an instruction the allocator could put a live value in the way of.
9082 let text = lower(&mut names, &source);
9083 assert!(text.contains("%8:gpr, %9:gpr = x64.fucomip_set_e_and_np"), "{text}");
9084 }
9085
9086 #[test]
9087 fn a_comparison_that_is_never_asked_is_reported() {
9088 let f64 = Type::float(rucc_ir::Float::F64);
9089 let (mut names, mut source, block, args) = blank(&[f64, f64]);
9090 let (left, right) = two_long_doubles(&mut source, block, &args);
9091 let mut build = Builder::new(&mut source, block);
9092 build.fcmp(FloatPred::False, left, right, Flags::default());
9093 build.ret(&[]);
9094
9095 // Always false is a constant and not a comparison, so there is no condition to pick and
9096 // nothing here folds it into one: an instruction that quietly agreed with it would hide
9097 // that the optimizer left a comparison in that it should have taken out.
9098 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9099 .expect_err("no condition is always false");
9100 assert_eq!(failed.to_string(), "no rule lowers a `fcmp` producing a `i1`");
9101 }
9102
9103 #[test]
9104 fn a_long_double_constant_is_the_bits_of_it_put_where_the_value_lives() {
9105 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
9106 let mut build = Builder::new(&mut source, block);
9107 // `1.5L`, which is the leading bit and one more of significand, and an exponent of zero.
9108 let one_and_a_half = build.fconst(long_double(), 0x3fff_c000_0000_0000_0000);
9109 build.store(one_and_a_half, args[0], plain(), Flags::default());
9110 build.ret(&[]);
9111
9112 // No x87 instruction at all. A slot holding one of these is the value, so a constant is
9113 // its ten bytes written where the value lives, and whatever reads it does the `fld`.
9114 let text = lower(&mut names, &source);
9115 assert!(text.contains("x64.mov_ri_64 -4611686018427387904"), "{text}");
9116 assert!(text.contains("x64.mov_ri_16 16383"), "{text}");
9117 assert!(text.contains("x64.mov_mr_16 %3, [%1 + 8]"), "{text}");
9118 // The six bytes above the ten are the padding that makes the type sixteen wide, and they
9119 // are unspecified rather than zero, so nothing writes them.
9120 assert_eq!(text.matches("x64.mov_mr").count(), 2, "{text}");
9121 }
9122
9123 #[test]
9124 fn a_negative_long_double_constant_keeps_the_bit_above_its_exponent() {
9125 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
9126 let mut build = Builder::new(&mut source, block);
9127 let minus = build.fconst(long_double(), 0xbfff_c000_0000_0000_0000);
9128 build.store(minus, args[0], plain(), Flags::default());
9129 build.ret(&[]);
9130
9131 // `-1.5L`. The sign is the top bit of the two byte half, so the immediate that half is put
9132 // in a register with is above the signed range of sixteen bits and has to stay there: read
9133 // as a number it would be negative, and it is not a number, it is two bytes.
9134 let text = lower(&mut names, &source);
9135 assert!(text.contains("x64.mov_ri_16 49151"), "{text}");
9136 }
9137
9138 #[test]
9139 fn a_long_double_crosses_an_edge_as_an_address_and_is_copied_where_it_lands() {
9140 let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
9141 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
9142 let next = source.create_block();
9143 let param = source.append_param(next, long_double());
9144 Builder::new(&mut source, block).jump(next, &[wide]);
9145 Builder::new(&mut source, next).ret(&[param]);
9146
9147 // What the edge carries is the address of the slot the value is already in, which is an
9148 // ordinary register the allocator has an opinion about. The block on the other side copies
9149 // the sixteen bytes into a slot of its own before anything reads them, so a second edge
9150 // handing over a second address would still leave one place for a reader to look.
9151 let text = lower(&mut names, &source);
9152 let second: Vec<&str> = text
9153 .lines()
9154 .skip_while(|line| !line.starts_with("block1"))
9155 .skip(1)
9156 .take(3)
9157 .map(str::trim)
9158 .collect();
9159 assert_eq!(
9160 second,
9161 ["x64.fld_t [%4]", "%5:gpr = x64.lea_64 [$rsp]", "x64.fstp_t [%5]"],
9162 "{text}"
9163 );
9164 }
9165
9166 #[test]
9167 fn more_long_doubles_at_a_block_than_the_stack_is_deep_are_reported() {
9168 let f64 = Type::float(rucc_ir::Float::F64);
9169 let (mut names, mut source, block, args) = blank(&[f64]);
9170 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
9171 let next = source.create_block();
9172 let params: Vec<Value> =
9173 (0..=X87_DEPTH).map(|_| source.append_param(next, long_double())).collect();
9174 let carried: Vec<Value> = params.iter().map(|_| wide).collect();
9175 Builder::new(&mut source, block).jump(next, &carried);
9176 Builder::new(&mut source, next).ret(&[params[0]]);
9177
9178 // The copies go through the x87 stack so that every one of them is read before any of them
9179 // is written, which is what makes a block that swaps two of these right. Nine of them do
9180 // not fit on the stack, and copying the ninth before or after the rest is the order that
9181 // could be wrong, so it is refused instead.
9182 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9183 .expect_err("nine do not fit on the stack");
9184 assert_eq!(
9185 failed.to_string(),
9186 "block1 takes 9 parameters of type `f80` and only 8 can cross an edge at once"
9187 );
9188 assert_eq!(failed.inst(), None);
9189 }
9190}