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::x86_64;
89use rucc_target::{CallRegs, Constraint, OperandDesc, PhysReg, RegClass, Role, Segment};
90
91use crate::abi::{self, Missing, Refused};
92use crate::coverage::Fired;
93use crate::elsewhere::Elsewhere;
94use crate::frame::{Layout, Local};
95use crate::select::{Match, Piece, Rule, Table};
96use crate::term::{MAX_ARGS, PLAIN, Plan, Shown, Term, Terms};
97use crate::varargs;
98
99/// The prefix a rule file puts in front of a machine term, which says which target it belongs
100/// to and is not part of the opcode.
101pub(crate) const PREFIX: &str = "x64.";
102
103/// The instruction a global offset table slot is read with.
104///
105/// Not in [`x86_64::FRAME`] with the other opcodes this file names, because a frame has no use for
106/// it. It is spelled out here because the relocation it takes is only legal on a `mov` with a REX
107/// prefix, so the width is part of the requirement rather than a choice.
108const GOT_LOAD: &str = "mov_rm_64";
109
110/// The instruction a template's `jmp` to a name outside it becomes.
111///
112/// Named here for [`GOT_LOAD`]'s reason turned round: a frame never writes one, because the only
113/// function it appears in has no prologue and no epilogue for the frame to write anything into.
114/// See [`x86_64::Step::Away`].
115const AWAY: &str = "jmp_away";
116
117/// How wide an address is on this target, which is the width a cast between a pointer and an
118/// integer has to be at for the cast to be nothing.
119const ADDRESS_BITS: u32 = 64;
120
121/// How much of a register an operand of an `asm` statement fills, which is the width of its type
122/// with two exceptions. A pointer is an address, and a truth value is the byte it is stored in: a
123/// program that writes `sete %0` into a `_Bool` is asking for exactly that byte, which is what tcc's
124/// own test of the width of one checks.
125fn held_bits(ty: Type) -> u32 {
126 if ty.is_ptr() {
127 ADDRESS_BITS
128 } else if ty.bits() == 1 {
129 8
130 } else {
131 ty.bits()
132 }
133}
134
135/// How many bytes a `long double` takes in memory, and what it is aligned to, which are the same
136/// number and are both more than the ten bytes that mean anything.
137///
138/// The psABI's answer rather than a choice here. `sizeof (long double)` is sixteen on this
139/// machine, so an array of them is laid out this way whatever a slot holding one does, and a slot
140/// that agreed with the array is one fewer thing to get wrong.
141const X87_BYTES: u32 = 16;
142
143/// How many values the x87 stack holds at once.
144///
145/// Eight, which is the machine's number rather than a choice here, and it matters in one place:
146/// the parameters of a block are copied through the stack so that they all move at once, and a
147/// block with more of them than this has nowhere to put the ninth.
148const X87_DEPTH: usize = 8;
149
150/// How far into the buffer of a `__builtin_setjmp` each of the four words it writes is.
151///
152/// The first three are gcc's, measured against gcc 16.2.0 on x86-64 at `-O0`: the frame pointer,
153/// the address control comes back to, and the stack pointer, in that order. The fourth is this
154/// compiler's own. gcc has no word for the answer because it writes a second block that sets the
155/// answer to one and is arrived at from the restore, and this writes the answer through memory
156/// instead, for the reason [`Lowering::saves_place`] gives.
157///
158/// None of the four is an interface. The buffer is the program's memory and its five words are
159/// the front end's promise about how much of it there is, but nothing except the matching restore
160/// ever reads a word of it, and a buffer written by one compiler was never going to be one another
161/// compiler could come back through.
162const JUMP_FRAME: i32 = 0;
163
164/// Where the address control comes back to is. See [`JUMP_FRAME`].
165const JUMP_PC: i32 = 8;
166
167/// Where the stack pointer is. See [`JUMP_FRAME`].
168const JUMP_STACK: i32 = 16;
169
170/// Where the address of the word the answer arrives in is. See [`JUMP_FRAME`].
171const JUMP_ANSWER: i32 = 24;
172
173/// How many bytes the word a `__builtin_setjmp` answers with takes in the frame, and what it is
174/// aligned to, which are the same number because it is one machine word.
175const JUMP_WORD: u32 = 8;
176
177/// How many registers the restore needs to hold things in while it puts the frame back.
178///
179/// Four, and every one of them is a register nothing else in the function may be in, which is why
180/// they are counted here rather than asked for one at a time. See [`Lowering::comes_back`].
181const JUMP_REGS: usize = 4;
182
183/// How many bytes a value passes through on its way between a register and the x87 stack.
184///
185/// Eight, because the widest thing that crosses is a `double` or a sixty four bit integer, and
186/// nothing crosses at eighty bits: a value that wide is already in the frame and the stack reaches
187/// it where it is.
188const X87_CROSSING: u32 = 8;
189
190/// Where the rounding field of the x87 control word is and what it has to be set to for the unit
191/// to cut towards zero, which is the one rounding C asks for that the unit does not do by default.
192///
193/// Both bits on is truncate. The field is ORed into the word that was already there rather than
194/// written over it, so the precision control and the exception masks somebody else set stay set.
195const X87_TRUNCATE: i64 = 0x0c00;
196
197/// Whether a type is the one this machine has no register for.
198///
199/// Only the eighty bit float is, and that is a fact about x86-64 rather than about floats: every
200/// other scalar the front end produces is in a general purpose register or a vector one, and this
201/// one is on the x87 stack while it is being worked on and in memory the rest of the time. So it
202/// has no place in [`Lowering::class_of`] and no name in [`crate::term`], and every instruction
203/// that touches one is written out by hand in this file.
204fn on_x87(ty: Type) -> bool {
205 ty.is_scalar() && ty.is_float() && ty.bits() == 80
206}
207
208/// Where one operand of an assembly statement is, on each side of the assembly.
209///
210/// Two registers rather than one, because an operand written `+` is a value that arrives and a
211/// value that leaves and those are two values. The machine IR has one definition per register by
212/// construction, so an instruction of the template that reads the operand and writes it has to name
213/// a different register in each place, and what makes the two one register in the end is the
214/// [`Constraint::Reuse`] the instruction's description carries: the allocator reads it, gives both
215/// the same physical register, and copies the incoming value somewhere first when something else is
216/// still using it.
217///
218/// Most operands have one of the two. An input has only a place it is read from and an output
219/// written `=` has only a place it is written to, and asking either of them for the other is an
220/// operand read where the opcode writes or written where it reads, which [`Lowering::placed`]
221/// refuses.
222#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
223struct Place {
224 /// The register the value arrives in, for an operand something reads.
225 read: Option<mir::Reg>,
226 /// The register the value leaves in, for an operand something writes.
227 write: Option<mir::Reg>,
228}
229
230/// Whether that operand of the statement is one the assembly may read, and so where a read of it
231/// gets its value from.
232///
233/// [`bound`] asks this question of an operand a constraint letter named and this asks it of one the
234/// template numbered, which is the same question twice because a two-address instruction reaches
235/// its first source both ways. `mulq %3` reaches `rax` by the letter on the output and libgmp says
236/// what is in it with `"%0"` on an input. `addq %5,%q1` reaches its first source by numbering the
237/// output, and libgmp says what is in it with `"0"` on an input in the same way.
238///
239/// So an output written `=` has no value of its own and is still readable when an input is tied to
240/// it, and the value the read wants is that input's. An output written `+` carries its own value
241/// and answers with that. An output nothing is tied to answers `None`, which is a program that told
242/// the compiler the assembly only writes the operand while the instruction reads it before it
243/// writes it, and is refused where it is asked.
244fn read_as(list: &[AsmOperand<'_>], index: usize) -> Option<Value> {
245 let operand = list.get(index)?;
246 if operand.value.is_some() {
247 return operand.value;
248 }
249 operand.result?;
250 list.iter().find(|entry| entry.tied == Some(index)).and_then(|entry| entry.value)
251}
252
253/// Which of an assembly statement's operands is in that register, for an instruction that reaches
254/// the register without its text saying so.
255///
256/// The constraint is what says so, and it is the only thing in such a statement that could:
257/// `"=a"` is an output in `rax`, `"c"` is an input in `rcx`, an operand that is a local register
258/// variable is in the register its declaration named, and a register nothing names is a register
259/// nobody has said anything about. So a write looks among the outputs and a read among the inputs,
260/// and an output written `+` answers for either, since it is read before it is written. See
261/// [`pinned`], which is the one question asked of both ways of saying it.
262///
263/// The other way a read of such a register is said is a matching constraint. `"=a"` on an output
264/// and `"0"` on an input is the program saying that one register holds the input on the way in and
265/// the output on the way out, and it is how a statement fills a register the instruction reads and
266/// writes without writing the register down twice. The letter is on the output, which has no value
267/// to read, and the value is on the input, which has no letter, and the answer is the output: its
268/// place is read out of the register the input arrived in, and in a template with a loop in it the
269/// place moves on to wherever the last write left it, which is what a read on the next time round
270/// wants. tcc steps a pointer along a string with `lodsb` and `"=&S"` tied to `"0"`, and a read of
271/// the input would start the string again every time round.
272///
273/// And a read of a register an output alone is in is a read of that output, the same as a read of
274/// an output the template numbered. tcc copies a string with `lodsb` and `stosb` and `"=&a"` on an
275/// output nothing is tied to, and what `stosb` stores is what `lodsb` loaded one line up, which is
276/// the output as the template left it rather than anything the statement handed in.
277///
278/// `None` is a register the instruction uses and the statement put nothing in, which is the usual
279/// answer rather than an unusual one. `cpuid` writes four registers and a program that wanted one
280/// of them names one. See [`Lowering::spare`], which is where that one goes.
281fn bound(list: &[AsmOperand<'_>], reg: PhysReg, role: Role) -> Option<usize> {
282 let output =
283 list.iter().position(|operand| operand.result.is_some() && pinned(operand) == Some(reg));
284 if role.is_def() {
285 return output;
286 }
287 // The output first when something is in it on the way in, which is what `+` and a matching
288 // constraint both say, since its place is where a write earlier in the template left it and
289 // the read wants that. See [`read_as`] for what it holds before anything wrote it.
290 let arrives = |at: usize| read_as(list, at).is_some();
291 if let Some(at) = output.filter(|&at| arrives(at)) {
292 return Some(at);
293 }
294 let named = list.iter().position(|operand| {
295 operand.result.is_none() && operand.value.is_some() && pinned(operand) == Some(reg)
296 });
297 named.or(output)
298}
299
300/// The register one of an assembly statement's operands is in, whichever of the two ways said it.
301///
302/// A constraint letter is one way and is the only way a program can say one of the six registers
303/// that have a letter. A local register variable is the other, and it is the only way to say any
304/// of the rest: there is no letter for `r12`, which is the whole reason the extension exists, so
305/// the declaration says it and the front end wrote the name into the constraint. The name is read
306/// against this machine's table here, the same place the letter is read against it, and a name the
307/// machine has not got answers nothing, which leaves the operand where an operand nobody placed
308/// goes.
309///
310/// The sigil gcc allows in front of a name is taken off here, because what a name is written with
311/// is syntax and which register it means is this question.
312fn pinned(operand: &AsmOperand<'_>) -> Option<PhysReg> {
313 match operand.named {
314 Some(name) => {
315 let (reg, _) = x86_64::gpr_named(name.strip_prefix('%').unwrap_or(name))?;
316 Some(reg)
317 }
318 None => operand.fixed.and_then(x86_64::gpr_letter),
319 }
320}
321
322/// Why a function could not be lowered.
323///
324/// One reason and then nothing. A function with no rule for something in it is a function this
325/// cannot finish, and the second thing it could not lower is not news.
326#[derive(Debug, Clone, PartialEq, Eq)]
327pub enum Unsupported {
328 /// An instruction no rule fires on.
329 Inst {
330 /// The instruction that stopped it.
331 inst: Inst,
332 /// What the rule file would call it, or nothing if the rule language has no name for it
333 /// at all, which is what an instruction at a width nothing is written about looks like.
334 term: Option<&'static str>,
335 /// The opcode, which is what gets named when the rule language has no word for it.
336 ///
337 /// An opcode the rule language has no word for is exactly the opcode no rule lowers, so
338 /// without this the message would be empty in every case where somebody needs it.
339 opcode: Opcode,
340 /// What it produces, or nothing for an instruction that is only an effect.
341 ty: Option<Type>,
342 },
343 /// A parameter that does not arrive somewhere this can bring it in from.
344 ///
345 /// Not an instruction, which is why it is a separate arm: it is a fact about the signature
346 /// and there is nothing in the body of the function to point at.
347 Argument {
348 /// Its position in the signature.
349 index: usize,
350 /// What is wrong with where it arrives.
351 missing: Missing,
352 },
353 /// A call that passes or gives back a value this cannot put where the convention wants it.
354 Call {
355 /// The call.
356 inst: Inst,
357 /// Which value, and what is wrong with where it travels.
358 refused: Refused,
359 },
360 /// A `return` this cannot put where the convention wants it.
361 ///
362 /// A separate arm from [`Unsupported::Inst`] because it is not an instruction no rule fires
363 /// on. A return of more than one value is built from the convention rather than matched, the
364 /// same way a call is, so what goes wrong with one is what goes wrong with a call and not the
365 /// absence of a rule.
366 Returned {
367 /// The `return`.
368 inst: Inst,
369 /// What is wrong with where one of the values travels.
370 missing: Missing,
371 },
372 /// A stack slot the frame cannot give the bytes it asked for.
373 ///
374 /// Not an instruction no rule covers. An `alloca` is built here rather than matched, so what
375 /// goes wrong with one is what the frame can and cannot hold rather than what the rules spell.
376 Dynamic {
377 /// The `alloca`.
378 inst: Inst,
379 /// What the frame could not do about it.
380 growing: Growing,
381 },
382 /// More parameters of a type that travels on the x87 stack than the stack is deep.
383 ///
384 /// Not an instruction either, for the reason a function's parameter is not one: it is a fact
385 /// about the block and there is nothing in the block to point at. What crosses an edge for one
386 /// of these is the address of where the value is, and the block copies the bytes into a slot
387 /// of its own, all of them through the stack at once so that a block carrying two of them
388 /// swapped is copied in an order that is right. Eight is as many as the stack holds, and a
389 /// ninth would have to be copied before or after the rest, which is the order that could be
390 /// wrong.
391 Phi {
392 /// Which block it arrives at.
393 block: Block,
394 /// How many of them arrive there, which is the whole of what is wrong.
395 count: usize,
396 /// What they are.
397 ty: Type,
398 },
399 /// An `asm` statement this cannot build.
400 ///
401 /// Not an instruction no rule fires on, for the reason a call is not one: what it stands for is
402 /// whatever its template says, and no pattern over terms can read a string.
403 Assembly {
404 /// The `inline_asm`.
405 inst: Inst,
406 /// What about it is not built here yet.
407 refused: Written,
408 },
409 /// A `register long x asm ("...")` naming something this machine has not got.
410 ///
411 /// Not an instruction no rule fires on. There is a rule's worth of instruction here and what
412 /// is wrong is the string beside it, which is a name rather than a term, so the message says
413 /// the name. Which names a machine has is the machine's own question and this is where it is
414 /// asked, at the table a clobber list is read against.
415 Register {
416 /// The `register_value`.
417 inst: Inst,
418 /// The name the program wrote, as it wrote it.
419 name: String,
420 },
421 /// A naked function whose frame is not empty.
422 ///
423 /// Not an instruction no rule fires on, and there is nothing in the body to point at: the
424 /// function asked for no prologue and then wanted bytes only a prologue takes. Refused rather
425 /// than given the bytes anyway, because an offset into a frame nothing set up reaches into
426 /// whatever the caller left below its own stack pointer, which is wrong code that assembles.
427 /// See [`crate::frame::Layout::naked`].
428 Naked {
429 /// How many bytes it wanted, which is the whole of what is wrong.
430 bytes: u32,
431 },
432}
433
434/// What about an `asm` statement is not built yet.
435#[derive(Debug, Clone, Copy, PartialEq, Eq)]
436pub enum Written {
437 /// A template with instructions in it.
438 Template,
439 /// An `asm goto`, whose labels make the statement a terminator.
440 Goto,
441 /// An operand this cannot put where the constraint says it goes.
442 Operand,
443 /// A clobber list naming something this has no register for.
444 Clobber,
445 /// A `jmp` out of the function in a function that has an epilogue behind it.
446 Away,
447}
448
449impl Written {
450 /// The rest of the sentence that starts with the statement.
451 #[must_use]
452 pub fn why(self) -> &'static str {
453 match self {
454 // The template is the assembler's to read and there is no assembler here yet, so a
455 // template with anything in it is a string nothing can turn into bytes. An empty one is
456 // no instructions, and no instructions is something this can write.
457 Written::Template => "has instructions in its template, which nothing here assembles",
458 Written::Goto => "jumps to a label, which nothing here builds an edge for",
459 Written::Operand => "has an operand this cannot place",
460 Written::Clobber => "says it destroys a register this has no name for",
461 Written::Away => {
462 "jumps out of the function, which only a function that is `naked` may do, since \
463 anywhere else there is an epilogue behind it to give the frame back"
464 }
465 }
466 }
467}
468
469/// What the frame could not do about a stack slot.
470#[derive(Debug, Clone, Copy, PartialEq, Eq)]
471pub enum Growing {
472 /// An object of a size the number a frame counts bytes in does not reach.
473 Huge,
474 /// A variable length array wanting more alignment than a call leaves the stack pointer with.
475 ///
476 /// Rounding the stack pointer down again after the bytes have been taken would put it
477 /// somewhere no constant reaches the rest of the frame from, so a frame like this needs a
478 /// second base register held for the whole of the function. Nothing here holds one.
479 ///
480 /// [`crate::expand::rounds`] takes the array away before this sees it, by asking for the
481 /// alignment in extra bytes and handing out an address inside them, so what is left of this
482 /// is IR that arrived without going through that pass and the fixed local in
483 /// [`crate::pipeline`] that wants the same thing from the other side.
484 Aligned,
485 /// A variable length array in a function written without a prologue.
486 ///
487 /// A frame that grows is reached from a frame pointer, and establishing one is the first two
488 /// instructions of a prologue that `__attribute__((naked))` asked there be none of. See
489 /// [`crate::frame::Layout::naked`].
490 Naked,
491}
492
493impl Growing {
494 /// The rest of the sentence that starts with the slot.
495 #[must_use]
496 pub fn why(self) -> &'static str {
497 match self {
498 Growing::Huge => "is more bytes than a frame counts",
499 Growing::Aligned => {
500 "wants more alignment than the stack pointer is left on, which needs a base \
501 register nothing here keeps"
502 }
503 Growing::Naked => {
504 "is in a function that is `naked`, which has no prologue to point a frame pointer \
505 at it with"
506 }
507 }
508 }
509}
510
511impl Unsupported {
512 /// The instruction it is about, or nothing for the one arm that is about a signature.
513 ///
514 /// What a caller wants this for is the span. The function knows where every instruction in
515 /// it came from, so a caller holding both can point a message at the line somebody wrote
516 /// rather than at the file as a whole, and nothing here has to carry a span of its own.
517 pub fn inst(&self) -> Option<Inst> {
518 match *self {
519 Unsupported::Inst { inst, .. }
520 | Unsupported::Call { inst, .. }
521 | Unsupported::Returned { inst, .. }
522 | Unsupported::Dynamic { inst, .. }
523 | Unsupported::Assembly { inst, .. }
524 | Unsupported::Register { inst, .. } => Some(inst),
525 Unsupported::Argument { .. } | Unsupported::Phi { .. } | Unsupported::Naked { .. } => {
526 None
527 }
528 }
529 }
530}
531
532impl fmt::Display for Unsupported {
533 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
534 match *self {
535 Unsupported::Inst { term: Some(term), .. } => write!(f, "no rule lowers `{term}`"),
536 Unsupported::Inst { term: None, opcode, ty: Some(ty), .. } => {
537 write!(f, "no rule lowers a `{opcode}` producing a `{ty}`")
538 }
539 Unsupported::Inst { term: None, opcode, ty: None, .. } => {
540 write!(f, "no rule lowers a `{opcode}`")
541 }
542 Unsupported::Argument { index, missing } => {
543 write!(f, "parameter {index} {}", missing.why())
544 }
545 Unsupported::Call { refused: Refused { argument: Some(index), missing }, .. } => {
546 write!(f, "argument {index} of this call {}", missing.why())
547 }
548 Unsupported::Call { refused: Refused { argument: None, missing }, .. } => {
549 write!(f, "what this call gives back {}", missing.why())
550 }
551 Unsupported::Returned { missing, .. } => {
552 write!(f, "what this function gives back {}", missing.why())
553 }
554 Unsupported::Dynamic { growing, .. } => {
555 write!(f, "this local {}", growing.why())
556 }
557 Unsupported::Phi { block, count, ty } => {
558 let block = block.index();
559 write!(
560 f,
561 "block{block} takes {count} parameters of type `{ty}` and only {X87_DEPTH} can cross an edge at once"
562 )
563 }
564 Unsupported::Assembly { refused, .. } => write!(f, "this `asm` {}", refused.why()),
565 Unsupported::Register { ref name, .. } => {
566 write!(
567 f,
568 "this object is kept in `{name}`, which is not a register this machine has"
569 )
570 }
571 Unsupported::Naked { bytes } => write!(
572 f,
573 "this function is `naked` and wants {bytes} bytes of frame, which there is no prologue to take"
574 ),
575 }
576 }
577}
578
579impl std::error::Error for Unsupported {}
580
581/// A lowered function, and what the frame needs that the machine IR does not hold.
582#[derive(Debug)]
583pub struct Lowered {
584 /// The function, in machine instructions.
585 pub func: mir::Func,
586 /// What it wants its stack to look like, which is separate from the function so that the two
587 /// can be read and written at the same time.
588 pub stack: Stack,
589 /// Which rules of the table lowered it, which is what `-Zrule-coverage` asks for and what
590 /// `crate::coverage` writes down.
591 pub fired: Fired,
592 /// Which machine IR block each IR block became, indexed by the IR block's own index, and
593 /// nothing for a block the walk never reached.
594 ///
595 /// Here because it is the only place the correspondence exists. Selection makes one block per
596 /// block, in the same order and with the arms in the same order, so anything the IR knows
597 /// about a block can be carried down through this and nothing else, and
598 /// [`crate::weights::carry`] is what does.
599 pub blocks: Vec<Option<mir::Block>>,
600}
601
602/// What a function's stack has to hold, as far as selection is able to say.
603///
604/// All of it is answered here because selection is where a call is built and where an `alloca`
605/// is read, and nothing after it could tell what either of them needed.
606#[derive(Debug, Default)]
607pub struct Stack {
608 /// How many bytes the widest call in the function needs below the stack pointer for the
609 /// arguments it passes there, or `None` for a function that makes no call at all.
610 ///
611 /// `None` is a leaf, which is the function that may use the red zone and the one whose stack
612 /// pointer does not have to be left aligned for anybody.
613 pub calls: Option<u32>,
614 /// The memory the function asked for itself, one entry for every `alloca` in it, in the order
615 /// the walk reached them.
616 pub locals: Vec<Local>,
617 /// Which instruction computes the address of which of those locals.
618 ///
619 /// An address in the frame is a distance from the stack pointer, and there is no frame until
620 /// after allocation, so the instruction is written here with nothing in its displacement and
621 /// [`crate::finish`] writes the number in once [`crate::frame::Frame`] knows it.
622 pub addresses: Vec<(mir::Inst, usize)>,
623 /// Which of those locals is which declaration in the source, for the ones the program declared.
624 ///
625 /// The number is the one the IR function carries and means nothing here. What it is for is the
626 /// debugging information, which has to say where a named local ended up and cannot ask the
627 /// frame directly: the frame knows a local by the order the `alloca` for it was lowered in and
628 /// by nothing else.
629 ///
630 /// Shorter than the list above rather than the same length, because most of what a function
631 /// keeps in its frame is memory an expression wanted somewhere to put.
632 pub declared: Vec<(usize, u32)>,
633 /// Which instruction computes the address of a piece of memory whose size the function works
634 /// out while it runs, which is what a variable length array is.
635 ///
636 /// Waiting on [`crate::finish`] for a different number from the one the addresses above are:
637 /// the bytes were taken off the stack pointer by the instruction in front of this one, so where
638 /// they start is however much of the bottom of the frame belongs to the arguments of a call,
639 /// and that is not known until the frame is.
640 pub dynamic: Vec<mir::Inst>,
641 /// Which instruction takes those bytes off the stack pointer, one for every one of them, in the
642 /// order the walk reached them.
643 ///
644 /// Read by [`crate::finish`] on a command line that asked for the stack to be touched a page at
645 /// a time, which is the one thing that has to find these again: the bytes are in a register by
646 /// then, so the walk down to them is a loop, and a loop is written around an instruction rather
647 /// than in front of a block. Nothing else looks at them, because everything else about a frame
648 /// that grows is answered by the address the instruction below this one computes.
649 pub grown: Vec<mir::Inst>,
650 /// Where the function first moves the stack pointer while it runs, if it does at all.
651 ///
652 /// Two things are read off this. One is whether at all, which is what [`crate::frame::Layout`]
653 /// wants, because a frame that moves its stack pointer has a different shape from one that does
654 /// not and the layout is built before the instructions are looked at again. See `Growing` in
655 /// [`crate::frame`]. The other is where, so that a caller that cannot accept such a frame has
656 /// somewhere to point when it says so.
657 pub grown_at: Option<Inst>,
658 /// Which instruction reads which of the arguments the caller passed on the stack, as how far up
659 /// the caller's argument area it reads.
660 ///
661 /// Waiting on [`crate::finish`] for the same reason the addresses above are, and on one thing
662 /// more: where the caller's argument area is from inside this function depends on whether the
663 /// prologue had to force the stack pointer's alignment, so which register the load reads
664 /// through is not settled here either.
665 pub arguments: Vec<(mir::Inst, u32)>,
666 /// Whether the function asked where its own frame is, which is what `__builtin_frame_address`
667 /// and `__builtin_return_address` both start from.
668 ///
669 /// A function like that keeps a frame pointer whatever the flags say, because the register is
670 /// the answer to the first of them and the start of the walk for every depth above zero. There
671 /// is no other way to reach it: the distance from the stack pointer to the frame is a number
672 /// the layout works out, and what a walk up the chain needs is the link the prologue saved.
673 pub walks_frames: bool,
674 /// Whether the function saved a place for a `__builtin_longjmp` to come back to, which is what
675 /// `__builtin_setjmp` does.
676 ///
677 /// A function like that keeps a frame pointer whatever the flags say as well, and for a reason
678 /// of the same shape: the two registers the restore puts back are the frame pointer and the
679 /// stack pointer, and a frame that did not keep the first of them has nothing in it saying
680 /// where the caller's frame is for the epilogue to find after control has come back.
681 pub saves_place: bool,
682}
683
684impl Stack {
685 /// The layout given, with the three fields only the lowering knows the answer to filled in.
686 ///
687 /// Everything else in a layout comes from the flags the function is compiled under or from the
688 /// allocation, so this takes one and returns it rather than building one.
689 ///
690 /// A function that saved a place is not a leaf whatever it called. What a leaf buys is the red
691 /// zone, which is the words below the stack pointer nothing else may write, and a function
692 /// control comes back into from a `__builtin_longjmp` has already had something else running
693 /// down there: whatever it called and whatever that called, or a signal handler on the same
694 /// stack. Every one of those has written over the red zone by the time control arrives, so a
695 /// value this function left there would not be there any more.
696 #[must_use]
697 pub fn layout<'a>(&'a self, base: Layout<'a>) -> Layout<'a> {
698 Layout {
699 leaf: self.calls.is_none() && !self.saves_place,
700 outgoing: self.calls.unwrap_or(0),
701 locals: &self.locals,
702 grows: self.grown_at.is_some(),
703 ..base
704 }
705 }
706}
707
708/// The x86-64 machine IR for that function.
709///
710/// # Errors
711///
712/// The first instruction no rule fires on, which today is anything at a width the rule set is not
713/// written at, a parameter that does not arrive in a register this can read, or a call that
714/// passes something this cannot put where the convention wants it.
715pub fn func(
716 source: &Func,
717 names: &mut Interner,
718 conv: &'static CallRegs,
719 elsewhere: &Elsewhere,
720) -> Result<Lowered, Unsupported> {
721 Lowering::new(source, names, conv, elsewhere).run()
722}
723
724/// What the matcher settled on for one block, indexed the way the block's instructions are.
725struct Decided {
726 /// What each instruction matched, and nothing for one that matched no rule or was folded
727 /// into a later one.
728 found: Vec<Option<Match<Term>>>,
729 /// How each instruction showed its operands to the matcher, which is what says what it took.
730 plans: Vec<Option<Plan>>,
731 /// The instructions some other instruction took, which are the ones with nothing to write.
732 folded: Vec<Inst>,
733}
734
735/// The instruction in front of an assignment that starts a declaration on a value, and the first
736/// machine instruction after it once the block is filled.
737type Mark = (Option<Inst>, Option<mir::Inst>);
738
739/// One function being lowered.
740struct Lowering<'a> {
741 source: &'a Func,
742 names: &'a mut Interner,
743 out: mir::Func,
744 /// The machine register each IR value is in, once it has one.
745 regs: Vec<Option<mir::Reg>>,
746 /// For a constant that has been written into a register, the block it was written into,
747 /// which is the only block that register is any good in.
748 written: Vec<Option<mir::Block>>,
749 /// How many times each IR value is read, which is what says whether an instruction may be
750 /// folded into the one that reads it.
751 uses: Vec<u32>,
752 /// The block being filled.
753 at: Option<mir::Block>,
754 /// The machine IR block each IR block became.
755 blocks: Vec<Option<mir::Block>>,
756 /// The class an address is in, which is the general purpose one and is not a question: every
757 /// register an addressing mode names holds part of an address, and there is no machine here
758 /// that computes an address anywhere but in this file. Which class a *value* is in is
759 /// [`Lowering::class_of`], and it is a question, because a float is in the other one.
760 gpr: RegClass,
761 /// Where the convention this function is compiled for puts things, which is read for the
762 /// arguments and for the calls.
763 conv: &'static CallRegs,
764 /// Which names this function may not work an address out for itself, which is a fact about the
765 /// module and so is worked out before any of this and handed in.
766 elsewhere: &'a Elsewhere,
767 /// What the function wants its stack to look like, filled in as the walk finds out.
768 stack: Stack,
769 /// What a `va_start` in this function has to write, or nothing for a function that takes no
770 /// arguments its signature does not name.
771 ///
772 /// Worked out once, when the entry block binds the parameters, because every number in it is
773 /// about where those parameters left the walk over the argument registers and there is nowhere
774 /// else that knows.
775 varargs: Option<Varargs>,
776 /// Which of the function's stack objects each eighty bit value lives in, once it has asked
777 /// for one.
778 ///
779 /// One slot per value and it is never given back, which is what makes an eighty bit value
780 /// behave like every other one: it is written once and read wherever it is read, and no two
781 /// of them share a slot the way two of them would share a register. What is in a register is
782 /// the address, and that is worked out again at every use rather than kept, so nothing here
783 /// holds a general purpose register open across a whole function.
784 slots: Vec<Option<usize>>,
785 /// The eight bytes a value passes through between a register and the x87 stack, once
786 /// something has wanted them.
787 ///
788 /// One for the whole function, because every group that uses it is a handful of instructions
789 /// with nothing in between: the bytes are written, read straight back and never looked at
790 /// again, so a second slot would be a second slot holding the same nothing.
791 crossing: Option<usize>,
792 /// The four bytes the control word is saved in and the changed copy written to, once
793 /// something has wanted them.
794 ///
795 /// One for the whole function for the reason above, and four rather than two because it is
796 /// two words: the one the unit had and the one with the rounding field turned to truncate.
797 control: Option<usize>,
798 /// The word a `__builtin_setjmp` in this function answers with, once one has asked for it.
799 ///
800 /// One for the whole function however many saves there are in it, because the word is written
801 /// and read back with nothing in between: the save writes a zero into it and the instruction
802 /// straight after reads it, and the only other thing that ever writes it is a restore arriving
803 /// between those two. Two saves sharing it is two pairs each doing that, and neither can be
804 /// inside the other.
805 answer: Option<usize>,
806 /// Which rules have fired so far.
807 fired: Fired,
808 /// Where each assignment that starts a declaration on a value part of the way through is, by
809 /// the IR block it is in and the instruction in front of it, and which machine instruction
810 /// is the first one after it once the block has been filled. See
811 /// [`rucc_ir::Func::declare_value_from`].
812 marks: HashMap<Block, Vec<Mark>>,
813}
814
815/// What a `va_start` in a variadic function writes into the list it is given.
816///
817/// Two shapes, because two conventions describe a list two ways, and [`crate::varargs`] is where
818/// both are written down. Neither is a set of numbers on its own: where the save area is and where
819/// the caller's argument area is are distances into a frame that does not exist until after
820/// allocation, so each is a `lea` [`crate::finish`] fills in.
821#[derive(Debug, Clone, Copy, PartialEq, Eq)]
822enum Varargs {
823 /// The four field list, whose two offsets are settled here and whose two addresses are not.
824 Fields {
825 /// Which of the function's stack objects is the register save area.
826 save: usize,
827 /// How far up the caller's argument area the first argument the signature does not name is,
828 /// which is the whole of that area the named ones did not take.
829 incoming: u32,
830 /// What `gp_offset` starts at, which is past the general purpose registers the named
831 /// arguments took.
832 integers: u32,
833 /// What `fp_offset` starts at, which is past the vector ones.
834 floats: u32,
835 },
836 /// The list that is a pointer, which is the one address and nothing else.
837 Pointer {
838 /// How far up the caller's argument area the first argument the signature does not name is,
839 /// which on this convention is the word belonging to the position the named ones stopped
840 /// at.
841 incoming: u32,
842 },
843}
844
845/// How far a function's name reaches, narrowed from the linkage the IR gave it.
846///
847/// The IR has five and an object file says three, and the two the linker cannot tell apart are
848/// the two weak ones: which of them a symbol had is a fact the optimizer reads and the linker has
849/// no way to record. A function is never `Common`, since that is what a tentative definition of an
850/// object is and there is no tentative definition of a function, and it is written here rather
851/// than left out so that a linkage added later has to come past this.
852const fn binding(linkage: Linkage) -> mir::Binding {
853 match linkage {
854 Linkage::Internal => mir::Binding::Local,
855 Linkage::Weak | Linkage::LinkOnce => mir::Binding::Weak,
856 Linkage::External | Linkage::Common => mir::Binding::Global,
857 }
858}
859
860/// How far a function's name reaches outside a shared library, carried across unchanged.
861///
862/// Nothing is narrowed here the way [`binding`] narrows the linkage, because ELF records all
863/// three of these and the two enumerations are the same three answers written twice: once in a
864/// crate that is not allowed to know what an object file is and once in one that is.
865const fn visibility(visibility: Visibility) -> mir::Visibility {
866 match visibility {
867 Visibility::Default => mir::Visibility::Default,
868 Visibility::Hidden => mir::Visibility::Hidden,
869 Visibility::Protected => mir::Visibility::Protected,
870 }
871}
872
873impl<'a> Lowering<'a> {
874 fn new(
875 source: &'a Func,
876 names: &'a mut Interner,
877 conv: &'static CallRegs,
878 elsewhere: &'a Elsewhere,
879 ) -> Self {
880 let counts = source.counts();
881 let name = source.name;
882 let mut uses = vec![0; counts.values];
883 for block in source.blocks() {
884 for inst in source.insts(block) {
885 for &arg in &source[source[inst].args] {
886 uses[arg.index()] += 1;
887 }
888 for call in source.successors(inst) {
889 for &arg in &source[call.args] {
890 uses[arg.index()] += 1;
891 }
892 }
893 }
894 }
895 let mut out = mir::Func::new(name);
896 out.align = source.align;
897 // Carried rather than worked out here, because where a function was declared is a fact
898 // about the source and this is a long way past it. What wants it is the line table.
899 out.declared = source.declared;
900 out.binding = binding(source.linkage);
901 out.visibility = visibility(source.visibility);
902 Self {
903 source,
904 names,
905 out,
906 regs: vec![None; counts.values],
907 written: vec![None; counts.values],
908 blocks: vec![None; counts.blocks],
909 uses,
910 at: None,
911 gpr: x86_64::GPR,
912 conv,
913 elsewhere,
914 stack: Stack::default(),
915 varargs: None,
916 slots: vec![None; counts.values],
917 crossing: None,
918 control: None,
919 answer: None,
920 fired: Fired::new(),
921 marks: HashMap::new(),
922 }
923 }
924
925 fn run(mut self) -> Result<Lowered, Unsupported> {
926 for value in self.source.values() {
927 for start in self.source.value_starts(value) {
928 let marks = self.marks.entry(start.block).or_default();
929 if !marks.iter().any(|&(after, _)| after == start.after) {
930 marks.push((start.after, None));
931 }
932 }
933 }
934 // Every block before any of them is filled, because a block that jumps forward has to
935 // name the block it jumps to and a machine IR block is named by a handle rather than by
936 // the IR block it came from.
937 for block in self.source.blocks() {
938 let out = self.out.create_block();
939 self.blocks[block.index()] = Some(out);
940 }
941 for block in self.order() {
942 self.block(block)?;
943 }
944 // And the name each block an image holds the address of was given, which nothing in the
945 // walk above would ask for: the `lea` a label address is inside the function needs no
946 // symbol, and the one thing that does is a relocation in another section.
947 let named: Vec<(Block, Symbol)> = self.source.named_blocks().collect();
948 let labels: Vec<(mir::Block, Symbol)> =
949 named.into_iter().map(|(block, name)| (self.out_block(block), name)).collect();
950 self.out.labels = labels;
951 self.naming();
952 Ok(Lowered { func: self.out, stack: self.stack, fired: self.fired, blocks: self.blocks })
953 }
954
955 /// Which register each declaration the front end kept in a value ended up in, as far as this
956 /// walk can say, which is the other half of what [`Lowering::new_reg`] writes down as it goes.
957 ///
958 /// Two halves because there are two ways a value gets a register here. Most of them ask for a
959 /// fresh one and that is where `new_reg` catches them, and the rest are put in a register
960 /// something else chose: a parameter arrives in whichever one the convention handed it, a block
961 /// parameter in whichever one the edge agreed on, and a result of a rule that names its own
962 /// registers in the one the rule named. None of those goes past the mint, so this is the map at
963 /// the end read off the other side, and the two together are every value a declaration is
964 /// behind.
965 ///
966 /// The map on its own would not do, which is why `new_reg` writes down what it writes down: the
967 /// entry for a constant is cleared every time the walk leaves the block that wrote it, so a
968 /// local a constant holds is in the map for one block of the function and nowhere else.
969 fn naming(&mut self) {
970 let mut named = std::mem::take(&mut self.out.named);
971 for value in self.source.values() {
972 let Some(reg) = self.regs[value.index()] else { continue };
973 named.extend(self.source.value_decls(value).map(|decl| (decl, reg)));
974 // A start in a block a pass took out was never reached above, and it says nothing
975 // rather than something about another place.
976 for start in self.source.value_starts(value) {
977 let first = self.marks.get(&start.block).and_then(|marks| {
978 marks.iter().find(|&&(after, _)| after == start.after).and_then(|&(_, at)| at)
979 });
980 if let Some(first) = first {
981 self.out.starts.push((start.decl, reg, first));
982 }
983 }
984 }
985 named.sort_unstable();
986 named.dedup();
987 self.out.named = named;
988 self.out.starts.sort_unstable();
989 self.out.starts.dedup();
990 }
991
992 /// The order the blocks are filled in, which is not the order they are written in.
993 ///
994 /// Reverse postorder, because a value is written in a block that dominates every block that
995 /// reads it and a block in reverse postorder comes before every block it dominates. The order
996 /// the blocks are written in does not have that property: a block written early can read a
997 /// value a block below it writes, and reading a value with no register yet mints one, so the
998 /// register the definition writes later is not the register the read named. Nothing writes the
999 /// one the read named, and what comes out is a function that loads a stack slot no store ever
1000 /// reached. It is the order this walk goes in rather than the order the blocks come out in,
1001 /// which is what the loop above fixes, so the machine function is still written the way the IR
1002 /// function was.
1003 ///
1004 /// Blocks the entry does not reach come last, in the order they are written in. Nothing runs
1005 /// them and nothing they name is read by anything that does, but they still have to be filled,
1006 /// because a machine block with no terminator is not one the passes below can read.
1007 fn order(&self) -> Vec<Block> {
1008 let Some(entry) = self.source.entry() else { return self.source.blocks().collect() };
1009 let count = self.blocks.len();
1010 let mut succs: Vec<Vec<Block>> = vec![Vec::new(); count];
1011 for block in self.source.blocks() {
1012 let Some(term) = self.source.terminator(block) else { continue };
1013 succs[block.index()] = self.source.successors(term).map(|call| call.block).collect();
1014 }
1015 // An explicit stack, because the depth of the walk is the number of blocks and a function
1016 // built by a generator has as many of those as it likes.
1017 let mut seen = vec![false; count];
1018 let mut order = Vec::with_capacity(count);
1019 let mut stack = vec![(entry, 0usize)];
1020 seen[entry.index()] = true;
1021 while let Some((block, at)) = stack.pop() {
1022 let Some(&next) = succs[block.index()].get(at) else {
1023 order.push(block);
1024 continue;
1025 };
1026 stack.push((block, at + 1));
1027 if !seen[next.index()] {
1028 seen[next.index()] = true;
1029 stack.push((next, 0));
1030 }
1031 }
1032 order.reverse();
1033 order.extend(self.source.blocks().filter(|block| !seen[block.index()]));
1034 order
1035 }
1036
1037 /// One block: its parameters, then every instruction in it that is not folded into another.
1038 fn block(&mut self, block: Block) -> Result<(), Unsupported> {
1039 let out = self.out_block(block);
1040 self.at = Some(out);
1041 if self.source.entry() == Some(block) {
1042 self.arrive(block, out)?;
1043 } else {
1044 let mut arriving = Vec::new();
1045 for ¶m in &self.source[block].params {
1046 // A value with no register to arrive in, which the class would not say, since
1047 // `class_of` puts one of these in the general purpose file on purpose and what it
1048 // means by that is that nothing there can hold it. What crosses the edge for one
1049 // of those is the address of where the value already is, so the parameter is a
1050 // pointer here and the bytes it points at are copied below.
1051 let ty = self.source[param].ty;
1052 let reg = self.out.append_param(out, self.class_of(ty));
1053 self.regs[param.index()] = Some(reg);
1054 if on_x87(ty) {
1055 arriving.push((param, reg));
1056 }
1057 }
1058 self.settle(block, &arriving)?;
1059 }
1060
1061 // What each instruction matched, and which instructions were folded into another. The
1062 // decision is made for the whole block before any of it is written, and it is made more
1063 // than once: a value that only some of its readers took has to be put back in a register
1064 // for all of them, and taking it away from those readers changes what they match.
1065 let insts: Vec<Inst> = self.source.insts(block).collect();
1066 let mut refused: HashSet<Value> = HashSet::new();
1067 let mut decided = self.decide(&insts, &refused);
1068 while let Some(value) = self.left_alive(&insts, &decided.plans) {
1069 refused.insert(value);
1070 decided = self.decide(&insts, &refused);
1071 }
1072 let Decided { found, folded, .. } = decided;
1073
1074 // Where each assignment in this block that starts a declaration on a value is, as the
1075 // machine instruction in front of the place its IR instruction left off, or the block
1076 // for one where nothing has been written yet. What comes after it is not known until the
1077 // block is filled, so that is read below.
1078 let wanted: HashSet<Option<Inst>> =
1079 self.marks.get(&block).into_iter().flatten().map(|&(after, _)| after).collect();
1080 let mut reached: Vec<(Option<Inst>, mir::Block, Option<mir::Inst>)> = Vec::new();
1081 for (index, (&inst, matched)) in insts.iter().zip(found).enumerate() {
1082 let before = index.checked_sub(1).map(|index| insts[index]);
1083 if wanted.contains(&before) {
1084 let at = self.at.unwrap_or(out);
1085 reached.push((before, at, self.out.terminator(at)));
1086 }
1087 if folded.contains(&inst) || self.writes_nothing(inst) {
1088 continue;
1089 }
1090 // A call is built from the convention rather than matched, which is why it is the one
1091 // opcode looked at by name here. Through an address it is a different instruction and
1092 // the same convention, so the two arrive at the same place and differ in one line of
1093 // it.
1094 match self.source[inst].opcode {
1095 Opcode::Call | Opcode::CallIndirect => {
1096 self.called(inst)?;
1097 continue;
1098 }
1099 // Built from the frame rather than matched, for the same shape of reason a call
1100 // is built from the convention: what a rule replaces a term with is instructions,
1101 // and what an `alloca` needs first is bytes, which the rule language has no way
1102 // to ask for.
1103 Opcode::Alloca => {
1104 self.reserve(inst)?;
1105 continue;
1106 }
1107 // Reading the stack pointer and writing it back, which are the two ends of a scope
1108 // holding a variable length array. Built here for the reason an `alloca` is: the
1109 // value is a register the rule language has no way to name, because what it holds
1110 // is not a value the program computed but where the machine's stack had got to.
1111 Opcode::StackSave => {
1112 self.stack_pointer(inst, false)?;
1113 continue;
1114 }
1115 Opcode::StackRestore => {
1116 self.stack_pointer(inst, true)?;
1117 continue;
1118 }
1119 // The address of a name, built here for the same reason an `alloca` is: what a
1120 // rule replaces a term with is instructions over values, and the operand of this
1121 // one is a symbol, which is a thing the rule language has no way to bind and the
1122 // solver has no way to say anything about. There is nothing in `lea sym(%rip)` a
1123 // proof over bitvectors could discharge, because what makes it the right answer
1124 // is the relocation and what the linker does with it.
1125 Opcode::GlobalAddr => {
1126 self.address_of(inst)?;
1127 continue;
1128 }
1129 // The address of a label and the branch that reads one, built here for the same
1130 // reason and for one more. The reason is the same: what the first of them names is
1131 // a block, which is not a value a rule pattern can bind, and there is nothing in
1132 // the distance between two places in one function that a proof over bitvectors
1133 // could discharge. The extra one is that the second is a terminator whose arms are
1134 // not two and not fixed, and a rule says what an instruction reads rather than
1135 // where a block goes.
1136 Opcode::BlockAddr => {
1137 self.block_address(inst)?;
1138 continue;
1139 }
1140 Opcode::IndirectBr => {
1141 self.indirect_branch(inst)?;
1142 continue;
1143 }
1144 // A `switch` that `crate::switch` found dense enough for a table, which is a load
1145 // out of the table and the same jump. Built here for the reasons the jump above
1146 // is, and because what the load reads is a place in this function.
1147 Opcode::Switch => {
1148 self.jump_table(inst)?;
1149 continue;
1150 }
1151 // The pair that saves a place in this function and comes back to it. Built here
1152 // for the reason the address of a label is, and for two more. The reason is the
1153 // same: the first of them writes down where control comes back to, which is a
1154 // place in this function and not a value a rule pattern can bind. The extra ones
1155 // are that each of them is a group of instructions over a buffer the program owns
1156 // rather than one instruction, and that the first of them leaves the block it was
1157 // written in and carries on in a new one, which is a thing no rule can do.
1158 Opcode::SetjmpMarker => {
1159 self.saves_place(inst)?;
1160 continue;
1161 }
1162 Opcode::LongjmpMarker => {
1163 self.comes_back(inst)?;
1164 continue;
1165 }
1166 // Where this thread's own storage starts, built here for a reason of the same
1167 // shape: what it reads is `%fs`, which is not a register the rule language can
1168 // bind and not one a proof over bitvectors could say anything about, because what
1169 // makes the load the right answer is an agreement between the loader and the C
1170 // library rather than any arithmetic.
1171 Opcode::ThreadPointer => {
1172 self.thread_pointer(inst)?;
1173 continue;
1174 }
1175 // What a named machine register holds, built here for the reason above written
1176 // about any register rather than about one: which register it is is a string
1177 // beside the instruction, and a rule matches on an opcode and a type and could
1178 // not see it. There is nothing to prove either, since the answer is the register
1179 // and the instruction is the move that reads it.
1180 Opcode::RegisterValue => {
1181 self.register_value(inst)?;
1182 continue;
1183 }
1184 // Where a frame is and what it returns to, built here for the same reason and one
1185 // more. The reason is the same: what the walk starts from is the frame pointer,
1186 // which is not a register a rule pattern can bind, and there is nothing in reading
1187 // the link the prologue saved that a proof over bitvectors could discharge. The
1188 // extra one is that how long the walk is comes out of a number beside the
1189 // instruction, so one of these is not one instruction but however many the depth
1190 // says, and a rule replaces a term with a term.
1191 Opcode::FrameAddress | Opcode::ReturnAddress => {
1192 self.frames(inst)?;
1193 continue;
1194 }
1195 // Built from the frame for the reason an `alloca` is, and from the convention for
1196 // the reason a call is: three of the four fields it writes are distances that do
1197 // not exist until the frame does, and the fourth is where the walk over the
1198 // argument registers stopped. A function that is not variadic has no such walk to
1199 // report, so it has nothing here and is refused below, which is the right answer
1200 // for a `va_start` in one.
1201 Opcode::VaStart if self.varargs.is_some() => {
1202 self.va_start(inst)?;
1203 continue;
1204 }
1205 // A return of more than one value, which is a structure small enough to come
1206 // back in a pair of registers. Built from the convention for the reason a call
1207 // is: which register each half goes in depends on the halves in front of it,
1208 // because the two register files are walked separately, and a pattern over a term
1209 // cannot see them. A return of one value is a term with a name and a rule, and it
1210 // stays one.
1211 //
1212 // A return of none in a function whose answer went through memory is here too,
1213 // and for a different reason: what it gives back is not written in the IR at all.
1214 // The convention says the address the caller handed over comes back, and only the
1215 // signature says this function was handed one.
1216 //
1217 // And a return of one eighty bit value, for a third reason: what a rule would
1218 // write is an instruction leaving the value in a register, and this one is left on
1219 // the x87 stack instead. A rule could not name that stack any more than any other
1220 // rule about this type could.
1221 Opcode::Return
1222 if self.source[self.source[inst].args].len() > 1
1223 || self.sret().is_some()
1224 || self.gives_back_x87(inst) =>
1225 {
1226 self.returned(inst)?;
1227 continue;
1228 }
1229 // A cast between a pointer and an integer of the same width, which on this
1230 // machine is every one the front end writes. No instruction at all, so no rule
1231 // could name one.
1232 Opcode::PtrToInt | Opcode::IntToPtr => {
1233 self.rename(inst)?;
1234 continue;
1235 }
1236 // A barrier, which is one instruction or none depending on the ordering. Written
1237 // by name because there is nothing about it a rule could be proved against, the
1238 // way there is nothing to prove about the address of a symbol.
1239 Opcode::Fence => {
1240 self.barrier(inst)?;
1241 continue;
1242 }
1243 // A hint, written by name for the reason a barrier is and one step further: not
1244 // only is there no equality for a proof to discharge, there is nothing about the
1245 // program around it either. Which of the four instructions it is comes out of the
1246 // number the builtin was given, which is beside the instruction rather than in it.
1247 Opcode::Prefetch => {
1248 self.hint(inst)?;
1249 continue;
1250 }
1251 // Stopping, written by name for the first half of the barrier's reason: it
1252 // computes nothing, so there is no term for a rule to replace, and what makes it
1253 // right is what the operating system does with the fault rather than anything a
1254 // proof over bitvectors could discharge.
1255 Opcode::Trap => {
1256 self.trap(inst);
1257 continue;
1258 }
1259 // A compare and exchange, which is written by name because it produces two values
1260 // and a rule produces one. The replacement of a rule is one term, a term names the
1261 // value an instruction computes, and there is no way in that language to say that
1262 // an instruction leaves an answer in one place and a yes or no in another.
1263 Opcode::Cmpxchg => {
1264 self.exchange(inst)?;
1265 continue;
1266 }
1267 // A read modify write, which is written by name for a different reason: it produces
1268 // one value, so a rule could name it, and what it does is not in the head a rule
1269 // matches on. Every one of the thirteen operations is the same opcode at the same
1270 // type and differs only in what is carried beside it, so one pattern would be all
1271 // thirteen patterns. Of the thirteen only the three with an instruction reach here,
1272 // since `crate::retry` turned the rest into loops a long way above this.
1273 Opcode::AtomicRmw => {
1274 self.modify(inst)?;
1275 continue;
1276 }
1277 // An `asm` statement, whose lowering is its template and there is no term for a
1278 // string. Written by name for the reason a barrier is, and before the x87 arm
1279 // below so that an `asm` holding a `long double` is refused as the `asm` it is
1280 // rather than as an instruction nothing computes.
1281 Opcode::InlineAsm => {
1282 self.assembly(inst)?;
1283 continue;
1284 }
1285 // Anything at all with an eighty bit float in it, which is the one arm here
1286 // chosen by a type rather than by an opcode, because what makes these different
1287 // is not what they do but where the value is. A `long double` has no register,
1288 // so it has no name in `crate::term` and no rule could bind one: every one of
1289 // these is a group of instructions over a frame slot, written out below.
1290 //
1291 // Last of the arms, so that a call and a return with one of these in them reach
1292 // the convention first and are refused by it, which is the truer answer: what is
1293 // wrong there is where the value has to travel and not that nothing can compute
1294 // it.
1295 _ if self.touches_x87(inst) => {
1296 self.x87(inst)?;
1297 continue;
1298 }
1299 _ => {}
1300 }
1301 let matched = matched.ok_or_else(|| self.unsupported(inst))?;
1302 self.emit(inst, &matched)?;
1303 // After it is built rather than when it matched, so that what is recorded is the rules
1304 // this function was lowered by and not the rules something was tried with.
1305 self.fired.mark(matched.rule);
1306 }
1307 // Whichever block the walk ended in rather than the one it started in. The two are the
1308 // same block for every function that does not save a place for a `__builtin_longjmp`, and
1309 // where they differ it is the last of them that the terminator and the arms belong to.
1310 // See [`Self::saves_place`].
1311 let last = self.at.expect("a block is being filled");
1312 self.edges(block, last)?;
1313 // Now that the block is filled, the instruction after each place an assignment was is the
1314 // first one it holds its value at. One with nothing after it, which a block ending in the
1315 // assignment would be, stays unanswered.
1316 if let Some(marks) = self.marks.get_mut(&block) {
1317 for &(before, at, last) in &reached {
1318 let first = match last {
1319 Some(last) => self.out.next_inst(last),
1320 None => self.out.insts(at).next(),
1321 };
1322 for mark in marks.iter_mut().filter(|(after, _)| *after == before) {
1323 mark.1 = first;
1324 }
1325 }
1326 }
1327 Ok(())
1328 }
1329
1330 /// One call, which is built from the convention rather than matched against the table for the
1331 /// same reason the arguments of the function itself are.
1332 ///
1333 /// The arguments are read before the call is built, which is what materializes a constant
1334 /// argument into a register, since no call passes an immediate.
1335 ///
1336 /// A call to a name and a call through an address are both here, and what tells them apart is
1337 /// the opcode rather than whether a callee was recorded, which is the same thing the verifier
1338 /// reads. Through an address the first operand is the address and the arguments are the ones
1339 /// behind it, and everything after that is the same: where each argument goes, where the value
1340 /// comes back and which registers are gone across it are the convention's answers and the
1341 /// convention does not ask what is being called.
1342 fn called(&mut self, inst: Inst) -> Result<(), Unsupported> {
1343 let data = &self.source[inst];
1344 let Extra::Call(info) = data.extra else { return Err(self.unsupported(inst)) };
1345 let info = self.source[info];
1346 let indirect = data.opcode == Opcode::CallIndirect;
1347
1348 let values: Vec<Value> = self.source[data.args].to_vec();
1349 let callee = if indirect {
1350 let &address = values.first().ok_or_else(|| self.unsupported(inst))?;
1351 abi::Callee::Through(self.reg_of(address)?)
1352 } else {
1353 abi::Callee::Named(info.callee.ok_or_else(|| self.unsupported(inst))?)
1354 };
1355
1356 // What the ABI asks of each argument, read out before any of them is, because reading one
1357 // borrows the function this is a table in. The ones the signature names are the signature's
1358 // answer and the ones behind them are the call's, which is where a structure passed to a
1359 // variadic callee by value says that its bytes travel: there is no parameter to say it on.
1360 let signature = &self.source[info.signature];
1361 let variadic = signature.variadic;
1362 let named: Vec<Abi> = signature.params.iter().map(|param| param.abi).collect();
1363 let beyond: Vec<Abi> = self.source[info.varargs].to_vec();
1364 // Every value that comes back and not only the first. A structure small enough to travel
1365 // in registers comes back in up to two of them, and which register each half is in is the
1366 // convention's answer, which is why the whole list goes to the same place the arguments do
1367 // rather than to a rule.
1368 let returns: Vec<Type> = signature.return_types().collect();
1369
1370 let mut args = Vec::with_capacity(values.len());
1371 for (index, value) in values.into_iter().skip(usize::from(indirect)).enumerate() {
1372 let abi = named.get(index).or_else(|| beyond.get(index - named.len()));
1373 let abi = abi.copied().unwrap_or_default();
1374 let ty = self.source[value].ty;
1375 // What travels for an eighty bit value is its bytes, so what the call is handed is
1376 // where they are rather than a register they are in, and there is no register they
1377 // could be in. Everything else about it is a sixteen byte object passed by value and
1378 // is built by the same code.
1379 let reg =
1380 if abi::on_the_stack(ty) { self.x87_slot(value) } else { self.reg_of(value)? };
1381 args.push(abi::Passing { ty, reg, abi });
1382 }
1383 let block = self.at.expect("a block is being filled");
1384 let what = abi::Calling {
1385 callee,
1386 args: &args,
1387 returns: &returns,
1388 variadic,
1389 named: named.len(),
1390 at: self.source.span(inst),
1391 };
1392 let made = abi::call(&mut self.out, block, &what, self.conv, self.names)
1393 .map_err(|refused| Unsupported::Call { inst, refused })?;
1394 let calls = &mut self.stack.calls;
1395 *calls = Some(calls.unwrap_or(0).max(made.outgoing));
1396 // An eighty bit value came back on the x87 stack, and the one thing that has to happen
1397 // before anything else touches that stack is taking it off. So the `fstp` goes here, in
1398 // front of everything the block does next, and after it the value is in its slot and is
1399 // read the way every other one is.
1400 let results: Vec<Value> = self.source[inst].results().collect();
1401 if let [result] = results[..] {
1402 if abi::on_the_stack(self.source[result].ty) {
1403 let span = self.source.span(inst);
1404 let into = self.x87_slot(result);
1405 let into = self.through(into);
1406 self.x87_at("fstp_t", span, into);
1407 return Ok(());
1408 }
1409 }
1410 for (result, ®) in results.into_iter().zip(&made.results) {
1411 self.regs[result.index()] = Some(reg);
1412 }
1413 Ok(())
1414 }
1415
1416 /// The pointer a function returning through memory was handed, or nothing in a function that
1417 /// was not.
1418 ///
1419 /// It is the first parameter and the signature is what says so, since in the IR it is an
1420 /// ordinary pointer and reads like one everywhere in the body. A function with a signature
1421 /// like that and no entry block has nothing to give back and no body to give it back from.
1422 fn sret(&self) -> Option<Value> {
1423 let first = self.source.signature().params.first()?;
1424 if !matches!(first.abi, Abi::Sret { .. }) {
1425 return None;
1426 }
1427 self.source[self.source.entry()?].params.first().copied()
1428 }
1429
1430 /// One `return` the convention has to write, as the place each value has to be in by the end.
1431 ///
1432 /// One pseudo per value, each a read constrained to a return register, which is what a return
1433 /// of one value already is and is the whole of what either does. The `ret` itself comes from
1434 /// the epilogue for both, long after this, because the frame has to be given back first.
1435 ///
1436 /// The two register files are counted separately, so a structure of a `double` and a `long`
1437 /// leaves the `double` in the first vector register and the `long` in the first integer one
1438 /// rather than in the second of either. That is the same walk `rucc_codegen::abi` makes on
1439 /// the other side of the call, which is what makes the two ends agree.
1440 ///
1441 /// A function whose answer went through memory gives back the address it was handed, in front
1442 /// of nothing else, because a signature that returns that way returns nothing else. That the
1443 /// caller already knows the address is not enough: it is allowed to read the register instead,
1444 /// and a caller that does gets whatever the allocator last left there. In a leaf function that
1445 /// is usually the right answer by accident, and one call in the body is enough to make it a
1446 /// wild pointer, which is why this is written rather than left to luck.
1447 ///
1448 /// Where everything goes is worked out before anything is written, so a return this cannot
1449 /// make leaves no half of one behind.
1450 /// Whether what a `return` gives back is the one value that goes back on the x87 stack.
1451 fn gives_back_x87(&self, inst: Inst) -> bool {
1452 let [value] = self.source[self.source[inst].args] else { return false };
1453 abi::on_the_stack(self.source[value].ty)
1454 }
1455
1456 fn returned(&mut self, inst: Inst) -> Result<(), Unsupported> {
1457 let values: Vec<Value> = self.source[self.source[inst].args].to_vec();
1458 let (mut ints, mut floats) = (0usize, 0usize);
1459 let mut parts = Vec::with_capacity(values.len() + 1);
1460 // An eighty bit value goes back on the x87 stack, which is where the convention says it is
1461 // and is the one place a value is left rather than put in a register. So the whole of the
1462 // return is an `fld` of its slot, and the stack it leaves the value on is not empty at the
1463 // `ret`, which is the one time in this file that is true and is what the convention asks
1464 // for. What comes after is the epilogue, which gives the frame back and touches nothing in
1465 // the unit.
1466 if let [value] = values[..] {
1467 let ty = self.source[value].ty;
1468 if abi::on_the_stack(ty) && self.sret().is_none() {
1469 let span = self.source.span(inst);
1470 let from = self.x87_slot(value);
1471 let from = self.through(from);
1472 self.x87_at("fld_t", span, from);
1473 return Ok(());
1474 }
1475 }
1476 for value in self.sret().into_iter().chain(values) {
1477 let ty = self.source[value].ty;
1478 let at = if crate::term::in_vector_file(ty) { &mut floats } else { &mut ints };
1479 // Why it cannot come back, and not only that it cannot. A type that travels nowhere
1480 // says so itself, and a type that travels perfectly well ran out of registers.
1481 let missing = abi::refuses(ty).unwrap_or(Missing::NoRoom);
1482 let name = abi::ret_of(ty, *at).ok_or(Unsupported::Returned { inst, missing })?;
1483 *at += 1;
1484 // The register is the target's answer and not one worked out here, the same as it is
1485 // for a return of one value, so that both halves of a pair and every rule that writes
1486 // half of one are reading the same table.
1487 let opcode = name.strip_prefix(PREFIX).expect("a machine instruction of this target");
1488 let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
1489 let [desc] = form.operands() else { return Err(self.unsupported(inst)) };
1490 parts.push((self.names.intern(name), self.reg_of(value)?, *desc));
1491 }
1492
1493 let block = self.at.expect("a block is being filled");
1494 let span = self.source.span(inst);
1495 for (opcode, reg, desc) in parts {
1496 let operand = mir::Operand {
1497 reg,
1498 class: desc.class,
1499 role: desc.role,
1500 constraint: desc.constraint,
1501 };
1502 self.out.build(block, mir::Opcode::new(opcode)).at(span).operand(operand).finish();
1503 }
1504 Ok(())
1505 }
1506
1507 /// One `alloca`: the bytes it asks for go on the list the frame is laid out from, and the
1508 /// address of them is one instruction.
1509 ///
1510 /// The instruction is a `lea` off the stack pointer, which is the one register that reaches
1511 /// the frame in every function, and its displacement is left at nothing because there is no
1512 /// frame yet. Which instruction is waiting for which local is remembered, and
1513 /// [`crate::finish`] fills the numbers in after [`crate::frame::Frame`] has placed them.
1514 ///
1515 /// There is deliberately no rule for `alloca` and no name for one in [`crate::term`], and
1516 /// that is what stops it being folded into something else. An operand shown as the
1517 /// instruction that computed it is offered to the matcher by its name, so an `alloca` with no
1518 /// name is one no pattern can reach past, and the address it computes is always in a register
1519 /// by the time anything reads it.
1520 fn reserve(&mut self, inst: Inst) -> Result<(), Unsupported> {
1521 let data = &self.source[inst];
1522 // A variable length array carries the size it wants as an operand rather than in the
1523 // instruction, which is the whole of what tells the two apart here.
1524 if let Some(&size) = self.source[data.args].first() {
1525 return self.grow(inst, size);
1526 }
1527 let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
1528 let info = self.source[mem];
1529 let size = u32::try_from(info.size)
1530 .map_err(|_| Unsupported::Dynamic { inst, growing: Growing::Huge })?;
1531 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1532
1533 // At least one, because the frame divides by the alignment and an object with no
1534 // alignment at all is one the front end had nothing to say about rather than one that may
1535 // go anywhere.
1536 let index = self.stack.locals.len();
1537 self.stack.locals.push(Local { size, align: info.align.max(1) });
1538 if let Some(decl) = self.source.mem_decl(mem) {
1539 self.stack.declared.push((index, decl));
1540 }
1541
1542 let block = self.at.expect("a block is being filled");
1543 let reg = self.new_reg(result);
1544 let span = self.source.span(inst);
1545 let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
1546 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
1547 let made =
1548 self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
1549 self.stack.addresses.push((made, index));
1550 Ok(())
1551 }
1552
1553 /// The other kind of `alloca`: one whose size the function does not know until it runs, which
1554 /// is what a variable length array is.
1555 ///
1556 /// Nothing about it is a slot the frame laid out, because the frame is laid out once and this
1557 /// happens as often as control reaches the declaration. The bytes come off the stack pointer
1558 /// where the declaration stands, which is two instructions:
1559 ///
1560 /// ```text
1561 /// sub sp, bytes the stack pointer moves down over the memory, which is what takes it
1562 /// lea reg, [sp+n] where the memory starts, which is above the outgoing argument area
1563 /// ```
1564 ///
1565 /// The displacement is left at nothing for the reason the constant kind leaves its own at
1566 /// nothing, and for a different number: that area belongs to the arguments of whatever this
1567 /// function calls, it stays at the bottom of the frame wherever the bottom has moved to, and
1568 /// how big it is is not known until every call in the function has been seen.
1569 ///
1570 /// The bytes are already a multiple of the stack pointer's alignment by the time they arrive,
1571 /// because [`crate::expand::rounds`] rounded them up in the IR, so nothing here has to mask the
1572 /// stack pointer afterwards and the stack pointer stays somewhere a call can be made from.
1573 ///
1574 /// Two instructions here and not always two in the finished function. On a command line that
1575 /// asked for the stack to be touched a page at a time, the subtraction becomes a loop that
1576 /// walks the same distance a page at a time, which [`crate::finish`] writes. That is why the
1577 /// instruction is written down in [`Stack::grown`] as well as left where it is.
1578 ///
1579 /// An array wanting more alignment than the convention leaves the stack pointer with does not
1580 /// reach here asking for it: [`crate::expand::rounds`] gives it the alignment in extra bytes
1581 /// and turns the array into a `ptr_add` of the offset that lands inside them, so what arrives
1582 /// is a block asking for the convention's alignment like any other. The refusal below is what
1583 /// answers IR that came from somewhere other than that pass, since forcing the alignment here
1584 /// would be a second rounding of a register the frame already rounded, and after it no
1585 /// constant reaches the rest of the frame from anywhere. See `Growing` in [`crate::frame`].
1586 fn grow(&mut self, inst: Inst, size: Value) -> Result<(), Unsupported> {
1587 let data = &self.source[inst];
1588 let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
1589 let info = self.source[mem];
1590 if info.align > self.conv.stack_align {
1591 return Err(Unsupported::Dynamic { inst, growing: Growing::Aligned });
1592 }
1593 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1594 let bytes = self.reg_of(size)?;
1595
1596 let block = self.at.expect("a block is being filled");
1597 let span = self.source.span(inst);
1598 let stack = mir::Reg::physical(self.conv.stack_pointer);
1599 let grow = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.grow)));
1600 let took = self
1601 .out
1602 .build(block, grow)
1603 .at(span)
1604 .operand(mir::Operand::write(stack, self.gpr))
1605 .operand(mir::Operand::read(stack, self.gpr))
1606 .operand(mir::Operand::read(bytes, self.gpr))
1607 .finish();
1608 self.stack.grown.push(took);
1609
1610 let reg = self.new_reg(result);
1611 let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
1612 let sp = mir::Operand::read(stack, self.gpr);
1613 let made =
1614 self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
1615 self.stack.dynamic.push(made);
1616 self.stack.grown_at.get_or_insert(inst);
1617 Ok(())
1618 }
1619
1620 /// Where the stack pointer is, kept so that something later can put it back.
1621 ///
1622 /// One move out of the stack pointer and one move into it, which is the whole of what the two
1623 /// halves are. What makes them worth writing is where the front end puts them: a scope holding
1624 /// a variable length array saves the stack pointer as it opens and puts it back as it closes,
1625 /// so a loop declaring one takes its bytes once round rather than once per iteration, and a
1626 /// jump out of the scope gives the bytes back on the way out.
1627 ///
1628 /// The value travels in an ordinary register the allocator hands out, so it may be spilled like
1629 /// any other, and a spill slot in a frame that grows is reached through the frame pointer,
1630 /// which is exactly the register that still means something after the stack pointer has moved.
1631 fn stack_pointer(&mut self, inst: Inst, into: bool) -> Result<(), Unsupported> {
1632 let data = &self.source[inst];
1633 let block = self.at.expect("a block is being filled");
1634 let span = self.source.span(inst);
1635 let stack = mir::Reg::physical(self.conv.stack_pointer);
1636 let mov = x86_64::FRAME.moves(self.gpr).expect("a class the target says how to move").mov;
1637 let mov = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{mov}")));
1638 let (write, read) = if into {
1639 let &saved = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
1640 (stack, self.reg_of(saved)?)
1641 } else {
1642 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1643 (self.new_reg(result), stack)
1644 };
1645 self.out
1646 .build(block, mov)
1647 .at(span)
1648 .operand(mir::Operand::write(write, self.gpr))
1649 .operand(mir::Operand::read(read, self.gpr))
1650 .finish();
1651 // Only the write is a move of the stack pointer, and it is the one that makes the frame a
1652 // growing one. A read of it in a function that never writes it back is a function that
1653 // asked where the stack was and did nothing with the answer.
1654 if into {
1655 self.stack.grown_at.get_or_insert(inst);
1656 }
1657 Ok(())
1658 }
1659
1660 /// Whether an instruction has an eighty bit float anywhere in it.
1661 ///
1662 /// Producing one and reading one are the same question here, because what makes one of these
1663 /// different from every other instruction is not the operation but where the value is. A
1664 /// `long double` is on the x87 stack while it is being worked on and in a frame slot the rest
1665 /// of the time, and neither of those is somewhere the operand of a rule could point.
1666 fn touches_x87(&self, inst: Inst) -> bool {
1667 let data = &self.source[inst];
1668 data.results().any(|value| on_x87(self.source[value].ty))
1669 || self.source[data.args].iter().any(|&arg| on_x87(self.source[arg].ty))
1670 }
1671
1672 /// Everything that happens to an eighty bit float, as the group of instructions it is.
1673 ///
1674 /// The first six move one, and every one of those is a load, a store, or a load and a store at
1675 /// two different formats, because that is the whole of what this machine converts with: the
1676 /// x87 has no instruction that turns one thing on its stack into another, so a widening is
1677 /// `fld` of the narrow format and a narrowing is `fstp` of it.
1678 ///
1679 /// The rest work on one, and they are here rather than in a rule for the same reason the six
1680 /// are. An add is a push, a push, the add and a pop, and what passes between those four is the
1681 /// top of a stack nothing allocates from, so there is no value in the middle of the group for
1682 /// a pattern to bind or a replacement to name. The comparison is the same shape with its last
1683 /// two instructions folded into one opcode, which is where the byte it produces comes from.
1684 ///
1685 /// Every group leaves the stack as empty as it found it, which is what `spec/10-backend.md`
1686 /// section 10.8 asks of one and is why nothing in this file has to track a depth: each push
1687 /// below is answered by a pop a line or two later, so no two groups can ever be looking at
1688 /// the same eight registers.
1689 fn x87(&mut self, inst: Inst) -> Result<(), Unsupported> {
1690 match self.source[inst].opcode {
1691 Opcode::Load => self.x87_load(inst),
1692 Opcode::Store => self.x87_store(inst),
1693 Opcode::FPExt => self.x87_widen(inst),
1694 Opcode::FPTrunc => self.x87_narrow(inst),
1695 Opcode::SIToFP => self.x87_from_signed(inst),
1696 Opcode::FPToSI => self.x87_to_signed(inst),
1697 Opcode::FAdd => self.x87_arith(inst, "fadd_p"),
1698 Opcode::FSub => self.x87_arith(inst, "fsubr_p"),
1699 Opcode::FMul => self.x87_arith(inst, "fmul_p"),
1700 Opcode::FDiv => self.x87_arith(inst, "fdivr_p"),
1701 Opcode::FNeg => self.x87_flip(inst),
1702 Opcode::FCmp => self.x87_compare(inst),
1703 Opcode::FConst => self.x87_const(inst),
1704 _ => Err(self.unsupported(inst)),
1705 }
1706 }
1707
1708 /// The eighty bit parameters of a block, copied out of the addresses an edge handed over and
1709 /// into slots of the block's own.
1710 ///
1711 /// What crosses an edge for a value of this type is an address, because the value is sixteen
1712 /// bytes of the frame and no register holds any of it. The block cannot keep that address: a
1713 /// second edge into the same block hands over a second one, and a read after the block would
1714 /// then be a read of whichever edge was taken rather than of one place. So the block has a
1715 /// slot per parameter and the bytes are copied into it here, which is the move on an edge that
1716 /// every other type gets from the allocator.
1717 ///
1718 /// Every load runs before every store and the stores run backwards, so all of the values are
1719 /// on the x87 stack at once and nothing reads a slot another one has already written. That
1720 /// costs nothing in the ordinary case of one parameter and is what makes the back edge of a
1721 /// loop that swaps two of these work. It is also the reason for the limit: the stack is eight
1722 /// deep, and a block with more of these than that is refused rather than copied in an order
1723 /// that could be wrong.
1724 fn settle(&mut self, block: Block, arriving: &[(Value, mir::Reg)]) -> Result<(), Unsupported> {
1725 let Some(&(first, _)) = arriving.first() else { return Ok(()) };
1726 if arriving.len() > X87_DEPTH {
1727 let ty = self.source[first].ty;
1728 return Err(Unsupported::Phi { block, count: arriving.len(), ty });
1729 }
1730 // A block parameter comes from no instruction, so what this points at is the first thing
1731 // in the block, which is where a reader looking for the copy would look.
1732 let first_inst = self.source.insts(block).next();
1733 let span = first_inst.map_or(Span::DUMMY, |it| self.source.span(it));
1734 for &(_, reg) in arriving {
1735 let from = self.through(reg);
1736 self.x87_at("fld_t", span, from);
1737 }
1738 for &(param, _) in arriving.iter().rev() {
1739 let into = self.x87_slot(param);
1740 let into = self.through(into);
1741 self.x87_at("fstp_t", span, into);
1742 }
1743 Ok(())
1744 }
1745
1746 /// The frame slot an eighty bit value lives in, as its address in a fresh register.
1747 ///
1748 /// The slot is the value's for the whole function and is taken the first time somebody asks.
1749 /// The address is worked out again every time, which is a `lea` per use and is deliberate: one
1750 /// address kept in a register from the definition to the last use would hold a general purpose
1751 /// register open across everything in between, and a function with a handful of these in it
1752 /// would spend its registers on addresses of things rather than on things.
1753 fn x87_slot(&mut self, value: Value) -> mir::Reg {
1754 // An argument of the function has a slot already and it is the caller's. The convention
1755 // puts the bytes in the argument area and hands over where they are, so the address that
1756 // arrived is the answer and no second copy of the value is made. Nothing ever writes to a
1757 // value of this type once it exists, so nothing writes to the caller's copy either. A
1758 // parameter of any other block is not this: what arrived there is an address a predecessor
1759 // chose, [`Lowering::settle`] has already copied the bytes out of it, and the slot those
1760 // bytes landed in is the one below.
1761 let entry = self.source.entry();
1762 if let (Def::Param { block, .. }, Some(reg)) =
1763 (self.source[value].def, self.regs[value.index()])
1764 {
1765 if entry == Some(block) {
1766 return reg;
1767 }
1768 }
1769 let index = match self.slots[value.index()] {
1770 Some(index) => index,
1771 None => {
1772 let index = self.stack.locals.len();
1773 self.stack.locals.push(Local { size: X87_BYTES, align: X87_BYTES });
1774 self.slots[value.index()] = Some(index);
1775 index
1776 }
1777 };
1778 let block = self.at.expect("a block is being filled");
1779 self.frame_address(block, index)
1780 }
1781
1782 /// The bytes a value crosses between a register and the x87 stack through, as their address
1783 /// in a fresh register.
1784 fn x87_crossing(&mut self) -> mir::Reg {
1785 let index = match self.crossing {
1786 Some(index) => index,
1787 None => {
1788 let index = self.stack.locals.len();
1789 self.stack.locals.push(Local { size: X87_CROSSING, align: X87_CROSSING });
1790 self.crossing = Some(index);
1791 index
1792 }
1793 };
1794 let block = self.at.expect("a block is being filled");
1795 self.frame_address(block, index)
1796 }
1797
1798 /// The two control words, as the address of the first of them in a fresh register.
1799 fn x87_control(&mut self) -> mir::Reg {
1800 let index = match self.control {
1801 Some(index) => index,
1802 None => {
1803 let index = self.stack.locals.len();
1804 self.stack.locals.push(Local { size: 4, align: 4 });
1805 self.control = Some(index);
1806 index
1807 }
1808 };
1809 let block = self.at.expect("a block is being filled");
1810 self.frame_address(block, index)
1811 }
1812
1813 /// An address held in a register, as the addressing mode that reaches it.
1814 fn through(&self, reg: mir::Reg) -> mir::Mem {
1815 mir::Mem::at(mir::Operand::read(reg, self.gpr))
1816 }
1817
1818 /// One instruction of a group, which names an address and nothing else.
1819 ///
1820 /// Every x87 instruction that moves a value is one of these. What it does to the stack is in
1821 /// the mnemonic rather than in an operand, so there is no register to write down and no
1822 /// register the allocator gets a say in.
1823 fn x87_at(&mut self, name: &str, span: Span, at: mir::Mem) {
1824 let block = self.at.expect("a block is being filled");
1825 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1826 self.out.build(block, opcode).at(span).mem(at).finish();
1827 }
1828
1829 /// The one instruction of a group that reaches the program's own memory.
1830 ///
1831 /// A `long double` moves in two instructions with a frame slot at one end of them, and the
1832 /// other end is the address the program wrote. That end is the access, so it is the one that
1833 /// carries what the program said about it, and the trip through the slot is this compiler's
1834 /// own business the way a spill is. See [`Self::carried`].
1835 fn x87_touching(&mut self, name: &str, inst: Inst, at: mir::Mem) {
1836 let block = self.at.expect("a block is being filled");
1837 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1838 let (span, flags) = (self.source.span(inst), self.carried(inst));
1839 self.out.build(block, opcode).at(span).flags(flags).mem(at).finish();
1840 }
1841
1842 /// One instruction of a group that names nothing at all.
1843 ///
1844 /// The arithmetic is these. Both of an add's operands are already on the stack when it runs
1845 /// and so is where the answer goes, and the stack is not somewhere an instruction says, so
1846 /// `faddp` has an argument in the assembler's syntax and nothing here for the argument to come
1847 /// from. What it works on is which two pushes came before it, which is a fact about the order
1848 /// of the group and is why the group is written in one place.
1849 fn x87_only(&mut self, name: &str, span: Span) {
1850 let block = self.at.expect("a block is being filled");
1851 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1852 self.out.build(block, opcode).at(span).finish();
1853 }
1854
1855 /// A `load` of a `long double`: onto the stack from where it was, and off it into the slot.
1856 ///
1857 /// Two instructions rather than the two general purpose moves the same sixteen bytes would
1858 /// take, because `fld` and `fstp` at this format neither convert nor look: the value goes on
1859 /// in the format it was already in and comes back off in it, so a signalling NaN stays one
1860 /// and nothing is raised. Which is what makes this a copy at all.
1861 fn x87_load(&mut self, inst: Inst) -> Result<(), Unsupported> {
1862 let (args, result) = self.ends(inst)?;
1863 let &address = args.first().ok_or_else(|| self.unsupported(inst))?;
1864 let span = self.source.span(inst);
1865 let from = self.reg_of(address)?;
1866 let from = self.through(from);
1867 let into = self.x87_slot(result);
1868 let into = self.through(into);
1869 self.x87_touching("fld_t", inst, from);
1870 self.x87_at("fstp_t", span, into);
1871 Ok(())
1872 }
1873
1874 /// A `store` of a `long double`: the same pair the other way round.
1875 fn x87_store(&mut self, inst: Inst) -> Result<(), Unsupported> {
1876 let args = self.source[self.source[inst].args].to_vec();
1877 let [value, address] = args[..] else { return Err(self.unsupported(inst)) };
1878 let span = self.source.span(inst);
1879 let from = self.x87_slot(value);
1880 let from = self.through(from);
1881 let into = self.reg_of(address)?;
1882 let into = self.through(into);
1883 self.x87_at("fld_t", span, from);
1884 self.x87_touching("fstp_t", inst, into);
1885 Ok(())
1886 }
1887
1888 /// A `float`, a `double` or an integer becoming a `long double`.
1889 ///
1890 /// Through memory, because the x87 reads memory and nothing else: the value is in a register
1891 /// the machine has and the unit has no way to be handed one, so it is written to the crossing
1892 /// bytes and loaded back at the format that widens it. Every one of these is exact. Sixty four
1893 /// bits of significand and fifteen of exponent hold every `float`, every `double` and every
1894 /// sixty four bit integer outright, so none of the four can round and none can raise.
1895 fn x87_across(
1896 &mut self,
1897 inst: Inst,
1898 put: &'static str,
1899 class: RegClass,
1900 get: &'static str,
1901 ) -> Result<(), Unsupported> {
1902 let (args, result) = self.ends(inst)?;
1903 let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1904 let span = self.source.span(inst);
1905 let value = self.reg_of(source)?;
1906 let across = self.x87_crossing();
1907 let across = self.through(across);
1908 let into = self.x87_slot(result);
1909 let into = self.through(into);
1910
1911 let block = self.at.expect("a block is being filled");
1912 let store = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{put}")));
1913 self.out.build(block, store).at(span).uses(value, class).mem(across).finish();
1914 self.x87_at(get, span, across);
1915 self.x87_at("fstp_t", span, into);
1916 Ok(())
1917 }
1918
1919 /// A `long double` becoming a `float`, a `double` or an integer.
1920 ///
1921 /// Through memory for the reason above and in the same three instructions backwards. The two
1922 /// that go to a float round to nearest, which is what the control word says unless somebody
1923 /// has changed it and is what C wants. The two that go to an integer do not, which is why they
1924 /// do not come here.
1925 fn x87_back(
1926 &mut self,
1927 inst: Inst,
1928 put: &'static str,
1929 get: &'static str,
1930 class: RegClass,
1931 ) -> Result<(), Unsupported> {
1932 let (args, result) = self.ends(inst)?;
1933 let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1934 let span = self.source.span(inst);
1935 let from = self.x87_slot(source);
1936 let from = self.through(from);
1937 let across = self.x87_crossing();
1938 let across = self.through(across);
1939
1940 self.x87_at("fld_t", span, from);
1941 self.x87_at(put, span, across);
1942 let block = self.at.expect("a block is being filled");
1943 let reg = self.new_reg(result);
1944 let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{get}")));
1945 self.out.build(block, load).at(span).def(reg, class).mem(across).finish();
1946 Ok(())
1947 }
1948
1949 /// An `fpext` up to a `long double`, which is the only direction this machine has one in.
1950 fn x87_widen(&mut self, inst: Inst) -> Result<(), Unsupported> {
1951 let sse = self.conv.sse_class;
1952 match self.source[self.narrow(inst)?].ty.bits() {
1953 32 => self.x87_across(inst, "movss_mr", sse, "fld_s"),
1954 64 => self.x87_across(inst, "movsd_mr", sse, "fld_l"),
1955 _ => Err(self.unsupported(inst)),
1956 }
1957 }
1958
1959 /// An `fptrunc` down from a `long double`, which is the other direction of the same.
1960 fn x87_narrow(&mut self, inst: Inst) -> Result<(), Unsupported> {
1961 let sse = self.conv.sse_class;
1962 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
1963 match self.source[result].ty.bits() {
1964 32 => self.x87_back(inst, "fstp_s", "movss_rm", sse),
1965 64 => self.x87_back(inst, "fstp_l", "movsd_rm", sse),
1966 _ => Err(self.unsupported(inst)),
1967 }
1968 }
1969
1970 /// A `sitofp` up to a `long double`.
1971 ///
1972 /// Thirty two bits and sixty four, and nothing narrower, because C widens an integer to `int`
1973 /// before it converts one and the front end writes that widening down. An unsigned integer is
1974 /// not here at all: `fild` reads its operand as signed, so a value above the signed range
1975 /// comes back short by two to the sixty fourth and has to be added back, which is arithmetic
1976 /// rather than a move and waits with the rest of it.
1977 fn x87_from_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
1978 let gpr = self.gpr;
1979 match self.source[self.narrow(inst)?].ty.bits() {
1980 32 => self.x87_across(inst, "mov_mr_32", gpr, "fild_l"),
1981 64 => self.x87_across(inst, "mov_mr_64", gpr, "fild_ll"),
1982 _ => Err(self.unsupported(inst)),
1983 }
1984 }
1985
1986 /// An `fptosi` down from a `long double`, which is the one conversion here with no single
1987 /// instruction behind it.
1988 ///
1989 /// C cuts towards zero and the unit rounds the way its control word says, so the store that
1990 /// takes the value off the stack is wrapped in the control word being saved, changed and put
1991 /// back. Five instructions around the one that does the work, and three more moving the word
1992 /// through a register, because this machine has no way to OR a constant into memory at this
1993 /// width. The unit has a shorter answer in `fisttp`, and `spec/10-backend.md` section 10.8
1994 /// says why it is not used: it is SSE3, the x86-64 baseline is not, and there is nothing here
1995 /// that can gate an instruction on a feature yet.
1996 fn x87_to_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
1997 let (args, result) = self.ends(inst)?;
1998 let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1999 let (put, get) = match self.source[result].ty.bits() {
2000 32 => ("fistp_l", "mov_rm_32"),
2001 64 => ("fistp_ll", "mov_rm_64"),
2002 _ => return Err(self.unsupported(inst)),
2003 };
2004 let span = self.source.span(inst);
2005 let gpr = self.gpr;
2006 let from = self.x87_slot(source);
2007 let from = self.through(from);
2008 let across = self.x87_crossing();
2009 let across = self.through(across);
2010 let control = self.x87_control();
2011 let saved = self.through(control).plus(0);
2012 let cut = self.through(control).plus(2);
2013
2014 // The word the unit has now, into the first of the two slots and into a register, with the
2015 // rounding field turned to truncate on the way to the second.
2016 self.x87_at("fnstcw", span, saved);
2017 let block = self.at.expect("a block is being filled");
2018 let was = self.out.new_vreg(gpr);
2019 let read = mir::Opcode::new(self.names.intern("x64.mov_rm_16"));
2020 self.out.build(block, read).at(span).def(was, gpr).mem(saved).finish();
2021 let now = self.out.new_vreg(gpr);
2022 let set = mir::Opcode::new(self.names.intern("x64.or_ri_16"));
2023 // Two address, which is written out here rather than taken from the two shorthands
2024 // because the shorthands leave an operand unconstrained: this machine ORs into the
2025 // register it read, so the two have to be the same one and only the constraint says so.
2026 self.out
2027 .build(block, set)
2028 .at(span)
2029 .operand(mir::Operand::write(now, gpr).with(Constraint::Reuse(1)))
2030 .operand(mir::Operand::read(was, gpr))
2031 .imm(X87_TRUNCATE)
2032 .finish();
2033 let write = mir::Opcode::new(self.names.intern("x64.mov_mr_16"));
2034 self.out.build(block, write).at(span).uses(now, gpr).mem(cut).finish();
2035
2036 // The conversion itself, under the changed word, and then the word the unit had put back
2037 // before anything else runs.
2038 self.x87_at("fldcw", span, cut);
2039 self.x87_at("fld_t", span, from);
2040 self.x87_at(put, span, across);
2041 self.x87_at("fldcw", span, saved);
2042
2043 let block = self.at.expect("a block is being filled");
2044 let reg = self.new_reg(result);
2045 let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{get}")));
2046 self.out.build(block, load).at(span).def(reg, gpr).mem(across).finish();
2047 Ok(())
2048 }
2049
2050 /// A constant of this type, as the bits of it written into its slot.
2051 ///
2052 /// No x87 instruction at all, which is the surprise here. A slot holding an eighty bit value is
2053 /// the value, so a constant is ten bytes put where the value lives, and the unit never has to
2054 /// see it: whatever reads it will `fld` it out of the slot the way it reads any other one.
2055 ///
2056 /// Ten bytes in two goes, because the machine stores eight at a time and there is no store of
2057 /// an immediate to memory, so each half is put in a register first. The six bytes above the ten
2058 /// are left alone, since nothing reads them: they are the padding that makes the type sixteen
2059 /// wide and they are unspecified in the psABI rather than zero.
2060 ///
2061 /// The other way is a constant pool, an `fldt` of a symbol, and a relocation, which is what a
2062 /// compiler with somewhere to put a literal does. This back end has nowhere to put one yet, and
2063 /// four instructions in the frame is what that costs until it does.
2064 fn x87_const(&mut self, inst: Inst) -> Result<(), Unsupported> {
2065 let Extra::Imm(imm) = self.source[inst].extra else { return Err(self.unsupported(inst)) };
2066 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2067 let bits = self.source[imm].bits();
2068 let span = self.source.span(inst);
2069 let gpr = self.gpr;
2070 let slot = self.x87_slot(result);
2071 let low = self.through(slot).plus(0);
2072 let high = self.through(slot).plus(8);
2073
2074 let block = self.at.expect("a block is being filled");
2075 for (bytes, at, into) in
2076 [(bits as u64 as i64, low, "64"), (((bits >> 64) & 0xffff) as i64, high, "16")]
2077 {
2078 let held = self.out.new_vreg(gpr);
2079 let put = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_ri_{into}")));
2080 self.out.build(block, put).at(span).def(held, gpr).imm(bytes).finish();
2081 let store = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_mr_{into}")));
2082 self.out.build(block, store).at(span).uses(held, gpr).mem(at).finish();
2083 }
2084 Ok(())
2085 }
2086
2087 /// One arithmetic instruction on two eighty bit values, as the four it takes.
2088 ///
2089 /// The left operand is pushed first and the right one on top of it, so the left ends up
2090 /// underneath and the answer wanted is the one below against the top in that order. Which of
2091 /// the two mnemonics computes that is a question about the spelling rather than about the
2092 /// machine, and the two spellings disagree. Intel's `FSUBP ST(i), ST(0)` is `ST(i) - ST(0)`
2093 /// and is `DE E8+i`, and AT&T's `fsubp` is `DE E0+i`, which is the other subtraction. This
2094 /// compiler writes AT&T and encodes what gas encodes, so what it asks for here is `fsubr_p`
2095 /// and `fdivr_p`, and the `r` is not a reversal of anything the code generator decided.
2096 ///
2097 /// An addition and a multiplication have one form each and do not care, which is why a test
2098 /// that reads the mnemonic back would not have caught this and one that computes a subtraction
2099 /// and checks the answer does.
2100 ///
2101 /// The answer is left where the deeper of the two was and the shallower is gone, which is what
2102 /// the `p` on the mnemonic means, so one push has already been paid back by the time the
2103 /// `fstp` runs and the stack is level again after it.
2104 ///
2105 /// Nothing here is folded and nothing is reused. Two values that are the same value get two
2106 /// pushes of the same slot, and an operand that was just computed is read back out of the slot
2107 /// it was written to rather than left on the stack, which costs a store and a load per
2108 /// instruction in an expression. Keeping a partial result on the stack across the next
2109 /// instruction's operands means knowing how deep the stack is at every point in the block, and
2110 /// that is a different thing from writing a group.
2111 fn x87_arith(&mut self, inst: Inst, with: &'static str) -> Result<(), Unsupported> {
2112 let (args, result) = self.ends(inst)?;
2113 let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
2114 let span = self.source.span(inst);
2115 let left = self.x87_slot(left);
2116 let left = self.through(left);
2117 let right = self.x87_slot(right);
2118 let right = self.through(right);
2119 let into = self.x87_slot(result);
2120 let into = self.through(into);
2121 self.x87_at("fld_t", span, left);
2122 self.x87_at("fld_t", span, right);
2123 self.x87_only(with, span);
2124 self.x87_at("fstp_t", span, into);
2125 Ok(())
2126 }
2127
2128 /// A negation, which is a push, the sign bit turned over and a pop.
2129 ///
2130 /// `fchs` does not read the value as a number, so this is right for a zero, for an infinity
2131 /// and for a NaN, and it raises nothing on any of them. Which is what C asks of a negation and
2132 /// is not what subtracting from zero would give: `0.0L - x` is a different answer at a
2133 /// negative zero and a signalling one at a NaN.
2134 fn x87_flip(&mut self, inst: Inst) -> Result<(), Unsupported> {
2135 let (args, result) = self.ends(inst)?;
2136 let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2137 let span = self.source.span(inst);
2138 let from = self.x87_slot(source);
2139 let from = self.through(from);
2140 let into = self.x87_slot(result);
2141 let into = self.through(into);
2142 self.x87_at("fld_t", span, from);
2143 self.x87_only("fchs", span);
2144 self.x87_at("fstp_t", span, into);
2145 Ok(())
2146 }
2147
2148 /// A comparison of two eighty bit values, as the two pushes and the one opcode that reads them.
2149 ///
2150 /// The right operand is pushed first and the left one on top of it, which is the other way
2151 /// round from the arithmetic and is because `fucomip` asks about the top against what is under
2152 /// it: the comparison this machine can do is the top's, so the value the predicate is about
2153 /// has to be the top. The pop that gets the loser off the stack and the byte that reads the
2154 /// flags are both inside the opcode, since what passes between those and the comparison is the
2155 /// flags and the flags are not something anything here can name.
2156 ///
2157 /// Which of the ten opcodes, and which way round, is the same table the vector comparisons
2158 /// match against in `rules/x86-64.rules`, and it has to stay the same table: a predicate that
2159 /// picked a different condition here than there would be a `long double` comparison that
2160 /// disagreed with the `double` comparison of the same two numbers, which is the one thing a
2161 /// wider format is not allowed to do.
2162 ///
2163 /// The always false and the always true are refused rather than folded into a constant,
2164 /// because a comparison this machine never has to do is one the optimizer should have removed
2165 /// and an instruction here that quietly agreed with it would hide that it did not.
2166 fn x87_compare(&mut self, inst: Inst) -> Result<(), Unsupported> {
2167 let Extra::FloatPred(pred) = self.source[inst].extra else {
2168 return Err(self.unsupported(inst));
2169 };
2170 let (args, result) = self.ends(inst)?;
2171 let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
2172 // Two of the fourteen need a second byte and an instruction to put the two together,
2173 // because they are two conditions at once: an ordered equal is equal and not unordered,
2174 // and an unordered not equal is either. The opcode carries all of that and says here only
2175 // that it writes somewhere else as well.
2176 let (name, reversed, both) = match pred {
2177 FloatPred::Ogt => ("fucomip_set_a", false, false),
2178 FloatPred::Oge => ("fucomip_set_ae", false, false),
2179 FloatPred::Olt => ("fucomip_set_a", true, false),
2180 FloatPred::Ole => ("fucomip_set_ae", true, false),
2181 FloatPred::One => ("fucomip_set_ne", false, false),
2182 FloatPred::Ord => ("fucomip_set_np", false, false),
2183 FloatPred::Uno => ("fucomip_set_p", false, false),
2184 FloatPred::Ueq => ("fucomip_set_e", false, false),
2185 FloatPred::Ult => ("fucomip_set_b", false, false),
2186 FloatPred::Ule => ("fucomip_set_be", false, false),
2187 FloatPred::Ugt => ("fucomip_set_b", true, false),
2188 FloatPred::Uge => ("fucomip_set_be", true, false),
2189 FloatPred::Oeq => ("fucomip_set_e_and_np", false, true),
2190 FloatPred::Une => ("fucomip_set_ne_or_p", false, true),
2191 FloatPred::False | FloatPred::True => return Err(self.unsupported(inst)),
2192 };
2193 let (top, under) = if reversed { (right, left) } else { (left, right) };
2194
2195 let span = self.source.span(inst);
2196 let gpr = self.gpr;
2197 let under = self.x87_slot(under);
2198 let under = self.through(under);
2199 let top = self.x87_slot(top);
2200 let top = self.through(top);
2201 self.x87_at("fld_t", span, under);
2202 self.x87_at("fld_t", span, top);
2203
2204 let block = self.at.expect("a block is being filled");
2205 let reg = self.new_reg(result);
2206 // Taken before the instruction is started rather than inside it, since both come from the
2207 // same function being built and only one thing at a time may be adding to it.
2208 let spare = both.then(|| self.out.new_vreg(gpr));
2209 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
2210 let mut build = self.out.build(block, opcode).at(span).def(reg, gpr);
2211 if let Some(spare) = spare {
2212 build = build.def(spare, gpr);
2213 }
2214 build.finish();
2215 Ok(())
2216 }
2217
2218 /// The operands and the one result of an instruction that has exactly one.
2219 fn ends(&self, inst: Inst) -> Result<(&'a [Value], Value), Unsupported> {
2220 let data = &self.source[inst];
2221 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2222 Ok((&self.source[data.args], result))
2223 }
2224
2225 /// The operand of a conversion, which is the end of it that is not the `long double`.
2226 fn narrow(&self, inst: Inst) -> Result<Value, Unsupported> {
2227 let args = &self.source[self.source[inst].args];
2228 args.first().copied().ok_or_else(|| self.unsupported(inst))
2229 }
2230
2231 /// One `va_start`, as the fields of the list it was handed.
2232 ///
2233 /// On the four field list, two of them are numbers this already knows, and each costs an
2234 /// instruction to put in a register before it can be stored, because the machine here has no
2235 /// store of an immediate to memory. The other two are addresses in the frame, and each is a
2236 /// `lea` [`crate::finish`] finishes: the save area is one of the function's own stack objects,
2237 /// and the caller's argument area is where the parameters that had no register came from, which
2238 /// is the same place and the same fixup a parameter past the sixth already uses.
2239 ///
2240 /// On the list that is a pointer it is the second of those four and nothing else, since the
2241 /// whole of what that list says is where the walk is and the walk starts at the first argument
2242 /// the signature does not name. One `lea` and one store.
2243 ///
2244 /// What is written is exactly the fields [`crate::varargs`] describes, in the order they are
2245 /// laid out, so that reading this beside that table is the whole of the check.
2246 fn va_start(&mut self, inst: Inst) -> Result<(), Unsupported> {
2247 let Some(&list) = self.source[self.source[inst].args].first() else {
2248 return Err(self.unsupported(inst));
2249 };
2250 let started = self.varargs.ok_or_else(|| self.unsupported(inst))?;
2251 let list = self.reg_of(list)?;
2252 let block = self.at.expect("a block is being filled");
2253 let span = self.source.span(inst);
2254
2255 let (save, incoming) = match started {
2256 Varargs::Pointer { incoming } => (None, incoming),
2257 Varargs::Fields { save, incoming, integers, floats } => {
2258 for (at, count) in [(varargs::GP_OFFSET, integers), (varargs::FP_OFFSET, floats)] {
2259 let held = self.out.new_vreg(self.gpr);
2260 let load = mir::Opcode::new(self.names.intern("x64.mov_ri_32"));
2261 let build = self.out.build(block, load).at(span);
2262 build.def(held, self.gpr).imm(i64::from(count)).finish();
2263
2264 let store = mir::Opcode::new(self.names.intern("x64.mov_mr_32"));
2265 let mem = self.field(list, at);
2266 self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
2267 }
2268 (Some(save), incoming)
2269 }
2270 };
2271
2272 // The first argument the signature did not name, which is as far up the caller's argument
2273 // area as the ones it did name reached. Nothing here knows where that area is, so the
2274 // distance is recorded the way a parameter read out of it is and finished with it.
2275 let overflow = self.out.new_vreg(self.gpr);
2276 let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
2277 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
2278 let made = self
2279 .out
2280 .build(block, lea)
2281 .at(span)
2282 .def(overflow, self.gpr)
2283 .mem(mir::Mem::at(sp))
2284 .finish();
2285 self.stack.arguments.push((made, incoming));
2286
2287 // At the front of the list when that address is the whole of it, and at the field the
2288 // layout gives it when there are four, with the save area behind it.
2289 let fields = match save {
2290 None => vec![(0, overflow)],
2291 Some(save) => {
2292 let save = self.frame_address(block, save);
2293 vec![(varargs::OVERFLOW, overflow), (varargs::SAVE_AREA, save)]
2294 }
2295 };
2296 for (at, held) in fields {
2297 let store = mir::Opcode::new(self.names.intern("x64.mov_mr_64"));
2298 let mem = self.field(list, at);
2299 self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
2300 }
2301 Ok(())
2302 }
2303
2304 /// One field of a list, as the addressing mode that reaches it.
2305 fn field(&self, list: mir::Reg, at: i64) -> mir::Mem {
2306 let base = mir::Operand::read(list, self.gpr);
2307 mir::Mem::at(base).plus(i32::try_from(at).expect("a field of a list is a small offset"))
2308 }
2309
2310 /// The address of a name: one `lea` off the instruction pointer, with the name on it.
2311 ///
2312 /// The same instruction an `alloca` gets and for a related reason. An address that is not in
2313 /// the program is a `lea` of an addressing mode that names no register, and the mode carries
2314 /// the symbol so that [`rucc_asm`] can write it relative to `%rip` and leave the relocation
2315 /// for the assembler. Both halves of that already existed: the printer writes `sym(%rip)` and
2316 /// the encoder emits the relocation, because a call to a name the file does not define needed
2317 /// them first.
2318 ///
2319 /// One `mov` and not one `lea` when the name is one [`Elsewhere`] holds, because the distance
2320 /// the `lea` adds to the instruction pointer is a number only a link that puts the name in
2321 /// this program can work out, and the address of a function this file merely declares is not
2322 /// such a number. The load reads the address out of the slot the linker fills in instead. The
2323 /// linker turns it back into the `lea` when the name turns out to have been here all along,
2324 /// so this is not slower in the case that was already right.
2325 ///
2326 /// There is deliberately no name for this in [`crate::term`], which is what stops the address
2327 /// being folded into the instruction that reads it. Folding it is the right thing to do and
2328 /// is what turns a load of a global from two instructions into one, but it is a separate
2329 /// question about addressing modes and issue #282 is it. Until then the address is in a
2330 /// register before anything uses it, which is correct and one instruction longer.
2331 ///
2332 /// What this does not do is give the name anything to refer to. A module carries its globals
2333 /// and nothing writes them out, so a file that defines the variable it reads compiles to a
2334 /// reference the linker cannot resolve. Issue #293 is the other half.
2335 ///
2336 /// A thread-local variable is neither of the two above and is [`Self::thread_address`].
2337 fn address_of(&mut self, inst: Inst) -> Result<(), Unsupported> {
2338 let data = &self.source[inst];
2339 let Extra::Symbol(symbol) = data.extra else { return Err(self.unsupported(inst)) };
2340 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2341 if self.elsewhere.thread(symbol) {
2342 return self.thread_address(inst, symbol, result);
2343 }
2344
2345 let block = self.at.expect("a block is being filled");
2346 let reg = self.new_reg(result);
2347 let span = self.source.span(inst);
2348 let (mnemonic, mem) = if self.elsewhere.holds(symbol) {
2349 (GOT_LOAD, mir::Mem::got(symbol))
2350 } else {
2351 (x86_64::FRAME.lea, mir::Mem::of(symbol))
2352 };
2353 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{mnemonic}")));
2354 self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
2355 Ok(())
2356 }
2357
2358 /// The address of a thread-local variable, which is this thread's copy of it.
2359 ///
2360 /// Neither instruction the ordinary case writes would mean anything here. There is no distance
2361 /// to the variable for a `lea` to add, because there is no variable: there is one copy of it per
2362 /// thread and they are at different addresses, so a link asked for the distance to the name
2363 /// refuses rather than picking one. And there is no address for a table slot to hold either, for
2364 /// the same reason.
2365 ///
2366 /// What is the same in every thread is where the variable sits inside the block of storage a
2367 /// thread gets, so that offset is what the link writes down, and the address of the running
2368 /// thread's block is what turns it into an address. x86-64 keeps that address in `%fs`, at the
2369 /// front of the block, so the whole of this is three instructions:
2370 ///
2371 /// ```text
2372 /// movq x@gottpoff(%rip), %off # how far into the block x sits, which the link fills in
2373 /// movq %fs:0, %tp # where this thread's block is, which only the machine knows
2374 /// addq %tp, %off # this thread's copy of x
2375 /// ```
2376 ///
2377 /// That is the initial exec model. It is one instruction longer than what gcc writes at `-O2`
2378 /// in an executable, which folds the addition into the instruction that uses the address, and
2379 /// the difference is issue #282 rather than anything about threads: nothing here folds an
2380 /// address into its reader yet. The link relaxes the first instruction into an immediate when it
2381 /// is making an executable, since it lays the blocks out and therefore knows the number, so the
2382 /// table slot costs nothing in the case that is common.
2383 ///
2384 /// It is not the most general model. A library loaded by `dlopen` gets its storage after the
2385 /// program is already running, and the block this reaches was laid out before it started, so
2386 /// the loader has to find room in that block for the library's variables. glibc keeps a little
2387 /// spare room for exactly this and a library that fits in it loads and runs; one that does not
2388 /// fails to load, with a message saying so. The model with no such limit calls `__tls_get_addr`
2389 /// and is what gcc writes under `-fPIC` by default, and it is issue #1104.
2390 ///
2391 /// So this is the model gcc writes under `-ftls-model=initial-exec`: right for an executable,
2392 /// right for a library the program is linked against, and a load that either works or is
2393 /// refused out loud for a library something opens later. What it is never is quietly wrong.
2394 fn thread_address(
2395 &mut self,
2396 inst: Inst,
2397 symbol: Symbol,
2398 result: Value,
2399 ) -> Result<(), Unsupported> {
2400 let block = self.at.expect("a block is being filled");
2401 let span = self.source.span(inst);
2402 let gpr = self.gpr;
2403 let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{GOT_LOAD}")));
2404
2405 let offset = self.out.new_vreg(gpr);
2406 self.out
2407 .build(block, load)
2408 .at(span)
2409 .def(offset, gpr)
2410 .mem(mir::Mem::thread(symbol))
2411 .finish();
2412 // The front of the block, which is the one thing on this machine that no instruction can
2413 // work out: `%fs` is not a register a program can read, and what it points at is a word
2414 // holding its own address, so reading through it at zero is how the address is come by.
2415 let pointer = self.out.new_vreg(gpr);
2416 let at = mir::Mem::in_segment(Segment::Fs, 0);
2417 self.out.build(block, load).at(span).def(pointer, gpr).mem(at).finish();
2418
2419 // Two address, spelled out for the reason `x87_to_int` gives: this machine adds into the
2420 // register it read, and only the constraint says the two are the same one.
2421 let reg = self.new_reg(result);
2422 let add = mir::Opcode::new(self.names.intern(&format!("{PREFIX}add_rr_64")));
2423 self.out
2424 .build(block, add)
2425 .at(span)
2426 .operand(mir::Operand::write(reg, gpr).with(Constraint::Reuse(1)))
2427 .operand(mir::Operand::read(offset, gpr))
2428 .operand(mir::Operand::read(pointer, gpr))
2429 .finish();
2430 Ok(())
2431 }
2432
2433 /// `&&label`, GNU's address of a label, which is the same `lea` a global gets against a place
2434 /// in this same function.
2435 ///
2436 /// What the two have in common is the whole of the instruction: an address worked out from
2437 /// where the instruction is, which is what `(%rip)` means and is the only way this compiler
2438 /// reaches anything. What they do not have in common is what fills the four bytes in. A
2439 /// global is a name, so the number is a relocation and the linker writes it. A block is a
2440 /// place in this function, so both ends are in one section and the number is known as soon as
2441 /// the blocks have been laid out, which is why `rucc_asm` fills it in the way it fills in a
2442 /// jump rather than leaving a relocation behind.
2443 ///
2444 /// Nothing here says the block is one control can arrive at. That is said by the
2445 /// [`Opcode::IndirectBr`] that reads the address, which lists every block it can arrive at,
2446 /// and by nothing else: an address on its own is a number.
2447 fn block_address(&mut self, inst: Inst) -> Result<(), Unsupported> {
2448 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2449 let Some(call) = self.source.successors(inst).next() else {
2450 return Err(self.unsupported(inst));
2451 };
2452 let block = self.at.expect("a block is being filled");
2453 let reg = self.new_reg(result);
2454 let span = self.source.span(inst);
2455 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
2456 let mem = mir::Mem::block(self.out_block(call.block));
2457 self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
2458 Ok(())
2459 }
2460
2461 /// `goto *p`, GNU's computed goto, which is a jump through a register.
2462 ///
2463 /// Where it goes is not written here and cannot be. Every block it can arrive at is on the
2464 /// block this ends, the way every other arm is, and which of them the address holds is decided
2465 /// while the program runs. So this is one instruction with one operand, and the arms are
2466 /// copied across by [`Self::edges`] like anybody else's.
2467 fn indirect_branch(&mut self, inst: Inst) -> Result<(), Unsupported> {
2468 let data = &self.source[inst];
2469 let &address = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
2470 let reg = self.reg_of(address)?;
2471 let block = self.at.expect("a block is being filled");
2472 let span = self.source.span(inst);
2473 let name = x86_64::BRANCH.indirect;
2474 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
2475 self.out.build(block, opcode).at(span).operand(mir::Operand::read(reg, self.gpr)).finish();
2476 Ok(())
2477 }
2478
2479 /// A `switch` on an index from zero up, as a jump through a table of this function.
2480 ///
2481 /// Every `switch` that reaches here is one `crate::switch` left behind on purpose: it has
2482 /// already checked the value is inside the table and taken the lowest case off it, so the
2483 /// operand is a 64 bit index, the cases are the values from zero up with gaps where the
2484 /// program had no case, and the default is only where those gaps go. What is written is the
2485 /// shape gcc writes for the same statement in position independent code:
2486 ///
2487 /// ```text
2488 /// leaq table(%rip), %base
2489 /// movslq (%base,%index,4), %offset
2490 /// addq %base, %offset
2491 /// jmp *%offset
2492 /// ```
2493 ///
2494 /// The table holds distances from itself to each arm rather than addresses, which is what
2495 /// lets it be filled in by the assembler with nothing left for a linker to do. Each cell is
2496 /// stored as the place of an arm among this block's successors, which [`Self::edges`] copies
2497 /// across in the IR's own order, the default first and then one per case. See
2498 /// [`mir::Table`] for why a place and not a block.
2499 fn jump_table(&mut self, inst: Inst) -> Result<(), Unsupported> {
2500 let data = &self.source[inst];
2501 let Extra::Switch(info) = data.extra else { return Err(self.unsupported(inst)) };
2502 let &index = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
2503 let ty = self.source[index].ty;
2504 if ty != Type::int(u64::BITS) {
2505 return Err(self.unsupported(inst));
2506 }
2507 let cases = self.source[self.source[info].cases].to_vec();
2508 let mut cells: Vec<u32> = Vec::new();
2509 for (arm, case) in cases.iter().enumerate() {
2510 let at = usize::try_from(case.signed(ty)).map_err(|_| self.unsupported(inst))?;
2511 if at >= cells.len() {
2512 cells.resize(at + 1, 0);
2513 }
2514 cells[at] = u32::try_from(arm + 1).map_err(|_| self.unsupported(inst))?;
2515 }
2516 let reg = self.reg_of(index)?;
2517 let block = self.at.expect("a block is being filled");
2518 let span = self.source.span(inst);
2519 let gpr = self.gpr;
2520 let table = u32::try_from(self.out.tables.len()).expect("fewer tables than that");
2521
2522 let base = self.out.new_vreg(gpr);
2523 let lea = self.named(x86_64::FRAME.lea);
2524 self.out.build(block, lea).at(span).def(base, gpr).mem(mir::Mem::table(table)).finish();
2525 let offset = self.out.new_vreg(gpr);
2526 let cell =
2527 mir::Mem::at(mir::Operand::read(base, gpr)).indexed(mir::Operand::read(reg, gpr), 4);
2528 let load = self.named("movsxd_rm_32_64");
2529 self.out.build(block, load).at(span).def(offset, gpr).mem(cell).finish();
2530 // Two address, for the reason `thread_pointer` gives.
2531 let to = self.out.new_vreg(gpr);
2532 let add = self.named("add_rr_64");
2533 self.out
2534 .build(block, add)
2535 .at(span)
2536 .operand(mir::Operand::write(to, gpr).with(Constraint::Reuse(1)))
2537 .operand(mir::Operand::read(offset, gpr))
2538 .operand(mir::Operand::read(base, gpr))
2539 .finish();
2540 let jump = self.named(x86_64::BRANCH.indirect);
2541 let jump =
2542 self.out.build(block, jump).at(span).operand(mir::Operand::read(to, gpr)).finish();
2543 self.out.tables.push(mir::Table { jump, cells });
2544 Ok(())
2545 }
2546
2547 /// `__builtin_setjmp`, which writes down where the function is so that a `__builtin_longjmp`
2548 /// somewhere else can bring control back here, and answers zero on the way past.
2549 ///
2550 /// Four words of the buffer, the three gcc writes and one of this compiler's own, and then the
2551 /// block ends: everything after the save in the IR block is put into a new machine IR block,
2552 /// and the address of that block is what went into the buffer. That is the whole reason the
2553 /// block is split here. An address points at a label, a machine IR block is the only thing in
2554 /// this representation that has one, and a save is in the middle of a block rather than at the
2555 /// end of one.
2556 ///
2557 /// # How the answer gets back
2558 ///
2559 /// Through the frame rather than through a register. The save writes a zero into a word of its
2560 /// own frame, puts the address of that word in the buffer, and the new block reads the word
2561 /// back. The restore writes a one through the address it finds in the buffer before it goes.
2562 /// So one load answers zero on the way past and one on the way back, and neither path has to
2563 /// agree with the other about a register.
2564 ///
2565 /// gcc does it the other way round, with a second block that sets the answer to one and is
2566 /// what the restore arrives at. That block is one nothing in the function jumps to, and a
2567 /// machine IR whose blocks are walked from the entry has nowhere to put such a thing: the
2568 /// allocator lays a function out in the line it is going to be emitted in, and a block no edge
2569 /// reaches is not in that line. The word in the frame costs eight bytes of stack and one load,
2570 /// and it needs nothing said anywhere about a block arrived at from outside.
2571 ///
2572 /// # What the allocator is told
2573 ///
2574 /// That every register it hands out is gone at the end of the first block. That is what makes
2575 /// the rest of the function right on the way back: control arrives from a `__builtin_longjmp`
2576 /// in some other function, and the only two registers that puts back are the stack pointer and
2577 /// the frame pointer, so anything this function still wants has to be in the frame those two
2578 /// reach. It is said with a write of every one of those registers, which is the same thing a
2579 /// call says about the registers a callee may destroy, on an instruction with nothing else on
2580 /// it so that the stores above are not caught up in it.
2581 fn saves_place(&mut self, inst: Inst) -> Result<(), Unsupported> {
2582 let data = &self.source[inst];
2583 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2584 let &buffer = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
2585 let span = self.source.span(inst);
2586 let buf = self.reg_of(buffer)?;
2587 let at = self.at.expect("a block is being filled");
2588 let gpr = self.gpr;
2589 let moves = x86_64::FRAME.moves(gpr).expect("a class the target says how to move");
2590 let store = self.named(moves.store);
2591 let load = self.named(moves.load);
2592 let lea = self.named(x86_64::FRAME.lea);
2593 let put = self.named(x86_64::FRAME.imm);
2594 let nothing = x86_64::FRAME.pad.expect("a target with an instruction that does nothing");
2595 let nothing = self.named(nothing);
2596 self.stack.saves_place = true;
2597 let answer = self.answer_slot();
2598 let back = self.out.create_block();
2599
2600 // The zero this answers with, into the word a restore writes a one into.
2601 let zero = self.out.new_vreg(gpr);
2602 self.out.build(at, put).at(span).def(zero, gpr).imm(0).finish();
2603 let mem = self.frame_mem();
2604 let made = self.out.build(at, store).at(span).uses(zero, gpr).mem(mem).finish();
2605 self.stack.addresses.push((made, answer));
2606
2607 // The four words: where that word is, where control comes back to, and the two registers
2608 // the restore puts back.
2609 let found = self.frame_address(at, answer);
2610 self.write_word(at, span, store, found, buf, JUMP_ANSWER);
2611 let pc = self.out.new_vreg(gpr);
2612 self.out.build(at, lea).at(span).def(pc, gpr).mem(mir::Mem::block(back)).finish();
2613 self.write_word(at, span, store, pc, buf, JUMP_PC);
2614 let frame = mir::Reg::physical(self.conv.frame_pointer);
2615 self.write_word(at, span, store, frame, buf, JUMP_FRAME);
2616 let stack = mir::Reg::physical(self.conv.stack_pointer);
2617 self.write_word(at, span, store, stack, buf, JUMP_STACK);
2618
2619 // Nothing is in a register past this point, which is what the rest of the function is
2620 // allowed to assume about the way back in.
2621 let gone = self.across_jump();
2622 let mut build = self.out.build(at, nothing).at(span);
2623 for (reg, class) in gone {
2624 build = build.operand(mir::Operand::write(reg, class));
2625 }
2626 build.finish();
2627
2628 // And the rest of the block, which is the block the address above was of.
2629 *self.out.succs_mut(at) = vec![mir::BlockCall::to(back)];
2630 self.at = Some(back);
2631 let reg = self.new_reg(result);
2632 let mem = self.frame_mem();
2633 let made = self.out.build(back, load).at(span).def(reg, gpr).mem(mem).finish();
2634 self.stack.addresses.push((made, answer));
2635 Ok(())
2636 }
2637
2638 /// `__builtin_longjmp`, which reads a buffer a `__builtin_setjmp` filled in and goes there.
2639 ///
2640 /// Everything comes out of the buffer before anything is put back, and the four registers it
2641 /// comes out into are physical ones rather than values the allocator places. Both of those are
2642 /// about the same moment. The stack pointer is one of the things being put back, a value the
2643 /// allocator sent to the stack is reached through the stack pointer, and between the
2644 /// instruction that moves it and the jump there is no stack this function owns any more. A
2645 /// register named outright is a register nothing reloads into and nothing else is in, which is
2646 /// the only way to hold something across that moment.
2647 ///
2648 /// Four of them because that is how many things are in the air at once: where to go, the frame
2649 /// pointer to put back, the one the matching save is to answer with, and one register used
2650 /// twice, first for the address that one is written through and then for the stack pointer.
2651 ///
2652 /// Nothing after this in the block is reached. The marker is not a terminator, for the reason
2653 /// `spec/08-ir.md` gives, so the block goes on and whatever the front end wrote after it is
2654 /// written out and never run.
2655 fn comes_back(&mut self, inst: Inst) -> Result<(), Unsupported> {
2656 let data = &self.source[inst];
2657 let &buffer = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
2658 let span = self.source.span(inst);
2659 let buf = self.reg_of(buffer)?;
2660 let at = self.at.expect("a block is being filled");
2661 let gpr = self.gpr;
2662 let moves = x86_64::FRAME.moves(gpr).expect("a class the target says how to move");
2663 let load = self.named(moves.load);
2664 let store = self.named(moves.store);
2665 let mov = self.named(moves.mov);
2666 let put = self.named(x86_64::FRAME.imm);
2667 let jump = self.named(x86_64::BRANCH.indirect);
2668
2669 let held = self.jump_regs();
2670 if held.len() < JUMP_REGS {
2671 return Err(self.unsupported(inst));
2672 }
2673 let pc = mir::Reg::physical(held[0]);
2674 let frame = mir::Reg::physical(held[1]);
2675 let spare = mir::Reg::physical(held[2]);
2676 let one = mir::Reg::physical(held[3]);
2677
2678 self.read_word(at, span, load, pc, buf, JUMP_PC);
2679 self.read_word(at, span, load, frame, buf, JUMP_FRAME);
2680 self.read_word(at, span, load, spare, buf, JUMP_ANSWER);
2681
2682 // What the matching save answers with, written through the address that came out of the
2683 // buffer, because the word it goes in is in the other function's frame and this one has no
2684 // way of knowing where that is.
2685 self.out.build(at, put).at(span).def(one, gpr).imm(1).finish();
2686 let mem = mir::Mem::at(mir::Operand::read(spare, gpr));
2687 self.out.build(at, store).at(span).uses(one, gpr).mem(mem).finish();
2688
2689 // The stack last of the four, so that the register the buffer is reached through is done
2690 // with before the stack it may have been spilled to stops being this function's.
2691 self.read_word(at, span, load, spare, buf, JUMP_STACK);
2692 let stack = mir::Reg::physical(self.conv.stack_pointer);
2693 self.copy(at, span, mov, stack, spare);
2694 let base = mir::Reg::physical(self.conv.frame_pointer);
2695 self.copy(at, span, mov, base, frame);
2696
2697 // And the jump, which reads the two registers just put back as well as the address it
2698 // goes through. Neither of those is printed, because the target's spelling of an indirect
2699 // jump has one argument and it is the first one read. They are there because the code
2700 // control arrives at reaches its frame through them, and because without them the two
2701 // instructions above write registers nothing reads: a scheduler is then free to put the
2702 // jump in front of them, and at `-O2` it does.
2703 self.out
2704 .build(at, jump)
2705 .at(span)
2706 .operand(mir::Operand::read(pc, gpr))
2707 .operand(mir::Operand::read(stack, gpr))
2708 .operand(mir::Operand::read(base, gpr))
2709 .finish();
2710 Ok(())
2711 }
2712
2713 /// One word of the buffer of a `__builtin_setjmp`, written from a register.
2714 fn write_word(
2715 &mut self,
2716 at: mir::Block,
2717 span: Span,
2718 store: mir::Opcode,
2719 from: mir::Reg,
2720 buf: mir::Reg,
2721 word: i32,
2722 ) {
2723 let mem = mir::Mem::at(mir::Operand::read(buf, self.gpr)).plus(word);
2724 self.out.build(at, store).at(span).uses(from, self.gpr).mem(mem).finish();
2725 }
2726
2727 /// One word of that buffer, read back into a register.
2728 fn read_word(
2729 &mut self,
2730 at: mir::Block,
2731 span: Span,
2732 load: mir::Opcode,
2733 into: mir::Reg,
2734 buf: mir::Reg,
2735 word: i32,
2736 ) {
2737 let mem = mir::Mem::at(mir::Operand::read(buf, self.gpr)).plus(word);
2738 self.out.build(at, load).at(span).def(into, self.gpr).mem(mem).finish();
2739 }
2740
2741 /// One register into another, which is the one shape of instruction the builder has no word
2742 /// for because neither operand is a definition of a value or a read of memory.
2743 fn copy(
2744 &mut self,
2745 at: mir::Block,
2746 span: Span,
2747 mov: mir::Opcode,
2748 into: mir::Reg,
2749 from: mir::Reg,
2750 ) {
2751 self.out
2752 .build(at, mov)
2753 .at(span)
2754 .operand(mir::Operand::write(into, self.gpr))
2755 .operand(mir::Operand::read(from, self.gpr))
2756 .finish();
2757 }
2758
2759 /// The word a `__builtin_setjmp` in this function answers with, asked for once and kept.
2760 fn answer_slot(&mut self) -> usize {
2761 match self.answer {
2762 Some(index) => index,
2763 None => {
2764 let index = self.stack.locals.len();
2765 self.stack.locals.push(Local { size: JUMP_WORD, align: JUMP_WORD });
2766 self.answer = Some(index);
2767 index
2768 }
2769 }
2770 }
2771
2772 /// An address in this function's frame with nothing in its displacement, which is what an
2773 /// instruction reaching one of its stack objects is written with until [`crate::finish`] knows
2774 /// where the object is.
2775 fn frame_mem(&self) -> mir::Mem {
2776 mir::Mem::at(mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr))
2777 }
2778
2779 /// Every register the allocator hands out, which is what a `__builtin_setjmp` destroys.
2780 ///
2781 /// Both files, since a `double` live across a save has the same problem an integer does. The
2782 /// two registers a frame is reached through are not here: the restore puts both of them back,
2783 /// which is the whole of what it puts back, and a function whose frame pointer was destroyed
2784 /// by its own save would have nothing left to find its caller with.
2785 fn across_jump(&self) -> Vec<(mir::Reg, RegClass)> {
2786 let mut gone = Vec::new();
2787 for ® in self.conv.int_order {
2788 if reg == self.conv.stack_pointer || reg == self.conv.frame_pointer {
2789 continue;
2790 }
2791 gone.push((mir::Reg::physical(reg), self.gpr));
2792 }
2793 for ® in self.conv.sse_order {
2794 gone.push((mir::Reg::physical(reg), self.conv.sse_class));
2795 }
2796 gone
2797 }
2798
2799 /// The registers a `__builtin_longjmp` may hold things in while it puts a frame back.
2800 ///
2801 /// The ones the allocator hands out, less the two a frame is reached through. The scratch
2802 /// registers are not among them on purpose: the rewriter writes a reload into one of those
2803 /// wherever it likes, and one of these has to survive from the load that fills it to the
2804 /// instruction that reads it however many instructions apart those are.
2805 fn jump_regs(&self) -> Vec<PhysReg> {
2806 self.conv
2807 .int_order
2808 .iter()
2809 .copied()
2810 .filter(|®| {
2811 reg != self.conv.stack_pointer
2812 && reg != self.conv.frame_pointer
2813 && !crate::pipeline::SCRATCH.contains(®)
2814 })
2815 .collect()
2816 }
2817
2818 /// A machine opcode of this target from the name the target gives it.
2819 fn named(&mut self, name: &str) -> mir::Opcode {
2820 mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")))
2821 }
2822
2823 /// `__builtin_frame_address` and `__builtin_return_address`, which are a walk up the chain of
2824 /// saved frame pointers and then one thing read at the end of it.
2825 ///
2826 /// Every frame that kept a frame pointer holds the caller's at the address the register points
2827 /// at, and the address that frame returns to one word above that, which is where the call
2828 /// instruction put it and where the prologue's push left it. So the walk is a load through the
2829 /// register for each link, the frame address is wherever the walk stopped, and the return
2830 /// address is one more load from a word above it. gcc 16.2.0 writes exactly this, measured on
2831 /// x86-64 at `-O2` for depths zero to three of both builtins.
2832 ///
2833 /// The function is given a frame pointer because of this, which is what [`Stack::walks_frames`]
2834 /// carries out to the layout. A depth of zero needs it as the answer and every depth above zero
2835 /// needs it as the start, so there is no case here where it is not wanted.
2836 ///
2837 /// How far the chain actually reaches is the program's business and not this one's. A caller
2838 /// compiled without a frame pointer has no link in it for the walk to follow, so a depth above
2839 /// zero is a promise about how the whole program was built. That is why gcc documents a nonzero
2840 /// depth as unsafe rather than as an answer, and why the depth is refused above a limit in
2841 /// `check/builtin/frame.rs` rather than walked as far as it says.
2842 fn frames(&mut self, inst: Inst) -> Result<(), Unsupported> {
2843 let data = &self.source[inst];
2844 let Extra::Depth(depth) = data.extra else { return Err(self.unsupported(inst)) };
2845 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2846 let returning = data.opcode == Opcode::ReturnAddress;
2847 let block = self.at.expect("a block is being filled");
2848 let span = self.source.span(inst);
2849 let moves = x86_64::FRAME.moves(self.gpr).expect("a class the target says how to move");
2850 let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", moves.load)));
2851 self.stack.walks_frames = true;
2852
2853 // Where the walk is up to. The frame pointer to begin with, and the register the last load
2854 // wrote after that.
2855 let reg = self.new_reg(result);
2856 let mut base = mir::Reg::physical(self.conv.frame_pointer);
2857 for link in 0..depth {
2858 // The last load of a walk that is looking for a frame writes the answer itself, which
2859 // is what keeps a walk of so many links that many instructions and not one more.
2860 let ends_here = link + 1 == depth && !returning;
2861 let next = if ends_here { reg } else { self.out.new_vreg(self.gpr) };
2862 let at = mir::Mem::at(mir::Operand::read(base, self.gpr));
2863 self.out.build(block, load).at(span).def(next, self.gpr).mem(at).finish();
2864 base = next;
2865 }
2866
2867 if returning {
2868 let up = i32::try_from(self.conv.return_address).expect("a word above the frame");
2869 let at = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
2870 self.out.build(block, load).at(span).def(reg, self.gpr).mem(at).finish();
2871 } else if depth == 0 {
2872 // The one case with no load in it at all: the frame this function is running in is the
2873 // register itself, and a physical register is not one the allocator hands out, so the
2874 // answer is a copy of it.
2875 let mov = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", moves.mov)));
2876 self.out
2877 .build(block, mov)
2878 .at(span)
2879 .operand(mir::Operand::write(reg, self.gpr))
2880 .operand(mir::Operand::read(base, self.gpr))
2881 .finish();
2882 }
2883 Ok(())
2884 }
2885
2886 /// `__builtin_thread_pointer`, which is the front of the block [`Self::thread_address`] adds
2887 /// an offset to.
2888 ///
2889 /// The same one instruction, on its own this time and with nothing to add to it. A program
2890 /// writes this when what it wants is a number that is different in every thread and cheap to
2891 /// come by, rather than a variable of its own in the block, so there is no relocation here and
2892 /// no name for the link to resolve.
2893 fn thread_pointer(&mut self, inst: Inst) -> Result<(), Unsupported> {
2894 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2895 let block = self.at.expect("a block is being filled");
2896 let span = self.source.span(inst);
2897 let reg = self.new_reg(result);
2898 let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{GOT_LOAD}")));
2899 let at = mir::Mem::in_segment(Segment::Fs, 0);
2900 self.out.build(block, load).at(span).def(reg, self.gpr).mem(at).finish();
2901 Ok(())
2902 }
2903
2904 /// What a named machine register holds, which is `register long x asm ("rbx");`.
2905 ///
2906 /// One move out of that register, with the register named as itself the way a register a
2907 /// template wrote is named, which is [`Self::itself`] and is the thing #1653 built. What it
2908 /// buys here is what it buys there: the register is part of the instruction the allocator
2909 /// sees, so it is a use the allocator will not have written over first, and the value goes
2910 /// into an ordinary one of its own that everything downstream reads.
2911 ///
2912 /// The whole sixty four bits are moved whatever the type is, because the register is that
2913 /// wide and a narrower type reads the low end of the copy, which is the same low end. A type
2914 /// wider than the register is refused, since there is no register holding it to read.
2915 ///
2916 /// A name the machine has not got is refused too, and is the only thing that can be wrong
2917 /// with the string: which register a name means is this machine's question and this is where
2918 /// the question is asked, at the same table `asm` asks about clobbers at. The sigil gcc
2919 /// allows in front of it is taken off here, because what the name is written with is syntax.
2920 fn register_value(&mut self, inst: Inst) -> Result<(), Unsupported> {
2921 let Extra::Symbol(symbol) = self.source[inst].extra else {
2922 return Err(self.unsupported(inst));
2923 };
2924 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2925 let ty = self.source[result].ty;
2926 let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
2927 if bits > ADDRESS_BITS {
2928 return Err(self.unsupported(inst));
2929 }
2930 let spelled = self.names.resolve(symbol).to_owned();
2931 let named = x86_64::gpr_named(spelled.strip_prefix('%').unwrap_or(&spelled));
2932 let Some((held, _)) = named else {
2933 return Err(Unsupported::Register { inst, name: spelled });
2934 };
2935 let block = self.at.expect("a block is being filled");
2936 let span = self.source.span(inst);
2937 let mov = x86_64::FRAME.moves(self.gpr).expect("a class the target says how to move").mov;
2938 let mov = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{mov}")));
2939 let into = self.new_reg(result);
2940 self.out
2941 .build(block, mov)
2942 .at(span)
2943 .operand(mir::Operand::write(into, self.gpr))
2944 .operand(
2945 mir::Operand::read(mir::Reg::physical(held), self.gpr)
2946 .with(Constraint::Fixed(held)),
2947 )
2948 .finish();
2949 Ok(())
2950 }
2951
2952 /// A conversion that converts nothing: the result is the operand under another type.
2953 ///
2954 /// `ptrtoint` and `inttoptr` at one width are the whole of this. An address on this machine is
2955 /// an integer as wide as the machine addresses, so a cast between the two changes what the
2956 /// type system calls the value and changes nothing about the value, and the register holding
2957 /// it is the register that already held it. The front end never writes either of them at any
2958 /// other width, because it widens or narrows around the cast rather than through it, so the
2959 /// two widths disagreeing here means the IR came from somewhere else and is refused rather
2960 /// than guessed at.
2961 ///
2962 /// Reading the operand first is what materializes it when it is a constant, which is the case
2963 /// that matters: a null pointer is an `inttoptr` of zero, and that zero has to reach a
2964 /// register before anything can call it an address.
2965 fn rename(&mut self, inst: Inst) -> Result<(), Unsupported> {
2966 let data = &self.source[inst];
2967 let [arg] = self.source[data.args] else { return Err(self.unsupported(inst)) };
2968 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2969 if !self.is_address_width(self.source[arg].ty)
2970 || !self.is_address_width(self.source[result].ty)
2971 {
2972 return Err(self.unsupported(inst));
2973 }
2974 let reg = self.reg_of(arg)?;
2975 self.regs[result.index()] = Some(reg);
2976 Ok(())
2977 }
2978
2979 /// One barrier, which on this machine is one instruction at the strongest ordering and no
2980 /// instruction at all at every other one.
2981 ///
2982 /// x86-64 is total store order, so the only reordering the machine does is a store followed by
2983 /// a load of a different address, and the only ordering that forbids that is sequential
2984 /// consistency. An acquire, a release and an acquire release fence are therefore already true
2985 /// of every program running here, and what a program wanted from writing one is that the
2986 /// compiler not move memory accesses across it. The optimizer has finished by the time this
2987 /// runs and nothing below reorders one access past another, so the constraint is already
2988 /// discharged and there is nothing to write.
2989 ///
2990 /// The strongest one is `mfence`, which is what gcc 16.2.0 writes for
2991 /// `__atomic_thread_fence(__ATOMIC_SEQ_CST)` and for `__sync_synchronize`. A locked instruction
2992 /// on the stack is faster on most parts and is what some compilers write instead; it is also a
2993 /// write to memory the program did not ask for, and the plain barrier is the one that says what
2994 /// it means.
2995 ///
2996 /// Written here by name rather than by a rule, for the same reason a `lea` of a symbol is:
2997 /// there is nothing in a barrier that a proof over bitvectors could discharge. It computes
2998 /// nothing, so there is no equality to state, and what makes it the right answer is the memory
2999 /// model, which the rule language cannot talk about.
3000 fn barrier(&mut self, inst: Inst) -> Result<(), Unsupported> {
3001 let Extra::Order(order) = self.source[inst].extra else {
3002 return Err(self.unsupported(inst));
3003 };
3004 if order != MemOrder::SeqCst {
3005 return Ok(());
3006 }
3007 let block = self.at.expect("a block is being filled");
3008 let span = self.source.span(inst);
3009 let fence = mir::Opcode::new(self.names.intern("x64.mfence"));
3010 self.out.build(block, fence).at(span).finish();
3011 Ok(())
3012 }
3013
3014 /// The instruction a program stops on, which is one byte pair and no operands.
3015 ///
3016 /// `ud2` is an opcode the manual promises will never be given a meaning, so a processor that
3017 /// reaches it raises the fault for an instruction it does not know, and on Linux that arrives
3018 /// at the program as `SIGILL`. That is what `__builtin_trap` is for: a stop that cannot be
3019 /// caught by anything the program installed for an ordinary error, cannot be returned from,
3020 /// and leaves the address of the fault in the core file.
3021 ///
3022 /// Why not a call to `abort`. It is two bytes against a call and a relocation, it needs no
3023 /// library, and it works in the places this one is written most, which are a kernel and a
3024 /// freestanding program that has no `abort` to call. gcc 16.2.0 writes `ud2` here too.
3025 fn trap(&mut self, inst: Inst) {
3026 let block = self.at.expect("a block is being filled");
3027 let span = self.source.span(inst);
3028 let stop = mir::Opcode::new(self.names.intern("x64.ud2"));
3029 self.out.build(block, stop).at(span).finish();
3030 }
3031
3032 /// One hint that an address is about to be used, which is one instruction and no promise.
3033 ///
3034 /// Four instructions on this machine and the locality picks between them, which is what the
3035 /// number means: how much of the data will still be wanted after the access. None of it wanted
3036 /// is `prefetchnta`, which brings the line in without keeping it, and all of it wanted is
3037 /// `prefetcht0`, which brings it as close as the machine can. The two in between are the levels
3038 /// between those. Measured against gcc 16.2.0 on x86-64 rather than read off the manual: zero
3039 /// gives `prefetchnta`, one `prefetcht2`, two `prefetcht1` and three `prefetcht0`.
3040 ///
3041 /// Whether the access will write is not read here, and that is this machine rather than an
3042 /// omission. The write hint is `prefetchw`, which is not in the base instruction set, and gcc
3043 /// writes it only when the command line said the part has it. So a prefetch for a write is the
3044 /// same instruction as a prefetch for a read, which is what gcc 16.2.0 writes without
3045 /// `-mprfchw`, and the difference is carried in the IR for a target that can use it.
3046 ///
3047 /// The address goes in the addressing mode rather than in an operand, the way a store's does.
3048 /// It is built here as the plainest one there is, a register and nothing else, because what
3049 /// arrives is a value and folding an addition into the mode is a rule's job and no rule reaches
3050 /// this instruction. An address the program computed is therefore one `lea` or one add in front
3051 /// of this, which is what it would have been for the load the hint is about anyway.
3052 fn hint(&mut self, inst: Inst) -> Result<(), Unsupported> {
3053 let Extra::Prefetch(hint) = self.source[inst].extra else {
3054 return Err(self.unsupported(inst));
3055 };
3056 let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3057 let [address] = args[..] else { return Err(self.unsupported(inst)) };
3058 let name = match hint.locality {
3059 0 => "prefetch_nta",
3060 1 => "prefetch_t2",
3061 2 => "prefetch_t1",
3062 PrefetchHint::MOST => "prefetch_t0",
3063 // Nothing else exists. The checker reads a locality outside the range as zero and the
3064 // verifier refuses one that got here another way, so this is a hint that was built
3065 // rather than checked, and the safe answer for a hint is to write no instruction.
3066 _ => return Err(self.unsupported(inst)),
3067 };
3068 let base = self.reg_of(address)?;
3069 let block = self.at.expect("a block is being filled");
3070 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
3071 self.out
3072 .build(block, opcode)
3073 .at(self.source.span(inst))
3074 .mem(mir::Mem::at(mir::Operand::read(base, self.gpr)))
3075 .finish();
3076 Ok(())
3077 }
3078
3079 /// One compare and exchange, which is the instruction every other atomic on this machine is
3080 /// built out of.
3081 ///
3082 /// What the IR asks for is: read what is at an address, compare it against a value the program
3083 /// expected, put a second value there if the two were equal, and say both what was read and
3084 /// whether the exchange happened. The machine has exactly that instruction, and the `lock` in
3085 /// front of it is what makes the whole of it one step as far as every other processor is
3086 /// concerned.
3087 ///
3088 /// The ordering is not read here, and that is the memory model rather than an omission. A
3089 /// locked instruction on x86-64 is a full barrier whatever the program asked for, so a relaxed
3090 /// compare and exchange and a sequentially consistent one are the same instruction, and there
3091 /// is nothing weaker to emit for the weaker orderings. The failure ordering is not read for the
3092 /// same reason.
3093 ///
3094 /// The two values it produces are why this is written by name. The one the program compares
3095 /// against and the one it gets back are both `rax`, which the instruction reads and writes
3096 /// without being told, and the table says so with a fixed constraint at each end rather than
3097 /// leaving the allocator to find out. The second value is the byte behind it, which is the zero
3098 /// flag read out by a `sete`, and it is a definition of the same instruction so that the
3099 /// allocator knows the two are live together and never gives the byte the register the answer
3100 /// is in.
3101 fn exchange(&mut self, inst: Inst) -> Result<(), Unsupported> {
3102 let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3103 let results: Vec<Value> = self.source[inst].results().collect();
3104 let [addr, expected, desired] = args[..] else { return Err(self.unsupported(inst)) };
3105 let [old, exchanged] = results[..] else { return Err(self.unsupported(inst)) };
3106
3107 // A value the machine can compare in one instruction, which is an integer or an address at
3108 // one of the four widths it has a compare and exchange for. Anything else is a type this
3109 // has no instruction for rather than a program that is wrong, and the front end refuses it
3110 // before ever getting here.
3111 let ty = self.source[old].ty;
3112 let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
3113 if (!ty.is_int() && !ty.is_ptr()) || !matches!(bits, 8 | 16 | 32 | 64) {
3114 return Err(self.unsupported(inst));
3115 }
3116
3117 let base = self.reg_of(addr)?;
3118 let want = self.reg_of(expected)?;
3119 let put = self.reg_of(desired)?;
3120 let got = self.new_reg(old);
3121 let flag = self.new_reg(exchanged);
3122
3123 let name = format!("cmpxchg_{bits}");
3124 let form = x86_64::form(&name).ok_or_else(|| self.unsupported(inst))?;
3125 let block = self.at.expect("a block is being filled");
3126 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
3127 let (span, flags) = (self.source.span(inst), self.carried(inst));
3128 let mut build = self.out.build(block, opcode).at(span).flags(flags);
3129 for (desc, reg) in form.operands().iter().zip([got, flag, want, put]) {
3130 let operand = mir::Operand {
3131 reg,
3132 class: desc.class,
3133 role: desc.role,
3134 constraint: desc.constraint,
3135 };
3136 build = build.operand(operand);
3137 }
3138 build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
3139 Ok(())
3140 }
3141
3142 /// One read modify write, for the three operations this machine does in a single instruction.
3143 ///
3144 /// What the IR asks for is: read what is at an address, do something to it, put the answer back,
3145 /// say what was there before, and let nothing get between the three steps. The machine has
3146 /// `xchg` for putting a value there and `lock xadd` for adding one, and both leave what they
3147 /// found in the register the operand arrived in, which is why the value that comes back and the
3148 /// value that went in are one register here.
3149 ///
3150 /// A subtraction is the add over the negated operand, which is right at every width because the
3151 /// machine's arithmetic wraps and negating then adding is subtracting in two's complement
3152 /// whatever the operands were. The negate is a separate instruction in front, over a register of
3153 /// its own, so that the value the program handed over is not the one written on: an operand may
3154 /// be live after this and a program that read it again would read the negation.
3155 ///
3156 /// The ordering is not read, for the reason the compare and exchange beside this does not read
3157 /// it. `xchg` with memory locks the bus whether it is asked to or not and `lock xadd` is asked
3158 /// to, so both are full barriers on this machine and there is nothing weaker to fall to.
3159 ///
3160 /// Eight of the other ten never arrive, because `crate::retry` turned each of them into a loop
3161 /// around a compare and exchange before anything here saw it. The two that do arrive are the
3162 /// ones on floating values, and they are refused: a compare and exchange of a float wants the
3163 /// value carried through an integer of the same width, and an eighty bit float has no such
3164 /// width. Neither family of builtins can write one yet either, so a program that reaches this
3165 /// refusal is a program that reached an unimplemented builtin first.
3166 fn modify(&mut self, inst: Inst) -> Result<(), Unsupported> {
3167 let Extra::Rmw(op, _) = self.source[inst].extra else {
3168 return Err(self.unsupported(inst));
3169 };
3170 let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3171 let [addr, operand] = args[..] else { return Err(self.unsupported(inst)) };
3172 let old = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3173
3174 // A value the machine can exchange in one instruction, which is an integer at one of the
3175 // four widths it has these for. A pointer arrives as an address, so it is an integer by the
3176 // time it is here, and anything else is a type this has no instruction for.
3177 let ty = self.source[old].ty;
3178 if !ty.is_int() || !matches!(ty.bits(), 8 | 16 | 32 | 64) {
3179 return Err(self.unsupported(inst));
3180 }
3181 let name = match op {
3182 RmwOp::Xchg => format!("xchg_{}", ty.bits()),
3183 RmwOp::Add | RmwOp::Sub => format!("xadd_{}", ty.bits()),
3184 _ => return Err(self.unsupported(inst)),
3185 };
3186
3187 let base = self.reg_of(addr)?;
3188 let mut put = self.reg_of(operand)?;
3189 let block = self.at.expect("a block is being filled");
3190 let span = self.source.span(inst);
3191 if op == RmwOp::Sub {
3192 let negated = self.out.new_vreg(self.gpr);
3193 let negate =
3194 mir::Opcode::new(self.names.intern(&format!("{PREFIX}neg_r_{}", ty.bits())));
3195 let form = x86_64::form(&format!("neg_r_{}", ty.bits()))
3196 .ok_or_else(|| self.unsupported(inst))?;
3197 let mut build = self.out.build(block, negate).at(span);
3198 for (desc, reg) in form.operands().iter().zip([negated, put]) {
3199 build = build.operand(mir::Operand {
3200 reg,
3201 class: desc.class,
3202 role: desc.role,
3203 constraint: desc.constraint,
3204 });
3205 }
3206 build.finish();
3207 put = negated;
3208 }
3209
3210 let got = self.new_reg(old);
3211 let form = x86_64::form(&name).ok_or_else(|| self.unsupported(inst))?;
3212 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
3213 let flags = self.carried(inst);
3214 let mut build = self.out.build(block, opcode).at(span).flags(flags);
3215 for (desc, reg) in form.operands().iter().zip([got, put]) {
3216 build = build.operand(mir::Operand {
3217 reg,
3218 class: desc.class,
3219 role: desc.role,
3220 constraint: desc.constraint,
3221 });
3222 }
3223 build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
3224 Ok(())
3225 }
3226
3227 /// One `asm` statement.
3228 ///
3229 /// An empty template is most of the inline assembly in a test suite, and it is not a corner
3230 /// case somebody wrote by accident. A program that wants a value computed where it stands, or a
3231 /// loop the optimizer must not touch, writes `asm volatile ("" : : : "memory")`, and forty
3232 /// years of bug reports about optimizers are full of them. What such a statement asks for is
3233 /// the barrier and the operand places, and no instructions at all.
3234 ///
3235 /// So the operands are the half that is always real: a constraint says where a value has to be,
3236 /// and where it has to be is still true when the template between them is empty.
3237 ///
3238 /// What the constraints ask for, on an empty template, is only ever that two operands share a
3239 /// place. Nothing reads a register no text names, so `"r"` on its own asks for a register and
3240 /// no particular one, and any register at all answers it. A matching constraint is different,
3241 /// because it says the output the assembly leaves is the place the input arrived in, and with
3242 /// no instructions between them that is the input unchanged. So it is a rename and not a move:
3243 /// the value is already in a register and the result is that register.
3244 ///
3245 /// An output nothing is tied to and no instruction writes is whatever the assembly left there,
3246 /// which for a template that writes nothing is whatever was in the register. That is a value
3247 /// the program is not entitled to, and this writes a zero rather than reading one, because the
3248 /// allocator has to be given a definition before a use whatever the program is entitled to.
3249 ///
3250 /// # A template with instructions in it
3251 ///
3252 /// [`x86_64::read`] turns the text into the opcodes this backend already has, which is what
3253 /// `spec/11-asm-objects-debug.md` section 11.1 asks for: the machine is described once, and an
3254 /// instruction a program wrote is looked up in that description rather than copied through to
3255 /// an assembler that has one of its own. So nothing here assembles anything. What it does is
3256 /// put the statement's operands where the opcode holds them, and from there an `asm` statement
3257 /// is ordinary machine code: the allocator picks the registers, the listing and the object file
3258 /// are written from the same table as every other instruction, and a spill around one works
3259 /// because there is nothing left about it for a spill to get wrong.
3260 ///
3261 /// A register the template named in its own text is the one thing in there that is nobody's
3262 /// operand, and it is placed as itself. See [`Self::itself`] for why that is safer here than
3263 /// the thing gcc does, which is to copy the name out and leave the allocator none the wiser.
3264 ///
3265 /// Two things are refused, both for one reason, which is that placing them by a guess gives a
3266 /// program that assembles into something other than what it says.
3267 ///
3268 /// An output the template writes more than once, which is one place with two definitions in it,
3269 /// and the machine IR between here and the allocator has one definition per register by
3270 /// construction. An output tied to an input and written once is not that: it is two registers
3271 /// the description ties together, which is what [`Place`] is about.
3272 ///
3273 /// An operand read where the opcode writes, or written where it reads. An output that has not
3274 /// been written yet is not a value, and an input the assembly writes over is a value something
3275 /// else may still be using.
3276 ///
3277 /// # A register the instruction uses without being told
3278 ///
3279 /// An instruction may reach a register its text does not name, and `cpuid` is all of them at
3280 /// once: the leaf goes in `eax`, the subleaf in `ecx`, and the answer comes back in all four
3281 /// registers. The description holds every bit of that already, so what is left is to say which
3282 /// of the statement's operands is in each of those registers, and the constraint letter is the
3283 /// one thing in an assembly statement that says it. `"=a"` is an output in `rax` and `"c"` is
3284 /// an input in `rcx`, which is why a program writing `cpuid` writes its constraints that way
3285 /// and has no choice about it.
3286 ///
3287 /// A register no letter named is one the statement put nothing in, and that is the usual case
3288 /// rather than an unusual one, since an instruction that answers four questions is written by
3289 /// programs that asked one. A write of one is the register being destroyed and gets a register
3290 /// of its own, which is what tells the allocator to keep everything else out of it. A read of
3291 /// one is a register the instruction looks at and the program never filled, which gets a zero
3292 /// for the reason [`Self::undefined`] gives.
3293 ///
3294 /// # The clobber list
3295 ///
3296 /// Read now, as the registers it names being written by every instruction of the template. By
3297 /// every one rather than by one of them, because the list says the assembly as a whole leaves
3298 /// them ruined and nothing here knows which line did it. Every entry has to be a register this
3299 /// machine has a name for or the statement is refused, since a name nobody read is a register
3300 /// nobody is keeping out of.
3301 ///
3302 /// `memory` and `cc` are the two entries that are not registers and both are skipped. `memory`
3303 /// says the assembly touches storage, which is already true of every `asm` this writes and is
3304 /// nothing a register list could hold. `cc` says it ruins the condition flags, and the flag
3305 /// tracking already has that from the instructions the template was read into, since it takes
3306 /// every instruction it does not recognize as writing them and every instruction here is one
3307 /// this machine describes. `flags` is the name gcc's own register table gives the same thing on
3308 /// this machine, so a program writing it has written `cc` and is read that way: tcc's
3309 /// `tests/tcctest.c` lists both on one statement.
3310 ///
3311 /// A clobber the instruction already writes is left off it. `cpuid` writes all four registers
3312 /// by description, and a statement listing three of them as clobbers as well is saying the
3313 /// same thing twice, which the allocator would read as one register with two definitions.
3314 ///
3315 /// On a template with nothing in it the list is ignored, as it was before, since a template
3316 /// with no instructions ruins nothing whatever it said about what it ruins.
3317 fn assembly(&mut self, inst: Inst) -> Result<(), Unsupported> {
3318 let data = &self.source[inst];
3319 let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
3320 let info = self.source[asm];
3321 if !self.source[info.targets].is_empty() {
3322 return Err(Unsupported::Assembly { inst, refused: Written::Goto });
3323 }
3324 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
3325
3326 let constraints = self.names.resolve(info.constraints).to_string();
3327 let results: Vec<Value> = data.results().collect();
3328 let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
3329 .ok_or_else(refused)?;
3330 let list: Vec<AsmOperand<'_>> = operands.iter().copied().collect();
3331
3332 // Read after the constraints and not before them, because a mnemonic whose suffix the
3333 // program left off is read at the width of the operands it names, and the operands are
3334 // what the constraints are a list of.
3335 let widths: Vec<Option<x86_64::Width>> = list
3336 .iter()
3337 .map(|operand| {
3338 let ty = self.source[operand.result.or(operand.value)?].ty;
3339 if !ty.is_scalar() {
3340 return None;
3341 }
3342 x86_64::Width::of_bits(held_bits(ty))
3343 })
3344 .collect();
3345 // An operand in memory is an address the statement holds and an object the template names,
3346 // so the reader is told which ones those are and spells `%0` for one as the object.
3347 let memory: Vec<bool> = list.iter().map(|operand| operand.memory).collect();
3348 let template = self.names.resolve(info.template).to_string();
3349 let steps = if template.trim().is_empty() {
3350 Vec::new()
3351 } else {
3352 match x86_64::read_in(&template, &widths, &memory) {
3353 Some(steps) => steps,
3354 None => return self.kept(inst, &template, &list),
3355 }
3356 };
3357
3358 // Which operands the template writes, counted before anything is placed, because the answer
3359 // decides where each of the three below comes from and one instruction may name an operand
3360 // that a later one writes. Which of them any instruction puts in a register at all is
3361 // counted in the same walk, since an operand no instruction reaches that way is one nothing
3362 // has to put anywhere: a constant a template names only as the distance into an address is
3363 // written into the instruction, and a register holding a copy of it would be one nobody
3364 // reads. An operand the address is counted from is reached that way and is counted here for
3365 // that reason, because the walk below it is over the opcode's operands and an address is
3366 // not one of those.
3367 //
3368 // Whether any instruction reads an operand an instruction above it wrote is counted in the
3369 // same walk too. Such a template is one whose instructions have to be written in order with
3370 // each read taken from wherever the last write left the operand, which is what
3371 // [`Self::woven`] does, and so is one that writes an operand twice.
3372 let mut writes = vec![0usize; list.len()];
3373 let mut reads = vec![false; list.len()];
3374 let mut held = vec![false; list.len()];
3375 let mut after = false;
3376 for step in &steps {
3377 // A call out of the template writes every register the convention lets the callee
3378 // leave anything in, and an output pinned to one of those is written by it.
3379 if let x86_64::Step::Call { .. } = step {
3380 for index in self.lost(&list).into_iter().filter_map(|(_, _, index)| index) {
3381 *writes.get_mut(index).ok_or_else(refused)? += 1;
3382 }
3383 continue;
3384 }
3385 let x86_64::Step::Line(line) = step else { continue };
3386 match line.at.and_then(|at| at.base) {
3387 Some(x86_64::Piece::Operand { index, .. }) => {
3388 *held.get_mut(index).ok_or_else(refused)? = true;
3389 after |= writes[index] > 0;
3390 }
3391 Some(x86_64::Piece::Reg { reg, .. }) => {
3392 if let Some(index) = bound(&list, reg, Role::Use) {
3393 *held.get_mut(index).ok_or_else(refused)? = true;
3394 after |= writes[index] > 0;
3395 }
3396 }
3397 _ => {}
3398 }
3399 let mut written = Vec::new();
3400 let form = x86_64::form(line.opcode).ok_or_else(refused)?;
3401 // Which registers the instruction reaches, asked the same way it is asked again when
3402 // the instruction is written. See [`Self::lettered`] for the one opcode whose answer
3403 // comes from the constraint letters rather than from the description.
3404 let lettered = (line.opcode == x86_64::LITERAL).then(|| self.lettered(&list));
3405 let (described, pieces) = match &lettered {
3406 Some((described, pieces)) => (described.as_slice(), pieces.as_slice()),
3407 None => (form.operands(), line.operands.as_slice()),
3408 };
3409 for (desc, piece) in described.iter().zip(pieces) {
3410 // An operand the instruction reaches without its text saying so is the statement's
3411 // only when a constraint letter put something there. One that is nobody's writes
3412 // nothing of the program's, so it is counted nowhere and is dealt with where it is
3413 // placed.
3414 let index = match *piece {
3415 x86_64::Piece::Operand { index, .. } => index,
3416 x86_64::Piece::Implicit { reg } => match bound(&list, reg, desc.role) {
3417 Some(index) => index,
3418 None => continue,
3419 },
3420 x86_64::Piece::Reg { reg, .. } => match bound(&list, reg, desc.role) {
3421 Some(index) => index,
3422 None => continue,
3423 },
3424 };
3425 *held.get_mut(index).ok_or_else(refused)? = true;
3426 if matches!(desc.role, Role::Def | Role::EarlyDef) {
3427 written.push(index);
3428 } else {
3429 *reads.get_mut(index).ok_or_else(refused)? = true;
3430 after |= writes[index] > 0;
3431 }
3432 }
3433 for index in written {
3434 *writes.get_mut(index).ok_or_else(refused)? += 1;
3435 }
3436 }
3437 let woven = after
3438 || writes.iter().any(|&count| count > 1)
3439 || steps.iter().any(|step| !matches!(step, x86_64::Step::Line(_)));
3440
3441 // Where every operand is. Worked out in full before the first instruction is written, since
3442 // reading a value may be what puts it in a register in the first place, and that has to
3443 // happen in front of the assembly rather than in the middle of it.
3444 let mut places: Vec<Place> = vec![Place::default(); list.len()];
3445 for (index, operand) in list.iter().copied().enumerate() {
3446 let Some(result) = operand.result else {
3447 // An input, or an output the assembly was handed the address of, and both are a
3448 // value that arrives in a register and is read out of it, unless no instruction of
3449 // the template reads it out of one.
3450 let value = operand.value.ok_or_else(refused)?;
3451 if held[index] {
3452 places[index].read = Some(self.reg_of(value)?);
3453 }
3454 continue;
3455 };
3456 let ty = self.source[result].ty;
3457 if on_x87(ty) {
3458 return Err(refused());
3459 }
3460 let tied = operands.tied_to(index);
3461 if let Some(from) = tied {
3462 if self.class_of(self.source[from].ty) != self.class_of(ty) {
3463 return Err(refused());
3464 }
3465 places[index].read = Some(self.reg_of(from)?);
3466 }
3467 if writes[index] > 0 {
3468 places[index].write = Some(self.new_reg(result));
3469 continue;
3470 }
3471 match tied {
3472 // The place the input arrived in, which the assembly wrote nothing over. One
3473 // register, so this is a rename rather than a move.
3474 Some(_) => {
3475 let reg = places[index].read.ok_or_else(refused)?;
3476 self.regs[result.index()] = Some(reg);
3477 places[index].write = Some(reg);
3478 }
3479 None => {
3480 self.undefined(inst, result)?;
3481 places[index].write = self.regs[result.index()];
3482 }
3483 }
3484 }
3485
3486 // An output an instruction of the template also reads, which the statement said nothing
3487 // about because an output is what a statement says the other thing about. What it holds
3488 // there is undefined, and a program writing one means it: `sbb %0, %0` in libgmp's
3489 // `add_mssaaaa` subtracts a register from itself and is asking for the borrow bit rather
3490 // than for the number, so whatever the register held, the answer is the same. Undefined is
3491 // not the same as absent though, since the allocator is owed a definition in front of every
3492 // use, so it gets the zero an output nothing wrote gets and for the same reason.
3493 //
3494 // Unless an input could have been in the same register, in which case gcc's allocator puts
3495 // it there whenever it can and a program may have been written against that. tcc's test of
3496 // a call from a template reads its output `"=a" (s)` to pass `"r" (str)` to `getenv`, which
3497 // is only the string because gcc gave the two of them `rax`. So an output nothing has
3498 // written yet reads the one input that could share its place, when there is exactly one.
3499 // One written `&` is written before the inputs are read and shares nothing.
3500 for index in 0..list.len() {
3501 if !reads[index] || places[index].read.is_some() || places[index].write.is_none() {
3502 continue;
3503 }
3504 let reg = match self.shared(&list, index) {
3505 Some(value) => self.reg_of(value)?,
3506 None => self.seeded(inst, list[index])?,
3507 };
3508 places[index].read = Some(reg);
3509 }
3510
3511 // Worked out once for the whole template, since the list is one list and every instruction
3512 // of the template gets it. Not worked out at all for a template with no instructions, which
3513 // is where there is nothing for it to go on.
3514 let clobbers = self.names.resolve(info.clobbers).to_string();
3515 let clobbered =
3516 if steps.is_empty() { Vec::new() } else { Self::clobbered(inst, &clobbers)? };
3517
3518 // A template with a label in it is not one run of instructions, and what it is instead is
3519 // in [`Self::woven`], which is also where a template goes whose instructions read what the
3520 // ones above them wrote. Every other template is what it has always been, which is every
3521 // instruction of it written into the block the statement stands in.
3522 if woven {
3523 return self.woven(inst, &steps, &mut places, &list, &clobbered, &writes);
3524 }
3525 for step in &steps {
3526 let x86_64::Step::Line(line) = step else { continue };
3527 self.instruction(inst, line, &places, &list, &clobbered)?;
3528 }
3529 Ok(())
3530 }
3531
3532 /// A template the reader could not take apart, kept as its text. See [`x86_64::Form::Template`].
3533 ///
3534 /// What the text names is spelled into it here, the way gcc prints it into its listing: a
3535 /// constant as `$5`, or as `5` under the `c` modifier, and the address of a name as the name.
3536 /// An object in memory is the one thing that cannot be spelled yet, since where it is depends on
3537 /// registers nothing has chosen, so it is left as a hole the writer fills and its address is the
3538 /// instruction's memory operand. One is all an instruction has room for, and every template this
3539 /// has met names one at most. An operand in a register is refused for now, as is a template
3540 /// that names one by name rather than by number.
3541 ///
3542 /// A statement written with no colons is basic assembly, where `%` is a character like any
3543 /// other and a register is written `%eax`. The front end keeps no mark of which kind a statement
3544 /// was, so one with no operands and no clobbers is read as basic, which is what gcc would do for
3545 /// every such template but one written with empty colons around it.
3546 ///
3547 /// The registers a call may write are taken as written, see below for why.
3548 fn kept(
3549 &mut self,
3550 inst: Inst,
3551 template: &str,
3552 list: &[AsmOperand<'_>],
3553 ) -> Result<(), Unsupported> {
3554 // Refused as the template it is, since keeping it is what was tried after reading it
3555 // failed, and what could not be kept is what it names rather than any one operand.
3556 let refused = || Unsupported::Assembly { inst, refused: Written::Template };
3557 let data = &self.source[inst];
3558 let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
3559 let clobbers = self.names.resolve(self.source[asm].clobbers).to_string();
3560 let basic = list.is_empty() && clobbers.trim().is_empty();
3561
3562 let mut text = String::with_capacity(template.len());
3563 let mut memory: Option<usize> = None;
3564 if basic {
3565 text.push_str(template);
3566 } else {
3567 let mut chars = template.chars().peekable();
3568 // Inside `{att|intel}`, and past the `|` in it, which is the half nobody reads.
3569 let mut dialect = false;
3570 let mut skipped = false;
3571 while let Some(c) = chars.next() {
3572 match c {
3573 '{' => {
3574 dialect = true;
3575 continue;
3576 }
3577 '|' if dialect => {
3578 skipped = true;
3579 continue;
3580 }
3581 '}' if dialect => {
3582 dialect = false;
3583 skipped = false;
3584 continue;
3585 }
3586 _ if skipped => continue,
3587 '%' => {}
3588 _ => {
3589 text.push(c);
3590 continue;
3591 }
3592 }
3593 match chars.peek().copied() {
3594 Some(c @ ('%' | '{' | '|' | '}')) => {
3595 chars.next();
3596 text.push(c);
3597 continue;
3598 }
3599 Some('=') => {
3600 chars.next();
3601 text.push_str(&inst.index().to_string());
3602 continue;
3603 }
3604 _ => {}
3605 }
3606 let modifier = match chars.peek().copied() {
3607 Some(c) if c.is_ascii_alphabetic() => {
3608 chars.next();
3609 Some(c)
3610 }
3611 _ => None,
3612 };
3613 let mut digits = String::new();
3614 while let Some(c) = chars.peek().copied().filter(char::is_ascii_digit) {
3615 digits.push(c);
3616 chars.next();
3617 }
3618 let index: usize = digits.parse().map_err(|_| refused())?;
3619 let operand = list.get(index).ok_or_else(refused)?;
3620 if operand.memory {
3621 if modifier.is_some() || memory.is_some_and(|had| had != index) {
3622 return Err(refused());
3623 }
3624 memory = Some(index);
3625 text.push_str(x86_64::TEMPLATE_MEM);
3626 continue;
3627 }
3628 if operand.result.is_some() {
3629 return Err(refused());
3630 }
3631 let value = operand.value.ok_or_else(refused)?;
3632 let bare = match modifier {
3633 None => false,
3634 Some('c' | 'P' | 'p') => true,
3635 Some(_) => return Err(refused()),
3636 };
3637 if !bare {
3638 text.push('$');
3639 }
3640 if let Some(number) = self.number(value) {
3641 text.push_str(&number.to_string());
3642 } else if let Some(symbol) = self.named_address(value) {
3643 text.push_str(&x86_64::template_name(self.names.resolve(symbol)));
3644 } else {
3645 return Err(refused());
3646 }
3647 }
3648 }
3649
3650 // Every register a call may leave anything in, as well as the ones the list names. The
3651 // text can write any register it likes without saying so, and tcc's tests do: gcc gets
3652 // away with that at `-O0` because nothing lives in a register between two statements
3653 // there, and taking these away from the allocator across the template is what gives the
3654 // same answer here. Nothing is written to them by this, so a register one template leaves
3655 // a value in is still holding it when the next template reads it.
3656 let mut clobbered: Vec<(PhysReg, RegClass)> =
3657 self.lost(list).into_iter().map(|(reg, class, _)| (reg, class)).collect();
3658 for reg in Self::clobbered(inst, &clobbers)? {
3659 if !clobbered.iter().any(|&(had, _)| had == reg) {
3660 clobbered.push((reg, self.gpr));
3661 }
3662 }
3663 // An object in this function's frame is named by where it is in the frame, the way gcc
3664 // names it, rather than by a register its address was put in first. The text may write
3665 // registers it does not declare, and tcc's tests do: one that writes `%ecx` behind the
3666 // compiler's back would otherwise take the address with it.
3667 let mut local = None;
3668 let at = match memory {
3669 Some(index) => {
3670 let value = list[index].value.ok_or_else(refused)?;
3671 local = self.local_of(value);
3672 let base = match local {
3673 Some(_) => mir::Reg::physical(self.conv.stack_pointer),
3674 None => self.reg_of(value)?,
3675 };
3676 Some(mir::Mem::at(mir::Operand::read(base, self.gpr)))
3677 }
3678 None => None,
3679 };
3680 let symbol = self.names.intern(&text);
3681 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::TEMPLATE)));
3682 let block = self.at.expect("a block is being filled");
3683 let span = self.source.span(inst);
3684 let mut build = self.out.build(block, opcode).at(span).symbol(symbol);
3685 for (reg, class) in clobbered {
3686 build = build.operand(mir::Operand::write(mir::Reg::physical(reg), class));
3687 }
3688 if let Some(mem) = at {
3689 build = build.mem(mem);
3690 }
3691 let made = build.finish();
3692 if let Some(local) = local {
3693 self.stack.addresses.push((made, local));
3694 }
3695 Ok(())
3696 }
3697
3698 /// The object in this function's frame a value is the address of, for one an `alloca` of a
3699 /// size known here made. See [`Self::reserve`], which is where the `lea` it is found by came
3700 /// from.
3701 fn local_of(&self, value: Value) -> Option<usize> {
3702 let Def::Result { inst, .. } = self.source[value].def else { return None };
3703 if self.source[inst].opcode != Opcode::Alloca
3704 || !self.source[self.source[inst].args].is_empty()
3705 {
3706 return None;
3707 }
3708 let reg = self.regs[value.index()]?;
3709 self.stack.addresses.iter().find_map(|&(made, local)| {
3710 let data = &self.out[made];
3711 let defined = self.out[data.operands].first()?;
3712 (defined.reg == reg).then_some(local)
3713 })
3714 }
3715
3716 /// The name a value is the address of, for one a `global_addr` defined.
3717 fn named_address(&self, value: Value) -> Option<Symbol> {
3718 let Def::Result { inst, .. } = self.source[value].def else { return None };
3719 if self.source[inst].opcode != Opcode::GlobalAddr {
3720 return None;
3721 }
3722 let Extra::Symbol(symbol) = self.source[inst].extra else { return None };
3723 Some(symbol)
3724 }
3725
3726 /// A register holding a zero, for an operand of a template that is read before anything filled
3727 /// it.
3728 ///
3729 /// Two things ask for this and they are the same thing twice. An output the template reads has
3730 /// nothing to be read out of until the instruction that writes it has run, and a loop carries
3731 /// an operand into a block before the instruction that fills it, so both are a use in front of
3732 /// every definition. What the program is owed there is nothing, since the value is undefined
3733 /// either way, and what the allocator is owed is a register something wrote.
3734 fn seeded(&mut self, inst: Inst, operand: AsmOperand<'_>) -> Result<mir::Reg, Unsupported> {
3735 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
3736 let value = operand.result.or(operand.value).ok_or_else(refused)?;
3737 let class = self.class_of(self.source[value].ty);
3738 if class != self.gpr {
3739 return Err(refused());
3740 }
3741 let block = self.at.expect("a block is being filled");
3742 let reg = self.out.new_vreg(class);
3743 let put = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_ri_64")));
3744 self.out.build(block, put).at(self.source.span(inst)).def(reg, class).imm(0).finish();
3745 Ok(reg)
3746 }
3747
3748 /// A template with labels in it, as the blocks its jumps leave and arrive at.
3749 ///
3750 /// A statement is an instruction of the IR and stands inside one block, so a template that
3751 /// jumps has to stop being one thing. Each label becomes a block, each jump ends the block it
3752 /// stands in and gives it two arms, and whatever follows the statement goes into whichever
3753 /// block the walk finished in, which is what [`Self::block`] already reads off `self.at` and
3754 /// what [`Self::saves_place`] already does for the same reason.
3755 ///
3756 /// # What is carried between them
3757 ///
3758 /// The machine IR here is in the form where a register is written once, so an operand written
3759 /// inside a loop and read again at the top of it cannot be one register. What arrives at the
3760 /// top is a parameter of that block, and every jump to it carries whichever register held the
3761 /// operand where the jump stands. That is the whole of the bookkeeping: every block a label
3762 /// made takes one parameter for each operand that is in a register at all, in one order, so an
3763 /// arm's arguments and a block's parameters are the same list read twice.
3764 ///
3765 /// Which register an operand is in at each point is kept in the read half of its place, since
3766 /// that is what the instructions below read it out of. An instruction that writes an operand
3767 /// leaves it in the register it wrote, and a jump below carries that one. The block an
3768 /// untaken jump falls into is arrived at one way only and so takes no parameters, and nothing
3769 /// about where the operands are changes there.
3770 ///
3771 /// An operand written by the template and filled by nothing is written as a zero first, for
3772 /// the reason [`Self::undefined`] gives and one more: a jump may carry it before the
3773 /// instruction that fills it has run, and an argument has to be a register something wrote.
3774 ///
3775 /// # The condition state
3776 ///
3777 /// Nothing carries it and nothing has to. The instruction that sets it and the jump that reads
3778 /// it are both written here, next to each other in one block, and what the allocator may put
3779 /// between them is a move, which on this machine leaves the condition state alone. The edge
3780 /// into a block a loop goes back to is a critical edge and `crate::split` gives it a block of
3781 /// its own, so the moves an arm turns into land behind the jump rather than in front of it.
3782 fn woven(
3783 &mut self,
3784 inst: Inst,
3785 steps: &[x86_64::Step],
3786 places: &mut [Place],
3787 list: &[AsmOperand<'_>],
3788 clobbered: &[PhysReg],
3789 writes: &[usize],
3790 ) -> Result<(), Unsupported> {
3791 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
3792 let span = self.source.span(inst);
3793
3794 // Which operands are carried, which is every one that is in a register at all. An operand
3795 // the template never puts in one, such as a constant it names only as the distance into an
3796 // address, is in the instruction and has nowhere to be carried from.
3797 let mut carried: Vec<(usize, RegClass)> = Vec::new();
3798 for (index, operand) in list.iter().enumerate() {
3799 if places[index].read.is_none() && places[index].write.is_none() {
3800 continue;
3801 }
3802 let value = operand.result.or(operand.value).ok_or_else(refused)?;
3803 let ty = self.source[value].ty;
3804 if on_x87(ty) {
3805 return Err(refused());
3806 }
3807 carried.push((index, self.class_of(ty)));
3808 }
3809
3810 // What each of them holds where the template starts.
3811 for &(index, _) in &carried {
3812 if places[index].read.is_some() {
3813 continue;
3814 }
3815 if writes[index] == 0 {
3816 places[index].read = places[index].write;
3817 continue;
3818 }
3819 places[index].read = Some(self.seeded(inst, list[index])?);
3820 }
3821
3822 // The blocks, made before the walk because a jump forwards names a label the walk has not
3823 // reached yet.
3824 let mut labels: Vec<(&str, mir::Block, Vec<mir::Reg>)> = Vec::new();
3825 for step in steps {
3826 let x86_64::Step::Label(name) = step else { continue };
3827 let block = self.out.create_block();
3828 let mut params = Vec::with_capacity(carried.len());
3829 for &(_, class) in &carried {
3830 params.push(self.out.append_param(block, class));
3831 }
3832 labels.push((name.as_str(), block, params));
3833 }
3834
3835 let mut wrote: Vec<usize> = Vec::new();
3836 for step in steps {
3837 match step {
3838 x86_64::Step::Label(name) => {
3839 let (block, params) = Self::went(&labels, name).ok_or_else(refused)?;
3840 let from = self.at.expect("a block is being filled");
3841 let args = Self::held(places, &carried).ok_or_else(refused)?;
3842 *self.out.succs_mut(from) = vec![mir::BlockCall::with(block, args)];
3843 self.at = Some(block);
3844 for (at, &(index, _)) in carried.iter().enumerate() {
3845 places[index].read = params.get(at).copied();
3846 }
3847 }
3848 x86_64::Step::Jump { opcode, to } => {
3849 let (block, _) = Self::went(&labels, to).ok_or_else(refused)?;
3850 let from = self.at.expect("a block is being filled");
3851 let args = Self::held(places, &carried).ok_or_else(refused)?;
3852 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{opcode}")));
3853 self.out.build(from, opcode).at(span).finish();
3854 let next = self.out.create_block();
3855 *self.out.succs_mut(from) =
3856 vec![mir::BlockCall::with(block, args), mir::BlockCall::to(next)];
3857 self.at = Some(next);
3858 }
3859 x86_64::Step::Away { symbol } => {
3860 // Only in a function that is written without a prologue, which is the one
3861 // place the jump means what it says. Anywhere else there is an epilogue behind
3862 // the statement that puts the registers back and gives the frame up, and a
3863 // jump over it goes to the next function with this function's frame still
3864 // taken. The reader already made sure it is the last step of the template, so
3865 // what is left to ask is about the function around it.
3866 if !self.source.attrs.set.contains(AttrSet::NAKED) {
3867 return Err(Unsupported::Assembly { inst, refused: Written::Away });
3868 }
3869 let from = self.at.expect("a block is being filled");
3870 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{AWAY}")));
3871 let symbol = self.names.intern(symbol);
3872 self.out.build(from, opcode).at(span).symbol(symbol).finish();
3873 // Nowhere, which is what a jump out of the function leaves behind it and is
3874 // the same list a `ret` leaves. The block after it is made for the walk above
3875 // rather than for the program: the statement may be in the middle of a body
3876 // that goes on being lowered, and what that lowering writes is reached by
3877 // nothing and thrown away with the block.
3878 *self.out.succs_mut(from) = Vec::new();
3879 self.at = Some(self.out.create_block());
3880 }
3881 x86_64::Step::Call { symbol } => {
3882 self.call_out(inst, symbol, places, list, clobbered, &carried, &mut wrote)?;
3883 }
3884 x86_64::Step::Line(line) => {
3885 let form = x86_64::form(line.opcode).ok_or_else(refused)?;
3886 let mut written = Vec::new();
3887 for (desc, piece) in form.operands().iter().zip(&line.operands) {
3888 if !desc.role.is_def() {
3889 continue;
3890 }
3891 let index = match *piece {
3892 x86_64::Piece::Operand { index, .. } => index,
3893 x86_64::Piece::Implicit { reg } => match bound(list, reg, desc.role) {
3894 Some(index) => index,
3895 None => continue,
3896 },
3897 x86_64::Piece::Reg { reg, .. } => match bound(list, reg, desc.role) {
3898 Some(index) => index,
3899 None => continue,
3900 },
3901 };
3902 written.push(index);
3903 }
3904 // A register is written once in this form of the machine IR, so an operand
3905 // an instruction above already wrote is written into a new one here, and what
3906 // reads it below reads that one.
3907 for &index in &written {
3908 if !wrote.contains(&index) {
3909 wrote.push(index);
3910 continue;
3911 }
3912 let &(_, class) =
3913 carried.iter().find(|&&(at, _)| at == index).ok_or_else(refused)?;
3914 let place = places.get_mut(index).ok_or_else(refused)?;
3915 place.write = Some(self.out.new_vreg(class));
3916 }
3917 self.instruction(inst, line, places, list, clobbered)?;
3918 for index in written {
3919 let place = places.get_mut(index).ok_or_else(refused)?;
3920 if place.write.is_some() {
3921 place.read = place.write;
3922 }
3923 }
3924 }
3925 }
3926 }
3927
3928 // Where the walk left each output, which is the parameter of the block a label made when
3929 // the template ends in one and the register an instruction wrote when it does not.
3930 for (index, operand) in list.iter().enumerate() {
3931 let Some(result) = operand.result else { continue };
3932 if let Some(reg) = places[index].read {
3933 self.regs[result.index()] = Some(reg);
3934 }
3935 }
3936 Ok(())
3937 }
3938
3939 /// A template's call to a function somewhere else, as the call the convention makes.
3940 ///
3941 /// The opcode is the one a call written in C becomes, so everything that asks whether a
3942 /// function calls anything gets the answer it would for one: the stack pointer is left aligned
3943 /// at the statement and nothing is kept in the red zone. What is not the same is the operands.
3944 /// Nothing is passed by the convention, since the template put the arguments where it wanted
3945 /// them, and what comes back is whatever an output is pinned to, since that is the only thing
3946 /// the template says about it. Every other register the callee may leave anything in is
3947 /// written here, which is what a program that calls from a template never says and always
3948 /// means.
3949 #[allow(clippy::too_many_arguments)]
3950 fn call_out(
3951 &mut self,
3952 inst: Inst,
3953 symbol: &str,
3954 places: &mut [Place],
3955 list: &[AsmOperand<'_>],
3956 clobbered: &[PhysReg],
3957 carried: &[(usize, RegClass)],
3958 wrote: &mut Vec<usize>,
3959 ) -> Result<(), Unsupported> {
3960 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
3961 let mut operands = Vec::new();
3962 let mut written = Vec::new();
3963 let lost = self.lost(list);
3964 for &(reg, class, index) in &lost {
3965 let Some(index) = index else {
3966 operands.push(mir::Operand::write(mir::Reg::physical(reg), class));
3967 continue;
3968 };
3969 // Written once in this form of the machine IR, so a second write is a new register,
3970 // the same as for an instruction in [`Self::woven`].
3971 if wrote.contains(&index) {
3972 let &(_, class) =
3973 carried.iter().find(|&&(at, _)| at == index).ok_or_else(refused)?;
3974 places.get_mut(index).ok_or_else(refused)?.write = Some(self.out.new_vreg(class));
3975 } else {
3976 wrote.push(index);
3977 }
3978 let place = places.get(index).ok_or_else(refused)?.write.ok_or_else(refused)?;
3979 operands.push(mir::Operand::write(place, class).with(Constraint::Fixed(reg)));
3980 written.push(index);
3981 }
3982 for ® in clobbered {
3983 if lost.iter().all(|&(gone, class, _)| gone != reg || class != self.gpr) {
3984 operands.push(mir::Operand::write(mir::Reg::physical(reg), self.gpr));
3985 }
3986 }
3987 let block = self.at.expect("a block is being filled");
3988 let span = self.source.span(inst);
3989 let opcode = mir::Opcode::new(self.names.intern(abi::CALL));
3990 let symbol = self.names.intern(symbol);
3991 let mut build = self.out.build(block, opcode).at(span).symbol(symbol);
3992 for operand in operands {
3993 build = build.operand(operand);
3994 }
3995 build.finish();
3996 let calls = &mut self.stack.calls;
3997 *calls = Some(calls.unwrap_or(0));
3998 for index in written {
3999 let place = places.get_mut(index).ok_or_else(refused)?;
4000 place.read = place.write;
4001 }
4002 Ok(())
4003 }
4004
4005 /// Every register a call may leave anything in, with its file and the output pinned to it if
4006 /// one is.
4007 ///
4008 /// Only a general purpose register is ever pinned to an output, since those are the only ones a
4009 /// constraint letter or a register variable names here. The vector registers are numbered from
4010 /// nought as well, so asking about one of them would find the output pinned to the register of
4011 /// the same number in the other file.
4012 fn lost(&self, list: &[AsmOperand<'_>]) -> Vec<(PhysReg, RegClass, Option<usize>)> {
4013 let conv = self.conv;
4014 let ints = conv.int_order.iter().filter(|&®| !conv.preserves_int(reg));
4015 let sses = conv.sse_order.iter().filter(|&®| !conv.preserves_sse(reg));
4016 ints.map(|®| (reg, conv.int_class, bound(list, reg, Role::Def)))
4017 .chain(sses.map(|®| (reg, conv.sse_class, None)))
4018 .collect()
4019 }
4020
4021 /// The input an output read before anything wrote it shares its register with, which is the
4022 /// one input that could be in that register, or nothing when there is none or more than one.
4023 ///
4024 /// Could be means nothing ties it elsewhere: it is in a register rather than in memory, no
4025 /// constraint pins it anywhere the output is not, and it is not tied to another output. An
4026 /// output written `&` shares nothing, since the assembly writes it before it reads the inputs.
4027 fn shared(&self, list: &[AsmOperand<'_>], index: usize) -> Option<Value> {
4028 let output = list.get(index)?;
4029 if output.early || output.tied.is_some() {
4030 return None;
4031 }
4032 let class = self.class_of(self.source[output.result?].ty);
4033 let mut fits = list.iter().filter(|operand| {
4034 operand.result.is_none()
4035 && !operand.memory
4036 && operand.tied.is_none()
4037 && operand.value.is_some_and(|value| self.class_of(self.source[value].ty) == class)
4038 && pinned(operand).is_none_or(|reg| pinned(output) == Some(reg))
4039 });
4040 let value = fits.next()?.value;
4041 if fits.next().is_some() {
4042 return None;
4043 }
4044 value
4045 }
4046
4047 /// The block one of the template's labels made, and the parameters it takes.
4048 fn went<'b>(
4049 labels: &'b [(&str, mir::Block, Vec<mir::Reg>)],
4050 name: &str,
4051 ) -> Option<(mir::Block, &'b [mir::Reg])> {
4052 labels
4053 .iter()
4054 .find(|(had, ..)| *had == name)
4055 .map(|(_, block, params)| (*block, params.as_slice()))
4056 }
4057
4058 /// The register each carried operand is in, which is what an arm to a label carries.
4059 fn held(places: &[Place], carried: &[(usize, RegClass)]) -> Option<Vec<mir::Reg>> {
4060 carried.iter().map(|&(index, _)| places.get(index)?.read).collect()
4061 }
4062
4063 /// The registers a clobber list names, in the order it named them.
4064 ///
4065 /// Nothing is dropped. A name this has no register for is refused, because the list is the
4066 /// program telling the compiler which registers it may not leave anything in, and an entry
4067 /// nobody read is a register something may still be left in. See [`Self::assembly`] for the
4068 /// two entries that are not registers and for why they are skipped rather than refused.
4069 fn clobbered(inst: Inst, clobbers: &str) -> Result<Vec<PhysReg>, Unsupported> {
4070 let refused = || Unsupported::Assembly { inst, refused: Written::Clobber };
4071 let mut named = Vec::new();
4072 for entry in clobbers.split(',') {
4073 let entry = entry.trim().trim_matches('"');
4074 // The sigil is optional in a clobber list and means nothing when it is there, unlike
4075 // in a template, where it is what tells a register from an operand.
4076 let entry = entry.strip_prefix('%').unwrap_or(entry);
4077 if entry.is_empty() || matches!(entry, "memory" | "cc" | "flags") {
4078 continue;
4079 }
4080 let (reg, _) = x86_64::gpr_named(entry).ok_or_else(refused)?;
4081 if !named.contains(®) {
4082 named.push(reg);
4083 }
4084 }
4085 Ok(named)
4086 }
4087
4088 /// One instruction of a template, as the machine instruction it was read back into.
4089 fn instruction(
4090 &mut self,
4091 inst: Inst,
4092 line: &x86_64::Line,
4093 places: &[Place],
4094 list: &[AsmOperand<'_>],
4095 clobbered: &[PhysReg],
4096 ) -> Result<(), Unsupported> {
4097 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4098 let form = x86_64::form(line.opcode).ok_or_else(refused)?;
4099 // What the instruction reaches and what is in each of them. The description answers the
4100 // first for every opcode but one, and the pieces the template was read into answer the
4101 // second. Bytes a program wrote out itself are the one, since nothing in a number is a
4102 // register anybody could read, so the constraint letters answer both. See
4103 // [`Self::lettered`].
4104 let lettered = (line.opcode == x86_64::LITERAL).then(|| self.lettered(list));
4105 let (described, pieces) = match &lettered {
4106 Some((described, pieces)) => (described.as_slice(), pieces.as_slice()),
4107 None => (form.operands(), line.operands.as_slice()),
4108 };
4109 let mut built = Vec::with_capacity(pieces.len() + clobbered.len());
4110 for (desc, piece) in described.iter().zip(pieces) {
4111 built.push(self.placed(inst, *desc, *piece, places, list)?);
4112 }
4113 // The clobbers go in among the definitions rather than behind the reads, because an operand
4114 // vector in the machine IR is every definition and then every use and what counts them
4115 // reads that order rather than each operand's role.
4116 let defs = built.iter().take_while(|operand| operand.role.is_def()).count();
4117 let mut added = 0usize;
4118 for ® in clobbered {
4119 if described.iter().any(|desc| desc.constraint == Constraint::Fixed(reg)) {
4120 continue;
4121 }
4122 built.insert(defs, mir::Operand::write(mir::Reg::physical(reg), self.gpr));
4123 added += 1;
4124 }
4125 // A constraint tying one operand to another names it by its place in this vector, and the
4126 // clobbers were put in the middle of the vector, so everything behind them moved. The
4127 // description is written against an instruction with no clobbers in it and cannot know
4128 // that, which makes this the one place the two numberings have to be reconciled.
4129 for operand in &mut built {
4130 if let Constraint::Reuse(at) = operand.constraint {
4131 if usize::from(at) >= defs {
4132 let moved = usize::from(at) + added;
4133 operand.constraint =
4134 Constraint::Reuse(u8::try_from(moved).map_err(|_| refused())?);
4135 }
4136 }
4137 }
4138 let at = match line.at {
4139 Some(at) => Some(self.addressed(inst, at, places, list)?),
4140 None => None,
4141 };
4142
4143 let block = self.at.expect("a block is being filled");
4144 let span = self.source.span(inst);
4145 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", line.opcode)));
4146 let mut build = self.out.build(block, opcode).at(span);
4147 for operand in built {
4148 build = build.operand(operand);
4149 }
4150 if let Some(value) = line.imm {
4151 build = build.imm(value);
4152 }
4153 if let Some(mem) = at {
4154 build = build.mem(mem);
4155 }
4156 build.finish();
4157 Ok(())
4158 }
4159
4160 /// The registers a run of bytes reaches, taken from the constraint letters rather than from the
4161 /// description of an opcode.
4162 ///
4163 /// Every other instruction of a template has a description saying which registers it reaches
4164 /// without naming them, and [`Self::assembly`] matches the letters against that. Bytes a program
4165 /// wrote out itself have no such description and could not have one: what the instruction is, is
4166 /// a number, and nothing in a number is a register anything could read. So the letters are the
4167 /// whole of what is known, and they are enough, because a program writing an instruction this
4168 /// way has to say where its operands go for exactly the reason a program writing `cpuid` does.
4169 ///
4170 /// Each register named by a letter gets one entry for the write and one for the read, the same
4171 /// two `cpuid` has, and only the half the statement asked for: a register no output names is not
4172 /// written here and one no input names is not read. The writes come first because that is the
4173 /// order an operand vector in the machine IR is counted in. A register named by nothing is left
4174 /// out rather than given a spare one, which is the difference from `cpuid` and is right for the
4175 /// same reason: `cpuid` writes four registers whatever the program said, and what these bytes
4176 /// touch is known only from what the program said.
4177 fn lettered(&self, list: &[AsmOperand<'_>]) -> (Vec<OperandDesc>, Vec<x86_64::Piece>) {
4178 let mut named: Vec<PhysReg> = Vec::new();
4179 for operand in list {
4180 if let Some(reg) = pinned(operand) {
4181 if !named.contains(®) {
4182 named.push(reg);
4183 }
4184 }
4185 }
4186 let mut described = Vec::with_capacity(named.len() * 2);
4187 let mut pieces = Vec::with_capacity(named.len() * 2);
4188 for role in [Role::Def, Role::Use] {
4189 for ® in &named {
4190 if bound(list, reg, role).is_none() {
4191 continue;
4192 }
4193 let desc = if role.is_def() {
4194 OperandDesc::write(self.gpr)
4195 } else {
4196 OperandDesc::read(self.gpr)
4197 };
4198 described.push(desc.with(Constraint::Fixed(reg)));
4199 pieces.push(x86_64::Piece::Implicit { reg });
4200 }
4201 }
4202 (described, pieces)
4203 }
4204
4205 /// One operand of one instruction of a template, in the register the statement put it in.
4206 fn placed(
4207 &mut self,
4208 inst: Inst,
4209 desc: OperandDesc,
4210 piece: x86_64::Piece,
4211 places: &[Place],
4212 list: &[AsmOperand<'_>],
4213 ) -> Result<mir::Operand, Unsupported> {
4214 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4215 // A register the instruction reaches without its text naming it belongs to whichever of the
4216 // statement's operands a constraint letter put there, and to nobody when no letter did.
4217 // There is no width to check in that case: the operand is the register the letter named and
4218 // the instruction does what it does to it, which is what a program writing `"=a"` asked for.
4219 let (index, spelled) = match piece {
4220 x86_64::Piece::Operand { index, width, stated } => (index, Some((width, stated))),
4221 x86_64::Piece::Implicit { reg } => match bound(list, reg, desc.role) {
4222 Some(index) => (index, None),
4223 None => return self.spare(inst, desc),
4224 },
4225 // A register the template named, which belongs to one of the statement's operands when
4226 // a constraint letter put that operand there and to nobody otherwise. Asked in that
4227 // order rather than placed straight away, because `"D" (p)` with `%rdi` in the text is
4228 // the program saying one thing twice, and answering it twice would hand the allocator
4229 // one register holding two values.
4230 x86_64::Piece::Reg { reg, .. } => match bound(list, reg, desc.role) {
4231 Some(index) => (index, None),
4232 None => return self.itself(inst, desc, reg),
4233 },
4234 };
4235 let operand = list.get(index).copied().ok_or_else(refused)?;
4236 // The two halves of an operand written `+`, which arrives in one register and leaves in
4237 // another with the allocator told to make them the same one. Everything else has one of
4238 // the two and asking for the other is the refusal below.
4239 let place = places.get(index).copied().ok_or_else(refused)?;
4240 let reg = match desc.role {
4241 Role::Use => place.read,
4242 Role::Def | Role::EarlyDef => place.write,
4243 }
4244 .ok_or_else(refused)?;
4245
4246 // Read where the opcode reads and written where it writes, which is what the first half of
4247 // this asks. An output has a result and an input has a value, an output written `+` has
4248 // both because it is read before it is written, and an output a matching constraint names
4249 // is read as the input that named it. See [`read_as`].
4250 // An output with neither is read as well, and what it holds there is undefined, which
4251 // [`Self::assembly`] says why and puts a zero in a register for.
4252 let placeable = match desc.role {
4253 Role::Use => read_as(list, index).is_some() || operand.result.is_some(),
4254 Role::Def | Role::EarlyDef => operand.result.is_some(),
4255 };
4256 let ty = match (operand.result, operand.value) {
4257 (Some(result), _) => self.source[result].ty,
4258 (None, Some(value)) => self.source[value].ty,
4259 (None, None) => return Err(refused()),
4260 };
4261 let bits = held_bits(ty);
4262 if !placeable || self.class_of(ty) != desc.class {
4263 return Err(refused());
4264 }
4265 if let Some((width, stated)) = spelled {
4266 // An operand the template wrote a width on may be written by an instruction that fills
4267 // more of the register than the object in it does, and the object is then the low part
4268 // of what was written. That is what gmp asks for when it counts the low zero bits of a
4269 // limb into an `unsigned` and spells the count `%q0`: one quadword instruction writes
4270 // the whole register and the `unsigned` is the bottom of it, which is every bit of an
4271 // answer that cannot exceed sixty four anyway.
4272 //
4273 // An operand read at a width the template wrote is the other way round: the object is
4274 // in the register and the instruction looks at the bottom of it. tcc tests the low bits
4275 // of a `size_t` count with `testb $2,%b4`, and every bit that test reads is one the
4276 // object put there.
4277 //
4278 // A write of less of a register than the object fills is right in one case, which is
4279 // an instruction that reads the register it writes and an operand that arrives with
4280 // the object in it. The top of the register is then the top of the object, and the
4281 // instruction leaves it alone. tcc swaps the bytes of an `unsigned` with `xchgb
4282 // %b0,%h0` and a rotate between two of them, and the swap only ever touches the low
4283 // half.
4284 //
4285 // The two that stay refused are a read of more of a register than its type fills,
4286 // which hands an instruction bits nothing ever put there, and a write of less of one
4287 // that nothing carried the object into, which leaves the top of the object holding
4288 // whatever the register held before. An operand the template left plain is refused
4289 // either way, because what gets spelled for that one is the register at the width of
4290 // its type and no other instruction is the one written down.
4291 let carried = matches!(desc.constraint, Constraint::Reuse(_) | Constraint::Fixed(_))
4292 && read_as(list, index).is_some();
4293 // The other case is the one the machine settles by itself: a write of the low four
4294 // bytes of a register clears the four above them, so a sixty four bit object written
4295 // that way holds the thirty two bit answer and nothing else. tcc loads a word through
4296 // `movl 4(%0),%k0` into a `long` and means exactly that.
4297 let cleared = desc.class == self.gpr && width == x86_64::Width::Long && bits == 64;
4298 let widened = stated && desc.role.is_def() && width.bits() > bits;
4299 let narrowed =
4300 stated && width.bits() < bits && (!desc.role.is_def() || carried || cleared);
4301 if bits != width.bits() && !widened && !narrowed {
4302 return Err(refused());
4303 }
4304 }
4305 // An operand the program pinned is in that register and nowhere else, whatever the opcode
4306 // would have allowed it. That is the whole of what a local register variable asks for, and
4307 // it is the same shape a division already has: the allocator is told the register, puts a
4308 // move in front or behind where it has to, and leaves it out where it does not.
4309 let constraint = match pinned(&operand) {
4310 Some(reg) => Constraint::Fixed(reg),
4311 None => desc.constraint,
4312 };
4313 Ok(mir::Operand { reg, class: desc.class, role: desc.role, constraint })
4314 }
4315
4316 /// A register the template named in its own text.
4317 ///
4318 /// Not one of the statement's operands and not something the allocator handed out. The program
4319 /// wrote `%rbx` in the middle of a template and meant that register, which is what code doing
4320 /// something the constraint letters cannot say is made of: micropython saves the callee-saved
4321 /// registers into a buffer by name because the whole point of the buffer is that those exact
4322 /// registers are in it, and there is no constraint letter for `%rsp`.
4323 ///
4324 /// So it is placed as itself, fixed to the register the template named. What that buys is the
4325 /// thing gcc does not do: the register becomes part of the instruction the allocator sees, so a
4326 /// write of one is a definition it knows about and will not leave anything of the program's
4327 /// across, and a read of one is a use it will not have put something else in first. gcc copies
4328 /// the text out and a register two things believe they own is a wrong program nothing reports.
4329 /// Here the allocator is told, and a program that also named the register in its clobber list
4330 /// says the same thing twice rather than something new.
4331 fn itself(
4332 &mut self,
4333 inst: Inst,
4334 desc: OperandDesc,
4335 reg: PhysReg,
4336 ) -> Result<mir::Operand, Unsupported> {
4337 let refused = Unsupported::Assembly { inst, refused: Written::Operand };
4338 if desc.class != self.gpr {
4339 return Err(refused);
4340 }
4341 Ok(mir::Operand {
4342 reg: mir::Reg::physical(reg),
4343 class: self.gpr,
4344 role: desc.role,
4345 constraint: Constraint::Fixed(reg),
4346 })
4347 }
4348
4349 /// A register an instruction of a template uses and the statement put nothing in.
4350 ///
4351 /// A write of one is the register being destroyed, which is what a clobber list is usually
4352 /// written to say and what an instruction with more answers than the program asked for does
4353 /// anyway: `cpuid` writes all four registers whether or not the statement wanted all four. A
4354 /// register of its own is the whole of what that needs, since a value nothing reads is one the
4355 /// allocator may put anywhere and is told about so that nothing else is put there.
4356 ///
4357 /// A read of one is a register the instruction looks at and the program never filled, which
4358 /// gcc leaves as whatever happened to be there. A zero is written instead, for the reason
4359 /// [`Self::undefined`] gives: the allocator has to be given a definition before a use, and a
4360 /// zero is the one answer that reads the same on every run.
4361 fn spare(&mut self, inst: Inst, desc: OperandDesc) -> Result<mir::Operand, Unsupported> {
4362 let refused = Unsupported::Assembly { inst, refused: Written::Operand };
4363 if desc.class != self.gpr {
4364 return Err(refused);
4365 }
4366 let reg = self.out.new_vreg(desc.class);
4367 if !desc.role.is_def() {
4368 let block = self.at.expect("a block is being filled");
4369 let span = self.source.span(inst);
4370 let put = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_ri_64")));
4371 self.out.build(block, put).at(span).def(reg, desc.class).imm(0).finish();
4372 }
4373 Ok(mir::Operand { reg, class: desc.class, role: desc.role, constraint: desc.constraint })
4374 }
4375
4376 /// The address one instruction of a template reads or writes.
4377 fn addressed(
4378 &mut self,
4379 inst: Inst,
4380 at: x86_64::At,
4381 places: &[Place],
4382 list: &[AsmOperand<'_>],
4383 ) -> Result<mir::Mem, Unsupported> {
4384 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4385 let base = match at.base {
4386 None => None,
4387 Some(x86_64::Piece::Operand { index, .. }) => {
4388 // The register an address is counted from is read and never written, whatever the
4389 // instruction does to what it finds there.
4390 let reg = places.get(index).and_then(|place| place.read).ok_or_else(refused)?;
4391 Some(mir::Operand::read(reg, self.gpr))
4392 }
4393 // A register the template named, counted from as itself. See [`Self::itself`], and note
4394 // that this is the half of it every one of these templates needs: `movq %rax, 16(%rdi)`
4395 // names one register as the thing being stored and another as where to store it. An
4396 // operand a constraint letter put in that register is that operand, for the reason
4397 // [`Self::placed`] gives.
4398 Some(x86_64::Piece::Reg { reg, .. }) => match bound(list, reg, Role::Use) {
4399 Some(index) => {
4400 let reg = places.get(index).and_then(|place| place.read).ok_or_else(refused)?;
4401 Some(mir::Operand::read(reg, self.gpr))
4402 }
4403 None => Some(
4404 mir::Operand::read(mir::Reg::physical(reg), self.gpr)
4405 .with(Constraint::Fixed(reg)),
4406 ),
4407 },
4408 // An address counted from a register the instruction reaches without being told is
4409 // not something this machine has: every addressing mode is written out in the text it
4410 // is part of, so a base that got here another way is a base nothing wrote down.
4411 Some(x86_64::Piece::Implicit { .. }) => return Err(refused()),
4412 };
4413 // A distance the template wrote, or the one in an operand the template pointed at, which is
4414 // the same distance said by something that knows how big a thing is. It has to be a number
4415 // the compiler can read at translation time, since it goes in the instruction rather than
4416 // in a register, and an operand holding anything else is refused rather than put somewhere.
4417 let disp = match at.disp {
4418 x86_64::Disp::Number(disp) => disp,
4419 x86_64::Disp::Operand(index) => {
4420 let value =
4421 list.get(index).and_then(|operand| operand.value).ok_or_else(refused)?;
4422 let number = self.number(value).ok_or_else(refused)?;
4423 i32::try_from(number).map_err(|_| refused())?
4424 }
4425 };
4426 Ok(mir::Mem { base, scale: 1, disp, segment: at.segment, ..mir::Mem::default() })
4427 }
4428
4429 /// The number in that value, for one an `iconst` defined, read at the width of its own type.
4430 ///
4431 /// Signed, because the two things a template asks this for are a distance into an address and
4432 /// the number on an instruction, and both of those are signed wherever they land. A constant
4433 /// whose type is unsigned and whose top bit is set therefore reads as a negative number here,
4434 /// which is the same number and is the reading that fits in the thirty two bits an addressing
4435 /// mode has room for.
4436 fn number(&self, value: Value) -> Option<i128> {
4437 let Def::Result { inst, .. } = self.source[value].def else { return None };
4438 if self.source[inst].opcode != Opcode::IConst {
4439 return None;
4440 }
4441 let Extra::Imm(imm) = self.source[inst].extra else { return None };
4442 let bits = self.source[imm].bits();
4443 let width = self.source[value].ty.bits();
4444 if width == 0 || width > 128 {
4445 return None;
4446 }
4447 let spare = 128 - width;
4448 Some(((bits << spare) as i128) >> spare)
4449 }
4450
4451 /// A register holding a value the program has no claim on, written as a zero.
4452 ///
4453 /// Every other way of saying it costs the same instruction or needs a word the machine IR does
4454 /// not have, and a zero is the one that reads the same on every run.
4455 fn undefined(&mut self, inst: Inst, result: Value) -> Result<(), Unsupported> {
4456 let ty = self.source[result].ty;
4457 let refused = Unsupported::Assembly { inst, refused: Written::Operand };
4458 let bits = held_bits(ty);
4459 if self.class_of(ty) != self.gpr || !matches!(bits, 8 | 16 | 32 | 64) {
4460 return Err(refused);
4461 }
4462 let block = self.at.expect("a block is being filled");
4463 let span = self.source.span(inst);
4464 let reg = self.new_reg(result);
4465 let put = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_ri_{bits}")));
4466 self.out.build(block, put).at(span).def(reg, self.gpr).imm(0).finish();
4467 Ok(())
4468 }
4469
4470 /// Whether a type is the width an address is, which is what makes a cast to or from one free.
4471 fn is_address_width(&self, ty: Type) -> bool {
4472 ty.is_ptr() || (ty.is_int() && ty.bits() == ADDRESS_BITS)
4473 }
4474
4475 /// Where a block goes, which in machine IR is on the block rather than on its terminator.
4476 ///
4477 /// That is why no rule ever names a block: a branch is selected for what it reads and the
4478 /// edges are copied across here, arguments and all. The arguments are read last, after every
4479 /// instruction of the block is written, because an argument that is a constant is
4480 /// materialized where it is first wanted and the end of the block is where an edge wants it.
4481 ///
4482 /// Which is not quite the end. A block that leaves two ways has the branch as its last
4483 /// instruction, and a block that leaves through a register has the indirect jump as its last,
4484 /// and anything appended after either is something it has already jumped past, so a constant
4485 /// materialized here would be a register the block below reads and nothing ever writes. The
4486 /// one that was there is put back on the end when that happened, which is the only reordering
4487 /// anything in this crate does and is why it is remembered before a single argument is read.
4488 fn edges(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
4489 let Some(term) = self.source.terminator(block) else { return Ok(()) };
4490 let leaves =
4491 matches!(self.source[term].opcode, Opcode::BrIf | Opcode::IndirectBr | Opcode::Switch);
4492 let branch = if leaves { self.out.terminator(out) } else { None };
4493
4494 let calls: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
4495 let mut succs = Vec::with_capacity(calls.len());
4496 for call in calls {
4497 let args: Vec<Value> = self.source[call.args].to_vec();
4498 let mut regs = Vec::with_capacity(args.len());
4499 for value in args {
4500 // The address of where the value is rather than the value, for the one type a
4501 // register holds none of. The block on the other side copies the bytes out of it
4502 // into a slot of its own, which is what makes a second edge into the same block
4503 // safe.
4504 let reg = if on_x87(self.source[value].ty) {
4505 self.x87_slot(value)
4506 } else {
4507 self.reg_of(value)?
4508 };
4509 regs.push(reg);
4510 }
4511 succs.push(mir::BlockCall::with(self.out_block(call.block), regs));
4512 }
4513 if let Some(branch) = branch {
4514 if self.out.terminator(out) != Some(branch) {
4515 self.out.remove_inst(branch);
4516 self.out.append_inst(out, branch);
4517 }
4518 }
4519 *self.out.succs_mut(out) = succs;
4520 Ok(())
4521 }
4522
4523 /// The machine IR block an IR block became.
4524 fn out_block(&self, block: Block) -> mir::Block {
4525 self.blocks[block.index()].expect("every block was created before any was filled")
4526 }
4527
4528 /// The parameters of the entry block, which are the function's arguments.
4529 ///
4530 /// They are not block parameters in the machine IR and they cannot be. A block parameter is
4531 /// given its value by a move on the edge into the block, and there is no edge into an entry
4532 /// block, so what arrives in a function is the convention's to say. [`crate::abi`] is what
4533 /// says it.
4534 ///
4535 /// The ones past the last register arrived in the caller's memory and are read out of it, and
4536 /// the loads that read them come back here so that the frame can finish them the way it
4537 /// finishes an `alloca`.
4538 fn arrive(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
4539 let params = self.source[block].params.clone();
4540 // The type of each is the block's answer and what the ABI asks of it is the signature's,
4541 // and the two lists are the same list: a parameter the classification turned into a
4542 // pointer is a pointer in the block too. A block with more parameters than the signature
4543 // names is not one the front end writes, and each of those is taken as a plain value.
4544 let asked: Vec<Abi> = self.source.signature().params.iter().map(|it| it.abi).collect();
4545 let types: Vec<Param> = params
4546 .iter()
4547 .enumerate()
4548 .map(|(index, &value)| {
4549 let abi = asked.get(index).copied().unwrap_or_default();
4550 Param { ty: self.source[value].ty, abi }
4551 })
4552 .collect();
4553 // A save area for a function that takes arguments its signature does not name, which is a
4554 // block of this function's frame on one convention and the shadow space the caller already
4555 // reserved on the other. Which of the two it is is [`varargs::Area::of`]'s answer and
4556 // [`Self::save_area`] is where the difference is spent.
4557 let variadic = self.source.signature().variadic;
4558 let area = variadic.then(|| varargs::Area::of(self.conv));
4559 let arrived = abi::entry(&mut self.out, out, &types, self.conv, self.names, area)
4560 .map_err(|(index, missing)| Unsupported::Argument { index, missing })?;
4561 for (¶m, reg) in params.iter().zip(&arrived.regs) {
4562 self.regs[param.index()] = Some(*reg);
4563 }
4564 if let Some(area) = area {
4565 self.save_area(out, &arrived, area);
4566 }
4567 self.stack.arguments.extend(arrived.stack);
4568 Ok(())
4569 }
4570
4571 /// The prologue of a variadic function, which is every argument register it was handed written
4572 /// into the frame.
4573 ///
4574 /// Every one the signature did not name, that is. Which of those hold anything is a thing only
4575 /// the caller knew and there is nothing here to ask, so all of them are written, and the ones a
4576 /// named parameter took are not, because `va_start` sets the two offsets past them and nothing
4577 /// ever reads their slots.
4578 ///
4579 /// What that costs is up to fourteen stores in the prologue of a function that may read none of
4580 /// them, and the convention's answer to that is the count of vector registers in `%al`, which
4581 /// lets a callee skip the eight vector stores when the call passed no floats. Skipping them is a
4582 /// branch in a prologue, and a prologue is written long after this by [`crate::finish`], which
4583 /// has no blocks to branch between. So they are all written every time, which is correct and is
4584 /// what `-O0` costs. Issue #323 is the branch.
4585 ///
4586 /// A vector register is written all sixteen bytes at a time, because a `_Float128` fills one and
4587 /// a `va_arg` of a quad reads the slot back whole. gcc writes the same sixteen with the same
4588 /// instruction, which is what [`crate::varargs`] says a list has to be built out of.
4589 ///
4590 /// The address is computed once into a register rather than written as a displacement off the
4591 /// stack pointer, because a displacement into a frame is not known until after allocation and
4592 /// one `lea` costs less than a fixup list for a dozen stores. It is the same `lea` an `alloca`
4593 /// gets and [`crate::finish`] fills it in the same way.
4594 ///
4595 /// A convention that homes its register arguments has none of that. Its area is the shadow
4596 /// space the caller reserved above the return address, so there is no object to make and no
4597 /// address to work out: each store reaches into the caller's argument area the way the load of
4598 /// a parameter the registers ran out before does, which is the same waiting list and the same
4599 /// fixup. There are at most four of them and none is a vector register, since a float the
4600 /// signature does not name arrived in a general purpose register too and that is the copy the
4601 /// walk reads.
4602 fn save_area(&mut self, out: mir::Block, arrived: &abi::Arrived, area: varargs::Area) {
4603 if self.conv.shared_positions {
4604 self.varargs = Some(Varargs::Pointer { incoming: arrived.beyond });
4605 let store = mir::Opcode::new(self.names.intern("x64.mov_mr_64"));
4606 for &(reg, class, at) in &arrived.spare {
4607 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
4608 let made =
4609 self.out.build(out, store).uses(reg, class).mem(mir::Mem::at(sp)).finish();
4610 self.stack.arguments.push((made, at));
4611 }
4612 return;
4613 }
4614
4615 let save = self.stack.locals.len();
4616 self.stack.locals.push(Local { size: area.size, align: varargs::VECTOR_SLOT });
4617 self.varargs = Some(Varargs::Fields {
4618 save,
4619 incoming: arrived.beyond,
4620 integers: u32::try_from(arrived.took.0).unwrap_or(0) * area.stride(false),
4621 floats: area.starts_at(true)
4622 + u32::try_from(arrived.took.1).unwrap_or(0) * area.stride(true),
4623 });
4624
4625 let base = self.frame_address(out, save);
4626 for &(reg, class, at) in &arrived.spare {
4627 let name = if class == self.gpr { "x64.mov_mr_64" } else { "x64.movaps_mr" };
4628 let store = mir::Opcode::new(self.names.intern(name));
4629 let up = i32::try_from(at).expect("a register save area under two gigabytes");
4630 let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
4631 self.out.build(out, store).uses(reg, class).mem(mem).finish();
4632 }
4633 }
4634
4635 /// The address of one of the function's stack objects, in a fresh register.
4636 ///
4637 /// Written with nothing in its displacement, because where an object is in a frame is not known
4638 /// until after allocation, and given to [`crate::finish`] to fill in the way an `alloca` is.
4639 fn frame_address(&mut self, out: mir::Block, local: usize) -> mir::Reg {
4640 let reg = self.out.new_vreg(self.gpr);
4641 let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
4642 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
4643 let made = self.out.build(out, lea).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
4644 self.stack.addresses.push((made, local));
4645 reg
4646 }
4647
4648 /// Whether an instruction is one no machine instruction is written for where it stands.
4649 ///
4650 /// Four of them, and none is a lowering decision, which is why none is a rule. A constant is
4651 /// written where a register for it is first wanted rather than where the IR put it, and every
4652 /// reader of one may have folded it into an immediate, in which case nowhere is the right
4653 /// place. A return of nothing has nothing to put anywhere: the epilogue gives the frame back
4654 /// and leaves, and it is appended to every block with no successors long after this has
4655 /// finished, so a return with a value is one instruction here and a return without one is
4656 /// none. Unless the value went back through memory, in which case there is something to put
4657 /// somewhere after all and the IR does not carry it: the address the caller handed over has
4658 /// to be in `rax` on the way out, and [`Lowering::returned`] is what writes that.
4659 ///
4660 /// An unconditional jump is the third, and there is even less of it: the edge is on the
4661 /// block, and whether the block it goes to is the next one and needs no jump at all is the
4662 /// block layout's answer rather than this one's.
4663 ///
4664 /// The fourth is a point control does not arrive at, in both of the forms the IR has for it:
4665 /// the `unreachable` terminator the front end puts at the end of a function whose body can run
4666 /// off the bottom, and the `unreachable_hint` a call to `__builtin_unreachable` becomes. What
4667 /// to write for a place nothing reaches is a question with no wrong answer, and nothing is the
4668 /// smallest one and the one gcc 16.2.0 gives at `-O0`. The terminator leaves the block with no
4669 /// successors, so the epilogue lands at the end of it the way it does on any other block that
4670 /// goes nowhere, and the function cannot fall out of its own last instruction into whatever
4671 /// the assembler puts next.
4672 fn writes_nothing(&self, inst: Inst) -> bool {
4673 let data = &self.source[inst];
4674 match data.opcode {
4675 Opcode::IConst | Opcode::Jump | Opcode::Unreachable | Opcode::UnreachableHint => true,
4676 Opcode::Return => self.source[data.args].is_empty() && self.sret().is_none(),
4677 _ => false,
4678 }
4679 }
4680
4681 /// What every instruction in one block matched, with a set of values nobody may take.
4682 ///
4683 /// Backwards, because an instruction that has been folded into a later one does not get to
4684 /// fold anything into itself: the rule that took it only reached one level down, so what is
4685 /// under it is not in the term the matcher saw and cannot be replaced.
4686 fn decide(&self, insts: &[Inst], refused: &HashSet<Value>) -> Decided {
4687 let mut found: Vec<Option<Match<Term>>> = (0..insts.len()).map(|_| None).collect();
4688 let mut plans: Vec<Option<Plan>> = vec![None; insts.len()];
4689 let mut folded: Vec<Inst> = Vec::new();
4690 for (index, &inst) in insts.iter().enumerate().rev() {
4691 if folded.contains(&inst) {
4692 continue;
4693 }
4694 if let Some((plan, matched)) = self.select(inst, refused) {
4695 folded.extend(self.folds(inst, plan));
4696 found[index] = Some(matched);
4697 plans[index] = Some(plan);
4698 }
4699 }
4700 Decided { found, plans, folded }
4701 }
4702
4703 /// A value some of its readers took and some of them did not, which is the one case folding
4704 /// buys nothing.
4705 ///
4706 /// Folding does not delete the instruction that computed a value for anybody else, so a
4707 /// reader that did not take it still needs it in a register and the instruction stays. The
4708 /// reader that did take it now does that work again. Either all of them take it, in which
4709 /// case nothing is left to read it and the instruction goes, or none of them do.
4710 ///
4711 /// The count is over the whole function rather than over the block, since a value read from
4712 /// another block is read from a register there whatever this block decides. An instruction
4713 /// built by name rather than matched, a call being the one that matters, has no plan and so
4714 /// takes nothing, which is the right answer for it as well.
4715 fn left_alive(&self, insts: &[Inst], plans: &[Option<Plan>]) -> Option<Value> {
4716 let mut taken = vec![0u32; self.uses.len()];
4717 for (&inst, plan) in insts.iter().zip(plans) {
4718 let Some(plan) = plan else { continue };
4719 let args = &self.source[self.source[inst].args];
4720 for (index, &arg) in args.iter().take(MAX_ARGS).enumerate() {
4721 if plan[index] == Shown::Expand {
4722 taken[arg.index()] += 1;
4723 }
4724 }
4725 }
4726 for (&inst, plan) in insts.iter().zip(plans) {
4727 let Some(plan) = plan else { continue };
4728 let args = &self.source[self.source[inst].args];
4729 for (index, &arg) in args.iter().take(MAX_ARGS).enumerate() {
4730 if plan[index] == Shown::Expand && taken[arg.index()] < self.uses[arg.index()] {
4731 return Some(arg);
4732 }
4733 }
4734 }
4735 None
4736 }
4737
4738 /// The rule that fires on an instruction, and what it bound.
4739 ///
4740 /// The plans are tried in order and the first that matches wins, which is the maximal munch
4741 /// `spec/10-backend.md` asks for: a plan that offers more to the matcher is tried before one
4742 /// that offers less.
4743 fn select(&self, inst: Inst, refused: &HashSet<Value>) -> Option<(Plan, Match<Term>)> {
4744 for plan in self.plans(inst, refused) {
4745 let terms = Terms::new(self.source, inst, plan);
4746 if let Some(matched) = TABLE.find(&terms, Term::Root) {
4747 return Some((plan, matched));
4748 }
4749 }
4750 None
4751 }
4752
4753 /// Every way this instruction can be shown to the matcher, most offered first.
4754 fn plans(&self, inst: Inst, refused: &HashSet<Value>) -> Vec<Plan> {
4755 let args = &self.source[self.source[inst].args];
4756 let mut plans = vec![PLAIN];
4757 for (index, &arg) in args.iter().enumerate().take(MAX_ARGS) {
4758 let mut ways = Vec::new();
4759 if self.foldable(inst, arg, refused) {
4760 ways.push(Shown::Expand);
4761 }
4762 if Terms::new(self.source, inst, PLAIN).constant(arg).is_some() {
4763 ways.push(Shown::Const);
4764 }
4765 ways.push(Shown::Reg);
4766 plans = plans
4767 .into_iter()
4768 .flat_map(|plan| {
4769 ways.iter().map(move |&way| {
4770 let mut next = plan;
4771 next[index] = way;
4772 next
4773 })
4774 })
4775 .collect();
4776 }
4777 plans
4778 }
4779
4780 /// Whether an operand may be shown as the instruction that computed it.
4781 ///
4782 /// It has to be in the same block, because a rule that folds one instruction into another
4783 /// moves the work to where the second one is. It has to be something rather than a block
4784 /// parameter, and not a constant, which is shown as a constant instead. And it has to be a
4785 /// value [`Lowering::left_alive`] has not put back, which is how the one reader at a time
4786 /// question is asked here: this says yes to a value with any number of readers, and a value
4787 /// only some of them could take is refused after the fact and asked again.
4788 ///
4789 /// A value with several readers used to be refused outright, on the reasoning that folding
4790 /// does not delete the instruction for anybody else. That reasoning is about the set of
4791 /// readers and was being applied to one reader at a time, which is stricter than it needs to
4792 /// be: when every reader takes it there is nobody left to read it and the instruction goes.
4793 /// An address a store and a load share is the shape that matters, since a memory operand has
4794 /// room for the whole of it and both readers have a memory operand.
4795 fn foldable(&self, into: Inst, value: Value, refused: &HashSet<Value>) -> bool {
4796 let Def::Result { inst, .. } = self.source[value].def else { return false };
4797 if self.source[inst].opcode == Opcode::IConst || refused.contains(&value) {
4798 return false;
4799 }
4800 self.source.block_of(inst).is_some()
4801 && self.source.block_of(inst) == self.source.block_of(into)
4802 }
4803
4804 /// The instructions a match folded into the one it matched.
4805 ///
4806 /// The plan is what says this, not the bindings: a binding is a register or a number either
4807 /// way, and an operand shown as the instruction that computed it is one no rule could have
4808 /// matched without taking that instruction, because the plan offered the matcher nothing
4809 /// else to call it.
4810 fn folds(&self, inst: Inst, plan: Plan) -> Vec<Inst> {
4811 let args = &self.source[self.source[inst].args];
4812 args.iter()
4813 .take(MAX_ARGS)
4814 .enumerate()
4815 .filter(|&(index, _)| plan[index] == Shown::Expand)
4816 .filter_map(|(_, &arg)| match self.source[arg].def {
4817 Def::Result { inst, .. } => Some(inst),
4818 Def::Param { .. } => None,
4819 })
4820 .collect()
4821 }
4822
4823 /// What the IR instruction said about itself that the machine instruction has to keep saying.
4824 ///
4825 /// One flag today. `volatile` says the access happens exactly once and is never moved or
4826 /// merged, and nothing below here can work that out again: a `volatile` load and an ordinary
4827 /// one are the same instruction over the same address, so a pass that puts two accesses
4828 /// together would put these together too. Carried rather than checked here, because the pass
4829 /// that has to refuse is a long way down and this is the last place the answer is known.
4830 ///
4831 /// The instructions this compiler writes for itself get nothing, which is the right answer
4832 /// for all of them: a prologue, a spill and the moves around a call were asked for by the
4833 /// machine rather than by the program.
4834 ///
4835 /// Every access the flag is legal on carries it: the loads and the stores a rule matched,
4836 /// the two ends of a `long double` copy that are the program's own memory, and the compare
4837 /// and exchange and the read modify write. An `asm` statement does not, and it is the one
4838 /// exception on purpose. What the flag says there is that the statement stays even when
4839 /// nothing reads what it wrote, which is a different sentence about a different thing, and
4840 /// every `asm` is already fixed where it stands whether the word was written or not.
4841 fn carried(&self, inst: Inst) -> mir::Flags {
4842 if self.source[inst].flags.contains(Flags::VOLATILE) {
4843 mir::Flags::VOLATILE
4844 } else {
4845 mir::Flags::NONE
4846 }
4847 }
4848
4849 /// Build the machine instruction a match calls for.
4850 fn emit(&mut self, inst: Inst, matched: &Match<Term>) -> Result<(), Unsupported> {
4851 let rule: &Rule = TABLE.rule(matched);
4852 let pieces = rule.replacement;
4853 let Some(Piece::App { head, arity }) = pieces.first() else {
4854 return Err(self.unsupported(inst));
4855 };
4856 let opcode = head.strip_prefix(PREFIX).ok_or_else(|| self.unsupported(inst))?;
4857 let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
4858
4859 let mut read = Read::default();
4860 let mut at = 1;
4861 for _ in 0..*arity {
4862 at = self.read(inst, pieces, at, &matched.bindings, &mut read)?;
4863 }
4864
4865 let descs = form.operands();
4866 let writes = descs.iter().take_while(|desc| desc.role.is_def()).count();
4867 if descs.len() - writes != read.regs.len() {
4868 return Err(self.unsupported(inst));
4869 }
4870
4871 // The first thing the instruction writes is what it computes, and any others are
4872 // registers the machine destroys on the way, which are fresh because nothing else is in
4873 // them and nothing reads them. An instruction that writes nothing at all is one whose
4874 // whole purpose is its effect, which is what a store is, and there is no result to put
4875 // anywhere.
4876 let mut regs = Vec::new();
4877 if writes > 0 {
4878 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
4879 regs.push(self.new_reg(result));
4880 // The rest are the registers the machine destroys on the way, and the class each is in
4881 // is the one the instruction's description gives it rather than a guess, so that an
4882 // instruction that wrecks a register in the other file says so.
4883 regs.extend(descs[1..writes].iter().map(|desc| self.out.new_vreg(desc.class)));
4884 } else if self.source[inst].first_result.is_some() {
4885 // A rule that throws away a value the IR gave a name to would leave every reader of
4886 // that name with nothing to read, so it is a rule this and the target disagree about.
4887 return Err(self.unsupported(inst));
4888 }
4889 regs.extend(read.regs.iter().copied());
4890
4891 let block = self.at.expect("a block is being filled");
4892 let opcode = mir::Opcode::new(self.names.intern(head));
4893 let (span, flags) = (self.source.span(inst), self.carried(inst));
4894 let mut build = self.out.build(block, opcode).at(span).flags(flags);
4895 for (desc, reg) in descs.iter().zip(regs) {
4896 let operand = mir::Operand {
4897 reg,
4898 class: desc.class,
4899 role: desc.role,
4900 constraint: desc.constraint,
4901 };
4902 build = build.operand(operand);
4903 }
4904 if let Some(mem) = read.mem {
4905 build = build.mem(mem);
4906 }
4907 if let Some(imm) = read.imm {
4908 build = build.imm(imm);
4909 }
4910 build.finish();
4911 Ok(())
4912 }
4913
4914 /// Read one argument of a replacement, which is a register, a number or an address.
4915 ///
4916 /// Gives back the position after it, because a replacement is flat and an address takes
4917 /// arguments of its own.
4918 fn read(
4919 &mut self,
4920 inst: Inst,
4921 pieces: &'static [Piece],
4922 at: usize,
4923 bindings: &[Term],
4924 out: &mut Read,
4925 ) -> Result<usize, Unsupported> {
4926 match pieces.get(at) {
4927 Some(Piece::Int(value)) => {
4928 out.imm = i64::try_from(*value).ok();
4929 Ok(at + 1)
4930 }
4931 // A number the rule worked out of the ones it matched rather than one it wrote down,
4932 // which is an immediate once it has been worked out and is read here as one. It gives
4933 // nothing back when a binding it reads is a register, and a replacement that cannot be
4934 // built is a rule this file and the matcher disagree about, which is what `unsupported`
4935 // is for.
4936 Some(Piece::Computed { work, .. }) => {
4937 let matched: Vec<Option<i128>> = bindings
4938 .iter()
4939 .map(|term| match *term {
4940 Term::Num(value) => Some(value),
4941 _ => None,
4942 })
4943 .collect();
4944 let number = work(&matched).ok_or_else(|| self.unsupported(inst))?;
4945 out.imm = i64::try_from(number).ok();
4946 Ok(at + 1)
4947 }
4948 Some(Piece::Var { index, .. }) => {
4949 match bindings.get(*index) {
4950 Some(&Term::Reg(value)) => {
4951 let reg = self.reg_of(value)?;
4952 out.regs.push(reg);
4953 }
4954 Some(&Term::Num(value)) => out.imm = i64::try_from(value).ok(),
4955 // A pattern binds a register or a number and nothing else, so this is a
4956 // rule the matcher and this file disagree about.
4957 _ => return Err(self.unsupported(inst)),
4958 }
4959 Ok(at + 1)
4960 }
4961 Some(Piece::App { head, arity }) => {
4962 let kind = x86_64::address(head).ok_or_else(|| self.unsupported(inst))?;
4963 let mut inner = Read::default();
4964 let mut next = at + 1;
4965 for _ in 0..*arity {
4966 next = self.read(inst, pieces, next, bindings, &mut inner)?;
4967 }
4968 let mem = address(kind, &inner, self.gpr).ok_or_else(|| self.unsupported(inst))?;
4969 out.mem = Some(mem);
4970 Ok(next)
4971 }
4972 None => Err(self.unsupported(inst)),
4973 }
4974 }
4975
4976 /// The register a value is in, materializing it if it is a constant that has not been put in
4977 /// one yet.
4978 ///
4979 /// A constant is written where it is wanted rather than where the IR defined it, and where it
4980 /// is wanted is a block that need not be the one the IR defined it in. So the register holding
4981 /// one is only good inside the block it was written into, and a second block that wants the
4982 /// same constant gets its own. Anything else is a register read where nothing wrote it: the
4983 /// IR guarantees a definition dominates its uses, and this moved the definition.
4984 ///
4985 /// Writing the number again is also the right answer and not merely the safe one. It is one
4986 /// instruction that reads nothing, which is cheaper than holding a register live across a
4987 /// branch for it, and it is what a rematerializing allocator would do with the value anyway.
4988 fn reg_of(&mut self, value: Value) -> Result<mir::Reg, Unsupported> {
4989 let constant = match self.source[value].def {
4990 Def::Result { inst, .. } => {
4991 (self.source[inst].opcode == Opcode::IConst).then_some(inst)
4992 }
4993 Def::Param { .. } => None,
4994 };
4995 let here = self.at.expect("a block is being filled");
4996 if let Some(reg) = self.regs[value.index()] {
4997 if constant.is_none() || self.written[value.index()] == Some(here) {
4998 return Ok(reg);
4999 }
5000 }
5001 if let Some(inst) = constant {
5002 // Cleared so that the register the constant is written into is a new one rather than
5003 // the one the block above wrote, which is still being read up there.
5004 self.regs[value.index()] = None;
5005 // Nothing is refused here. A constant is written on its own, out of the loop over the
5006 // block, and the operands of the rule that writes one are the number and nothing else.
5007 let matched = self
5008 .select(inst, &HashSet::new())
5009 .map(|(_, matched)| matched)
5010 .ok_or_else(|| self.unsupported(inst))?;
5011 self.emit(inst, &matched)?;
5012 // The same mark the loop over the instructions makes, and it has to be made here as
5013 // well because this is the only place a constant is ever selected: the loop skips one
5014 // where the IR wrote it, so a rule that lowers a constant fires from nowhere else and
5015 // would be reported as a rule nothing reaches.
5016 self.fired.mark(matched.rule);
5017 self.written[value.index()] = Some(here);
5018 return Ok(self.regs[value.index()].expect("a constant is written into a register"));
5019 }
5020 Ok(self.new_reg(value))
5021 }
5022
5023 /// Which register file a value of that type lives in.
5024 ///
5025 /// The vector one for the two float widths the machine has scalar instructions for and for the
5026 /// one it only moves, and the general purpose one for everything else. An eighty bit `long
5027 /// double` is in neither, and it is here rather than in the vector class on purpose: it would
5028 /// be put in a register that cannot hold it, and there is no rule that names one, so the
5029 /// instruction computing it is reported. The wrong class would make that a wrong program
5030 /// instead of a refused one.
5031 ///
5032 /// A hundred and twenty eight bit float is in the vector class and fits it exactly, which is
5033 /// the difference. Nothing computes in it, so every arithmetic on one is still reported, and
5034 /// what the class buys is the moves: a register that holds the whole value is a register a
5035 /// spill, a reload and a copy are each one instruction for.
5036 fn class_of(&self, ty: Type) -> RegClass {
5037 if crate::term::in_vector_file(ty) { self.conv.sse_class } else { self.gpr }
5038 }
5039
5040 /// A fresh register for a value, which is what the instruction computing it writes.
5041 ///
5042 /// Any declaration the value is a value of comes with it. Here rather than once at the end over
5043 /// the whole map, because a constant is written again in every block that wants one and the map
5044 /// only remembers the last of those registers, and a local held in a constant is a local that
5045 /// would otherwise be findable in one block of the function and nowhere else.
5046 fn new_reg(&mut self, value: Value) -> mir::Reg {
5047 if let Some(reg) = self.regs[value.index()] {
5048 return reg;
5049 }
5050 let reg = self.out.new_vreg(self.class_of(self.source[value].ty));
5051 self.regs[value.index()] = Some(reg);
5052 let source = self.source;
5053 for decl in source.value_decls(value) {
5054 self.out.named.push((decl, reg));
5055 }
5056 reg
5057 }
5058
5059 fn unsupported(&self, inst: Inst) -> Unsupported {
5060 let data = &self.source[inst];
5061 Unsupported::Inst {
5062 inst,
5063 term: Terms::new(self.source, inst, PLAIN).name(inst),
5064 opcode: data.opcode,
5065 ty: data.first_result.map(|result| self.source[result].ty),
5066 }
5067 }
5068}
5069
5070/// What the arguments of one replacement came to.
5071#[derive(Debug, Default)]
5072struct Read {
5073 regs: Vec<mir::Reg>,
5074 imm: Option<i64>,
5075 mem: Option<mir::Mem>,
5076}
5077
5078/// The addressing mode an address constructor's arguments make.
5079///
5080/// One arm per constructor rather than a question asked of the kind, because what the arguments
5081/// mean is the whole of what tells the four apart: the same register is a base in one and an
5082/// index in another, and the same constant is a scale in one and a displacement in another.
5083fn address(kind: x86_64::Address, read: &Read, gpr: RegClass) -> Option<mir::Mem> {
5084 let mut regs = read.regs.iter().copied().map(|reg| mir::Operand::read(reg, gpr));
5085 match kind {
5086 x86_64::Address::BaseIndexScale => {
5087 let base = regs.next()?;
5088 let index = regs.next()?;
5089 Some(mir::Mem::at(base).indexed(index, u8::try_from(read.imm?).ok()?))
5090 }
5091 x86_64::Address::IndexScale => Some(mir::Mem {
5092 base: None,
5093 index: Some(regs.next()?),
5094 scale: u8::try_from(read.imm?).ok()?,
5095 disp: 0,
5096 symbol: None,
5097 block: None,
5098 table: None,
5099 reach: mir::Reach::Itself,
5100 segment: None,
5101 }),
5102 x86_64::Address::Base => Some(mir::Mem::at(regs.next()?)),
5103 // The rule that writes this has a guard saying the constant fits, so a displacement that
5104 // does not is a rule and a target that disagree rather than a program this cannot compile.
5105 x86_64::Address::BaseOffset => {
5106 Some(mir::Mem { disp: i32::try_from(read.imm?).ok()?, ..mir::Mem::at(regs.next()?) })
5107 }
5108 }
5109}
5110
5111/// The table this selector matches with.
5112///
5113/// One target for now, because one target has a rule file. Which table to use becomes a question
5114/// the moment a second one does, and the answer will be the target the session was given rather
5115/// than a constant here.
5116static TABLE: &Table = &crate::select::x86_64::TABLE;
5117
5118#[cfg(test)]
5119mod tests {
5120 use rucc_ir::{
5121 AsmInfo, Builder, CallInfo, Flags, InstData, MemInfo, MemOrder, Restrict, Signature, Type,
5122 };
5123 use rucc_regalloc::assign::Env;
5124 use rucc_target::x86_64::{FRAME, REGS, SYSV};
5125
5126 use super::*;
5127 use crate::finish::{Convention, finish};
5128 use crate::frame::{Frame, Incoming, Layout};
5129
5130 /// A function of as many 64 bit parameters as the test wants, and the block they are in.
5131 fn blank(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
5132 let mut names = Interner::new();
5133 let mut func = Func::new(names.intern("f"), Signature::new());
5134 let block = func.create_block();
5135 let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
5136 (names, func, block, values)
5137 }
5138
5139 /// An ordinary access: not atomic, and aligned enough that nothing here has an opinion.
5140 /// Neither field reaches selection, which is the point of saying it once here.
5141 fn plain() -> MemInfo {
5142 MemInfo {
5143 size: 0,
5144 align: 1,
5145 order: MemOrder::NotAtomic,
5146 tbaa: None,
5147 owns: 0,
5148 restrict: Restrict::NONE,
5149 }
5150 }
5151
5152 /// What the allocator is given: every integer register the convention offers except two, held
5153 /// back so that a move on an edge has somewhere to break a cycle and a spilled value has
5154 /// somewhere to be read into. Which two does not matter, and holding back the last two the
5155 /// convention would reach for leaves every expectation below unchanged.
5156 fn env() -> Env {
5157 const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
5158 let order: Vec<PhysReg> =
5159 SYSV.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
5160 Env::new().with(x86_64::GPR, &order, &SCRATCH)
5161 }
5162
5163 /// The machine IR text a function lowers to.
5164 fn lower(names: &mut Interner, source: &Func) -> String {
5165 let out = func(source, names, &SYSV, &Elsewhere::default())
5166 .expect("every instruction has a rule");
5167 mir::print_func(&out.func, names, ®S)
5168 }
5169
5170 #[test]
5171 fn an_addition_of_two_registers_is_one_instruction() {
5172 let i32 = Type::int(32);
5173 let (mut names, mut func, block, args) = blank(&[i32, i32]);
5174 let mut build = Builder::new(&mut func, block);
5175 build.binary(Opcode::Add, args[0], args[1], Flags::default());
5176
5177 assert_eq!(
5178 lower(&mut names, &func),
5179 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
5180 %1:gpr($rsi) = x64.arg_val_32\n %2:gpr(reuse 1) = x64.add_rr_32 %0, %1\n}\n"
5181 );
5182 }
5183
5184 #[test]
5185 fn a_constant_operand_becomes_an_immediate() {
5186 let i32 = Type::int(32);
5187 let (mut names, mut func, block, args) = blank(&[i32]);
5188 let mut build = Builder::new(&mut func, block);
5189 let seven = build.iconst(i32, 7);
5190 build.binary(Opcode::Add, args[0], seven, Flags::default());
5191
5192 // The constant is in the instruction and nothing was written to hold it, which is what
5193 // materializing one where a register for it is wanted buys.
5194 assert_eq!(
5195 lower(&mut names, &func),
5196 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
5197 %1:gpr(reuse 1) = x64.add_ri_32 %0, 7\n}\n"
5198 );
5199 }
5200
5201 #[test]
5202 fn a_constant_too_wide_for_an_immediate_goes_into_a_register() {
5203 let i64 = Type::int(64);
5204 let (mut names, mut func, block, args) = blank(&[i64]);
5205 let mut build = Builder::new(&mut func, block);
5206 let big = build.iconst(i64, i128::from(i32::MAX) + 1);
5207 build.binary(Opcode::Add, args[0], big, Flags::default());
5208
5209 // Nobody wrote this fallback down. The rule that takes an immediate has a guard that
5210 // turns a number this wide down, so it does not fire, and the next way of showing the
5211 // operand puts it in a register.
5212 assert_eq!(
5213 lower(&mut names, &func),
5214 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
5215 %1:gpr = x64.mov_ri_64 2147483648\n %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n}\n"
5216 );
5217 }
5218
5219 #[test]
5220 fn an_index_calculation_folds_into_an_address() {
5221 let i64 = Type::int(64);
5222 let (mut names, mut func, block, args) = blank(&[i64, i64]);
5223 let mut build = Builder::new(&mut func, block);
5224 let four = build.iconst(i64, 4);
5225 let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
5226 build.binary(Opcode::Add, args[0], scaled, Flags::default());
5227
5228 // Three IR instructions and one machine instruction. The multiply is gone because the
5229 // rule that matched reached down and took it.
5230 assert_eq!(
5231 lower(&mut names, &func),
5232 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
5233 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr = x64.lea_64 [%0 + %1*4]\n}\n"
5234 );
5235 }
5236
5237 #[test]
5238 fn an_instruction_every_reader_can_take_is_folded_into_all_of_them() {
5239 let i64 = Type::int(64);
5240 let (mut names, mut func, block, args) = blank(&[i64, i64]);
5241 let mut build = Builder::new(&mut func, block);
5242 let four = build.iconst(i64, 4);
5243 let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
5244 let first = build.binary(Opcode::Add, args[0], scaled, Flags::default());
5245 build.binary(Opcode::Add, first, scaled, Flags::default());
5246
5247 // Both readers have room for a scaled index, so both of them take it and nothing is left
5248 // to read the multiply. Three IR instructions become two machine ones, where refusing to
5249 // fold into either reader would have left three.
5250 assert_eq!(
5251 lower(&mut names, &func),
5252 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
5253 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr = x64.lea_64 [%0 + %1*4]\n \
5254 %3:gpr = x64.lea_64 [%2 + %1*4]\n}\n"
5255 );
5256 }
5257
5258 #[test]
5259 fn an_instruction_one_of_its_readers_cannot_take_is_folded_into_none_of_them() {
5260 let i64 = Type::int(64);
5261 let (mut names, mut func, block, args) = blank(&[i64, i64]);
5262 let mut build = Builder::new(&mut func, block);
5263 let four = build.iconst(i64, 4);
5264 let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
5265 build.binary(Opcode::Add, args[0], scaled, Flags::default());
5266 build.store(scaled, args[0], plain(), Flags::default());
5267
5268 // The addition has room for the multiply and the store does not: what a store writes is
5269 // a register, and no rule reaches through it. Folding into the addition alone would
5270 // leave the multiply where it is for the store to read and do the work twice, so the
5271 // multiply is put back and both readers read the register it wrote.
5272 let text = lower(&mut names, &func);
5273 assert!(text.contains("x64.lea_64 [%1*4]"), "{text}");
5274 assert!(text.contains("x64.add_rr_64"), "{text}");
5275 }
5276
5277 #[test]
5278 fn a_shift_by_a_register_asks_for_it_in_cl() {
5279 let i32 = Type::int(32);
5280 let (mut names, mut func, block, args) = blank(&[i32, i32]);
5281 let mut build = Builder::new(&mut func, block);
5282 build.binary(Opcode::Shl, args[0], args[1], Flags::default());
5283
5284 // The fixed register is not in the rule. It is what the target says the instruction does
5285 // with its operands, and the allocator is what will act on it.
5286 let text = lower(&mut names, &func);
5287 assert!(text.contains("x64.shl_rcl_32 %0, %1($rcx)"), "{text}");
5288 }
5289
5290 #[test]
5291 fn a_division_names_the_registers_and_the_register_it_destroys() {
5292 let i32 = Type::int(32);
5293 let (mut names, mut func, block, args) = blank(&[i32, i32]);
5294 let mut build = Builder::new(&mut func, block);
5295 build.binary(Opcode::SDiv, args[0], args[1], Flags::default());
5296
5297 // Two definitions, because a division writes the remainder whether anybody wanted it or
5298 // not, and the second one is early because it is destroyed before the operands are read.
5299 let text = lower(&mut names, &func);
5300 assert!(
5301 text.contains("%2:gpr($rax), early %3:gpr($rdx) = x64.idiv_quo_32 %0($rax), %1"),
5302 "{text}"
5303 );
5304 }
5305
5306 #[test]
5307 fn a_load_reads_through_the_register_the_address_is_in() {
5308 let i64 = Type::int(64);
5309 let (mut names, mut func, block, args) = blank(&[i64]);
5310 let mut build = Builder::new(&mut func, block);
5311 build.load(Type::int(32), args[0], plain(), Flags::default());
5312
5313 assert_eq!(
5314 lower(&mut names, &func),
5315 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
5316 %1:gpr = x64.mov_rm_32 [%0]\n}\n"
5317 );
5318 }
5319
5320 #[test]
5321 fn a_store_writes_no_register_and_the_value_it_writes_is_the_one_the_ir_gave_it() {
5322 let (mut names, mut func, block, args) = blank(&[Type::int(32), Type::int(64)]);
5323 let mut build = Builder::new(&mut func, block);
5324 build.store(args[0], args[1], plain(), Flags::default());
5325
5326 // The value is the first parameter and the address is the second, and the instruction
5327 // takes them the other way round. Getting that backwards would compile to a store of the
5328 // address into the value, which is a program that runs and does the wrong thing.
5329 assert_eq!(
5330 lower(&mut names, &func),
5331 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
5332 %1:gpr($rsi) = x64.arg_val_64\n x64.mov_mr_32 %0, [%1]\n}\n"
5333 );
5334 }
5335
5336 #[test]
5337 fn an_address_with_a_constant_added_folds_into_the_access() {
5338 let i64 = Type::int(64);
5339 let (mut names, mut func, block, args) = blank(&[i64]);
5340 let mut build = Builder::new(&mut func, block);
5341 let twelve = build.iconst(i64, 12);
5342 let field = build.binary(Opcode::Add, args[0], twelve, Flags::default());
5343 build.load(Type::int(64), field, plain(), Flags::default());
5344
5345 // Two IR instructions and one machine instruction, which is what every read of a field
5346 // of a structure comes to.
5347 assert_eq!(
5348 lower(&mut names, &func),
5349 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
5350 %1:gpr = x64.mov_rm_64 [%0 + 12]\n}\n"
5351 );
5352 }
5353
5354 #[test]
5355 fn a_displacement_too_wide_to_encode_leaves_the_addition_where_it_is() {
5356 let i64 = Type::int(64);
5357 let (mut names, mut func, block, args) = blank(&[i64]);
5358 let mut build = Builder::new(&mut func, block);
5359 let big = build.iconst(i64, i128::from(i32::MAX) + 1);
5360 let far = build.binary(Opcode::Add, args[0], big, Flags::default());
5361 build.load(Type::int(32), far, plain(), Flags::default());
5362
5363 // A displacement is signed and 32 bits. The rule that folds one has a guard that turns
5364 // this down, so the addition stays and the load reads through what it produced. Nobody
5365 // wrote that fallback: it is the next way of showing the operand.
5366 let text = lower(&mut names, &func);
5367 assert!(text.contains("x64.mov_rm_32 [%2]"), "{text}");
5368 assert!(text.contains("x64.add_rr_64"), "{text}");
5369 }
5370
5371 #[test]
5372 fn a_store_of_a_value_that_was_loaded_is_two_instructions_and_no_arithmetic() {
5373 let i64 = Type::int(64);
5374 let (mut names, mut func, block, args) = blank(&[i64, i64]);
5375 let mut build = Builder::new(&mut func, block);
5376 let got = build.load(Type::int(8), args[0], plain(), Flags::default());
5377 build.store(got, args[1], plain(), Flags::default());
5378
5379 // A load feeding a store is the one place folding would be wrong: an x86-64 `mov` has at
5380 // most one memory operand, and there is no rule that takes two, so the load is left where
5381 // it is and the store reads the register it wrote.
5382 assert_eq!(
5383 lower(&mut names, &func),
5384 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
5385 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr = x64.mov_rm_8 [%0]\n \
5386 x64.mov_mr_8 %2, [%1]\n}\n"
5387 );
5388 }
5389
5390 #[test]
5391 fn an_access_at_a_width_no_rule_is_written_at_is_reported() {
5392 let i64 = Type::int(64);
5393 let (mut names, mut source, block, args) = blank(&[i64]);
5394 let mut build = Builder::new(&mut source, block);
5395 build.load(Type::int(128), args[0], plain(), Flags::default());
5396
5397 // The width is the whole of what is wrong here, so the width is in the message: `load`
5398 // on its own is written about at every other width and would send a reader looking in
5399 // the wrong place.
5400 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
5401 .expect_err("nothing loads 128 bits");
5402 assert_eq!(failed.to_string(), "no rule lowers a `load` producing a `i128`");
5403 }
5404
5405 #[test]
5406 fn a_return_asks_for_the_value_in_the_register_the_caller_reads() {
5407 let (mut names, mut func, block, args) = blank(&[Type::int(32)]);
5408 let mut build = Builder::new(&mut func, block);
5409 build.ret(&[args[0]]);
5410
5411 // The register is not in the rule, the same way `cl` is not in the rule for a shift. It
5412 // is what the target says the instruction does with its operand, and the allocator is
5413 // what will act on it. There is no `ret` here, because giving the frame back has to
5414 // happen between this and leaving and the frame is not worked out yet.
5415 assert_eq!(
5416 lower(&mut names, &func),
5417 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
5418 x64.ret_val_32 %0($rax)\n}\n"
5419 );
5420 }
5421
5422 #[test]
5423 fn a_return_of_two_values_asks_for_the_second_register_as_well() {
5424 let i64 = Type::int(64);
5425 let (mut names, mut func, block, args) = blank(&[i64, i64]);
5426 let mut build = Builder::new(&mut func, block);
5427 build.ret(&[args[0], args[1]]);
5428
5429 // `struct { long a, b; } f(long a, long b)`, after the front end has classified it. Both
5430 // halves are integers, so the second is in the second integer return register, and both
5431 // pseudos say so the same way the one for a single value does.
5432 assert_eq!(
5433 lower(&mut names, &func),
5434 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
5435 %1:gpr($rsi) = x64.arg_val_64\n x64.ret_val_64 %0($rax)\n \
5436 x64.ret_val2_64 %1($rdx)\n}\n"
5437 );
5438 }
5439
5440 #[test]
5441 fn two_values_back_in_different_files_are_both_the_first_of_their_own() {
5442 let f64 = Type::float(rucc_ir::Float::F64);
5443 let (mut names, mut func, block, args) = blank(&[f64, Type::int(64)]);
5444 let mut build = Builder::new(&mut func, block);
5445 build.ret(&[args[0], args[1]]);
5446
5447 // `struct { double a; long b; } f(double a, long b)`. The two files are counted apart, so
5448 // neither half is the second of anything and the `double` is in `xmm0` rather than in the
5449 // register a second `double` would have been in. Getting this wrong is not a crash: the
5450 // caller reads a register nobody wrote, and this is where that is ruled out.
5451 assert_eq!(
5452 lower(&mut names, &func),
5453 "mfunc @f {\nblock0:\n %0:xmm($xmm0) = x64.arg_val_f64\n \
5454 %1:gpr($rdi) = x64.arg_val_64\n x64.ret_val_f64 %0($xmm0)\n \
5455 x64.ret_val_64 %1($rax)\n}\n"
5456 );
5457 }
5458
5459 #[test]
5460 fn two_of_the_same_file_back_take_the_first_two_of_it() {
5461 let f64 = Type::float(rucc_ir::Float::F64);
5462 let (mut names, mut func, block, args) = blank(&[f64, f64]);
5463 let mut build = Builder::new(&mut func, block);
5464 build.ret(&[args[0], args[1]]);
5465
5466 // `struct { double x, y; } f(double x, double y)`, which is the vector half of the pair
5467 // above and counts in its own file the same way.
5468 assert_eq!(
5469 lower(&mut names, &func),
5470 "mfunc @f {\nblock0:\n %0:xmm($xmm0) = x64.arg_val_f64\n \
5471 %1:xmm($xmm1) = x64.arg_val_f64\n x64.ret_val_f64 %0($xmm0)\n \
5472 x64.ret_val2_f64 %1($xmm1)\n}\n"
5473 );
5474 }
5475
5476 /// A function whose answer goes back through memory, with the pointer to the space for it in
5477 /// front of whatever else it takes. Only the signature says it is one.
5478 fn returning_through_memory(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
5479 let mut names = Interner::new();
5480 let sret = Abi::Sret { size: 32, align: 8 };
5481 let mut signature = Signature::new().and_param(Param::with_abi(Type::PTR, sret));
5482 signature.params.extend(params.iter().copied().map(Param::new));
5483 let mut func = Func::new(names.intern("f"), signature);
5484 let block = func.create_block();
5485 let space = func.append_param(block, Type::PTR);
5486 let values = std::iter::once(space)
5487 .chain(params.iter().map(|&ty| func.append_param(block, ty)))
5488 .collect();
5489 (names, func, block, values)
5490 }
5491
5492 #[test]
5493 fn the_space_a_return_through_memory_was_given_goes_back_in_the_first_return_register() {
5494 let (mut names, mut func, block, _) = returning_through_memory(&[]);
5495 Builder::new(&mut func, block).ret(&[]);
5496
5497 // `struct big f(void)`, where `big` is too large to come back in registers. The `return`
5498 // carries nothing, because the value went into the space the caller handed over, and the
5499 // document still says that address comes back in `rax`. Nothing in the IR says it, so the
5500 // convention says it, and the pseudo is the one any other pointer return would use.
5501 assert_eq!(
5502 lower(&mut names, &func),
5503 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
5504 x64.ret_val_64 %0($rax)\n}\n"
5505 );
5506 }
5507
5508 #[test]
5509 fn what_the_function_did_in_between_does_not_take_the_register_off_it() {
5510 let (mut names, mut func, block, args) = returning_through_memory(&[Type::int(32)]);
5511 let mut build = Builder::new(&mut func, block);
5512 build.store(args[1], args[0], plain(), Flags::default());
5513 build.ret(&[]);
5514
5515 // The register is a read at the end and not a move at the start, so it is live across
5516 // everything between the two and the allocator has to keep it somewhere. In a function
5517 // with a call in it that somewhere is a callee saved register, and the address comes back
5518 // into `rax` here rather than whatever the last instruction happened to leave there. That
5519 // is issue #333, and a store is enough to show the value outlives the entry block.
5520 let text = lower(&mut names, &func);
5521 assert!(text.contains("x64.mov_mr_32 %1, [%0]"), "{text}");
5522 assert!(text.ends_with(" x64.ret_val_64 %0($rax)\n}\n"), "{text}");
5523 }
5524
5525 #[test]
5526 fn a_pointer_that_is_only_a_pointer_is_not_given_back() {
5527 let (mut names, mut func, block, args) = blank(&[Type::PTR]);
5528 let mut build = Builder::new(&mut func, block);
5529 build.store(args[0], args[0], plain(), Flags::default());
5530 build.ret(&[]);
5531
5532 // `void f(void **p)`. It takes a pointer first and returns nothing, which is the shape of
5533 // the one above and none of its meaning, and what tells them apart is the signature. A
5534 // `void` function leaves `rax` alone.
5535 assert!(!lower(&mut names, &func).contains("ret_val"));
5536 }
5537
5538 #[test]
5539 fn a_return_of_a_constant_puts_it_in_a_register_first() {
5540 let (mut names, mut func, block, _) = blank(&[]);
5541 let mut build = Builder::new(&mut func, block);
5542 let zero = build.iconst(Type::int(32), 0);
5543 build.ret(&[zero]);
5544
5545 // No rule returns an immediate, so the plan that offers one is turned down and the next
5546 // one materializes it. That is `int main(void) { return 0; }` in full, once the epilogue
5547 // is appended to it.
5548 assert_eq!(
5549 lower(&mut names, &func),
5550 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_32 0\n x64.ret_val_32 %0($rax)\n}\n"
5551 );
5552 }
5553
5554 #[test]
5555 fn the_rule_that_writes_a_constant_down_is_recorded_as_a_rule_that_fired() {
5556 let (mut names, mut func, block, _) = blank(&[]);
5557 let mut build = Builder::new(&mut func, block);
5558 let zero = build.iconst(Type::int(32), 0);
5559 build.ret(&[zero]);
5560
5561 // The loop over the instructions passes a constant by, because a constant is written where
5562 // a register for it is first wanted rather than where the IR put it. So the only place a
5563 // rule about one is ever selected is the materialization, and a mark made in the loop
5564 // alone would report every rule about a constant as a rule nothing reaches.
5565 let out = super::func(&func, &mut names, &SYSV, &Elsewhere::default())
5566 .expect("every instruction has a rule");
5567 let rules = &crate::select::x86_64::TABLE.rules;
5568 let fired: Vec<&str> = rules
5569 .iter()
5570 .enumerate()
5571 .filter(|(index, _)| out.fired.has(*index))
5572 .map(|(_, rule)| rule.pattern)
5573 .collect();
5574 assert!(fired.contains(&"(iconst.i32 k)"), "{fired:?}");
5575 }
5576
5577 #[test]
5578 fn a_return_of_nothing_is_no_instruction_at_all() {
5579 let (mut names, mut func, block, _) = blank(&[]);
5580 let mut build = Builder::new(&mut func, block);
5581 build.ret(&[]);
5582
5583 // Every part of leaving a function that returns nothing is the epilogue's, and the
5584 // epilogue goes in after allocation. A block with nothing in it is the right answer here
5585 // rather than a function that could not be lowered.
5586 assert_eq!(lower(&mut names, &func), "mfunc @f {\nblock0:\n}\n");
5587 }
5588
5589 #[test]
5590 fn the_allocator_is_what_moves_the_answer_into_the_return_register() {
5591 let (mut names, mut source, block, _) = blank(&[]);
5592 let mut build = Builder::new(&mut source, block);
5593 let zero = build.iconst(Type::int(32), 0);
5594 build.ret(&[zero]);
5595
5596 let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
5597 .expect("every instruction has a rule")
5598 .func;
5599 let env = env();
5600 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
5601 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
5602 finish(
5603 &mut out,
5604 &allocation,
5605 &frame,
5606 &Stack::default(),
5607 Convention::new(&SYSV, &FRAME),
5608 &mut names,
5609 );
5610
5611 // `int main(void) { return 0; }` end to end. Nothing here asked for `rax`: the rule said
5612 // the value goes back, the target said where, and the allocator is what made it true. The
5613 // epilogue is what leaves, and this function needs no frame, so it is the return alone.
5614 //
5615 // Two instructions and no copy, which is what a hint buys. The return insists on `rax`,
5616 // so `rax` is the register the allocator tries first for the value the return reads, and
5617 // the constant is written straight into it.
5618 assert_eq!(
5619 mir::print_func(&out, &names, ®S),
5620 "mfunc @f {\nblock0:\n $rax = x64.mov_ri_32 0\n \
5621 x64.ret_val_32 $rax($rax)\n x64.ret\n}\n"
5622 );
5623 }
5624
5625 #[test]
5626 fn a_function_of_two_arguments_is_a_whole_function_now() {
5627 let i32 = Type::int(32);
5628 let (mut names, mut source, block, args) = blank(&[i32, i32]);
5629 let mut build = Builder::new(&mut source, block);
5630 let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
5631 build.ret(&[sum]);
5632
5633 let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
5634 .expect("every instruction has a rule")
5635 .func;
5636 let env = env();
5637 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
5638 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
5639 finish(
5640 &mut out,
5641 &allocation,
5642 &frame,
5643 &Stack::default(),
5644 Convention::new(&SYSV, &FRAME),
5645 &mut names,
5646 );
5647
5648 // `int f(int a, int b) { return a + b; }` end to end, and this is the test the argument
5649 // side exists for. Before it there was no way to write one: the allocator refuses a
5650 // function whose entry block takes parameters, because there is no edge into an entry
5651 // block for the moves that give a block parameter its value to go on.
5652 //
5653 // One move, and it is the one the machine's addition needs rather than one the allocator
5654 // owes anybody. Each argument stays in the register it arrived in, because the pseudo
5655 // that defines it insists on that register and the allocator now tries it first, and the
5656 // sum stays in the register the addition wrote it to until the return reads it out. The
5657 // copy in front of a two address instruction is what makes its destination one of the
5658 // registers it reads, and the source operand keeps its own name because the destination
5659 // is what the encoder writes.
5660 assert_eq!(
5661 mir::print_func(&out, &names, ®S),
5662 "mfunc @f {\nblock0:\n $rdi($rdi) = x64.arg_val_32\n \
5663 $rsi($rsi) = x64.arg_val_32\n \
5664 $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n $rax = x64.mov_rr_64 $rdi\n \
5665 x64.ret_val_32 $rax($rax)\n x64.ret\n}\n"
5666 );
5667 }
5668
5669 #[test]
5670 fn an_argument_with_no_register_left_for_it_is_read_out_of_the_caller_s_stack() {
5671 let i64 = Type::int(64);
5672 let (mut names, mut source, block, args) = blank(&[i64; 7]);
5673 let mut build = Builder::new(&mut source, block);
5674 build.ret(&[args[6]]);
5675
5676 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
5677 .expect("the seventh is read from memory");
5678
5679 // SysV passes six integers in registers and the seventh in the caller's memory, so six of
5680 // these are pseudos that encode to nothing and the seventh is a load that encodes to real
5681 // bytes. Its displacement is nothing here for the reason a local's is: there is no frame
5682 // yet. What the walk hands on is which instruction is waiting, and for how far up the
5683 // caller's argument area, which is the bottom of it because it is the first one there.
5684 assert_eq!(lowered.stack.arguments.len(), 1);
5685 assert_eq!(lowered.stack.arguments[0].1, 0);
5686 let text = mir::print_func(&lowered.func, &names, ®S);
5687 assert!(text.contains("%6:gpr = x64.mov_rm_64 [$rsp]"), "{text}");
5688 assert_eq!(text.matches("x64.arg_val_64").count(), 6, "{text}");
5689 }
5690
5691 #[test]
5692 fn the_frame_is_what_says_how_far_up_the_caller_s_stack_an_argument_is() {
5693 let i64 = Type::int(64);
5694 let (mut names, mut source, block, args) = blank(&[i64; 8]);
5695 let mut build = Builder::new(&mut source, block);
5696 let sum = build.binary(Opcode::Add, args[6], args[7], Flags::default());
5697 build.ret(&[sum]);
5698
5699 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
5700 .expect("both are read from memory");
5701 let stack = lowered.stack;
5702 let mut out = lowered.func;
5703 let env = env();
5704 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
5705 let layout = stack.layout(Layout::new(&SYSV, REGS));
5706 let frame = Frame::of(&out, &allocation, &layout);
5707 finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
5708
5709 // A leaf that takes no frame, so the stack pointer never moves and the only thing between
5710 // it and the caller's arguments is the return address the call pushed. The seventh
5711 // parameter is at the bottom of the caller's argument area and the eighth is one word
5712 // further up, which is the eight bytes between the two offsets.
5713 let text = mir::print_func(&out, &names, ®S);
5714 assert_eq!(frame.size(), 0);
5715 assert_eq!(frame.incoming(), Incoming::from_stack(8));
5716 assert!(text.contains("x64.mov_rm_64 [$rsp + 8]"), "{text}");
5717 assert!(text.contains("x64.mov_rm_64 [$rsp + 16]"), "{text}");
5718 }
5719
5720 #[test]
5721 fn a_realigned_frame_reaches_the_caller_s_arguments_through_the_frame_pointer() {
5722 let i64 = Type::int(64);
5723 let (mut names, mut source, block, args) = blank(&[i64; 7]);
5724 let wide = slot(&mut source, block, 64, 32);
5725 let mut build = Builder::new(&mut source, block);
5726 build.store(args[6], wide, plain(), Flags::default());
5727 build.ret(&[args[6]]);
5728
5729 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
5730 .expect("every instruction has a rule");
5731 let stack = lowered.stack;
5732 let mut out = lowered.func;
5733 let env = env();
5734 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
5735 let layout = stack.layout(Layout::new(&SYSV, REGS));
5736 let frame = Frame::of(&out, &allocation, &layout);
5737 finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
5738
5739 // A local wanting thirty two byte alignment makes the prologue force the stack pointer,
5740 // which throws away how far the caller's stack was. So the load the lowering wrote off the
5741 // stack pointer is rewritten to read through the frame pointer, at the one distance that
5742 // survives: the word the prologue pushed the frame pointer into, and the return address
5743 // above it.
5744 let text = mir::print_func(&out, &names, ®S);
5745 assert_eq!(frame.realign(), Some(32));
5746 assert_eq!(frame.incoming(), Incoming::from_frame(16));
5747 assert!(text.contains("x64.mov_rm_64 [$rbp + 16]"), "{text}");
5748 assert!(!text.contains("x64.mov_rm_64 [$rsp"), "{text}");
5749 }
5750
5751 #[test]
5752 fn a_jump_is_the_edge_and_nothing_else() {
5753 let i32 = Type::int(32);
5754 let (mut names, mut source, entry, args) = blank(&[i32]);
5755 let next = source.create_block();
5756 let got = source.append_param(next, i32);
5757 Builder::new(&mut source, entry).jump(next, &[args[0]]);
5758 Builder::new(&mut source, next).ret(&[got]);
5759
5760 // Two blocks and two instructions, and the jump is neither of them. What it was is the
5761 // arm on the first block, and what the arm carries is the argument it was called with.
5762 assert_eq!(
5763 lower(&mut names, &source),
5764 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32 block1(%0)\n\n\
5765 block1(%1:gpr):\n x64.ret_val_32 %1($rax)\n}\n"
5766 );
5767 }
5768
5769 /// A block that reads what a block below it writes is filled after it, not before it.
5770 ///
5771 /// The blocks are written entry, `early`, `late`, `exit`, and the entry jumps straight past
5772 /// `early` to `late`, so `late` dominates `early` while sitting below it in the function.
5773 /// Filling them in the order they are written reaches the read in `early` first, and reading
5774 /// a value with no register yet mints one. The cast in `late` is no instruction at all, so
5775 /// what it does is give its answer the register its operand is already in, and that is not
5776 /// the register the read minted. Nothing writes the register the read minted. The printer
5777 /// says `%?` for a register nothing defines, which is what this looks for, and what came out
5778 /// of the real bug was SQLite loading a stack slot no store ever reached.
5779 #[test]
5780 fn a_block_that_reads_what_a_block_below_it_writes_is_filled_after_it() {
5781 let i64 = Type::int(64);
5782 let (mut names, mut source, entry, args) = blank(&[i64, i64]);
5783 let early = source.create_block();
5784 let late = source.create_block();
5785 let exit = source.create_block();
5786
5787 Builder::new(&mut source, entry).jump(late, &[]);
5788 let ptr = cast(&mut source, late, Opcode::IntToPtr, args[0], Type::PTR);
5789 Builder::new(&mut source, early).ret(&[ptr]);
5790 let mut build = Builder::new(&mut source, late);
5791 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
5792 build.br_if(cond, early, &[], exit, &[]);
5793 Builder::new(&mut source, exit).ret(&[args[1]]);
5794
5795 let text = lower(&mut names, &source);
5796 assert!(!text.contains("%?"), "every register has something that writes it: {text}");
5797 }
5798
5799 /// A constant is written where it is wanted rather than where the IR defined it, and two
5800 /// blocks wanting the same one is two places. Writing it once and reading it in both is a
5801 /// register read where nothing wrote it, unless the block it was written in happens to
5802 /// dominate the other, which nothing here checks and which the second arm of a branch never
5803 /// does. Each block gets its own copy of the number instead.
5804 #[test]
5805 fn a_constant_two_blocks_want_is_written_in_both_of_them() {
5806 let i32 = Type::int(32);
5807 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
5808 let then = source.create_block();
5809 let other = source.create_block();
5810 let join = source.create_block();
5811 let got = source.append_param(join, i32);
5812
5813 let mut build = Builder::new(&mut source, entry);
5814 let seven = build.iconst(i32, 7);
5815 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
5816 build.br_if(cond, then, &[], other, &[]);
5817 // Both arms want the seven in a register, because a block argument is never an immediate,
5818 // and neither arm dominates the other.
5819 Builder::new(&mut source, then).jump(join, &[seven]);
5820 Builder::new(&mut source, other).jump(join, &[seven]);
5821 Builder::new(&mut source, join).ret(&[got]);
5822
5823 let text = lower(&mut names, &source);
5824 assert_eq!(text.matches("x64.mov_ri_32 7").count(), 2, "one seven per block: {text}");
5825 }
5826
5827 /// An argument on an edge out of a block that leaves two ways is read after every instruction
5828 /// of the block is written, and reading one can write an instruction, which would land after
5829 /// the branch that has already jumped past it. The branch goes back on the end.
5830 #[test]
5831 fn a_constant_an_edge_wants_is_written_before_the_branch_and_not_after_it() {
5832 let i32 = Type::int(32);
5833 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
5834 let then = source.create_block();
5835 let join = source.create_block();
5836 let got = source.append_param(join, i32);
5837
5838 let mut build = Builder::new(&mut source, entry);
5839 let nine = build.iconst(i32, 9);
5840 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
5841 build.br_if(cond, then, &[], join, &[nine]);
5842 Builder::new(&mut source, then).jump(join, &[args[0]]);
5843 Builder::new(&mut source, join).ret(&[got]);
5844
5845 let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
5846 .expect("every instruction has a rule")
5847 .func;
5848 let entry = out.entry().expect("an entry block");
5849 let last = out.terminator(entry).expect("a block that leaves two ways has a branch");
5850 let branch = names.intern("x64.br_cond_8");
5851 assert_eq!(
5852 out[last].opcode,
5853 mir::Opcode::new(branch),
5854 "the branch is last: {}",
5855 mir::print_func(&out, &names, ®S)
5856 );
5857 }
5858
5859 #[test]
5860 fn a_conditional_branch_is_lowered_to_the_condition_and_nothing_about_where_it_goes() {
5861 let i32 = Type::int(32);
5862 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
5863 let then = source.create_block();
5864 let other = source.create_block();
5865 let mut build = Builder::new(&mut source, entry);
5866 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
5867 build.br_if(cond, then, &[], other, &[]);
5868 Builder::new(&mut source, then).ret(&[args[0]]);
5869 Builder::new(&mut source, other).ret(&[args[1]]);
5870
5871 // The comparison writes a byte and the branch reads it, and neither says a block. Both
5872 // arms are on the entry block, in the order the branch took them, so the arm that runs
5873 // when the condition holds is the first.
5874 assert_eq!(
5875 lower(&mut names, &source),
5876 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
5877 %1:gpr($rsi) = x64.arg_val_32\n %2:gpr = x64.cmp_set_l_32 %0, %1\n \
5878 x64.br_cond_8 %2, block1, block2\n\n\
5879 block1:\n x64.ret_val_32 %0($rax)\n\n\
5880 block2:\n x64.ret_val_32 %1($rax)\n}\n"
5881 );
5882 }
5883
5884 /// A choice between two values, which is one instruction and no blocks at all.
5885 ///
5886 /// The arms come out the other way round from the IR, because a conditional move overwrites its
5887 /// destination and the destination is the arm taken when the condition does not hold. The
5888 /// condition arrives last for the same reason: it is read by the test in front of the move
5889 /// rather than by the move.
5890 #[test]
5891 fn a_select_is_lowered_to_a_test_and_a_conditional_move() {
5892 let i32 = Type::int(32);
5893 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
5894 let mut build = Builder::new(&mut source, entry);
5895 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
5896 let picked = build.select(cond, args[0], args[1]);
5897 build.ret(&[picked]);
5898
5899 assert_eq!(
5900 lower(&mut names, &source),
5901 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
5902 %1:gpr($rsi) = x64.arg_val_32\n %2:gpr = x64.cmp_set_l_32 %0, %1\n \
5903 %3:gpr(reuse 1) = x64.test_cmov_ne_32 %1, %0, %2\n \
5904 x64.ret_val_32 %3($rax)\n}\n"
5905 );
5906 }
5907
5908 #[test]
5909 fn a_branch_over_a_block_is_a_whole_function_now() {
5910 let i32 = Type::int(32);
5911 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
5912 let then = source.create_block();
5913 let other = source.create_block();
5914 let join = source.create_block();
5915 let got = source.append_param(join, i32);
5916 let mut build = Builder::new(&mut source, entry);
5917 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
5918 build.br_if(cond, then, &[], other, &[]);
5919 let mut build = Builder::new(&mut source, then);
5920 let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
5921 build.jump(join, &[sum]);
5922 Builder::new(&mut source, other).jump(join, &[args[1]]);
5923 Builder::new(&mut source, join).ret(&[got]);
5924
5925 // `int f(int a, int b) { if (a < b) return a + b; else return b; }` end to end, written
5926 // the way a front end writes it: both arms of the branch are blocks of their own and the
5927 // return is the block they meet at. No edge here is critical, because the two arms out of
5928 // the entry carry nothing and the two arms into the join each leave a block that goes
5929 // nowhere else, so each has its own end to put its move at.
5930 let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
5931 .expect("every instruction has a rule")
5932 .func;
5933 assert_eq!(crate::split::critical(&mut out), 0, "no edge here is critical");
5934 let env = env();
5935 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
5936 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
5937 finish(
5938 &mut out,
5939 &allocation,
5940 &frame,
5941 &Stack::default(),
5942 Convention::new(&SYSV, &FRAME),
5943 &mut names,
5944 );
5945
5946 // One epilogue, on the join, which is the one block the function leaves from, and the
5947 // moves that give the join its parameter are at the end of each arm. Every register is
5948 // physical and the branch is still a branch on a register, because turning it into a
5949 // `test` and a `jcc` is the block layout's and there is no block layout yet.
5950 let text = mir::print_func(&out, &names, ®S);
5951 assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
5952 assert!(text.contains("x64.br_cond_8"), "{text}");
5953 assert!(text.contains("x64.add_rr_32"), "{text}");
5954 assert!(!text.contains('%'), "{text}");
5955 }
5956
5957 #[test]
5958 fn a_critical_edge_is_split_before_the_allocator_ever_sees_it() {
5959 let i32 = Type::int(32);
5960 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
5961 let then = source.create_block();
5962 let join = source.create_block();
5963 let got = source.append_param(join, i32);
5964 let mut build = Builder::new(&mut source, entry);
5965 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
5966 build.br_if(cond, then, &[], join, &[args[1]]);
5967 Builder::new(&mut source, then).jump(join, &[args[0]]);
5968 let mut build = Builder::new(&mut source, join);
5969 let twice = build.binary(Opcode::Add, got, got, Flags::default());
5970 build.ret(&[twice]);
5971
5972 // The else arm is critical: the entry block leaves two ways and the join is arrived at
5973 // two ways, and the arm carries a value. Without splitting it the allocator asserts,
5974 // because the move that gives the join its parameter would have to run at the end of a
5975 // block that also goes to the other arm.
5976 let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
5977 .expect("every instruction has a rule")
5978 .func;
5979 assert_eq!(crate::split::critical(&mut out), 1);
5980 let env = env();
5981 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
5982 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
5983 finish(
5984 &mut out,
5985 &allocation,
5986 &frame,
5987 &Stack::default(),
5988 Convention::new(&SYSV, &FRAME),
5989 &mut names,
5990 );
5991
5992 // The block the split added is where the move went, and it is the whole of that block.
5993 let text = mir::print_func(&out, &names, ®S);
5994 assert_eq!(out.block_count(), 4, "{text}");
5995 assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
5996 }
5997
5998 #[test]
5999 fn a_call_passes_what_the_convention_says_and_takes_back_what_it_says() {
6000 let i32 = Type::int(32);
6001 let (mut names, mut source, block, args) = blank(&[i32, i32]);
6002 let sig =
6003 source.add_signature(Signature::new().with_params(&[i32, i32]).with_returns(&[i32]));
6004 let callee = names.intern("g");
6005 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0], args[1]]);
6006 let got = source[call].first_result.expect("an integer comes back");
6007 Builder::new(&mut source, block).ret(&[got]);
6008
6009 // `int f(int a, int b) { return g(a, b); }`. The arguments arrived where the call wants
6010 // them, so what the call reads is what arrived, and the whole of the convention is in the
6011 // constraints rather than in a move.
6012 let text = lower(&mut names, &source);
6013 assert!(text.contains("= x64.call %0($rdi), %1($rsi), @g"), "{text}");
6014 assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
6015 // What the call writes is the value that comes back and then every register the callee is
6016 // free to destroy, in both classes, which is the whole of what stops the allocator from
6017 // leaving something in one of them.
6018 assert!(text.contains("%2:gpr($rax), $rcx, $rdx, $r8, $r9, $r10, $r11, $xmm0,"), "{text}");
6019 assert!(text.contains("$xmm15 = x64.call"), "{text}");
6020 }
6021
6022 #[test]
6023 fn what_the_frame_owes_a_call_comes_back_with_the_function() {
6024 let i32 = Type::int(32);
6025 let sig = |source: &mut Func| source.add_signature(Signature::new().with_params(&[i32]));
6026
6027 let (mut names, mut source, block, args) = blank(&[i32]);
6028 let sig = sig(&mut source);
6029 let callee = names.intern("g");
6030 Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
6031 let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
6032 .expect("every instruction has a rule");
6033
6034 // Nothing on the stack, so nothing owed, but not a leaf either: a function that calls
6035 // owes the callee an aligned stack pointer and may not use the red zone.
6036 assert_eq!(out.stack.calls, Some(0));
6037 let layout = out.stack.layout(Layout::new(&SYSV, REGS));
6038 assert!(!layout.leaf);
6039 assert_eq!(layout.outgoing, 0);
6040
6041 // The same call under the other convention owes thirty two bytes for the callee to spill
6042 // its register arguments into, which is a fact about the convention and not about the call.
6043 let out = func(&source, &mut names, &x86_64::WIN64, &Elsewhere::default())
6044 .expect("every instruction has a rule");
6045 assert_eq!(out.stack.calls, Some(32));
6046
6047 // And a function that calls nothing is a leaf, which is what says it may use the red zone.
6048 let (mut names, mut source, block, args) = blank(&[i32]);
6049 Builder::new(&mut source, block).ret(&[args[0]]);
6050 let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
6051 .expect("every instruction has a rule");
6052 assert_eq!(out.stack.calls, None);
6053 assert!(out.stack.layout(Layout::new(&SYSV, REGS)).leaf);
6054 }
6055
6056 /// A Windows variadic prologue writes the argument registers the signature did not name into
6057 /// the shadow space the caller already reserved, which makes every argument one run of words up
6058 /// there and a `va_start` the address of the first of them. One `lea` and one store, and no
6059 /// counts, because a list that is a pointer has nowhere to put one and nothing that reads one.
6060 #[test]
6061 fn a_windows_variadic_function_homes_its_spare_registers_in_the_callers_area() {
6062 let mut names = Interner::new();
6063 let params = [Type::int(32), Type::PTR];
6064 let signature = Signature::new().with_params(¶ms).variadic();
6065 let mut source = Func::new(names.intern("f"), signature);
6066 let block = source.create_block();
6067 let values: Vec<Value> = params.iter().map(|&ty| source.append_param(block, ty)).collect();
6068 let mut build = Builder::new(&mut source, block);
6069 let args = build.func().push_values(&values[1..]);
6070 build.inst(InstData { args, ..InstData::new(Opcode::VaStart) }, &[]);
6071 build.ret(&[]);
6072
6073 let out = func(&source, &mut names, &x86_64::WIN64, &Elsewhere::default())
6074 .expect("every instruction has a rule");
6075 let text = mir::print_func(&out.func, &names, ®S);
6076
6077 // Two named parameters, so the registers at the next two positions hold arguments nobody
6078 // named and both are written up into the caller's area. The displacement is empty here and
6079 // `finish` fills it in, the same way it does for a parameter the registers ran out before.
6080 assert!(text.contains("($r8) = x64.arg_val_64"), "{text}");
6081 assert!(text.contains("($r9) = x64.arg_val_64"), "{text}");
6082 assert_eq!(text.matches("x64.mov_mr_64").count(), 3, "two homed and one stored: {text}");
6083 assert!(!text.contains("x64.mov_ri_32"), "and no field holds a count: {text}");
6084
6085 // All three waiting on the same fixup, and the last of them is the `lea` the list is given,
6086 // sixteen bytes up, which is where the two arguments the signature does name stopped.
6087 assert_eq!(out.stack.arguments.len(), 3);
6088 assert_eq!(out.stack.arguments[2].1, 16);
6089 }
6090
6091 #[test]
6092 fn a_value_that_outlives_a_call_is_not_left_where_the_call_destroys_it() {
6093 let i32 = Type::int(32);
6094 let (mut names, mut source, block, args) = blank(&[i32]);
6095 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
6096 let callee = names.intern("g");
6097 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
6098 let got = source[call].first_result.expect("an integer comes back");
6099 let mut build = Builder::new(&mut source, block);
6100 let sum = build.binary(Opcode::Add, got, args[0], Flags::default());
6101 build.ret(&[sum]);
6102
6103 // `int f(int a) { return g(a) + a; }`, which is the smallest program that asks the
6104 // question: `a` is read after the call and `rdi` is a register the call destroys.
6105 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
6106 .expect("every instruction has a rule");
6107 let layout = lowered.stack.layout(Layout::new(&SYSV, REGS));
6108 let mut out = lowered.func;
6109 let env = env();
6110 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
6111 let frame = Frame::of(&out, &allocation, &layout);
6112 finish(
6113 &mut out,
6114 &allocation,
6115 &frame,
6116 &Stack::default(),
6117 Convention::new(&SYSV, &FRAME),
6118 &mut names,
6119 );
6120
6121 // It went to a register the callee has to put back, and the prologue and epilogue are what
6122 // put it back, which is the whole bargain the two halves of a convention make.
6123 let text = mir::print_func(&out, &names, ®S);
6124 assert!(text.contains("$rbx"), "{text}");
6125 assert!(!text.contains('%'), "{text}");
6126 assert_eq!(text.matches("x64.call").count(), 1, "{text}");
6127 }
6128
6129 #[test]
6130 fn a_call_with_more_arguments_than_registers_writes_the_rest_into_the_outgoing_area() {
6131 let i64 = Type::int(64);
6132 let (mut names, mut source, block, args) = blank(&[i64]);
6133 let seven = vec![i64; 7];
6134 let sig = source.add_signature(Signature::new().with_params(&seven));
6135 let callee = names.intern("g");
6136 let passed = vec![args[0]; 7];
6137 Builder::new(&mut source, block).call(callee, sig, &passed);
6138
6139 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
6140 .expect("the seventh goes to memory");
6141 // The bytes the call needs are on the layout the frame is worked out from, so that the
6142 // frame reserves as many as the widest call in the function asked for.
6143 assert_eq!(lowered.stack.calls, Some(8));
6144 let text = mir::print_func(&lowered.func, &names, ®S);
6145 assert!(text.contains("x64.mov_mr_64 %0, [$rsp]\n"), "{text}");
6146 }
6147
6148 #[test]
6149 fn a_call_this_cannot_make_is_reported_rather_than_made() {
6150 let (mut names, mut source, block, _) = blank(&[]);
6151 let returns = [Type::float(rucc_ir::Float::F80), Type::int(64)];
6152 let sig = source.add_signature(Signature::new().with_returns(&returns));
6153 let callee = names.intern("g");
6154 Builder::new(&mut source, block).call(callee, sig, &[]);
6155 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
6156 .expect_err("a long double is on the x87");
6157 assert_eq!(failed.to_string(), "what this call gives back is on the x87 stack");
6158 }
6159
6160 /// A `long double` on its own is a different answer, because on its own it comes back on the
6161 /// x87 stack rather than in a register, which is somewhere the call cannot be said to write.
6162 ///
6163 /// So the call gives back nothing at all and the value is taken off the stack by the `fstp`
6164 /// straight after it. That instruction has to be straight after it: the stack is one place and
6165 /// anything else that touched it before this ran would be looking at the value still on it.
6166 #[test]
6167 fn a_call_that_gives_back_a_long_double_takes_it_off_the_stack_at_once() {
6168 let (mut names, mut source, block, _) = blank(&[]);
6169 let long_double = Type::float(rucc_ir::Float::F80);
6170 let sig = source.add_signature(Signature::new().with_returns(&[long_double]));
6171 let callee = names.intern("g");
6172 Builder::new(&mut source, block).call(callee, sig, &[]);
6173
6174 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
6175 .expect("the value comes back in st0");
6176 let text = mir::print_func(&lowered.func, &names, ®S);
6177 let after: Vec<&str> =
6178 text.lines().skip_while(|line| !line.contains("x64.call")).skip(1).collect();
6179 assert_eq!(after[0].trim(), "%0:gpr = x64.lea_64 [$rsp]", "{text}");
6180 assert_eq!(after[1].trim(), "x64.fstp_t [%0]", "{text}");
6181 // And the slot it went into is the sixteen bytes the type takes, like every other one.
6182 assert_eq!(lowered.stack.locals.len(), 1, "{text}");
6183 assert_eq!(lowered.stack.locals[0].size, X87_BYTES);
6184 }
6185
6186 #[test]
6187 fn a_call_through_an_address_goes_through_the_register_the_address_is_in() {
6188 let i32 = Type::int(32);
6189 let (mut names, mut source, block, args) = blank(&[Type::PTR, i32]);
6190 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
6191 let varargs = source.push_abis(&[]);
6192 let info = source.add_call(CallInfo { callee: None, signature: sig, varargs });
6193 let mut build = Builder::new(&mut source, block);
6194 let inst = InstData {
6195 args: build.func().push_values(&[args[0], args[1]]),
6196 extra: Extra::Call(info),
6197 ..InstData::new(Opcode::CallIndirect)
6198 };
6199 let called = build.inst(inst, &[i32]);
6200 let got = source[called].first_result.expect("an integer comes back");
6201 Builder::new(&mut source, block).ret(&[got]);
6202
6203 // `int f(int (*g)(int), int a) { return g(a); }`. The first operand is the address and
6204 // the arguments are the ones behind it, and everything else about the call is what a call
6205 // to a name would have been.
6206 let text = lower(&mut names, &source);
6207 assert!(text.contains("= x64.call_reg %0, %1($rdi)"), "{text}");
6208 assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
6209 assert!(!text.contains("@g"), "a call through an address names nobody: {text}");
6210 }
6211
6212 #[test]
6213 fn an_instruction_no_rule_covers_is_reported() {
6214 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
6215 let mut build = Builder::new(&mut source, block);
6216 let operands = build.func().push_values(&[args[0]]);
6217 build.inst(InstData { args: operands, ..InstData::new(Opcode::MetaBegin) }, &[]);
6218
6219 // The mark that an object has come into being, which nothing writes an instruction for
6220 // yet: what it needs is a write over a range of the lifetime plane, and that is
6221 // `tamnd/rucc#856`. Nothing about it is a width or a register, so there is nothing for the
6222 // message to add beyond the name.
6223 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
6224 .expect_err("no rule writes the beginning of a lifetime");
6225 assert_eq!(failed.to_string(), "no rule lowers a `meta_begin`");
6226
6227 // It produces nothing, so there is no type in the message and nothing invents one, and the
6228 // instruction comes back so a caller can ask the function where it was.
6229 let inst = failed.inst().expect("the instruction it is about");
6230 assert_eq!(source[inst].opcode, Opcode::MetaBegin);
6231 }
6232
6233 /// A barrier is written by name here, and what it is depends on the ordering and on nothing
6234 /// else. `crate::expand` is where the reasoning about this machine's memory model lives.
6235 #[test]
6236 fn a_barrier_is_one_instruction_at_the_strongest_ordering_and_none_below_it() {
6237 for order in MemOrder::all().filter(|&order| order != MemOrder::NotAtomic) {
6238 let (mut names, mut source, block, _) = blank(&[]);
6239 let mut build = Builder::new(&mut source, block);
6240 build
6241 .inst(InstData { extra: Extra::Order(order), ..InstData::new(Opcode::Fence) }, &[]);
6242
6243 let text = lower(&mut names, &source);
6244 assert_eq!(text.contains("x64.mfence"), order == MemOrder::SeqCst, "{order:?}: {text}");
6245 }
6246 }
6247
6248 /// A compare and exchange is written by name too, and at the width of the value rather than at
6249 /// the width of the address, which is the mistake worth pinning: everything here is a pointer
6250 /// and only the value says how many bytes the instruction touches.
6251 #[test]
6252 fn a_compare_and_exchange_is_one_instruction_at_the_width_of_the_value() {
6253 for bits in [8, 16, 32, 64] {
6254 let ty = Type::int(bits);
6255 let (mut names, mut source, block, args) = blank(&[Type::PTR, ty, ty]);
6256 let mut build = Builder::new(&mut source, block);
6257 let mem = build.func().add_mem(MemInfo {
6258 size: u64::from(bits / 8),
6259 align: bits / 8,
6260 order: MemOrder::SeqCst,
6261 ..plain()
6262 });
6263 let operands = build.func().push_values(&[args[0], args[1], args[2]]);
6264 build.inst(
6265 InstData {
6266 args: operands,
6267 extra: Extra::Mem(mem),
6268 ..InstData::new(Opcode::Cmpxchg)
6269 },
6270 &[ty, Type::I1],
6271 );
6272
6273 // Two values out of one instruction, the first of them in the register the machine
6274 // reads the expected value out of, the second free for the allocator to place. The
6275 // address is the memory operand and neither of the two values is.
6276 let text = lower(&mut names, &source);
6277 let written = format!("%3:gpr($rax), %4:gpr = x64.cmpxchg_{bits} %1($rax), %2, [%0]");
6278 assert!(text.contains(&written), "{bits}: {text}");
6279 }
6280 }
6281
6282 #[test]
6283 fn more_values_back_than_the_convention_has_registers_for_is_reported() {
6284 let i64 = Type::int(64);
6285 let (mut names, mut source, block, args) = blank(&[i64, i64, i64]);
6286 let mut build = Builder::new(&mut source, block);
6287 build.ret(&[args[0], args[1], args[2]]);
6288
6289 // Two integers come back in `rax` and `rdx` and a third has nowhere to go, which is not a
6290 // gap in the rules but the convention saying no. The front end classifies before it gets
6291 // here, so this is the shape that would mean the classification went wrong.
6292 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
6293 .expect_err("only two come back");
6294 assert_eq!(
6295 failed.to_string(),
6296 "what this function gives back takes more registers than this convention has for it"
6297 );
6298
6299 let inst = failed.inst().expect("the instruction it is about");
6300 assert_eq!(source[inst].opcode, Opcode::Return);
6301 }
6302
6303 /// A refusal about a signature has no instruction, which is what makes it the one arm apart.
6304 ///
6305 /// Everything else is about something written somewhere in the body and hands it back so a
6306 /// caller can ask the function where it came from. A parameter arrives before the first
6307 /// instruction runs, so there is nothing in the body to point at and the message is about
6308 /// the function.
6309 #[test]
6310 fn a_refusal_about_a_parameter_has_no_instruction_to_point_at() {
6311 let missing = Unsupported::Argument { index: 0, missing: Missing::OnX87 };
6312 assert_eq!(missing.inst(), None);
6313 }
6314
6315 /// An `alloca` of a fixed size, which is what every local whose address is taken becomes.
6316 fn slot(source: &mut Func, block: Block, size: u64, align: u32) -> Value {
6317 let info = MemInfo { size, align, ..plain() };
6318 let mut build = Builder::new(source, block);
6319 let mem = build.func().add_mem(info);
6320 build.value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR)
6321 }
6322
6323 #[test]
6324 fn a_local_is_memory_in_the_frame_and_one_instruction_that_says_where() {
6325 let (mut names, mut source, block, _) = blank(&[]);
6326 let slot = slot(&mut source, block, 4, 4);
6327 let mut build = Builder::new(&mut source, block);
6328 let nine = build.iconst(Type::int(32), 9);
6329 build.store(nine, slot, plain(), Flags::default());
6330 let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
6331 build.ret(&[loaded]);
6332
6333 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
6334 .expect("every instruction has a rule");
6335
6336 // Four bytes on the list the frame is laid out from, and the one instruction that reads
6337 // where they went. Its displacement is nothing here because there is no frame yet, and
6338 // which instruction is waiting for which local is what `finish` is handed.
6339 assert_eq!(lowered.stack.locals, vec![Local { size: 4, align: 4 }]);
6340 assert_eq!(lowered.stack.addresses.len(), 1);
6341 assert_eq!(lowered.stack.addresses[0].1, 0);
6342 assert_eq!(
6343 mir::print_func(&lowered.func, &names, ®S),
6344 "mfunc @f {\nblock0:\n %0:gpr = x64.lea_64 [$rsp]\n \
6345 %1:gpr = x64.mov_ri_32 9\n x64.mov_mr_32 %1, [%0]\n \
6346 %2:gpr = x64.mov_rm_32 [%0]\n x64.ret_val_32 %2($rax)\n}\n"
6347 );
6348 }
6349
6350 #[test]
6351 fn a_local_the_program_declared_says_which_declaration_it_is_and_the_rest_say_nothing() {
6352 let (mut names, mut source, block, _) = blank(&[]);
6353 let scratch = slot(&mut source, block, 4, 4);
6354 let mut build = Builder::new(&mut source, block);
6355 let mem = build.func().add_mem(MemInfo { size: 8, align: 8, ..plain() });
6356 let declared = build
6357 .value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR);
6358 build.func().declare_mem(mem, 41);
6359 build.store(scratch, declared, MemInfo { size: 8, align: 8, ..plain() }, Flags::default());
6360 build.ret(&[]);
6361
6362 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
6363 .expect("every instruction has a rule");
6364
6365 // Two locals and one declaration, held against the order the allocas were lowered in,
6366 // which is the only name a local has by the time the frame places it. The scratch one was
6367 // reached first and is local zero, so the declared one is local one.
6368 assert_eq!(lowered.stack.locals.len(), 2);
6369 assert_eq!(lowered.stack.declared, vec![(1, 41)]);
6370 }
6371
6372 /// A local the program kept in a value comes out saying which register holds it.
6373 ///
6374 /// The other half of the local above, which had a slot. This one has none, so what carries the
6375 /// declaration is the register the instruction computing it writes into.
6376 #[test]
6377 fn a_local_the_program_kept_in_a_value_says_which_register_holds_it() {
6378 let (mut names, mut source, block, _) = blank(&[]);
6379 let mut build = Builder::new(&mut source, block);
6380 let nine = build.iconst(Type::int(32), 9);
6381 let ten = build.iconst(Type::int(32), 10);
6382 let sum = build.binary(Opcode::Add, nine, ten, Flags::default());
6383 build.func().declare_value(sum, 41);
6384 build.ret(&[sum]);
6385
6386 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
6387 .expect("every instruction has a rule");
6388
6389 // One pair and not three. The constants are values the program never declared, and a
6390 // register holding one of those is nobody's. The register is the one the addition writes,
6391 // which the listing under it is what pins down.
6392 assert_eq!(lowered.func.named, vec![(41, mir::Reg::virtual_reg(1))]);
6393 assert_eq!(
6394 mir::print_func(&lowered.func, &names, ®S),
6395 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_32 9\n \
6396 %1:gpr(reuse 1) = x64.add_ri_32 %0, 10\n x64.ret_val_32 %1($rax)\n}\n"
6397 );
6398 }
6399
6400 /// A local held in a constant two blocks want is two registers and both of them are it.
6401 ///
6402 /// Why the declaration is written down as each register is handed out rather than once at the
6403 /// end over the map from values to registers. That map remembers the last register a value was
6404 /// written into, and a constant is written again in every block that wants one, so a local held
6405 /// in one would come out findable in the last block of the function and nowhere else.
6406 #[test]
6407 fn a_local_held_in_a_constant_two_blocks_want_is_named_in_both_of_them() {
6408 let i32 = Type::int(32);
6409 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
6410 let then = source.create_block();
6411 let other = source.create_block();
6412 let join = source.create_block();
6413 let got = source.append_param(join, i32);
6414
6415 let mut build = Builder::new(&mut source, entry);
6416 let seven = build.iconst(i32, 7);
6417 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
6418 build.func().declare_value(seven, 41);
6419 build.br_if(cond, then, &[], other, &[]);
6420 Builder::new(&mut source, then).jump(join, &[seven]);
6421 Builder::new(&mut source, other).jump(join, &[seven]);
6422 Builder::new(&mut source, join).ret(&[got]);
6423
6424 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
6425 .expect("every instruction has a rule");
6426
6427 let held = &lowered.func.named;
6428 assert_eq!(held.len(), 2, "one register per block that wanted the seven: {held:?}");
6429 assert!(held.iter().all(|&(decl, _)| decl == 41), "{held:?}");
6430 assert_ne!(held[0].1, held[1].1, "the same register in two blocks: {held:?}");
6431 }
6432
6433 /// A parameter the program declared comes out named too, in the register it arrived in.
6434 ///
6435 /// The case the walk over the map at the end is for. A parameter is put in a register the
6436 /// convention chose rather than in a fresh one, so nothing asks the mint for it and the pair
6437 /// would otherwise never be written down.
6438 #[test]
6439 fn a_parameter_the_program_declared_says_which_register_it_arrived_in() {
6440 let i32 = Type::int(32);
6441 let (mut names, mut source, block, args) = blank(&[i32]);
6442 let mut build = Builder::new(&mut source, block);
6443 build.func().declare_value(args[0], 41);
6444 build.ret(&[args[0]]);
6445
6446 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
6447 .expect("every instruction has a rule");
6448
6449 let held = &lowered.func.named;
6450 assert_eq!(held.len(), 1, "one pair for the one parameter: {held:?}");
6451 assert_eq!(held[0].0, 41);
6452 }
6453
6454 /// A function with nothing declared in it says nothing, which is every function compiled
6455 /// without debugging information asked for.
6456 #[test]
6457 fn a_function_the_front_end_named_nothing_in_names_no_registers() {
6458 let (mut names, mut source, block, _) = blank(&[]);
6459 let mut build = Builder::new(&mut source, block);
6460 let nine = build.iconst(Type::int(32), 9);
6461 build.ret(&[nine]);
6462
6463 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
6464 .expect("every instruction has a rule");
6465 assert!(lowered.func.named.is_empty(), "{:?}", lowered.func.named);
6466 }
6467
6468 #[test]
6469 fn the_frame_is_what_fills_the_address_of_a_local_in() {
6470 let (mut names, mut source, block, _) = blank(&[]);
6471 let slot = slot(&mut source, block, 4, 4);
6472 let mut build = Builder::new(&mut source, block);
6473 let nine = build.iconst(Type::int(32), 9);
6474 build.store(nine, slot, plain(), Flags::default());
6475 let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
6476 build.ret(&[loaded]);
6477
6478 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
6479 .expect("every instruction has a rule");
6480 let stack = lowered.stack;
6481 let mut out = lowered.func;
6482 let env = env();
6483 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
6484 let layout = stack.layout(Layout::new(&SYSV, REGS));
6485 let frame = Frame::of(&out, &allocation, &layout);
6486 finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
6487
6488 // `int f(void) { int x; x = 9; return x; }` with the address of `x` taken, end to end.
6489 // A leaf small enough to live in the red zone takes no frame at all, so the stack pointer
6490 // never moves and the four bytes are below it, which is what the negative offset is. The
6491 // instruction the lowering left with nothing in its displacement now has the answer in it.
6492 let text = mir::print_func(&out, &names, ®S);
6493 assert!(text.contains("$rax = x64.lea_64 [$rsp - 8]"), "{text}");
6494 assert!(!text.contains("x64.sub_ri_64"), "{text}");
6495 assert_eq!(frame.size(), 0);
6496 assert_eq!(frame.local(0), Some(-8));
6497 }
6498
6499 /// An `alloca` whose size is an operand, which is a variable length array.
6500 fn growing(source: &mut Func, block: Block, size: Value, align: u32) -> Value {
6501 let info = MemInfo { size: 0, align, ..plain() };
6502 let mut build = Builder::new(source, block);
6503 let mem = build.func().add_mem(info);
6504 let args = build.func().push_values(&[size]);
6505 build.value(
6506 InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) },
6507 Type::PTR,
6508 )
6509 }
6510
6511 #[test]
6512 fn a_stack_slot_whose_size_is_not_known_until_it_runs_takes_the_bytes_off_the_stack_pointer() {
6513 let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
6514 let slot = growing(&mut source, block, args[0], 16);
6515 Builder::new(&mut source, block).ret(&[slot]);
6516
6517 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
6518 .expect("every instruction has a rule");
6519
6520 // The bytes come off the stack pointer where the declaration stands and the address is
6521 // where the stack pointer then is, which is one subtraction and one `lea` rather than a
6522 // slot the frame laid out. Nothing is on the list of locals, because there is nothing
6523 // about this the frame could place.
6524 let text = mir::print_func(&lowered.func, &names, ®S);
6525 assert!(text.contains("$rsp = x64.sub_rr_64 $rsp, %0"), "{text}");
6526 assert!(text.contains("x64.lea_64 [$rsp]"), "{text}");
6527 assert!(lowered.stack.locals.is_empty(), "{text}");
6528 assert_eq!(lowered.stack.dynamic.len(), 1);
6529 assert!(lowered.stack.grown_at.is_some());
6530 }
6531
6532 #[test]
6533 fn a_growing_slot_wanting_more_alignment_than_the_stack_pointer_has_is_reported() {
6534 let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
6535 let slot = growing(&mut source, block, args[0], 32);
6536 Builder::new(&mut source, block).ret(&[slot]);
6537
6538 // Thirty two is more than a call leaves the stack pointer on, so giving it what it asked
6539 // for means masking the stack pointer after moving it, and after that no constant reaches
6540 // the rest of the frame from the frame pointer either. A second pointer held for the
6541 // purpose is what fixes it and there is not one yet.
6542 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
6543 .expect_err("nothing realigns a frame that grows");
6544 assert_eq!(
6545 failed.to_string(),
6546 "this local wants more alignment than the stack pointer is left on, which needs a \
6547 base register nothing here keeps"
6548 );
6549 }
6550
6551 #[test]
6552 fn a_frame_that_grows_reaches_its_own_locals_through_the_frame_pointer() {
6553 let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
6554 let fixed = slot(&mut source, block, 4, 4);
6555 let mut build = Builder::new(&mut source, block);
6556 let nine = build.iconst(Type::int(32), 9);
6557 build.store(nine, fixed, plain(), Flags::default());
6558 let grown = growing(&mut source, block, args[0], 16);
6559 Builder::new(&mut source, block).ret(&[grown]);
6560
6561 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
6562 .expect("every instruction has a rule");
6563 let stack = lowered.stack;
6564 let mut out = lowered.func;
6565 let env = env();
6566 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
6567 let layout = stack.layout(Layout::new(&SYSV, REGS));
6568 let frame = Frame::of(&out, &allocation, &layout);
6569 finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
6570
6571 // The stack pointer moves in the middle of the function, so the four bytes of the fixed
6572 // local are not a constant away from it any more and the frame pointer is what reaches
6573 // them. The frame keeps one whatever the flags asked for, takes its bytes rather than
6574 // living in the red zone, and the address of the growing slot is off the stack pointer as
6575 // it stands after the subtraction rather than off anything the prologue left.
6576 let text = mir::print_func(&out, &names, ®S);
6577 assert!(frame.grows());
6578 assert!(frame.frame_pointer());
6579 assert!(frame.size() > 0, "{text}");
6580 assert!(text.contains("x64.lea_64 [$rbp"), "{text}");
6581 assert!(text.contains("$rsp = x64.sub_rr_64 $rsp"), "{text}");
6582 assert!(text.contains("x64.lea_64 [$rsp]"), "{text}");
6583 }
6584
6585 #[test]
6586 fn an_address_is_read_written_and_added_to_like_the_integer_it_is() {
6587 let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
6588 let mut build = Builder::new(&mut source, block);
6589 let stepped = build.func().push_values(&[args[0], args[1]]);
6590 let next =
6591 build.value(InstData { args: stepped, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
6592 let loaded = build.load(Type::int(32), next, plain(), Flags::default());
6593 build.ret(&[loaded]);
6594
6595 // `int f(int *p, long i) { return *(int *)((char *)p + i); }`. Nothing about this is new
6596 // in the rule set, which is the point: the two addresses arrive in registers because an
6597 // address is an integer as wide as one, and the arithmetic on them is the add it always
6598 // was, so every rule written about an add reaches it.
6599 //
6600 // The add stays its own instruction here rather than folding into the address the load
6601 // reads from. Two registers with no scale on either is the one addressing mode the rules
6602 // have no load through, because the folds that exist are the displacement one and the
6603 // scaled ones, and this is neither. `crate::fold` is what puts the two together, after
6604 // selection, and this is the pair it is handed.
6605 assert_eq!(
6606 lower(&mut names, &source),
6607 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
6608 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n \
6609 %3:gpr = x64.mov_rm_32 [%2]\n x64.ret_val_32 %3($rax)\n}\n"
6610 );
6611 }
6612
6613 /// The address of a file scope name, which is what every use of a global and every string
6614 /// literal starts from.
6615 fn address_of(source: &mut Func, block: Block, names: &mut Interner, name: &str) -> Value {
6616 let symbol = names.intern(name);
6617 let mut build = Builder::new(source, block);
6618 build.value(
6619 InstData { extra: Extra::Symbol(symbol), ..InstData::new(Opcode::GlobalAddr) },
6620 Type::PTR,
6621 )
6622 }
6623
6624 #[test]
6625 fn the_address_of_a_name_is_one_instruction_carrying_the_name() {
6626 let (mut names, mut source, block, _) = blank(&[]);
6627 let counter = address_of(&mut source, block, &mut names, "counter");
6628 let mut build = Builder::new(&mut source, block);
6629 let loaded = build.load(Type::int(32), counter, plain(), Flags::default());
6630 build.ret(&[loaded]);
6631
6632 // `extern int counter; int f(void) { return counter; }`. The address is an addressing mode
6633 // that names no register and carries the symbol, which is what the assembler writes
6634 // relative to `%rip` and what the object writer leaves a relocation for.
6635 assert_eq!(
6636 lower(&mut names, &source),
6637 "mfunc @f {\nblock0:\n %0:gpr = x64.lea_64 [@counter]\n \
6638 %1:gpr = x64.mov_rm_32 [%0]\n x64.ret_val_32 %1($rax)\n}\n"
6639 );
6640 }
6641
6642 #[test]
6643 fn the_address_of_a_name_outside_the_file_is_read_out_of_the_offset_table() {
6644 let (mut names, mut source, block, _) = blank(&[]);
6645 let away = address_of(&mut source, block, &mut names, "away");
6646 Builder::new(&mut source, block).ret(&[away]);
6647 let elsewhere: Elsewhere = [names.intern("away")].into_iter().collect();
6648
6649 // `extern void away(void); void *f(void) { return away; }`. A load and not an address
6650 // computation, because the distance from here to a name a shared library may be the one
6651 // that defines is not a number any link can work out, and the slot the linker fills in is
6652 // in this program and so is a distance it has.
6653 let out =
6654 func(&source, &mut names, &SYSV, &elsewhere).expect("every instruction has a rule");
6655 assert_eq!(
6656 mir::print_func(&out.func, &names, ®S),
6657 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rm_64 [got @away]\n \
6658 x64.ret_val_64 %0($rax)\n}\n"
6659 );
6660 }
6661
6662 #[test]
6663 fn the_address_of_a_thread_local_is_an_offset_out_of_the_table_plus_where_this_thread_starts() {
6664 let (mut names, mut source, block, _) = blank(&[]);
6665 let own = address_of(&mut source, block, &mut names, "own");
6666 Builder::new(&mut source, block).ret(&[own]);
6667 let elsewhere = Elsewhere::default().with_threads([names.intern("own")]);
6668
6669 // `extern _Thread_local int own; void *f(void) { return &own; }`. Three instructions where
6670 // the two cases above are one, because there is no address to load or to work out: the
6671 // slot holds how far into a thread's block the variable sits, `%fs:0` is where this
6672 // thread's block starts, and the sum of the two is this thread's copy.
6673 let out =
6674 func(&source, &mut names, &SYSV, &elsewhere).expect("every instruction has a rule");
6675 assert_eq!(
6676 mir::print_func(&out.func, &names, ®S),
6677 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rm_64 [thread @own]\n \
6678 %1:gpr = x64.mov_rm_64 [fs:0]\n %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n \
6679 x64.ret_val_64 %2($rax)\n}\n"
6680 );
6681 }
6682
6683 /// The same load with nothing added to it, which is the whole of `__builtin_thread_pointer`.
6684 #[test]
6685 fn the_start_of_this_thread_s_own_storage_is_the_one_load_and_no_arithmetic() {
6686 let (mut names, mut source, block, _) = blank(&[]);
6687 let here =
6688 Builder::new(&mut source, block).value(InstData::new(Opcode::ThreadPointer), Type::PTR);
6689 Builder::new(&mut source, block).ret(&[here]);
6690
6691 let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
6692 .expect("every instruction has a rule");
6693 assert_eq!(
6694 mir::print_func(&out.func, &names, ®S),
6695 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rm_64 [fs:0]\n \
6696 x64.ret_val_64 %0($rax)\n}\n"
6697 );
6698 }
6699
6700 /// One `asm` statement, with its template and its constraint list written as a program does.
6701 fn assembly(
6702 source: &mut Func,
6703 block: Block,
6704 names: &mut Interner,
6705 template: &str,
6706 constraints: &str,
6707 args: &[Value],
6708 results: &[Type],
6709 ) -> Inst {
6710 clobbering(source, block, names, template, constraints, "memory", args, results)
6711 }
6712
6713 /// The same with a clobber list of its own, for the statements that are about one.
6714 #[allow(clippy::too_many_arguments)]
6715 fn clobbering(
6716 source: &mut Func,
6717 block: Block,
6718 names: &mut Interner,
6719 template: &str,
6720 constraints: &str,
6721 clobbers: &str,
6722 args: &[Value],
6723 results: &[Type],
6724 ) -> Inst {
6725 let info = AsmInfo {
6726 template: names.intern(template),
6727 constraints: names.intern(constraints),
6728 clobbers: names.intern(clobbers),
6729 targets: rucc_ir::BlockCallList::EMPTY,
6730 };
6731 Builder::new(source, block).inline_asm(info, args, results, Flags::VOLATILE)
6732 }
6733
6734 /// What a program asking the processor what it can do writes, which is the instruction whose
6735 /// every operand is a register its text does not name.
6736 #[test]
6737 fn a_template_whose_registers_are_named_by_the_constraints_places_them_from_the_letters() {
6738 let u32 = Type::int(32);
6739 let (mut names, mut source, block, _) = blank(&[]);
6740 let zero = Builder::new(&mut source, block).iconst(u32, 0);
6741 let out = clobbering(
6742 &mut source,
6743 block,
6744 &mut names,
6745 "cpuid",
6746 "=a,a",
6747 "ebx,ecx,edx",
6748 &[zero],
6749 &[u32],
6750 );
6751 let produced = source[out].results().next().expect("one result");
6752 Builder::new(&mut source, block).ret(&[produced]);
6753
6754 // `asm ("cpuid" : "=a" (n) : "a" (0) : "ebx", "ecx", "edx")`, which is the first thing
6755 // every program that has a faster path on some machines writes. Four registers written and
6756 // two read, none of them in the template, all of them out of the description, and the two
6757 // that the letters named are the statement's own. The subleaf is a zero because the
6758 // instruction reads `ecx` and the program said nothing about what is in it. The three
6759 // clobbers are gone because `cpuid` writes those three anyway, and saying it twice is one
6760 // register with two definitions.
6761 assert_eq!(
6762 lower(&mut names, &source),
6763 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_32 0\n \
6764 %1:gpr = x64.mov_ri_64 0\n \
6765 %2:gpr($rax), %3:gpr($rbx), %4:gpr($rcx), %5:gpr($rdx) = x64.cpuid %0($rax), \
6766 %1($rcx)\n x64.ret_val_32 %2($rax)\n}\n"
6767 );
6768 }
6769
6770 /// An operand the program pinned, by declaring the object it comes from `register long x asm
6771 /// ("r12")`. The letter on its own leaves the allocator to pick, and a template that reads the
6772 /// register by name needs the two to be the same register, so the brace is what ties them
6773 /// together. That is the one use of a local register variable the GNU manual calls reliable,
6774 /// and it is what tcc's `tests/tcctest.c` counts on.
6775 #[test]
6776 fn an_operand_the_program_pinned_is_placed_in_the_register_it_named() {
6777 let u64 = Type::int(64);
6778 let (mut names, mut source, block, _) = blank(&[]);
6779 let out =
6780 assembly(&mut source, block, &mut names, "mov $0x4542, %r12", "=r{r12}", &[], &[u64]);
6781 let produced = source[out].results().next().expect("one result");
6782 Builder::new(&mut source, block).ret(&[produced]);
6783
6784 // The template is one instruction the table already has, so it lowers to that instruction
6785 // rather than to text nobody read, and the register it names is the statement's own output
6786 // because the brace put the output there. Without the brace the letter would have let the
6787 // allocator pick, the two `%r12` would have been different registers, and the program would
6788 // have come back with whatever was in the one it picked.
6789 assert_eq!(
6790 lower(&mut names, &source),
6791 "mfunc @f {\nblock0:\n %0:gpr($r12) = x64.mov_ri_64 17730\n \
6792 x64.ret_val_64 %0($rax)\n}\n"
6793 );
6794 }
6795
6796 /// A clobber the instruction does not write itself, which is the case the list is there for.
6797 /// It goes on as a definition of the register, in among the other definitions, because that is
6798 /// the whole of how a machine function says a register is not worth anything after this.
6799 #[test]
6800 fn a_clobber_the_instruction_does_not_write_itself_is_a_definition_of_that_register() {
6801 let (mut names, mut source, block, _) = blank(&[]);
6802 clobbering(&mut source, block, &mut names, "pause", "", "rsi,cc,memory", &[], &[]);
6803 Builder::new(&mut source, block).ret(&[]);
6804
6805 assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n $rsi = x64.pause\n}\n");
6806 }
6807
6808 /// A clobber naming something this has no register for. Refused rather than dropped, since the
6809 /// list is the program saying which registers it may not leave anything in, and an entry
6810 /// nobody read is a register something may still be left in.
6811 #[test]
6812 fn a_clobber_this_has_no_register_for_is_refused() {
6813 let (mut names, mut source, block, _) = blank(&[]);
6814 clobbering(&mut source, block, &mut names, "pause", "", "zmm0", &[], &[]);
6815 Builder::new(&mut source, block).ret(&[]);
6816
6817 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
6818 .expect_err("there is no such register here");
6819 assert_eq!(
6820 failed.to_string(),
6821 "this `asm` says it destroys a register this has no name for"
6822 );
6823 }
6824
6825 #[test]
6826 fn an_asm_with_an_empty_template_and_no_operands_is_no_instructions() {
6827 let (mut names, mut source, block, _) = blank(&[]);
6828 assembly(&mut source, block, &mut names, "", "", &[], &[]);
6829 Builder::new(&mut source, block).ret(&[]);
6830
6831 // `asm volatile ("" : : : "memory")`, which is a barrier and nothing else. The barrier was
6832 // spent on the optimizer, which has finished by now, so what is left is nothing.
6833 assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n}\n");
6834 }
6835
6836 #[test]
6837 fn an_output_an_input_is_tied_to_is_the_register_that_input_arrived_in() {
6838 let i32 = Type::int(32);
6839 let (mut names, mut source, block, args) = blank(&[i32]);
6840 let out = assembly(&mut source, block, &mut names, "", "=r,0", &args, &[i32]);
6841 let produced = source[out].results().next().expect("one result");
6842 Builder::new(&mut source, block).ret(&[produced]);
6843
6844 // `asm ("" : "=r" (x) : "0" (x))`, which is how a program stops the optimizer following a
6845 // value without changing it. The two share a place and the template writes nothing over
6846 // it, so the value comes back out of the register it went in.
6847 assert_eq!(
6848 lower(&mut names, &source),
6849 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
6850 x64.ret_val_32 %0($rax)\n}\n"
6851 );
6852 }
6853
6854 #[test]
6855 fn an_output_written_plus_is_the_same_rename() {
6856 let i32 = Type::int(32);
6857 let (mut names, mut source, block, args) = blank(&[i32]);
6858 let out = assembly(&mut source, block, &mut names, "", "+r", &args, &[i32]);
6859 let produced = source[out].results().next().expect("one result");
6860 Builder::new(&mut source, block).ret(&[produced]);
6861
6862 // `asm ("" : "+r" (x))`, which says the same thing in one operand instead of two.
6863 assert_eq!(
6864 lower(&mut names, &source),
6865 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
6866 x64.ret_val_32 %0($rax)\n}\n"
6867 );
6868 }
6869
6870 #[test]
6871 fn an_output_nothing_is_tied_to_is_a_zero() {
6872 let i32 = Type::int(32);
6873 let (mut names, mut source, block, _) = blank(&[]);
6874 let out = assembly(&mut source, block, &mut names, "", "=r", &[], &[i32]);
6875 let produced = source[out].results().next().expect("one result");
6876 Builder::new(&mut source, block).ret(&[produced]);
6877
6878 // `asm ("" : "=r" (y))`, whose answer is whatever the assembly left in the register, and
6879 // an empty template leaves nothing. A definite value rather than a register nothing wrote,
6880 // because the allocator is owed a definition before the use however little the program is.
6881 assert_eq!(
6882 lower(&mut names, &source),
6883 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_32 0\n x64.ret_val_32 %0($rax)\n}\n"
6884 );
6885 }
6886
6887 #[test]
6888 fn a_template_that_is_one_instruction_becomes_that_instruction() {
6889 let (mut names, mut source, block, _) = blank(&[]);
6890 assembly(&mut source, block, &mut names, "pause", "", &[], &[]);
6891 Builder::new(&mut source, block).ret(&[]);
6892
6893 // `asm volatile ("pause")`, which is what every spin lock in every allocator writes. One
6894 // instruction, no operands, and nothing between the template and the machine but the table
6895 // that already says what a `pause` is.
6896 assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n x64.pause\n}\n");
6897 }
6898
6899 #[test]
6900 fn a_template_that_reads_a_segment_becomes_the_load_it_already_was() {
6901 let i64 = Type::int(64);
6902 let (mut names, mut source, block, _) = blank(&[]);
6903 let out = assembly(&mut source, block, &mut names, "movq %%fs:0, %0", "=r", &[], &[i64]);
6904 let produced = source[out].results().next().expect("one result");
6905 Builder::new(&mut source, block).ret(&[produced]);
6906
6907 // `asm ("movq %%fs:0, %0" : "=r" (tid))`, which is how a program finds the block its own
6908 // thread owns. The same instruction `crate::lower` already writes for a thread-local
6909 // variable, reached this time because a program wrote it out by hand.
6910 assert_eq!(
6911 lower(&mut names, &source),
6912 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rm_64 [fs:0]\n \
6913 x64.ret_val_64 %0($rax)\n}\n"
6914 );
6915 }
6916
6917 /// A template this cannot read is kept as its text, which is what gcc does with every template.
6918 /// Whether the text is an instruction is the assembler's question, asked when the unit is
6919 /// assembled from its listing.
6920 #[test]
6921 fn a_template_naming_an_instruction_this_machine_has_not_got_is_kept_as_text() {
6922 let (mut names, mut source, block, _) = blank(&[]);
6923 assembly(&mut source, block, &mut names, "hcf", "", &[], &[]);
6924 Builder::new(&mut source, block).ret(&[]);
6925
6926 let printed = lower(&mut names, &source);
6927 assert!(printed.contains("x64.template"), "{printed}");
6928 assert!(printed.contains("@hcf"), "{printed}");
6929 }
6930
6931 /// A template kept as text with an operand in a register is refused, since nothing here spells
6932 /// a register into the text yet, and the refusal is about the template.
6933 #[test]
6934 fn a_template_kept_as_text_with_an_operand_in_a_register_is_refused() {
6935 let i32 = Type::int(32);
6936 let (mut names, mut source, block, args) = blank(&[i32]);
6937 assembly(&mut source, block, &mut names, "hcf %0", "r", &[args[0]], &[]);
6938 Builder::new(&mut source, block).ret(&[]);
6939
6940 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
6941 .expect_err("a register is not spelled into kept text");
6942 assert_eq!(
6943 failed.to_string(),
6944 "this `asm` has instructions in its template, which nothing here assembles"
6945 );
6946 }
6947
6948 /// A register the template named is placed as itself, fixed to the register the program wrote
6949 /// down. A register a constraint letter names is a different thing and is placed too, which the
6950 /// test above is about: there the statement said which of its own operands is in the register,
6951 /// and a name in the middle of a template says the register and nothing about any operand.
6952 #[test]
6953 fn a_template_naming_a_register_gets_that_register() {
6954 let i64 = Type::int(64);
6955 let (mut names, mut source, block, _) = blank(&[]);
6956 let out = assembly(&mut source, block, &mut names, "movq %%rax, %0", "=r", &[], &[i64]);
6957 let produced = source[out].results().next().expect("one result");
6958 Builder::new(&mut source, block).ret(&[produced]);
6959
6960 // `asm ("movq %%rax, %0" : "=r" (x))`, which is a program reading whatever is in `%rax`.
6961 // The source is the register itself and the destination is one the allocator picks.
6962 assert_eq!(
6963 lower(&mut names, &source),
6964 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rr_64 $rax($rax)\n \
6965 x64.ret_val_64 %0($rax)\n}\n"
6966 );
6967 }
6968
6969 /// The half of the same thing every register saving template needs. micropython writes the
6970 /// callee-saved registers into a buffer one `movq %%r12, 48(%%rdi)` at a time, and both halves
6971 /// of that line are a register the template named: the one being stored and the one the address
6972 /// is counted from.
6973 #[test]
6974 fn a_template_counting_an_address_from_a_register_it_named_gets_that_register() {
6975 let (mut names, mut source, block, _) = blank(&[]);
6976 assembly(&mut source, block, &mut names, "movq %%r12, 48(%%rdi)", "", &[], &[]);
6977 Builder::new(&mut source, block).ret(&[]);
6978
6979 assert_eq!(
6980 lower(&mut names, &source),
6981 "mfunc @f {\nblock0:\n x64.mov_mr_64 $r12($r12), [$rdi + 48]\n}\n"
6982 );
6983 }
6984
6985 /// A local kept in a named register, which is the same register named as itself and reached
6986 /// from the other side. micropython's collector writes six of these and reads them with
6987 /// ordinary C rather than with a template.
6988 #[test]
6989 fn a_local_kept_in_a_named_register_is_one_move_out_of_it() {
6990 let (mut names, mut source, block, _) = blank(&[]);
6991 let held = names.intern("rbx");
6992 let value = Builder::new(&mut source, block).value(
6993 InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
6994 Type::int(64),
6995 );
6996 Builder::new(&mut source, block).ret(&[value]);
6997
6998 assert_eq!(
6999 lower(&mut names, &source),
7000 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rr_64 $rbx($rbx)\n \
7001 x64.ret_val_64 %0($rax)\n}\n"
7002 );
7003 }
7004
7005 /// The sigil gcc allows in front of the name is syntax and comes off, and a name that is not
7006 /// a register of this machine is refused in words that say which name it was.
7007 #[test]
7008 fn a_register_name_is_read_with_or_without_its_sigil_and_refused_when_there_is_no_such_one() {
7009 for written in ["%r12", "r12"] {
7010 let (mut names, mut source, block, _) = blank(&[]);
7011 let held = names.intern(written);
7012 let value = Builder::new(&mut source, block).value(
7013 InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
7014 Type::int(64),
7015 );
7016 Builder::new(&mut source, block).ret(&[value]);
7017 assert!(lower(&mut names, &source).contains("$r12($r12)"), "{written} is not read");
7018 }
7019
7020 let (mut names, mut source, block, _) = blank(&[]);
7021 let held = names.intern("nowhere");
7022 let value = Builder::new(&mut source, block).value(
7023 InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
7024 Type::int(64),
7025 );
7026 Builder::new(&mut source, block).ret(&[value]);
7027
7028 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
7029 .expect_err("there is no such register");
7030 assert_eq!(
7031 failed.to_string(),
7032 "this object is kept in `nowhere`, which is not a register this machine has"
7033 );
7034 }
7035
7036 #[test]
7037 fn a_constraint_list_that_does_not_describe_the_operands_is_refused() {
7038 let i32 = Type::int(32);
7039 let (mut names, mut source, block, args) = blank(&[i32]);
7040 assembly(&mut source, block, &mut names, "", "=r", &args, &[]);
7041 Builder::new(&mut source, block).ret(&[]);
7042
7043 // An output with no result to be, which is what the front end never writes and what a
7044 // hand written module can. Refused rather than placed by a guess.
7045 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
7046 .expect_err("the list and the instruction disagree");
7047 assert_eq!(failed.to_string(), "this `asm` has an operand this cannot place");
7048 }
7049
7050 /// A cast between a pointer and an integer, at whatever width the result is asked for.
7051 fn cast(source: &mut Func, block: Block, opcode: Opcode, from: Value, to: Type) -> Value {
7052 let mut build = Builder::new(source, block);
7053 let args = build.func().push_values(&[from]);
7054 build.value(InstData { args, ..InstData::new(opcode) }, to)
7055 }
7056
7057 #[test]
7058 fn a_cast_between_a_pointer_and_an_integer_as_wide_is_no_instruction_at_all() {
7059 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
7060 let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(64));
7061 Builder::new(&mut source, block).ret(&[number]);
7062
7063 // `long f(void *p) { return (long)p; }`. An address on this machine is an integer as wide
7064 // as the machine addresses, so the cast changes what the type system calls the value and
7065 // changes nothing about the value, and the register holding it is the one that held it.
7066 assert_eq!(
7067 lower(&mut names, &source),
7068 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
7069 x64.ret_val_64 %0($rax)\n}\n"
7070 );
7071 }
7072
7073 #[test]
7074 fn a_null_pointer_is_a_constant_that_reaches_a_register_before_anything_reads_it() {
7075 let (mut names, mut source, block, _) = blank(&[]);
7076 let mut build = Builder::new(&mut source, block);
7077 let zero = build.iconst(Type::int(64), 0);
7078 let null = cast(&mut source, block, Opcode::IntToPtr, zero, Type::PTR);
7079 Builder::new(&mut source, block).ret(&[null]);
7080
7081 // `void *f(void) { return 0; }`. The cast is nothing, and reading its operand is what
7082 // writes the zero down: a constant is materialized where it is wanted rather than where
7083 // the IR defined it, and without the read there would be no instruction at all.
7084 assert_eq!(
7085 lower(&mut names, &source),
7086 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_64 0\n x64.ret_val_64 %0($rax)\n}\n"
7087 );
7088 }
7089
7090 #[test]
7091 fn the_five_linkages_the_ir_has_narrow_to_the_three_an_object_file_can_say() {
7092 let readings = [
7093 (Linkage::External, mir::Binding::Global),
7094 (Linkage::Common, mir::Binding::Global),
7095 (Linkage::Internal, mir::Binding::Local),
7096 (Linkage::Weak, mir::Binding::Weak),
7097 (Linkage::LinkOnce, mir::Binding::Weak),
7098 ];
7099 for (linkage, wanted) in readings {
7100 let (mut names, mut source, block, _) = blank(&[]);
7101 source.linkage = linkage;
7102 Builder::new(&mut source, block).ret(&[]);
7103 let out = func(&source, &mut names, &SYSV, &Elsewhere::default()).expect("a return");
7104 // The narrowing is done here rather than where the object is written, because a
7105 // machine function is all the assembler and the writer are ever handed.
7106 assert_eq!(out.func.binding, wanted, "{linkage:?}");
7107 }
7108 }
7109
7110 /// The visibility makes the same trip and is not narrowed on the way, because ELF says all
7111 /// three of them.
7112 ///
7113 /// Here for the reason the linkage above is here. A machine function is the whole of what the
7114 /// assembler and the object writer are handed, so a fact about the symbol that does not get
7115 /// onto one is a fact that is gone by the time anything could write it down, and the way that
7116 /// shows up is a shared library exporting the wrong set of names with nothing said anywhere.
7117 #[test]
7118 fn the_visibility_survives_the_trip_from_the_ir_to_a_machine_function() {
7119 let readings = [
7120 (Visibility::Default, mir::Visibility::Default),
7121 (Visibility::Hidden, mir::Visibility::Hidden),
7122 (Visibility::Protected, mir::Visibility::Protected),
7123 ];
7124 for (visibility, wanted) in readings {
7125 let (mut names, mut source, block, _) = blank(&[]);
7126 source.visibility = visibility;
7127 Builder::new(&mut source, block).ret(&[]);
7128 let out = func(&source, &mut names, &SYSV, &Elsewhere::default()).expect("a return");
7129 assert_eq!(out.func.visibility, wanted, "{visibility:?}");
7130 }
7131 }
7132
7133 #[test]
7134 fn a_cast_between_a_pointer_and_a_narrower_integer_is_reported() {
7135 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
7136 let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(32));
7137 Builder::new(&mut source, block).ret(&[number]);
7138
7139 // The front end never writes one: it casts at the address width and truncates or extends
7140 // around it, so both of those are the rules they always were. IR from somewhere else that
7141 // does write one is refused rather than compiled to a move that keeps the high half.
7142 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
7143 .expect_err("no rule narrows an address");
7144 assert_eq!(failed.to_string(), "no rule lowers a `ptrtoint` producing a `i32`");
7145 }
7146
7147 /// The type this machine has no register for.
7148 fn long_double() -> Type {
7149 Type::float(rucc_ir::Float::F80)
7150 }
7151
7152 #[test]
7153 fn a_double_widened_and_narrowed_again_goes_out_through_the_frame_and_back() {
7154 let f64 = Type::float(rucc_ir::Float::F64);
7155 let (mut names, mut source, block, args) = blank(&[f64]);
7156 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
7157 let back = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
7158 Builder::new(&mut source, block).ret(&[back]);
7159
7160 // `double f(double d) { long double x = d; return x; }`. The x87 reads memory and nothing
7161 // else, so the value is written to the crossing slot, loaded at the format that widens it
7162 // and put in the slot the eighty bit value lives in. Coming back is the same three the
7163 // other way. Both slots are addressed by a `lea` with nothing in it yet, which is what
7164 // every address in a frame looks like here until `finish` has the numbers.
7165 assert_eq!(
7166 lower(&mut names, &source),
7167 "mfunc @f {\nblock0:\n \
7168 %0:xmm($xmm0) = x64.arg_val_f64\n \
7169 %1:gpr = x64.lea_64 [$rsp]\n \
7170 %2:gpr = x64.lea_64 [$rsp]\n \
7171 x64.movsd_mr %0, [%1]\n \
7172 x64.fld_l [%1]\n \
7173 x64.fstp_t [%2]\n \
7174 %3:gpr = x64.lea_64 [$rsp]\n \
7175 %4:gpr = x64.lea_64 [$rsp]\n \
7176 x64.fld_t [%3]\n \
7177 x64.fstp_l [%4]\n \
7178 %5:xmm = x64.movsd_rm [%4]\n \
7179 x64.ret_val_f64 %5($xmm0)\n}\n"
7180 );
7181 }
7182
7183 #[test]
7184 fn a_long_double_has_sixteen_bytes_of_its_own_and_keeps_them() {
7185 let f64 = Type::float(rucc_ir::Float::F64);
7186 let (mut names, mut source, block, args) = blank(&[f64]);
7187 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
7188 let once = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
7189 let twice = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
7190 let mut build = Builder::new(&mut source, block);
7191 let sum = build.binary(Opcode::FAdd, once, twice, Flags::default());
7192 build.ret(&[sum]);
7193
7194 let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
7195 .expect("every instruction is written");
7196
7197 // Two slots and not four: sixteen bytes for the one eighty bit value, which is what the
7198 // psABI says one takes and is aligned to, and eight for the crossing, which every group
7199 // in the function shares because nothing is ever left in it. The value's slot is its own
7200 // for the whole function, so reading it twice reads the same sixteen bytes.
7201 assert_eq!(
7202 out.stack.locals,
7203 vec![Local { size: 8, align: 8 }, Local { size: 16, align: 16 }]
7204 );
7205 }
7206
7207 #[test]
7208 fn an_integer_becomes_a_long_double_by_being_loaded_as_one() {
7209 let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
7210 let wide = cast(&mut source, block, Opcode::SIToFP, args[0], long_double());
7211 let back =
7212 cast(&mut source, block, Opcode::FPTrunc, wide, Type::float(rucc_ir::Float::F64));
7213 Builder::new(&mut source, block).ret(&[back]);
7214
7215 // `double f(long n) { long double x = n; return x; }`. `fild` is the same push at another
7216 // format, so the conversion is the load and there is no instruction that converts.
7217 let text = lower(&mut names, &source);
7218 assert!(text.contains("x64.mov_mr_64 %0, [%1]"), "{text}");
7219 assert!(text.contains("x64.fild_ll [%1]"), "{text}");
7220 }
7221
7222 #[test]
7223 fn a_long_double_becoming_an_integer_cuts_towards_zero_with_the_control_word() {
7224 let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
7225 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
7226 let whole = cast(&mut source, block, Opcode::FPToSI, wide, Type::int(32));
7227 Builder::new(&mut source, block).ret(&[whole]);
7228
7229 // The one conversion here with no single instruction behind it. C cuts towards zero and
7230 // the unit rounds the way its control word says, so the word is saved, ORed with the two
7231 // bits that mean truncate, loaded, used and put back. Nine instructions for what `fisttp`
7232 // does in one, and `spec/10-backend.md` section 10.8 says why that one is not used.
7233 let text = lower(&mut names, &source);
7234 let group: Vec<&str> = text
7235 .lines()
7236 .map(str::trim)
7237 .filter(|line| line.starts_with("x64.f") || line.contains("_16"))
7238 .collect();
7239 assert_eq!(
7240 group,
7241 [
7242 "x64.fld_l [%1]",
7243 "x64.fstp_t [%2]",
7244 "x64.fnstcw [%5]",
7245 "%6:gpr = x64.mov_rm_16 [%5]",
7246 "%7:gpr(reuse 1) = x64.or_ri_16 %6, 3072",
7247 "x64.mov_mr_16 %7, [%5 + 2]",
7248 "x64.fldcw [%5 + 2]",
7249 "x64.fld_t [%3]",
7250 "x64.fistp_l [%4]",
7251 "x64.fldcw [%5]",
7252 ],
7253 "{text}"
7254 );
7255 }
7256
7257 #[test]
7258 fn a_long_double_is_read_and_written_as_the_bits_it_already_is() {
7259 let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::PTR]);
7260 let mut build = Builder::new(&mut source, block);
7261 let value = build.load(long_double(), args[0], plain(), Flags::default());
7262 build.store(value, args[1], plain(), Flags::default());
7263 build.ret(&[]);
7264
7265 // `void f(long double *a, long double *b) { *b = *a; }`. A copy is a push and a pop at the
7266 // format the value is already in, which neither converts nor looks: a signalling NaN stays
7267 // one and nothing is raised, which is the whole of what makes it a copy.
7268 let text = lower(&mut names, &source);
7269 let group: Vec<&str> =
7270 text.lines().map(str::trim).filter(|line| line.starts_with("x64.f")).collect();
7271 assert_eq!(
7272 group,
7273 ["x64.fld_t [%0]", "x64.fstp_t [%2]", "x64.fld_t [%3]", "x64.fstp_t [%1]"],
7274 "{text}"
7275 );
7276 }
7277
7278 /// Two `long double` values, from two `double` parameters, and the instructions that made
7279 /// them, which every test below this one throws away.
7280 fn two_long_doubles(source: &mut Func, block: Block, args: &[Value]) -> (Value, Value) {
7281 let left = cast(source, block, Opcode::FPExt, args[0], long_double());
7282 let right = cast(source, block, Opcode::FPExt, args[1], long_double());
7283 (left, right)
7284 }
7285
7286 /// The x87 instructions of a function, in order, with everything else dropped.
7287 fn stack_only(text: &str) -> Vec<&str> {
7288 text.lines().map(str::trim).filter(|line| line.contains("x64.f")).collect()
7289 }
7290
7291 /// The two frame slots the last two addresses of a function were taken of, which in a
7292 /// comparison are the two operands in the order they go on the stack.
7293 fn pushed(out: &Lowered) -> Vec<usize> {
7294 let taken: Vec<usize> = out.stack.addresses.iter().map(|&(_, local)| local).collect();
7295 taken[taken.len() - 2..].to_vec()
7296 }
7297
7298 #[test]
7299 fn adding_two_long_doubles_pushes_both_and_leaves_the_answer_in_a_slot() {
7300 let f64 = Type::float(rucc_ir::Float::F64);
7301 let (mut names, mut source, block, args) = blank(&[f64, f64]);
7302 let (left, right) = two_long_doubles(&mut source, block, &args);
7303 let sum =
7304 Builder::new(&mut source, block).binary(Opcode::FAdd, left, right, Flags::default());
7305 let back = cast(&mut source, block, Opcode::FPTrunc, sum, f64);
7306 Builder::new(&mut source, block).ret(&[back]);
7307
7308 // `double f(double a, double b) { return (long double) a + (long double) b; }`. The last
7309 // four lines are the add: both operands pushed, the instruction that names neither of
7310 // them because they are the top two of a stack, and the answer taken off into its slot.
7311 let text = lower(&mut names, &source);
7312 assert_eq!(
7313 stack_only(&text),
7314 [
7315 "x64.fld_l [%2]",
7316 "x64.fstp_t [%3]",
7317 "x64.fld_l [%4]",
7318 "x64.fstp_t [%5]",
7319 "x64.fld_t [%6]",
7320 "x64.fld_t [%7]",
7321 "x64.fadd_p",
7322 "x64.fstp_t [%8]",
7323 "x64.fld_t [%9]",
7324 "x64.fstp_l [%10]",
7325 ],
7326 "{text}"
7327 );
7328 }
7329
7330 #[test]
7331 fn a_subtraction_pushes_the_left_operand_first_and_asks_for_the_att_spelling() {
7332 let f64 = Type::float(rucc_ir::Float::F64);
7333 let (mut names, mut source, block, args) = blank(&[f64, f64]);
7334 let (left, right) = two_long_doubles(&mut source, block, &args);
7335 let less =
7336 Builder::new(&mut source, block).binary(Opcode::FSub, left, right, Flags::default());
7337 let back = cast(&mut source, block, Opcode::FPTrunc, less, f64);
7338 Builder::new(&mut source, block).ret(&[back]);
7339
7340 // The left one goes on first, so it ends up under the right one, and the answer wanted is
7341 // the one below minus the top. In AT&T that is `fsubrp`, since `fsubp` there is `DE E0+i`
7342 // and computes the other one. The `r` says which spelling this is and not which order the
7343 // pushes were in. `crates/rucc/tests/x87.rs` is what says the answer is right, because a
7344 // name is what got this wrong the first time.
7345 let text = lower(&mut names, &source);
7346 assert_eq!(
7347 &stack_only(&text)[4..8],
7348 ["x64.fld_t [%6]", "x64.fld_t [%7]", "x64.fsubr_p", "x64.fstp_t [%8]"],
7349 "{text}"
7350 );
7351 }
7352
7353 #[test]
7354 fn negating_a_long_double_turns_the_sign_over_and_reads_nothing() {
7355 let f64 = Type::float(rucc_ir::Float::F64);
7356 let (mut names, mut source, block, args) = blank(&[f64]);
7357 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
7358 let flipped = Builder::new(&mut source, block).unary(Opcode::FNeg, wide, long_double());
7359 let back = cast(&mut source, block, Opcode::FPTrunc, flipped, f64);
7360 Builder::new(&mut source, block).ret(&[back]);
7361
7362 // `fchs` and not a subtraction from zero, which would give a different answer at a negative
7363 // zero and would signal at a NaN. It does not read the value as a number at all.
7364 let text = lower(&mut names, &source);
7365 assert_eq!(
7366 &stack_only(&text)[2..5],
7367 ["x64.fld_t [%3]", "x64.fchs", "x64.fstp_t [%4]"],
7368 "{text}"
7369 );
7370 }
7371
7372 #[test]
7373 fn comparing_two_long_doubles_puts_the_left_one_on_top() {
7374 let f64 = Type::float(rucc_ir::Float::F64);
7375 let (mut names, mut source, block, args) = blank(&[f64, f64]);
7376 let (left, right) = two_long_doubles(&mut source, block, &args);
7377 let mut build = Builder::new(&mut source, block);
7378 build.fcmp(FloatPred::Ogt, left, right, Flags::default());
7379 build.ret(&[]);
7380
7381 // `a > b`. `fucomip` asks about the top of the stack against what is under it, so the
7382 // operand the predicate is about has to go on last, which is the other way round from the
7383 // arithmetic above. The pop that clears the loser and the byte that reads the flags are
7384 // both inside the one opcode.
7385 let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
7386 .expect("every instruction is written");
7387 let slots = pushed(&out);
7388 assert_eq!(slots, [2, 1], "the right operand goes on first and the left one on top");
7389 let text = mir::print_func(&out.func, &names, ®S);
7390 assert_eq!(
7391 &stack_only(&text)[4..],
7392 ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
7393 "{text}"
7394 );
7395 }
7396
7397 #[test]
7398 fn a_comparison_that_the_machine_has_backwards_swaps_the_two_pushes() {
7399 let f64 = Type::float(rucc_ir::Float::F64);
7400 let (mut names, mut source, block, args) = blank(&[f64, f64]);
7401 let (left, right) = two_long_doubles(&mut source, block, &args);
7402 let mut build = Builder::new(&mut source, block);
7403 build.fcmp(FloatPred::Olt, left, right, Flags::default());
7404 build.ret(&[]);
7405
7406 // `a < b` is `b > a` and this machine has the one condition, so the same opcode runs with
7407 // the operands the other way round. The same trade the vector rules make, and it has to
7408 // be the same one: a `long double` comparison that picked a different condition from the
7409 // `double` comparison of the same two numbers would be wrong at exactly the unordered
7410 // cases the two conditions differ on.
7411 //
7412 // Which slot each push names is the whole of the difference from the test above, and the
7413 // text does not show it, since an address in a frame is a `lea` with nothing in it until
7414 // `finish` has the numbers. So the slots are what is read here.
7415 let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
7416 .expect("every instruction is written");
7417 let slots = pushed(&out);
7418 assert_eq!(slots, [1, 2], "the left operand goes on first and the right one on top");
7419 let text = mir::print_func(&out.func, &names, ®S);
7420 assert_eq!(
7421 &stack_only(&text)[4..],
7422 ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
7423 "{text}"
7424 );
7425 }
7426
7427 #[test]
7428 fn an_ordered_equal_needs_a_second_byte_to_put_the_two_conditions_together() {
7429 let f64 = Type::float(rucc_ir::Float::F64);
7430 let (mut names, mut source, block, args) = blank(&[f64, f64]);
7431 let (left, right) = two_long_doubles(&mut source, block, &args);
7432 let mut build = Builder::new(&mut source, block);
7433 build.fcmp(FloatPred::Oeq, left, right, Flags::default());
7434 build.ret(&[]);
7435
7436 // Equal and ordered are two conditions and the flags carry both, so the opcode writes a
7437 // second register as well as the one the value is in and ANDs them together. Said here by
7438 // handing it a spare, since an instruction that wrote a register nothing knew about would
7439 // be an instruction the allocator could put a live value in the way of.
7440 let text = lower(&mut names, &source);
7441 assert!(text.contains("%8:gpr, %9:gpr = x64.fucomip_set_e_and_np"), "{text}");
7442 }
7443
7444 #[test]
7445 fn a_comparison_that_is_never_asked_is_reported() {
7446 let f64 = Type::float(rucc_ir::Float::F64);
7447 let (mut names, mut source, block, args) = blank(&[f64, f64]);
7448 let (left, right) = two_long_doubles(&mut source, block, &args);
7449 let mut build = Builder::new(&mut source, block);
7450 build.fcmp(FloatPred::False, left, right, Flags::default());
7451 build.ret(&[]);
7452
7453 // Always false is a constant and not a comparison, so there is no condition to pick and
7454 // nothing here folds it into one: an instruction that quietly agreed with it would hide
7455 // that the optimizer left a comparison in that it should have taken out.
7456 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
7457 .expect_err("no condition is always false");
7458 assert_eq!(failed.to_string(), "no rule lowers a `fcmp` producing a `i1`");
7459 }
7460
7461 #[test]
7462 fn a_long_double_constant_is_the_bits_of_it_put_where_the_value_lives() {
7463 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
7464 let mut build = Builder::new(&mut source, block);
7465 // `1.5L`, which is the leading bit and one more of significand, and an exponent of zero.
7466 let one_and_a_half = build.fconst(long_double(), 0x3fff_c000_0000_0000_0000);
7467 build.store(one_and_a_half, args[0], plain(), Flags::default());
7468 build.ret(&[]);
7469
7470 // No x87 instruction at all. A slot holding one of these is the value, so a constant is
7471 // its ten bytes written where the value lives, and whatever reads it does the `fld`.
7472 let text = lower(&mut names, &source);
7473 assert!(text.contains("x64.mov_ri_64 -4611686018427387904"), "{text}");
7474 assert!(text.contains("x64.mov_ri_16 16383"), "{text}");
7475 assert!(text.contains("x64.mov_mr_16 %3, [%1 + 8]"), "{text}");
7476 // The six bytes above the ten are the padding that makes the type sixteen wide, and they
7477 // are unspecified rather than zero, so nothing writes them.
7478 assert_eq!(text.matches("x64.mov_mr").count(), 2, "{text}");
7479 }
7480
7481 #[test]
7482 fn a_negative_long_double_constant_keeps_the_bit_above_its_exponent() {
7483 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
7484 let mut build = Builder::new(&mut source, block);
7485 let minus = build.fconst(long_double(), 0xbfff_c000_0000_0000_0000);
7486 build.store(minus, args[0], plain(), Flags::default());
7487 build.ret(&[]);
7488
7489 // `-1.5L`. The sign is the top bit of the two byte half, so the immediate that half is put
7490 // in a register with is above the signed range of sixteen bits and has to stay there: read
7491 // as a number it would be negative, and it is not a number, it is two bytes.
7492 let text = lower(&mut names, &source);
7493 assert!(text.contains("x64.mov_ri_16 49151"), "{text}");
7494 }
7495
7496 #[test]
7497 fn a_long_double_crosses_an_edge_as_an_address_and_is_copied_where_it_lands() {
7498 let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
7499 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
7500 let next = source.create_block();
7501 let param = source.append_param(next, long_double());
7502 Builder::new(&mut source, block).jump(next, &[wide]);
7503 Builder::new(&mut source, next).ret(&[param]);
7504
7505 // What the edge carries is the address of the slot the value is already in, which is an
7506 // ordinary register the allocator has an opinion about. The block on the other side copies
7507 // the sixteen bytes into a slot of its own before anything reads them, so a second edge
7508 // handing over a second address would still leave one place for a reader to look.
7509 let text = lower(&mut names, &source);
7510 let second: Vec<&str> = text
7511 .lines()
7512 .skip_while(|line| !line.starts_with("block1"))
7513 .skip(1)
7514 .take(3)
7515 .map(str::trim)
7516 .collect();
7517 assert_eq!(
7518 second,
7519 ["x64.fld_t [%4]", "%5:gpr = x64.lea_64 [$rsp]", "x64.fstp_t [%5]"],
7520 "{text}"
7521 );
7522 }
7523
7524 #[test]
7525 fn more_long_doubles_at_a_block_than_the_stack_is_deep_are_reported() {
7526 let f64 = Type::float(rucc_ir::Float::F64);
7527 let (mut names, mut source, block, args) = blank(&[f64]);
7528 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
7529 let next = source.create_block();
7530 let params: Vec<Value> =
7531 (0..=X87_DEPTH).map(|_| source.append_param(next, long_double())).collect();
7532 let carried: Vec<Value> = params.iter().map(|_| wide).collect();
7533 Builder::new(&mut source, block).jump(next, &carried);
7534 Builder::new(&mut source, next).ret(&[params[0]]);
7535
7536 // The copies go through the x87 stack so that every one of them is read before any of them
7537 // is written, which is what makes a block that swaps two of these right. Nine of them do
7538 // not fit on the stack, and copying the ninth before or after the rest is the order that
7539 // could be wrong, so it is refused instead.
7540 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
7541 .expect_err("nine do not fit on the stack");
7542 assert_eq!(
7543 failed.to_string(),
7544 "block1 takes 9 parameters of type `f80` and only 8 can cross an edge at once"
7545 );
7546 assert_eq!(failed.inst(), None);
7547 }
7548}