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::HashSet;
79use std::fmt;
80
81use rucc_base::{Interner, Symbol};
82use rucc_diag::Span;
83use rucc_ir::{
84 Abi, AsmOperand, AsmOperands, Block, Def, Extra, FloatPred, Func, Inst, Linkage, MemOrder,
85 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/// How wide an address is on this target, which is the width a cast between a pointer and an
111/// integer has to be at for the cast to be nothing.
112const ADDRESS_BITS: u32 = 64;
113
114/// How many bytes a `long double` takes in memory, and what it is aligned to, which are the same
115/// number and are both more than the ten bytes that mean anything.
116///
117/// The psABI's answer rather than a choice here. `sizeof (long double)` is sixteen on this
118/// machine, so an array of them is laid out this way whatever a slot holding one does, and a slot
119/// that agreed with the array is one fewer thing to get wrong.
120const X87_BYTES: u32 = 16;
121
122/// How many values the x87 stack holds at once.
123///
124/// Eight, which is the machine's number rather than a choice here, and it matters in one place:
125/// the parameters of a block are copied through the stack so that they all move at once, and a
126/// block with more of them than this has nowhere to put the ninth.
127const X87_DEPTH: usize = 8;
128
129/// How many bytes a value passes through on its way between a register and the x87 stack.
130///
131/// Eight, because the widest thing that crosses is a `double` or a sixty four bit integer, and
132/// nothing crosses at eighty bits: a value that wide is already in the frame and the stack reaches
133/// it where it is.
134const X87_CROSSING: u32 = 8;
135
136/// Where the rounding field of the x87 control word is and what it has to be set to for the unit
137/// to cut towards zero, which is the one rounding C asks for that the unit does not do by default.
138///
139/// Both bits on is truncate. The field is ORed into the word that was already there rather than
140/// written over it, so the precision control and the exception masks somebody else set stay set.
141const X87_TRUNCATE: i64 = 0x0c00;
142
143/// Whether a type is the one this machine has no register for.
144///
145/// Only the eighty bit float is, and that is a fact about x86-64 rather than about floats: every
146/// other scalar the front end produces is in a general purpose register or a vector one, and this
147/// one is on the x87 stack while it is being worked on and in memory the rest of the time. So it
148/// has no place in [`Lowering::class_of`] and no name in [`crate::term`], and every instruction
149/// that touches one is written out by hand in this file.
150fn on_x87(ty: Type) -> bool {
151 ty.is_scalar() && ty.is_float() && ty.bits() == 80
152}
153
154/// Which of an assembly statement's operands is in that register, for an instruction that reaches
155/// the register without its text saying so.
156///
157/// The constraint letter is what says so, and it is the only thing in such a statement that could:
158/// `"=a"` is an output in `rax` and `"c"` is an input in `rcx`, and a register nothing names is a
159/// register nobody has said anything about. So a write looks among the outputs and a read among the
160/// inputs, and an output written `+` answers for either, since it is read before it is written.
161///
162/// `None` is a register the instruction uses and the statement put nothing in, which is the usual
163/// answer rather than an unusual one. `cpuid` writes four registers and a program that wanted one
164/// of them names one. See [`Lowering::spare`], which is where that one goes.
165fn bound(list: &[AsmOperand], reg: PhysReg, role: Role) -> Option<usize> {
166 list.iter().position(|operand| {
167 operand.fixed.and_then(x86_64::gpr_letter) == Some(reg)
168 && if role.is_def() { operand.result.is_some() } else { operand.value.is_some() }
169 })
170}
171
172/// Why a function could not be lowered.
173///
174/// One reason and then nothing. A function with no rule for something in it is a function this
175/// cannot finish, and the second thing it could not lower is not news.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub enum Unsupported {
178 /// An instruction no rule fires on.
179 Inst {
180 /// The instruction that stopped it.
181 inst: Inst,
182 /// What the rule file would call it, or nothing if the rule language has no name for it
183 /// at all, which is what an instruction at a width nothing is written about looks like.
184 term: Option<&'static str>,
185 /// The opcode, which is what gets named when the rule language has no word for it.
186 ///
187 /// An opcode the rule language has no word for is exactly the opcode no rule lowers, so
188 /// without this the message would be empty in every case where somebody needs it.
189 opcode: Opcode,
190 /// What it produces, or nothing for an instruction that is only an effect.
191 ty: Option<Type>,
192 },
193 /// A parameter that does not arrive somewhere this can bring it in from.
194 ///
195 /// Not an instruction, which is why it is a separate arm: it is a fact about the signature
196 /// and there is nothing in the body of the function to point at.
197 Argument {
198 /// Its position in the signature.
199 index: usize,
200 /// What is wrong with where it arrives.
201 missing: Missing,
202 },
203 /// A call that passes or gives back a value this cannot put where the convention wants it.
204 Call {
205 /// The call.
206 inst: Inst,
207 /// Which value, and what is wrong with where it travels.
208 refused: Refused,
209 },
210 /// A `return` this cannot put where the convention wants it.
211 ///
212 /// A separate arm from [`Unsupported::Inst`] because it is not an instruction no rule fires
213 /// on. A return of more than one value is built from the convention rather than matched, the
214 /// same way a call is, so what goes wrong with one is what goes wrong with a call and not the
215 /// absence of a rule.
216 Returned {
217 /// The `return`.
218 inst: Inst,
219 /// What is wrong with where one of the values travels.
220 missing: Missing,
221 },
222 /// A stack slot the frame cannot give the bytes it asked for.
223 ///
224 /// Not an instruction no rule covers. An `alloca` is built here rather than matched, so what
225 /// goes wrong with one is what the frame can and cannot hold rather than what the rules spell.
226 Dynamic {
227 /// The `alloca`.
228 inst: Inst,
229 /// What the frame could not do about it.
230 growing: Growing,
231 },
232 /// More parameters of a type that travels on the x87 stack than the stack is deep.
233 ///
234 /// Not an instruction either, for the reason a function's parameter is not one: it is a fact
235 /// about the block and there is nothing in the block to point at. What crosses an edge for one
236 /// of these is the address of where the value is, and the block copies the bytes into a slot
237 /// of its own, all of them through the stack at once so that a block carrying two of them
238 /// swapped is copied in an order that is right. Eight is as many as the stack holds, and a
239 /// ninth would have to be copied before or after the rest, which is the order that could be
240 /// wrong.
241 Phi {
242 /// Which block it arrives at.
243 block: Block,
244 /// How many of them arrive there, which is the whole of what is wrong.
245 count: usize,
246 /// What they are.
247 ty: Type,
248 },
249 /// An `asm` statement this cannot build.
250 ///
251 /// Not an instruction no rule fires on, for the reason a call is not one: what it stands for is
252 /// whatever its template says, and no pattern over terms can read a string.
253 Assembly {
254 /// The `inline_asm`.
255 inst: Inst,
256 /// What about it is not built here yet.
257 refused: Written,
258 },
259}
260
261/// What about an `asm` statement is not built yet.
262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
263pub enum Written {
264 /// A template with instructions in it.
265 Template,
266 /// An `asm goto`, whose labels make the statement a terminator.
267 Goto,
268 /// An operand this cannot put where the constraint says it goes.
269 Operand,
270 /// A clobber list naming something this has no register for.
271 Clobber,
272}
273
274impl Written {
275 /// The rest of the sentence that starts with the statement.
276 #[must_use]
277 pub fn why(self) -> &'static str {
278 match self {
279 // The template is the assembler's to read and there is no assembler here yet, so a
280 // template with anything in it is a string nothing can turn into bytes. An empty one is
281 // no instructions, and no instructions is something this can write.
282 Written::Template => "has instructions in its template, which nothing here assembles",
283 Written::Goto => "jumps to a label, which nothing here builds an edge for",
284 Written::Operand => "has an operand this cannot place",
285 Written::Clobber => "says it destroys a register this has no name for",
286 }
287 }
288}
289
290/// What the frame could not do about a stack slot.
291#[derive(Debug, Clone, Copy, PartialEq, Eq)]
292pub enum Growing {
293 /// An object of a size the number a frame counts bytes in does not reach.
294 Huge,
295 /// A variable length array wanting more alignment than a call leaves the stack pointer with.
296 ///
297 /// Rounding the stack pointer down again after the bytes have been taken would put it
298 /// somewhere no constant reaches the rest of the frame from, so a frame like this needs a
299 /// second base register held for the whole of the function. Nothing here holds one.
300 Aligned,
301 /// A variable length array in a function whose frame is meant to be touched a page at a time.
302 ///
303 /// The pages a prologue takes are touched by the prologue, which knows how many there are when
304 /// it is written. The pages a variable length array takes are not known until the declaration
305 /// runs, so touching them is a loop next to the declaration, and there is no loop here yet.
306 Probed,
307}
308
309impl Growing {
310 /// The rest of the sentence that starts with the slot.
311 #[must_use]
312 pub fn why(self) -> &'static str {
313 match self {
314 Growing::Huge => "is more bytes than a frame counts",
315 Growing::Aligned => {
316 "wants more alignment than the stack pointer is left on, which needs a base \
317 register nothing here keeps"
318 }
319 Growing::Probed => {
320 "grows the stack, and nothing here touches the pages it takes a page at a time"
321 }
322 }
323 }
324}
325
326impl Unsupported {
327 /// The instruction it is about, or nothing for the one arm that is about a signature.
328 ///
329 /// What a caller wants this for is the span. The function knows where every instruction in
330 /// it came from, so a caller holding both can point a message at the line somebody wrote
331 /// rather than at the file as a whole, and nothing here has to carry a span of its own.
332 pub fn inst(&self) -> Option<Inst> {
333 match *self {
334 Unsupported::Inst { inst, .. }
335 | Unsupported::Call { inst, .. }
336 | Unsupported::Returned { inst, .. }
337 | Unsupported::Dynamic { inst, .. }
338 | Unsupported::Assembly { inst, .. } => Some(inst),
339 Unsupported::Argument { .. } | Unsupported::Phi { .. } => None,
340 }
341 }
342}
343
344impl fmt::Display for Unsupported {
345 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346 match *self {
347 Unsupported::Inst { term: Some(term), .. } => write!(f, "no rule lowers `{term}`"),
348 Unsupported::Inst { term: None, opcode, ty: Some(ty), .. } => {
349 write!(f, "no rule lowers a `{opcode}` producing a `{ty}`")
350 }
351 Unsupported::Inst { term: None, opcode, ty: None, .. } => {
352 write!(f, "no rule lowers a `{opcode}`")
353 }
354 Unsupported::Argument { index, missing } => {
355 write!(f, "parameter {index} {}", missing.why())
356 }
357 Unsupported::Call { refused: Refused { argument: Some(index), missing }, .. } => {
358 write!(f, "argument {index} of this call {}", missing.why())
359 }
360 Unsupported::Call { refused: Refused { argument: None, missing }, .. } => {
361 write!(f, "what this call gives back {}", missing.why())
362 }
363 Unsupported::Returned { missing, .. } => {
364 write!(f, "what this function gives back {}", missing.why())
365 }
366 Unsupported::Dynamic { growing, .. } => {
367 write!(f, "this local {}", growing.why())
368 }
369 Unsupported::Phi { block, count, ty } => {
370 let block = block.index();
371 write!(
372 f,
373 "block{block} takes {count} parameters of type `{ty}` and only {X87_DEPTH} can cross an edge at once"
374 )
375 }
376 Unsupported::Assembly { refused, .. } => write!(f, "this `asm` {}", refused.why()),
377 }
378 }
379}
380
381impl std::error::Error for Unsupported {}
382
383/// A lowered function, and what the frame needs that the machine IR does not hold.
384#[derive(Debug)]
385pub struct Lowered {
386 /// The function, in machine instructions.
387 pub func: mir::Func,
388 /// What it wants its stack to look like, which is separate from the function so that the two
389 /// can be read and written at the same time.
390 pub stack: Stack,
391 /// Which rules of the table lowered it, which is what `-Zrule-coverage` asks for and what
392 /// `crate::coverage` writes down.
393 pub fired: Fired,
394 /// Which machine IR block each IR block became, indexed by the IR block's own index, and
395 /// nothing for a block the walk never reached.
396 ///
397 /// Here because it is the only place the correspondence exists. Selection makes one block per
398 /// block, in the same order and with the arms in the same order, so anything the IR knows
399 /// about a block can be carried down through this and nothing else, and
400 /// [`crate::weights::carry`] is what does.
401 pub blocks: Vec<Option<mir::Block>>,
402}
403
404/// What a function's stack has to hold, as far as selection is able to say.
405///
406/// All of it is answered here because selection is where a call is built and where an `alloca`
407/// is read, and nothing after it could tell what either of them needed.
408#[derive(Debug, Default)]
409pub struct Stack {
410 /// How many bytes the widest call in the function needs below the stack pointer for the
411 /// arguments it passes there, or `None` for a function that makes no call at all.
412 ///
413 /// `None` is a leaf, which is the function that may use the red zone and the one whose stack
414 /// pointer does not have to be left aligned for anybody.
415 pub calls: Option<u32>,
416 /// The memory the function asked for itself, one entry for every `alloca` in it, in the order
417 /// the walk reached them.
418 pub locals: Vec<Local>,
419 /// Which instruction computes the address of which of those locals.
420 ///
421 /// An address in the frame is a distance from the stack pointer, and there is no frame until
422 /// after allocation, so the instruction is written here with nothing in its displacement and
423 /// [`crate::finish`] writes the number in once [`crate::frame::Frame`] knows it.
424 pub addresses: Vec<(mir::Inst, usize)>,
425 /// Which instruction computes the address of a piece of memory whose size the function works
426 /// out while it runs, which is what a variable length array is.
427 ///
428 /// Waiting on [`crate::finish`] for a different number from the one the addresses above are:
429 /// the bytes were taken off the stack pointer by the instruction in front of this one, so where
430 /// they start is however much of the bottom of the frame belongs to the arguments of a call,
431 /// and that is not known until the frame is.
432 pub dynamic: Vec<mir::Inst>,
433 /// Where the function first moves the stack pointer while it runs, if it does at all.
434 ///
435 /// Two things are read off this. One is whether at all, which is what [`crate::frame::Layout`]
436 /// wants, because a frame that moves its stack pointer has a different shape from one that does
437 /// not and the layout is built before the instructions are looked at again. See `Growing` in
438 /// [`crate::frame`]. The other is where, so that a caller that cannot accept such a frame has
439 /// somewhere to point when it says so.
440 pub grown_at: Option<Inst>,
441 /// Which instruction reads which of the arguments the caller passed on the stack, as how far up
442 /// the caller's argument area it reads.
443 ///
444 /// Waiting on [`crate::finish`] for the same reason the addresses above are, and on one thing
445 /// more: where the caller's argument area is from inside this function depends on whether the
446 /// prologue had to force the stack pointer's alignment, so which register the load reads
447 /// through is not settled here either.
448 pub arguments: Vec<(mir::Inst, u32)>,
449 /// Whether the function asked where its own frame is, which is what `__builtin_frame_address`
450 /// and `__builtin_return_address` both start from.
451 ///
452 /// A function like that keeps a frame pointer whatever the flags say, because the register is
453 /// the answer to the first of them and the start of the walk for every depth above zero. There
454 /// is no other way to reach it: the distance from the stack pointer to the frame is a number
455 /// the layout works out, and what a walk up the chain needs is the link the prologue saved.
456 pub walks_frames: bool,
457}
458
459impl Stack {
460 /// The layout given, with the three fields only the lowering knows the answer to filled in.
461 ///
462 /// Everything else in a layout comes from the flags the function is compiled under or from the
463 /// allocation, so this takes one and returns it rather than building one.
464 #[must_use]
465 pub fn layout<'a>(&'a self, base: Layout<'a>) -> Layout<'a> {
466 Layout {
467 leaf: self.calls.is_none(),
468 outgoing: self.calls.unwrap_or(0),
469 locals: &self.locals,
470 grows: self.grown_at.is_some(),
471 ..base
472 }
473 }
474}
475
476/// The x86-64 machine IR for that function.
477///
478/// # Errors
479///
480/// The first instruction no rule fires on, which today is anything at a width the rule set is not
481/// written at, a parameter that does not arrive in a register this can read, or a call that
482/// passes something this cannot put where the convention wants it.
483pub fn func(
484 source: &Func,
485 names: &mut Interner,
486 conv: &'static CallRegs,
487 elsewhere: &Elsewhere,
488) -> Result<Lowered, Unsupported> {
489 Lowering::new(source, names, conv, elsewhere).run()
490}
491
492/// What the matcher settled on for one block, indexed the way the block's instructions are.
493struct Decided {
494 /// What each instruction matched, and nothing for one that matched no rule or was folded
495 /// into a later one.
496 found: Vec<Option<Match<Term>>>,
497 /// How each instruction showed its operands to the matcher, which is what says what it took.
498 plans: Vec<Option<Plan>>,
499 /// The instructions some other instruction took, which are the ones with nothing to write.
500 folded: Vec<Inst>,
501}
502
503/// One function being lowered.
504struct Lowering<'a> {
505 source: &'a Func,
506 names: &'a mut Interner,
507 out: mir::Func,
508 /// The machine register each IR value is in, once it has one.
509 regs: Vec<Option<mir::Reg>>,
510 /// For a constant that has been written into a register, the block it was written into,
511 /// which is the only block that register is any good in.
512 written: Vec<Option<mir::Block>>,
513 /// How many times each IR value is read, which is what says whether an instruction may be
514 /// folded into the one that reads it.
515 uses: Vec<u32>,
516 /// The block being filled.
517 at: Option<mir::Block>,
518 /// The machine IR block each IR block became.
519 blocks: Vec<Option<mir::Block>>,
520 /// The class an address is in, which is the general purpose one and is not a question: every
521 /// register an addressing mode names holds part of an address, and there is no machine here
522 /// that computes an address anywhere but in this file. Which class a *value* is in is
523 /// [`Lowering::class_of`], and it is a question, because a float is in the other one.
524 gpr: RegClass,
525 /// Where the convention this function is compiled for puts things, which is read for the
526 /// arguments and for the calls.
527 conv: &'static CallRegs,
528 /// Which names this function may not work an address out for itself, which is a fact about the
529 /// module and so is worked out before any of this and handed in.
530 elsewhere: &'a Elsewhere,
531 /// What the function wants its stack to look like, filled in as the walk finds out.
532 stack: Stack,
533 /// What a `va_start` in this function has to write, or nothing for a function that takes no
534 /// arguments its signature does not name.
535 ///
536 /// Worked out once, when the entry block binds the parameters, because every number in it is
537 /// about where those parameters left the walk over the argument registers and there is nowhere
538 /// else that knows.
539 varargs: Option<Varargs>,
540 /// Which of the function's stack objects each eighty bit value lives in, once it has asked
541 /// for one.
542 ///
543 /// One slot per value and it is never given back, which is what makes an eighty bit value
544 /// behave like every other one: it is written once and read wherever it is read, and no two
545 /// of them share a slot the way two of them would share a register. What is in a register is
546 /// the address, and that is worked out again at every use rather than kept, so nothing here
547 /// holds a general purpose register open across a whole function.
548 slots: Vec<Option<usize>>,
549 /// The eight bytes a value passes through between a register and the x87 stack, once
550 /// something has wanted them.
551 ///
552 /// One for the whole function, because every group that uses it is a handful of instructions
553 /// with nothing in between: the bytes are written, read straight back and never looked at
554 /// again, so a second slot would be a second slot holding the same nothing.
555 crossing: Option<usize>,
556 /// The four bytes the control word is saved in and the changed copy written to, once
557 /// something has wanted them.
558 ///
559 /// One for the whole function for the reason above, and four rather than two because it is
560 /// two words: the one the unit had and the one with the rounding field turned to truncate.
561 control: Option<usize>,
562 /// Which rules have fired so far.
563 fired: Fired,
564}
565
566/// What a `va_start` in a variadic function writes into the list it is given.
567///
568/// Three of the four are settled here and the fourth is not a number at all yet: where the save
569/// area is and where the caller's argument area is are both distances into a frame that does not
570/// exist until after allocation, so both are `lea` instructions [`crate::finish`] fills in.
571#[derive(Debug, Clone, Copy, PartialEq, Eq)]
572struct Varargs {
573 /// Which of the function's stack objects is the register save area.
574 save: usize,
575 /// How far up the caller's argument area the first argument the signature does not name is,
576 /// which is the whole of that area the named ones did not take.
577 incoming: u32,
578 /// What `gp_offset` starts at, which is past the general purpose registers the named arguments
579 /// took.
580 integers: u32,
581 /// What `fp_offset` starts at, which is past the vector ones.
582 floats: u32,
583}
584
585/// How far a function's name reaches, narrowed from the linkage the IR gave it.
586///
587/// The IR has five and an object file says three, and the two the linker cannot tell apart are
588/// the two weak ones: which of them a symbol had is a fact the optimizer reads and the linker has
589/// no way to record. A function is never `Common`, since that is what a tentative definition of an
590/// object is and there is no tentative definition of a function, and it is written here rather
591/// than left out so that a linkage added later has to come past this.
592const fn binding(linkage: Linkage) -> mir::Binding {
593 match linkage {
594 Linkage::Internal => mir::Binding::Local,
595 Linkage::Weak | Linkage::LinkOnce => mir::Binding::Weak,
596 Linkage::External | Linkage::Common => mir::Binding::Global,
597 }
598}
599
600/// How far a function's name reaches outside a shared library, carried across unchanged.
601///
602/// Nothing is narrowed here the way [`binding`] narrows the linkage, because ELF records all
603/// three of these and the two enumerations are the same three answers written twice: once in a
604/// crate that is not allowed to know what an object file is and once in one that is.
605const fn visibility(visibility: Visibility) -> mir::Visibility {
606 match visibility {
607 Visibility::Default => mir::Visibility::Default,
608 Visibility::Hidden => mir::Visibility::Hidden,
609 Visibility::Protected => mir::Visibility::Protected,
610 }
611}
612
613impl<'a> Lowering<'a> {
614 fn new(
615 source: &'a Func,
616 names: &'a mut Interner,
617 conv: &'static CallRegs,
618 elsewhere: &'a Elsewhere,
619 ) -> Self {
620 let counts = source.counts();
621 let name = source.name;
622 let mut uses = vec![0; counts.values];
623 for block in source.blocks() {
624 for inst in source.insts(block) {
625 for &arg in &source[source[inst].args] {
626 uses[arg.index()] += 1;
627 }
628 for call in source.successors(inst) {
629 for &arg in &source[call.args] {
630 uses[arg.index()] += 1;
631 }
632 }
633 }
634 }
635 let mut out = mir::Func::new(name);
636 out.align = source.align;
637 out.binding = binding(source.linkage);
638 out.visibility = visibility(source.visibility);
639 Self {
640 source,
641 names,
642 out,
643 regs: vec![None; counts.values],
644 written: vec![None; counts.values],
645 blocks: vec![None; counts.blocks],
646 uses,
647 at: None,
648 gpr: x86_64::GPR,
649 conv,
650 elsewhere,
651 stack: Stack::default(),
652 varargs: None,
653 slots: vec![None; counts.values],
654 crossing: None,
655 control: None,
656 fired: Fired::new(),
657 }
658 }
659
660 fn run(mut self) -> Result<Lowered, Unsupported> {
661 // Every block before any of them is filled, because a block that jumps forward has to
662 // name the block it jumps to and a machine IR block is named by a handle rather than by
663 // the IR block it came from.
664 for block in self.source.blocks() {
665 let out = self.out.create_block();
666 self.blocks[block.index()] = Some(out);
667 }
668 for block in self.order() {
669 self.block(block)?;
670 }
671 // And the name each block an image holds the address of was given, which nothing in the
672 // walk above would ask for: the `lea` a label address is inside the function needs no
673 // symbol, and the one thing that does is a relocation in another section.
674 let named: Vec<(Block, Symbol)> = self.source.named_blocks().collect();
675 let labels: Vec<(mir::Block, Symbol)> =
676 named.into_iter().map(|(block, name)| (self.out_block(block), name)).collect();
677 self.out.labels = labels;
678 Ok(Lowered { func: self.out, stack: self.stack, fired: self.fired, blocks: self.blocks })
679 }
680
681 /// The order the blocks are filled in, which is not the order they are written in.
682 ///
683 /// Reverse postorder, because a value is written in a block that dominates every block that
684 /// reads it and a block in reverse postorder comes before every block it dominates. The order
685 /// the blocks are written in does not have that property: a block written early can read a
686 /// value a block below it writes, and reading a value with no register yet mints one, so the
687 /// register the definition writes later is not the register the read named. Nothing writes the
688 /// one the read named, and what comes out is a function that loads a stack slot no store ever
689 /// reached. It is the order this walk goes in rather than the order the blocks come out in,
690 /// which is what the loop above fixes, so the machine function is still written the way the IR
691 /// function was.
692 ///
693 /// Blocks the entry does not reach come last, in the order they are written in. Nothing runs
694 /// them and nothing they name is read by anything that does, but they still have to be filled,
695 /// because a machine block with no terminator is not one the passes below can read.
696 fn order(&self) -> Vec<Block> {
697 let Some(entry) = self.source.entry() else { return self.source.blocks().collect() };
698 let count = self.blocks.len();
699 let mut succs: Vec<Vec<Block>> = vec![Vec::new(); count];
700 for block in self.source.blocks() {
701 let Some(term) = self.source.terminator(block) else { continue };
702 succs[block.index()] = self.source.successors(term).map(|call| call.block).collect();
703 }
704 // An explicit stack, because the depth of the walk is the number of blocks and a function
705 // built by a generator has as many of those as it likes.
706 let mut seen = vec![false; count];
707 let mut order = Vec::with_capacity(count);
708 let mut stack = vec![(entry, 0usize)];
709 seen[entry.index()] = true;
710 while let Some((block, at)) = stack.pop() {
711 let Some(&next) = succs[block.index()].get(at) else {
712 order.push(block);
713 continue;
714 };
715 stack.push((block, at + 1));
716 if !seen[next.index()] {
717 seen[next.index()] = true;
718 stack.push((next, 0));
719 }
720 }
721 order.reverse();
722 order.extend(self.source.blocks().filter(|block| !seen[block.index()]));
723 order
724 }
725
726 /// One block: its parameters, then every instruction in it that is not folded into another.
727 fn block(&mut self, block: Block) -> Result<(), Unsupported> {
728 let out = self.out_block(block);
729 self.at = Some(out);
730 if self.source.entry() == Some(block) {
731 self.arrive(block, out)?;
732 } else {
733 let mut arriving = Vec::new();
734 for ¶m in &self.source[block].params {
735 // A value with no register to arrive in, which the class would not say, since
736 // `class_of` puts one of these in the general purpose file on purpose and what it
737 // means by that is that nothing there can hold it. What crosses the edge for one
738 // of those is the address of where the value already is, so the parameter is a
739 // pointer here and the bytes it points at are copied below.
740 let ty = self.source[param].ty;
741 let reg = self.out.append_param(out, self.class_of(ty));
742 self.regs[param.index()] = Some(reg);
743 if on_x87(ty) {
744 arriving.push((param, reg));
745 }
746 }
747 self.settle(block, &arriving)?;
748 }
749
750 // What each instruction matched, and which instructions were folded into another. The
751 // decision is made for the whole block before any of it is written, and it is made more
752 // than once: a value that only some of its readers took has to be put back in a register
753 // for all of them, and taking it away from those readers changes what they match.
754 let insts: Vec<Inst> = self.source.insts(block).collect();
755 let mut refused: HashSet<Value> = HashSet::new();
756 let mut decided = self.decide(&insts, &refused);
757 while let Some(value) = self.left_alive(&insts, &decided.plans) {
758 refused.insert(value);
759 decided = self.decide(&insts, &refused);
760 }
761 let Decided { found, folded, .. } = decided;
762
763 for (&inst, matched) in insts.iter().zip(found) {
764 if folded.contains(&inst) || self.writes_nothing(inst) {
765 continue;
766 }
767 // A call is built from the convention rather than matched, which is why it is the one
768 // opcode looked at by name here. Through an address it is a different instruction and
769 // the same convention, so the two arrive at the same place and differ in one line of
770 // it.
771 match self.source[inst].opcode {
772 Opcode::Call | Opcode::CallIndirect => {
773 self.called(inst)?;
774 continue;
775 }
776 // Built from the frame rather than matched, for the same shape of reason a call
777 // is built from the convention: what a rule replaces a term with is instructions,
778 // and what an `alloca` needs first is bytes, which the rule language has no way
779 // to ask for.
780 Opcode::Alloca => {
781 self.reserve(inst)?;
782 continue;
783 }
784 // Reading the stack pointer and writing it back, which are the two ends of a scope
785 // holding a variable length array. Built here for the reason an `alloca` is: the
786 // value is a register the rule language has no way to name, because what it holds
787 // is not a value the program computed but where the machine's stack had got to.
788 Opcode::StackSave => {
789 self.stack_pointer(inst, false)?;
790 continue;
791 }
792 Opcode::StackRestore => {
793 self.stack_pointer(inst, true)?;
794 continue;
795 }
796 // The address of a name, built here for the same reason an `alloca` is: what a
797 // rule replaces a term with is instructions over values, and the operand of this
798 // one is a symbol, which is a thing the rule language has no way to bind and the
799 // solver has no way to say anything about. There is nothing in `lea sym(%rip)` a
800 // proof over bitvectors could discharge, because what makes it the right answer
801 // is the relocation and what the linker does with it.
802 Opcode::GlobalAddr => {
803 self.address_of(inst)?;
804 continue;
805 }
806 // The address of a label and the branch that reads one, built here for the same
807 // reason and for one more. The reason is the same: what the first of them names is
808 // a block, which is not a value a rule pattern can bind, and there is nothing in
809 // the distance between two places in one function that a proof over bitvectors
810 // could discharge. The extra one is that the second is a terminator whose arms are
811 // not two and not fixed, and a rule says what an instruction reads rather than
812 // where a block goes.
813 Opcode::BlockAddr => {
814 self.block_address(inst)?;
815 continue;
816 }
817 Opcode::IndirectBr => {
818 self.indirect_branch(inst)?;
819 continue;
820 }
821 // Where this thread's own storage starts, built here for a reason of the same
822 // shape: what it reads is `%fs`, which is not a register the rule language can
823 // bind and not one a proof over bitvectors could say anything about, because what
824 // makes the load the right answer is an agreement between the loader and the C
825 // library rather than any arithmetic.
826 Opcode::ThreadPointer => {
827 self.thread_pointer(inst)?;
828 continue;
829 }
830 // Where a frame is and what it returns to, built here for the same reason and one
831 // more. The reason is the same: what the walk starts from is the frame pointer,
832 // which is not a register a rule pattern can bind, and there is nothing in reading
833 // the link the prologue saved that a proof over bitvectors could discharge. The
834 // extra one is that how long the walk is comes out of a number beside the
835 // instruction, so one of these is not one instruction but however many the depth
836 // says, and a rule replaces a term with a term.
837 Opcode::FrameAddress | Opcode::ReturnAddress => {
838 self.frames(inst)?;
839 continue;
840 }
841 // Built from the frame for the reason an `alloca` is, and from the convention for
842 // the reason a call is: three of the four fields it writes are distances that do
843 // not exist until the frame does, and the fourth is where the walk over the
844 // argument registers stopped. A function that is not variadic has no such walk to
845 // report, so it has nothing here and is refused below, which is the right answer
846 // for a `va_start` in one.
847 Opcode::VaStart if self.varargs.is_some() => {
848 self.va_start(inst)?;
849 continue;
850 }
851 // A return of more than one value, which is a structure small enough to come
852 // back in a pair of registers. Built from the convention for the reason a call
853 // is: which register each half goes in depends on the halves in front of it,
854 // because the two register files are walked separately, and a pattern over a term
855 // cannot see them. A return of one value is a term with a name and a rule, and it
856 // stays one.
857 //
858 // A return of none in a function whose answer went through memory is here too,
859 // and for a different reason: what it gives back is not written in the IR at all.
860 // The convention says the address the caller handed over comes back, and only the
861 // signature says this function was handed one.
862 //
863 // And a return of one eighty bit value, for a third reason: what a rule would
864 // write is an instruction leaving the value in a register, and this one is left on
865 // the x87 stack instead. A rule could not name that stack any more than any other
866 // rule about this type could.
867 Opcode::Return
868 if self.source[self.source[inst].args].len() > 1
869 || self.sret().is_some()
870 || self.gives_back_x87(inst) =>
871 {
872 self.returned(inst)?;
873 continue;
874 }
875 // A cast between a pointer and an integer of the same width, which on this
876 // machine is every one the front end writes. No instruction at all, so no rule
877 // could name one.
878 Opcode::PtrToInt | Opcode::IntToPtr => {
879 self.rename(inst)?;
880 continue;
881 }
882 // A barrier, which is one instruction or none depending on the ordering. Written
883 // by name because there is nothing about it a rule could be proved against, the
884 // way there is nothing to prove about the address of a symbol.
885 Opcode::Fence => {
886 self.barrier(inst)?;
887 continue;
888 }
889 // A hint, written by name for the reason a barrier is and one step further: not
890 // only is there no equality for a proof to discharge, there is nothing about the
891 // program around it either. Which of the four instructions it is comes out of the
892 // number the builtin was given, which is beside the instruction rather than in it.
893 Opcode::Prefetch => {
894 self.hint(inst)?;
895 continue;
896 }
897 // Stopping, written by name for the first half of the barrier's reason: it
898 // computes nothing, so there is no term for a rule to replace, and what makes it
899 // right is what the operating system does with the fault rather than anything a
900 // proof over bitvectors could discharge.
901 Opcode::Trap => {
902 self.trap(inst);
903 continue;
904 }
905 // A compare and exchange, which is written by name because it produces two values
906 // and a rule produces one. The replacement of a rule is one term, a term names the
907 // value an instruction computes, and there is no way in that language to say that
908 // an instruction leaves an answer in one place and a yes or no in another.
909 Opcode::Cmpxchg => {
910 self.exchange(inst)?;
911 continue;
912 }
913 // A read modify write, which is written by name for a different reason: it produces
914 // one value, so a rule could name it, and what it does is not in the head a rule
915 // matches on. Every one of the thirteen operations is the same opcode at the same
916 // type and differs only in what is carried beside it, so one pattern would be all
917 // thirteen patterns. Of the thirteen only the three with an instruction reach here,
918 // since `crate::retry` turned the rest into loops a long way above this.
919 Opcode::AtomicRmw => {
920 self.modify(inst)?;
921 continue;
922 }
923 // An `asm` statement, whose lowering is its template and there is no term for a
924 // string. Written by name for the reason a barrier is, and before the x87 arm
925 // below so that an `asm` holding a `long double` is refused as the `asm` it is
926 // rather than as an instruction nothing computes.
927 Opcode::InlineAsm => {
928 self.assembly(inst)?;
929 continue;
930 }
931 // Anything at all with an eighty bit float in it, which is the one arm here
932 // chosen by a type rather than by an opcode, because what makes these different
933 // is not what they do but where the value is. A `long double` has no register,
934 // so it has no name in `crate::term` and no rule could bind one: every one of
935 // these is a group of instructions over a frame slot, written out below.
936 //
937 // Last of the arms, so that a call and a return with one of these in them reach
938 // the convention first and are refused by it, which is the truer answer: what is
939 // wrong there is where the value has to travel and not that nothing can compute
940 // it.
941 _ if self.touches_x87(inst) => {
942 self.x87(inst)?;
943 continue;
944 }
945 _ => {}
946 }
947 let matched = matched.ok_or_else(|| self.unsupported(inst))?;
948 self.emit(inst, &matched)?;
949 // After it is built rather than when it matched, so that what is recorded is the rules
950 // this function was lowered by and not the rules something was tried with.
951 self.fired.mark(matched.rule);
952 }
953 self.edges(block, out)
954 }
955
956 /// One call, which is built from the convention rather than matched against the table for the
957 /// same reason the arguments of the function itself are.
958 ///
959 /// The arguments are read before the call is built, which is what materializes a constant
960 /// argument into a register, since no call passes an immediate.
961 ///
962 /// A call to a name and a call through an address are both here, and what tells them apart is
963 /// the opcode rather than whether a callee was recorded, which is the same thing the verifier
964 /// reads. Through an address the first operand is the address and the arguments are the ones
965 /// behind it, and everything after that is the same: where each argument goes, where the value
966 /// comes back and which registers are gone across it are the convention's answers and the
967 /// convention does not ask what is being called.
968 fn called(&mut self, inst: Inst) -> Result<(), Unsupported> {
969 let data = &self.source[inst];
970 let Extra::Call(info) = data.extra else { return Err(self.unsupported(inst)) };
971 let info = self.source[info];
972 let indirect = data.opcode == Opcode::CallIndirect;
973
974 let values: Vec<Value> = self.source[data.args].to_vec();
975 let callee = if indirect {
976 let &address = values.first().ok_or_else(|| self.unsupported(inst))?;
977 abi::Callee::Through(self.reg_of(address)?)
978 } else {
979 abi::Callee::Named(info.callee.ok_or_else(|| self.unsupported(inst))?)
980 };
981
982 // What the ABI asks of each argument, read out before any of them is, because reading one
983 // borrows the function this is a table in. The ones the signature names are the signature's
984 // answer and the ones behind them are the call's, which is where a structure passed to a
985 // variadic callee by value says that its bytes travel: there is no parameter to say it on.
986 let signature = &self.source[info.signature];
987 let variadic = signature.variadic;
988 let named: Vec<Abi> = signature.params.iter().map(|param| param.abi).collect();
989 let beyond: Vec<Abi> = self.source[info.varargs].to_vec();
990 // Every value that comes back and not only the first. A structure small enough to travel
991 // in registers comes back in up to two of them, and which register each half is in is the
992 // convention's answer, which is why the whole list goes to the same place the arguments do
993 // rather than to a rule.
994 let returns: Vec<Type> = signature.return_types().collect();
995
996 let mut args = Vec::with_capacity(values.len());
997 for (index, value) in values.into_iter().skip(usize::from(indirect)).enumerate() {
998 let abi = named.get(index).or_else(|| beyond.get(index - named.len()));
999 let abi = abi.copied().unwrap_or_default();
1000 let ty = self.source[value].ty;
1001 // What travels for an eighty bit value is its bytes, so what the call is handed is
1002 // where they are rather than a register they are in, and there is no register they
1003 // could be in. Everything else about it is a sixteen byte object passed by value and
1004 // is built by the same code.
1005 let reg =
1006 if abi::on_the_stack(ty) { self.x87_slot(value) } else { self.reg_of(value)? };
1007 args.push(abi::Passing { ty, reg, abi });
1008 }
1009 let block = self.at.expect("a block is being filled");
1010 let what = abi::Calling { callee, args: &args, returns: &returns, variadic };
1011 let made = abi::call(&mut self.out, block, &what, self.conv, self.names)
1012 .map_err(|refused| Unsupported::Call { inst, refused })?;
1013 let calls = &mut self.stack.calls;
1014 *calls = Some(calls.unwrap_or(0).max(made.outgoing));
1015 // An eighty bit value came back on the x87 stack, and the one thing that has to happen
1016 // before anything else touches that stack is taking it off. So the `fstp` goes here, in
1017 // front of everything the block does next, and after it the value is in its slot and is
1018 // read the way every other one is.
1019 let results: Vec<Value> = self.source[inst].results().collect();
1020 if let [result] = results[..] {
1021 if abi::on_the_stack(self.source[result].ty) {
1022 let span = self.source.span(inst);
1023 let into = self.x87_slot(result);
1024 let into = self.through(into);
1025 self.x87_at("fstp_t", span, into);
1026 return Ok(());
1027 }
1028 }
1029 for (result, ®) in results.into_iter().zip(&made.results) {
1030 self.regs[result.index()] = Some(reg);
1031 }
1032 Ok(())
1033 }
1034
1035 /// The pointer a function returning through memory was handed, or nothing in a function that
1036 /// was not.
1037 ///
1038 /// It is the first parameter and the signature is what says so, since in the IR it is an
1039 /// ordinary pointer and reads like one everywhere in the body. A function with a signature
1040 /// like that and no entry block has nothing to give back and no body to give it back from.
1041 fn sret(&self) -> Option<Value> {
1042 let first = self.source.signature().params.first()?;
1043 if !matches!(first.abi, Abi::Sret { .. }) {
1044 return None;
1045 }
1046 self.source[self.source.entry()?].params.first().copied()
1047 }
1048
1049 /// One `return` the convention has to write, as the place each value has to be in by the end.
1050 ///
1051 /// One pseudo per value, each a read constrained to a return register, which is what a return
1052 /// of one value already is and is the whole of what either does. The `ret` itself comes from
1053 /// the epilogue for both, long after this, because the frame has to be given back first.
1054 ///
1055 /// The two register files are counted separately, so a structure of a `double` and a `long`
1056 /// leaves the `double` in the first vector register and the `long` in the first integer one
1057 /// rather than in the second of either. That is the same walk `rucc_codegen::abi` makes on
1058 /// the other side of the call, which is what makes the two ends agree.
1059 ///
1060 /// A function whose answer went through memory gives back the address it was handed, in front
1061 /// of nothing else, because a signature that returns that way returns nothing else. That the
1062 /// caller already knows the address is not enough: it is allowed to read the register instead,
1063 /// and a caller that does gets whatever the allocator last left there. In a leaf function that
1064 /// is usually the right answer by accident, and one call in the body is enough to make it a
1065 /// wild pointer, which is why this is written rather than left to luck.
1066 ///
1067 /// Where everything goes is worked out before anything is written, so a return this cannot
1068 /// make leaves no half of one behind.
1069 /// Whether what a `return` gives back is the one value that goes back on the x87 stack.
1070 fn gives_back_x87(&self, inst: Inst) -> bool {
1071 let [value] = self.source[self.source[inst].args] else { return false };
1072 abi::on_the_stack(self.source[value].ty)
1073 }
1074
1075 fn returned(&mut self, inst: Inst) -> Result<(), Unsupported> {
1076 let values: Vec<Value> = self.source[self.source[inst].args].to_vec();
1077 let (mut ints, mut floats) = (0usize, 0usize);
1078 let mut parts = Vec::with_capacity(values.len() + 1);
1079 // An eighty bit value goes back on the x87 stack, which is where the convention says it is
1080 // and is the one place a value is left rather than put in a register. So the whole of the
1081 // return is an `fld` of its slot, and the stack it leaves the value on is not empty at the
1082 // `ret`, which is the one time in this file that is true and is what the convention asks
1083 // for. What comes after is the epilogue, which gives the frame back and touches nothing in
1084 // the unit.
1085 if let [value] = values[..] {
1086 let ty = self.source[value].ty;
1087 if abi::on_the_stack(ty) && self.sret().is_none() {
1088 let span = self.source.span(inst);
1089 let from = self.x87_slot(value);
1090 let from = self.through(from);
1091 self.x87_at("fld_t", span, from);
1092 return Ok(());
1093 }
1094 }
1095 for value in self.sret().into_iter().chain(values) {
1096 let ty = self.source[value].ty;
1097 let at = if crate::term::in_vector_file(ty) { &mut floats } else { &mut ints };
1098 // Why it cannot come back, and not only that it cannot. A type that travels nowhere
1099 // says so itself, and a type that travels perfectly well ran out of registers.
1100 let missing = abi::refuses(ty).unwrap_or(Missing::NoRoom);
1101 let name = abi::ret_of(ty, *at).ok_or(Unsupported::Returned { inst, missing })?;
1102 *at += 1;
1103 // The register is the target's answer and not one worked out here, the same as it is
1104 // for a return of one value, so that both halves of a pair and every rule that writes
1105 // half of one are reading the same table.
1106 let opcode = name.strip_prefix(PREFIX).expect("a machine instruction of this target");
1107 let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
1108 let [desc] = form.operands() else { return Err(self.unsupported(inst)) };
1109 parts.push((self.names.intern(name), self.reg_of(value)?, *desc));
1110 }
1111
1112 let block = self.at.expect("a block is being filled");
1113 let span = self.source.span(inst);
1114 for (opcode, reg, desc) in parts {
1115 let operand = mir::Operand {
1116 reg,
1117 class: desc.class,
1118 role: desc.role,
1119 constraint: desc.constraint,
1120 };
1121 self.out.build(block, mir::Opcode::new(opcode)).at(span).operand(operand).finish();
1122 }
1123 Ok(())
1124 }
1125
1126 /// One `alloca`: the bytes it asks for go on the list the frame is laid out from, and the
1127 /// address of them is one instruction.
1128 ///
1129 /// The instruction is a `lea` off the stack pointer, which is the one register that reaches
1130 /// the frame in every function, and its displacement is left at nothing because there is no
1131 /// frame yet. Which instruction is waiting for which local is remembered, and
1132 /// [`crate::finish`] fills the numbers in after [`crate::frame::Frame`] has placed them.
1133 ///
1134 /// There is deliberately no rule for `alloca` and no name for one in [`crate::term`], and
1135 /// that is what stops it being folded into something else. An operand shown as the
1136 /// instruction that computed it is offered to the matcher by its name, so an `alloca` with no
1137 /// name is one no pattern can reach past, and the address it computes is always in a register
1138 /// by the time anything reads it.
1139 fn reserve(&mut self, inst: Inst) -> Result<(), Unsupported> {
1140 let data = &self.source[inst];
1141 // A variable length array carries the size it wants as an operand rather than in the
1142 // instruction, which is the whole of what tells the two apart here.
1143 if let Some(&size) = self.source[data.args].first() {
1144 return self.grow(inst, size);
1145 }
1146 let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
1147 let info = self.source[mem];
1148 let size = u32::try_from(info.size)
1149 .map_err(|_| Unsupported::Dynamic { inst, growing: Growing::Huge })?;
1150 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1151
1152 // At least one, because the frame divides by the alignment and an object with no
1153 // alignment at all is one the front end had nothing to say about rather than one that may
1154 // go anywhere.
1155 let index = self.stack.locals.len();
1156 self.stack.locals.push(Local { size, align: info.align.max(1) });
1157
1158 let block = self.at.expect("a block is being filled");
1159 let reg = self.new_reg(result);
1160 let span = self.source.span(inst);
1161 let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
1162 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
1163 let made =
1164 self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
1165 self.stack.addresses.push((made, index));
1166 Ok(())
1167 }
1168
1169 /// The other kind of `alloca`: one whose size the function does not know until it runs, which
1170 /// is what a variable length array is.
1171 ///
1172 /// Nothing about it is a slot the frame laid out, because the frame is laid out once and this
1173 /// happens as often as control reaches the declaration. The bytes come off the stack pointer
1174 /// where the declaration stands, which is two instructions:
1175 ///
1176 /// ```text
1177 /// sub sp, bytes the stack pointer moves down over the memory, which is what takes it
1178 /// lea reg, [sp+n] where the memory starts, which is above the outgoing argument area
1179 /// ```
1180 ///
1181 /// The displacement is left at nothing for the reason the constant kind leaves its own at
1182 /// nothing, and for a different number: that area belongs to the arguments of whatever this
1183 /// function calls, it stays at the bottom of the frame wherever the bottom has moved to, and
1184 /// how big it is is not known until every call in the function has been seen.
1185 ///
1186 /// The bytes are already a multiple of the stack pointer's alignment by the time they arrive,
1187 /// because [`crate::expand::rounds`] rounded them up in the IR, so nothing here has to mask the
1188 /// stack pointer afterwards and the stack pointer stays somewhere a call can be made from.
1189 ///
1190 /// Refused for an array wanting more alignment than the convention leaves the stack pointer
1191 /// with. Forcing that would be a second rounding of a register the frame already rounded, and
1192 /// after it no constant reaches the rest of the frame from anywhere. See `Growing` in
1193 /// [`crate::frame`].
1194 fn grow(&mut self, inst: Inst, size: Value) -> Result<(), Unsupported> {
1195 let data = &self.source[inst];
1196 let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
1197 let info = self.source[mem];
1198 if info.align > self.conv.stack_align {
1199 return Err(Unsupported::Dynamic { inst, growing: Growing::Aligned });
1200 }
1201 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1202 let bytes = self.reg_of(size)?;
1203
1204 let block = self.at.expect("a block is being filled");
1205 let span = self.source.span(inst);
1206 let stack = mir::Reg::physical(self.conv.stack_pointer);
1207 let grow = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.grow)));
1208 self.out
1209 .build(block, grow)
1210 .at(span)
1211 .operand(mir::Operand::write(stack, self.gpr))
1212 .operand(mir::Operand::read(stack, self.gpr))
1213 .operand(mir::Operand::read(bytes, self.gpr))
1214 .finish();
1215
1216 let reg = self.new_reg(result);
1217 let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
1218 let sp = mir::Operand::read(stack, self.gpr);
1219 let made =
1220 self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
1221 self.stack.dynamic.push(made);
1222 self.stack.grown_at.get_or_insert(inst);
1223 Ok(())
1224 }
1225
1226 /// Where the stack pointer is, kept so that something later can put it back.
1227 ///
1228 /// One move out of the stack pointer and one move into it, which is the whole of what the two
1229 /// halves are. What makes them worth writing is where the front end puts them: a scope holding
1230 /// a variable length array saves the stack pointer as it opens and puts it back as it closes,
1231 /// so a loop declaring one takes its bytes once round rather than once per iteration, and a
1232 /// jump out of the scope gives the bytes back on the way out.
1233 ///
1234 /// The value travels in an ordinary register the allocator hands out, so it may be spilled like
1235 /// any other, and a spill slot in a frame that grows is reached through the frame pointer,
1236 /// which is exactly the register that still means something after the stack pointer has moved.
1237 fn stack_pointer(&mut self, inst: Inst, into: bool) -> Result<(), Unsupported> {
1238 let data = &self.source[inst];
1239 let block = self.at.expect("a block is being filled");
1240 let span = self.source.span(inst);
1241 let stack = mir::Reg::physical(self.conv.stack_pointer);
1242 let mov = x86_64::FRAME.moves(self.gpr).expect("a class the target says how to move").mov;
1243 let mov = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{mov}")));
1244 let (write, read) = if into {
1245 let &saved = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
1246 (stack, self.reg_of(saved)?)
1247 } else {
1248 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1249 (self.new_reg(result), stack)
1250 };
1251 self.out
1252 .build(block, mov)
1253 .at(span)
1254 .operand(mir::Operand::write(write, self.gpr))
1255 .operand(mir::Operand::read(read, self.gpr))
1256 .finish();
1257 // Only the write is a move of the stack pointer, and it is the one that makes the frame a
1258 // growing one. A read of it in a function that never writes it back is a function that
1259 // asked where the stack was and did nothing with the answer.
1260 if into {
1261 self.stack.grown_at.get_or_insert(inst);
1262 }
1263 Ok(())
1264 }
1265
1266 /// Whether an instruction has an eighty bit float anywhere in it.
1267 ///
1268 /// Producing one and reading one are the same question here, because what makes one of these
1269 /// different from every other instruction is not the operation but where the value is. A
1270 /// `long double` is on the x87 stack while it is being worked on and in a frame slot the rest
1271 /// of the time, and neither of those is somewhere the operand of a rule could point.
1272 fn touches_x87(&self, inst: Inst) -> bool {
1273 let data = &self.source[inst];
1274 data.results().any(|value| on_x87(self.source[value].ty))
1275 || self.source[data.args].iter().any(|&arg| on_x87(self.source[arg].ty))
1276 }
1277
1278 /// Everything that happens to an eighty bit float, as the group of instructions it is.
1279 ///
1280 /// The first six move one, and every one of those is a load, a store, or a load and a store at
1281 /// two different formats, because that is the whole of what this machine converts with: the
1282 /// x87 has no instruction that turns one thing on its stack into another, so a widening is
1283 /// `fld` of the narrow format and a narrowing is `fstp` of it.
1284 ///
1285 /// The rest work on one, and they are here rather than in a rule for the same reason the six
1286 /// are. An add is a push, a push, the add and a pop, and what passes between those four is the
1287 /// top of a stack nothing allocates from, so there is no value in the middle of the group for
1288 /// a pattern to bind or a replacement to name. The comparison is the same shape with its last
1289 /// two instructions folded into one opcode, which is where the byte it produces comes from.
1290 ///
1291 /// Every group leaves the stack as empty as it found it, which is what `spec/10-backend.md`
1292 /// section 10.8 asks of one and is why nothing in this file has to track a depth: each push
1293 /// below is answered by a pop a line or two later, so no two groups can ever be looking at
1294 /// the same eight registers.
1295 fn x87(&mut self, inst: Inst) -> Result<(), Unsupported> {
1296 match self.source[inst].opcode {
1297 Opcode::Load => self.x87_load(inst),
1298 Opcode::Store => self.x87_store(inst),
1299 Opcode::FPExt => self.x87_widen(inst),
1300 Opcode::FPTrunc => self.x87_narrow(inst),
1301 Opcode::SIToFP => self.x87_from_signed(inst),
1302 Opcode::FPToSI => self.x87_to_signed(inst),
1303 Opcode::FAdd => self.x87_arith(inst, "fadd_p"),
1304 Opcode::FSub => self.x87_arith(inst, "fsubr_p"),
1305 Opcode::FMul => self.x87_arith(inst, "fmul_p"),
1306 Opcode::FDiv => self.x87_arith(inst, "fdivr_p"),
1307 Opcode::FNeg => self.x87_flip(inst),
1308 Opcode::FCmp => self.x87_compare(inst),
1309 Opcode::FConst => self.x87_const(inst),
1310 _ => Err(self.unsupported(inst)),
1311 }
1312 }
1313
1314 /// The eighty bit parameters of a block, copied out of the addresses an edge handed over and
1315 /// into slots of the block's own.
1316 ///
1317 /// What crosses an edge for a value of this type is an address, because the value is sixteen
1318 /// bytes of the frame and no register holds any of it. The block cannot keep that address: a
1319 /// second edge into the same block hands over a second one, and a read after the block would
1320 /// then be a read of whichever edge was taken rather than of one place. So the block has a
1321 /// slot per parameter and the bytes are copied into it here, which is the move on an edge that
1322 /// every other type gets from the allocator.
1323 ///
1324 /// Every load runs before every store and the stores run backwards, so all of the values are
1325 /// on the x87 stack at once and nothing reads a slot another one has already written. That
1326 /// costs nothing in the ordinary case of one parameter and is what makes the back edge of a
1327 /// loop that swaps two of these work. It is also the reason for the limit: the stack is eight
1328 /// deep, and a block with more of these than that is refused rather than copied in an order
1329 /// that could be wrong.
1330 fn settle(&mut self, block: Block, arriving: &[(Value, mir::Reg)]) -> Result<(), Unsupported> {
1331 let Some(&(first, _)) = arriving.first() else { return Ok(()) };
1332 if arriving.len() > X87_DEPTH {
1333 let ty = self.source[first].ty;
1334 return Err(Unsupported::Phi { block, count: arriving.len(), ty });
1335 }
1336 // A block parameter comes from no instruction, so what this points at is the first thing
1337 // in the block, which is where a reader looking for the copy would look.
1338 let first_inst = self.source.insts(block).next();
1339 let span = first_inst.map_or(Span::DUMMY, |it| self.source.span(it));
1340 for &(_, reg) in arriving {
1341 let from = self.through(reg);
1342 self.x87_at("fld_t", span, from);
1343 }
1344 for &(param, _) in arriving.iter().rev() {
1345 let into = self.x87_slot(param);
1346 let into = self.through(into);
1347 self.x87_at("fstp_t", span, into);
1348 }
1349 Ok(())
1350 }
1351
1352 /// The frame slot an eighty bit value lives in, as its address in a fresh register.
1353 ///
1354 /// The slot is the value's for the whole function and is taken the first time somebody asks.
1355 /// The address is worked out again every time, which is a `lea` per use and is deliberate: one
1356 /// address kept in a register from the definition to the last use would hold a general purpose
1357 /// register open across everything in between, and a function with a handful of these in it
1358 /// would spend its registers on addresses of things rather than on things.
1359 fn x87_slot(&mut self, value: Value) -> mir::Reg {
1360 // An argument of the function has a slot already and it is the caller's. The convention
1361 // puts the bytes in the argument area and hands over where they are, so the address that
1362 // arrived is the answer and no second copy of the value is made. Nothing ever writes to a
1363 // value of this type once it exists, so nothing writes to the caller's copy either. A
1364 // parameter of any other block is not this: what arrived there is an address a predecessor
1365 // chose, [`Lowering::settle`] has already copied the bytes out of it, and the slot those
1366 // bytes landed in is the one below.
1367 let entry = self.source.entry();
1368 if let (Def::Param { block, .. }, Some(reg)) =
1369 (self.source[value].def, self.regs[value.index()])
1370 {
1371 if entry == Some(block) {
1372 return reg;
1373 }
1374 }
1375 let index = match self.slots[value.index()] {
1376 Some(index) => index,
1377 None => {
1378 let index = self.stack.locals.len();
1379 self.stack.locals.push(Local { size: X87_BYTES, align: X87_BYTES });
1380 self.slots[value.index()] = Some(index);
1381 index
1382 }
1383 };
1384 let block = self.at.expect("a block is being filled");
1385 self.frame_address(block, index)
1386 }
1387
1388 /// The bytes a value crosses between a register and the x87 stack through, as their address
1389 /// in a fresh register.
1390 fn x87_crossing(&mut self) -> mir::Reg {
1391 let index = match self.crossing {
1392 Some(index) => index,
1393 None => {
1394 let index = self.stack.locals.len();
1395 self.stack.locals.push(Local { size: X87_CROSSING, align: X87_CROSSING });
1396 self.crossing = Some(index);
1397 index
1398 }
1399 };
1400 let block = self.at.expect("a block is being filled");
1401 self.frame_address(block, index)
1402 }
1403
1404 /// The two control words, as the address of the first of them in a fresh register.
1405 fn x87_control(&mut self) -> mir::Reg {
1406 let index = match self.control {
1407 Some(index) => index,
1408 None => {
1409 let index = self.stack.locals.len();
1410 self.stack.locals.push(Local { size: 4, align: 4 });
1411 self.control = Some(index);
1412 index
1413 }
1414 };
1415 let block = self.at.expect("a block is being filled");
1416 self.frame_address(block, index)
1417 }
1418
1419 /// An address held in a register, as the addressing mode that reaches it.
1420 fn through(&self, reg: mir::Reg) -> mir::Mem {
1421 mir::Mem::at(mir::Operand::read(reg, self.gpr))
1422 }
1423
1424 /// One instruction of a group, which names an address and nothing else.
1425 ///
1426 /// Every x87 instruction that moves a value is one of these. What it does to the stack is in
1427 /// the mnemonic rather than in an operand, so there is no register to write down and no
1428 /// register the allocator gets a say in.
1429 fn x87_at(&mut self, name: &str, span: Span, at: mir::Mem) {
1430 let block = self.at.expect("a block is being filled");
1431 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1432 self.out.build(block, opcode).at(span).mem(at).finish();
1433 }
1434
1435 /// One instruction of a group that names nothing at all.
1436 ///
1437 /// The arithmetic is these. Both of an add's operands are already on the stack when it runs
1438 /// and so is where the answer goes, and the stack is not somewhere an instruction says, so
1439 /// `faddp` has an argument in the assembler's syntax and nothing here for the argument to come
1440 /// from. What it works on is which two pushes came before it, which is a fact about the order
1441 /// of the group and is why the group is written in one place.
1442 fn x87_only(&mut self, name: &str, span: Span) {
1443 let block = self.at.expect("a block is being filled");
1444 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1445 self.out.build(block, opcode).at(span).finish();
1446 }
1447
1448 /// A `load` of a `long double`: onto the stack from where it was, and off it into the slot.
1449 ///
1450 /// Two instructions rather than the two general purpose moves the same sixteen bytes would
1451 /// take, because `fld` and `fstp` at this format neither convert nor look: the value goes on
1452 /// in the format it was already in and comes back off in it, so a signalling NaN stays one
1453 /// and nothing is raised. Which is what makes this a copy at all.
1454 fn x87_load(&mut self, inst: Inst) -> Result<(), Unsupported> {
1455 let (args, result) = self.ends(inst)?;
1456 let &address = args.first().ok_or_else(|| self.unsupported(inst))?;
1457 let span = self.source.span(inst);
1458 let from = self.reg_of(address)?;
1459 let from = self.through(from);
1460 let into = self.x87_slot(result);
1461 let into = self.through(into);
1462 self.x87_at("fld_t", span, from);
1463 self.x87_at("fstp_t", span, into);
1464 Ok(())
1465 }
1466
1467 /// A `store` of a `long double`: the same pair the other way round.
1468 fn x87_store(&mut self, inst: Inst) -> Result<(), Unsupported> {
1469 let args = self.source[self.source[inst].args].to_vec();
1470 let [value, address] = args[..] else { return Err(self.unsupported(inst)) };
1471 let span = self.source.span(inst);
1472 let from = self.x87_slot(value);
1473 let from = self.through(from);
1474 let into = self.reg_of(address)?;
1475 let into = self.through(into);
1476 self.x87_at("fld_t", span, from);
1477 self.x87_at("fstp_t", span, into);
1478 Ok(())
1479 }
1480
1481 /// A `float`, a `double` or an integer becoming a `long double`.
1482 ///
1483 /// Through memory, because the x87 reads memory and nothing else: the value is in a register
1484 /// the machine has and the unit has no way to be handed one, so it is written to the crossing
1485 /// bytes and loaded back at the format that widens it. Every one of these is exact. Sixty four
1486 /// bits of significand and fifteen of exponent hold every `float`, every `double` and every
1487 /// sixty four bit integer outright, so none of the four can round and none can raise.
1488 fn x87_across(
1489 &mut self,
1490 inst: Inst,
1491 put: &'static str,
1492 class: RegClass,
1493 get: &'static str,
1494 ) -> Result<(), Unsupported> {
1495 let (args, result) = self.ends(inst)?;
1496 let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1497 let span = self.source.span(inst);
1498 let value = self.reg_of(source)?;
1499 let across = self.x87_crossing();
1500 let across = self.through(across);
1501 let into = self.x87_slot(result);
1502 let into = self.through(into);
1503
1504 let block = self.at.expect("a block is being filled");
1505 let store = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{put}")));
1506 self.out.build(block, store).at(span).uses(value, class).mem(across).finish();
1507 self.x87_at(get, span, across);
1508 self.x87_at("fstp_t", span, into);
1509 Ok(())
1510 }
1511
1512 /// A `long double` becoming a `float`, a `double` or an integer.
1513 ///
1514 /// Through memory for the reason above and in the same three instructions backwards. The two
1515 /// that go to a float round to nearest, which is what the control word says unless somebody
1516 /// has changed it and is what C wants. The two that go to an integer do not, which is why they
1517 /// do not come here.
1518 fn x87_back(
1519 &mut self,
1520 inst: Inst,
1521 put: &'static str,
1522 get: &'static str,
1523 class: RegClass,
1524 ) -> Result<(), Unsupported> {
1525 let (args, result) = self.ends(inst)?;
1526 let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1527 let span = self.source.span(inst);
1528 let from = self.x87_slot(source);
1529 let from = self.through(from);
1530 let across = self.x87_crossing();
1531 let across = self.through(across);
1532
1533 self.x87_at("fld_t", span, from);
1534 self.x87_at(put, span, across);
1535 let block = self.at.expect("a block is being filled");
1536 let reg = self.new_reg(result);
1537 let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{get}")));
1538 self.out.build(block, load).at(span).def(reg, class).mem(across).finish();
1539 Ok(())
1540 }
1541
1542 /// An `fpext` up to a `long double`, which is the only direction this machine has one in.
1543 fn x87_widen(&mut self, inst: Inst) -> Result<(), Unsupported> {
1544 let sse = self.conv.sse_class;
1545 match self.source[self.narrow(inst)?].ty.bits() {
1546 32 => self.x87_across(inst, "movss_mr", sse, "fld_s"),
1547 64 => self.x87_across(inst, "movsd_mr", sse, "fld_l"),
1548 _ => Err(self.unsupported(inst)),
1549 }
1550 }
1551
1552 /// An `fptrunc` down from a `long double`, which is the other direction of the same.
1553 fn x87_narrow(&mut self, inst: Inst) -> Result<(), Unsupported> {
1554 let sse = self.conv.sse_class;
1555 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
1556 match self.source[result].ty.bits() {
1557 32 => self.x87_back(inst, "fstp_s", "movss_rm", sse),
1558 64 => self.x87_back(inst, "fstp_l", "movsd_rm", sse),
1559 _ => Err(self.unsupported(inst)),
1560 }
1561 }
1562
1563 /// A `sitofp` up to a `long double`.
1564 ///
1565 /// Thirty two bits and sixty four, and nothing narrower, because C widens an integer to `int`
1566 /// before it converts one and the front end writes that widening down. An unsigned integer is
1567 /// not here at all: `fild` reads its operand as signed, so a value above the signed range
1568 /// comes back short by two to the sixty fourth and has to be added back, which is arithmetic
1569 /// rather than a move and waits with the rest of it.
1570 fn x87_from_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
1571 let gpr = self.gpr;
1572 match self.source[self.narrow(inst)?].ty.bits() {
1573 32 => self.x87_across(inst, "mov_mr_32", gpr, "fild_l"),
1574 64 => self.x87_across(inst, "mov_mr_64", gpr, "fild_ll"),
1575 _ => Err(self.unsupported(inst)),
1576 }
1577 }
1578
1579 /// An `fptosi` down from a `long double`, which is the one conversion here with no single
1580 /// instruction behind it.
1581 ///
1582 /// C cuts towards zero and the unit rounds the way its control word says, so the store that
1583 /// takes the value off the stack is wrapped in the control word being saved, changed and put
1584 /// back. Five instructions around the one that does the work, and three more moving the word
1585 /// through a register, because this machine has no way to OR a constant into memory at this
1586 /// width. The unit has a shorter answer in `fisttp`, and `spec/10-backend.md` section 10.8
1587 /// says why it is not used: it is SSE3, the x86-64 baseline is not, and there is nothing here
1588 /// that can gate an instruction on a feature yet.
1589 fn x87_to_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
1590 let (args, result) = self.ends(inst)?;
1591 let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1592 let (put, get) = match self.source[result].ty.bits() {
1593 32 => ("fistp_l", "mov_rm_32"),
1594 64 => ("fistp_ll", "mov_rm_64"),
1595 _ => return Err(self.unsupported(inst)),
1596 };
1597 let span = self.source.span(inst);
1598 let gpr = self.gpr;
1599 let from = self.x87_slot(source);
1600 let from = self.through(from);
1601 let across = self.x87_crossing();
1602 let across = self.through(across);
1603 let control = self.x87_control();
1604 let saved = self.through(control).plus(0);
1605 let cut = self.through(control).plus(2);
1606
1607 // The word the unit has now, into the first of the two slots and into a register, with the
1608 // rounding field turned to truncate on the way to the second.
1609 self.x87_at("fnstcw", span, saved);
1610 let block = self.at.expect("a block is being filled");
1611 let was = self.out.new_vreg(gpr);
1612 let read = mir::Opcode::new(self.names.intern("x64.mov_rm_16"));
1613 self.out.build(block, read).at(span).def(was, gpr).mem(saved).finish();
1614 let now = self.out.new_vreg(gpr);
1615 let set = mir::Opcode::new(self.names.intern("x64.or_ri_16"));
1616 // Two address, which is written out here rather than taken from the two shorthands
1617 // because the shorthands leave an operand unconstrained: this machine ORs into the
1618 // register it read, so the two have to be the same one and only the constraint says so.
1619 self.out
1620 .build(block, set)
1621 .at(span)
1622 .operand(mir::Operand::write(now, gpr).with(Constraint::Reuse(1)))
1623 .operand(mir::Operand::read(was, gpr))
1624 .imm(X87_TRUNCATE)
1625 .finish();
1626 let write = mir::Opcode::new(self.names.intern("x64.mov_mr_16"));
1627 self.out.build(block, write).at(span).uses(now, gpr).mem(cut).finish();
1628
1629 // The conversion itself, under the changed word, and then the word the unit had put back
1630 // before anything else runs.
1631 self.x87_at("fldcw", span, cut);
1632 self.x87_at("fld_t", span, from);
1633 self.x87_at(put, span, across);
1634 self.x87_at("fldcw", span, saved);
1635
1636 let block = self.at.expect("a block is being filled");
1637 let reg = self.new_reg(result);
1638 let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{get}")));
1639 self.out.build(block, load).at(span).def(reg, gpr).mem(across).finish();
1640 Ok(())
1641 }
1642
1643 /// A constant of this type, as the bits of it written into its slot.
1644 ///
1645 /// No x87 instruction at all, which is the surprise here. A slot holding an eighty bit value is
1646 /// the value, so a constant is ten bytes put where the value lives, and the unit never has to
1647 /// see it: whatever reads it will `fld` it out of the slot the way it reads any other one.
1648 ///
1649 /// Ten bytes in two goes, because the machine stores eight at a time and there is no store of
1650 /// an immediate to memory, so each half is put in a register first. The six bytes above the ten
1651 /// are left alone, since nothing reads them: they are the padding that makes the type sixteen
1652 /// wide and they are unspecified in the psABI rather than zero.
1653 ///
1654 /// The other way is a constant pool, an `fldt` of a symbol, and a relocation, which is what a
1655 /// compiler with somewhere to put a literal does. This back end has nowhere to put one yet, and
1656 /// four instructions in the frame is what that costs until it does.
1657 fn x87_const(&mut self, inst: Inst) -> Result<(), Unsupported> {
1658 let Extra::Imm(imm) = self.source[inst].extra else { return Err(self.unsupported(inst)) };
1659 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
1660 let bits = self.source[imm].bits();
1661 let span = self.source.span(inst);
1662 let gpr = self.gpr;
1663 let slot = self.x87_slot(result);
1664 let low = self.through(slot).plus(0);
1665 let high = self.through(slot).plus(8);
1666
1667 let block = self.at.expect("a block is being filled");
1668 for (bytes, at, into) in
1669 [(bits as u64 as i64, low, "64"), (((bits >> 64) & 0xffff) as i64, high, "16")]
1670 {
1671 let held = self.out.new_vreg(gpr);
1672 let put = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_ri_{into}")));
1673 self.out.build(block, put).at(span).def(held, gpr).imm(bytes).finish();
1674 let store = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_mr_{into}")));
1675 self.out.build(block, store).at(span).uses(held, gpr).mem(at).finish();
1676 }
1677 Ok(())
1678 }
1679
1680 /// One arithmetic instruction on two eighty bit values, as the four it takes.
1681 ///
1682 /// The left operand is pushed first and the right one on top of it, so the left ends up
1683 /// underneath and the answer wanted is the one below against the top in that order. Which of
1684 /// the two mnemonics computes that is a question about the spelling rather than about the
1685 /// machine, and the two spellings disagree. Intel's `FSUBP ST(i), ST(0)` is `ST(i) - ST(0)`
1686 /// and is `DE E8+i`, and AT&T's `fsubp` is `DE E0+i`, which is the other subtraction. This
1687 /// compiler writes AT&T and encodes what gas encodes, so what it asks for here is `fsubr_p`
1688 /// and `fdivr_p`, and the `r` is not a reversal of anything the code generator decided.
1689 ///
1690 /// An addition and a multiplication have one form each and do not care, which is why a test
1691 /// that reads the mnemonic back would not have caught this and one that computes a subtraction
1692 /// and checks the answer does.
1693 ///
1694 /// The answer is left where the deeper of the two was and the shallower is gone, which is what
1695 /// the `p` on the mnemonic means, so one push has already been paid back by the time the
1696 /// `fstp` runs and the stack is level again after it.
1697 ///
1698 /// Nothing here is folded and nothing is reused. Two values that are the same value get two
1699 /// pushes of the same slot, and an operand that was just computed is read back out of the slot
1700 /// it was written to rather than left on the stack, which costs a store and a load per
1701 /// instruction in an expression. Keeping a partial result on the stack across the next
1702 /// instruction's operands means knowing how deep the stack is at every point in the block, and
1703 /// that is a different thing from writing a group.
1704 fn x87_arith(&mut self, inst: Inst, with: &'static str) -> Result<(), Unsupported> {
1705 let (args, result) = self.ends(inst)?;
1706 let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
1707 let span = self.source.span(inst);
1708 let left = self.x87_slot(left);
1709 let left = self.through(left);
1710 let right = self.x87_slot(right);
1711 let right = self.through(right);
1712 let into = self.x87_slot(result);
1713 let into = self.through(into);
1714 self.x87_at("fld_t", span, left);
1715 self.x87_at("fld_t", span, right);
1716 self.x87_only(with, span);
1717 self.x87_at("fstp_t", span, into);
1718 Ok(())
1719 }
1720
1721 /// A negation, which is a push, the sign bit turned over and a pop.
1722 ///
1723 /// `fchs` does not read the value as a number, so this is right for a zero, for an infinity
1724 /// and for a NaN, and it raises nothing on any of them. Which is what C asks of a negation and
1725 /// is not what subtracting from zero would give: `0.0L - x` is a different answer at a
1726 /// negative zero and a signalling one at a NaN.
1727 fn x87_flip(&mut self, inst: Inst) -> Result<(), Unsupported> {
1728 let (args, result) = self.ends(inst)?;
1729 let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1730 let span = self.source.span(inst);
1731 let from = self.x87_slot(source);
1732 let from = self.through(from);
1733 let into = self.x87_slot(result);
1734 let into = self.through(into);
1735 self.x87_at("fld_t", span, from);
1736 self.x87_only("fchs", span);
1737 self.x87_at("fstp_t", span, into);
1738 Ok(())
1739 }
1740
1741 /// A comparison of two eighty bit values, as the two pushes and the one opcode that reads them.
1742 ///
1743 /// The right operand is pushed first and the left one on top of it, which is the other way
1744 /// round from the arithmetic and is because `fucomip` asks about the top against what is under
1745 /// it: the comparison this machine can do is the top's, so the value the predicate is about
1746 /// has to be the top. The pop that gets the loser off the stack and the byte that reads the
1747 /// flags are both inside the opcode, since what passes between those and the comparison is the
1748 /// flags and the flags are not something anything here can name.
1749 ///
1750 /// Which of the ten opcodes, and which way round, is the same table the vector comparisons
1751 /// match against in `rules/x86-64.rules`, and it has to stay the same table: a predicate that
1752 /// picked a different condition here than there would be a `long double` comparison that
1753 /// disagreed with the `double` comparison of the same two numbers, which is the one thing a
1754 /// wider format is not allowed to do.
1755 ///
1756 /// The always false and the always true are refused rather than folded into a constant,
1757 /// because a comparison this machine never has to do is one the optimizer should have removed
1758 /// and an instruction here that quietly agreed with it would hide that it did not.
1759 fn x87_compare(&mut self, inst: Inst) -> Result<(), Unsupported> {
1760 let Extra::FloatPred(pred) = self.source[inst].extra else {
1761 return Err(self.unsupported(inst));
1762 };
1763 let (args, result) = self.ends(inst)?;
1764 let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
1765 // Two of the fourteen need a second byte and an instruction to put the two together,
1766 // because they are two conditions at once: an ordered equal is equal and not unordered,
1767 // and an unordered not equal is either. The opcode carries all of that and says here only
1768 // that it writes somewhere else as well.
1769 let (name, reversed, both) = match pred {
1770 FloatPred::Ogt => ("fucomip_set_a", false, false),
1771 FloatPred::Oge => ("fucomip_set_ae", false, false),
1772 FloatPred::Olt => ("fucomip_set_a", true, false),
1773 FloatPred::Ole => ("fucomip_set_ae", true, false),
1774 FloatPred::One => ("fucomip_set_ne", false, false),
1775 FloatPred::Ord => ("fucomip_set_np", false, false),
1776 FloatPred::Uno => ("fucomip_set_p", false, false),
1777 FloatPred::Ueq => ("fucomip_set_e", false, false),
1778 FloatPred::Ult => ("fucomip_set_b", false, false),
1779 FloatPred::Ule => ("fucomip_set_be", false, false),
1780 FloatPred::Ugt => ("fucomip_set_b", true, false),
1781 FloatPred::Uge => ("fucomip_set_be", true, false),
1782 FloatPred::Oeq => ("fucomip_set_e_and_np", false, true),
1783 FloatPred::Une => ("fucomip_set_ne_or_p", false, true),
1784 FloatPred::False | FloatPred::True => return Err(self.unsupported(inst)),
1785 };
1786 let (top, under) = if reversed { (right, left) } else { (left, right) };
1787
1788 let span = self.source.span(inst);
1789 let gpr = self.gpr;
1790 let under = self.x87_slot(under);
1791 let under = self.through(under);
1792 let top = self.x87_slot(top);
1793 let top = self.through(top);
1794 self.x87_at("fld_t", span, under);
1795 self.x87_at("fld_t", span, top);
1796
1797 let block = self.at.expect("a block is being filled");
1798 let reg = self.new_reg(result);
1799 // Taken before the instruction is started rather than inside it, since both come from the
1800 // same function being built and only one thing at a time may be adding to it.
1801 let spare = both.then(|| self.out.new_vreg(gpr));
1802 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1803 let mut build = self.out.build(block, opcode).at(span).def(reg, gpr);
1804 if let Some(spare) = spare {
1805 build = build.def(spare, gpr);
1806 }
1807 build.finish();
1808 Ok(())
1809 }
1810
1811 /// The operands and the one result of an instruction that has exactly one.
1812 fn ends(&self, inst: Inst) -> Result<(&'a [Value], Value), Unsupported> {
1813 let data = &self.source[inst];
1814 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1815 Ok((&self.source[data.args], result))
1816 }
1817
1818 /// The operand of a conversion, which is the end of it that is not the `long double`.
1819 fn narrow(&self, inst: Inst) -> Result<Value, Unsupported> {
1820 let args = &self.source[self.source[inst].args];
1821 args.first().copied().ok_or_else(|| self.unsupported(inst))
1822 }
1823
1824 /// One `va_start`, as the four fields of the list it was handed.
1825 ///
1826 /// Two of them are numbers this already knows, and each costs an instruction to put in a
1827 /// register before it can be stored, because the machine here has no store of an immediate to
1828 /// memory. The other two are addresses in the frame, and each is a `lea` [`crate::finish`]
1829 /// finishes: the save area is one of the function's own stack objects, and the caller's
1830 /// argument area is where the parameters that had no register came from, which is the same
1831 /// place and the same fixup a parameter past the sixth already uses.
1832 ///
1833 /// What is written is exactly the four fields [`crate::varargs`] describes, in the order they
1834 /// are laid out, so that reading this beside that table is the whole of the check.
1835 fn va_start(&mut self, inst: Inst) -> Result<(), Unsupported> {
1836 let Some(&list) = self.source[self.source[inst].args].first() else {
1837 return Err(self.unsupported(inst));
1838 };
1839 let started = self.varargs.ok_or_else(|| self.unsupported(inst))?;
1840 let list = self.reg_of(list)?;
1841 let block = self.at.expect("a block is being filled");
1842 let span = self.source.span(inst);
1843
1844 for (at, count) in
1845 [(varargs::GP_OFFSET, started.integers), (varargs::FP_OFFSET, started.floats)]
1846 {
1847 let held = self.out.new_vreg(self.gpr);
1848 let load = mir::Opcode::new(self.names.intern("x64.mov_ri_32"));
1849 self.out.build(block, load).at(span).def(held, self.gpr).imm(i64::from(count)).finish();
1850
1851 let store = mir::Opcode::new(self.names.intern("x64.mov_mr_32"));
1852 let mem = self.field(list, at);
1853 self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
1854 }
1855
1856 // The first argument the signature did not name, which is as far up the caller's argument
1857 // area as the ones it did name reached. Nothing here knows where that area is, so the
1858 // distance is recorded the way a parameter read out of it is and finished with it.
1859 let overflow = self.out.new_vreg(self.gpr);
1860 let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
1861 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
1862 let made = self
1863 .out
1864 .build(block, lea)
1865 .at(span)
1866 .def(overflow, self.gpr)
1867 .mem(mir::Mem::at(sp))
1868 .finish();
1869 self.stack.arguments.push((made, started.incoming));
1870
1871 let save = self.frame_address(block, started.save);
1872 for (at, held) in [(varargs::OVERFLOW, overflow), (varargs::SAVE_AREA, save)] {
1873 let store = mir::Opcode::new(self.names.intern("x64.mov_mr_64"));
1874 let mem = self.field(list, at);
1875 self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
1876 }
1877 Ok(())
1878 }
1879
1880 /// One field of a list, as the addressing mode that reaches it.
1881 fn field(&self, list: mir::Reg, at: i64) -> mir::Mem {
1882 let base = mir::Operand::read(list, self.gpr);
1883 mir::Mem::at(base).plus(i32::try_from(at).expect("a field of a list is a small offset"))
1884 }
1885
1886 /// The address of a name: one `lea` off the instruction pointer, with the name on it.
1887 ///
1888 /// The same instruction an `alloca` gets and for a related reason. An address that is not in
1889 /// the program is a `lea` of an addressing mode that names no register, and the mode carries
1890 /// the symbol so that [`rucc_asm`] can write it relative to `%rip` and leave the relocation
1891 /// for the assembler. Both halves of that already existed: the printer writes `sym(%rip)` and
1892 /// the encoder emits the relocation, because a call to a name the file does not define needed
1893 /// them first.
1894 ///
1895 /// One `mov` and not one `lea` when the name is one [`Elsewhere`] holds, because the distance
1896 /// the `lea` adds to the instruction pointer is a number only a link that puts the name in
1897 /// this program can work out, and the address of a function this file merely declares is not
1898 /// such a number. The load reads the address out of the slot the linker fills in instead. The
1899 /// linker turns it back into the `lea` when the name turns out to have been here all along,
1900 /// so this is not slower in the case that was already right.
1901 ///
1902 /// There is deliberately no name for this in [`crate::term`], which is what stops the address
1903 /// being folded into the instruction that reads it. Folding it is the right thing to do and
1904 /// is what turns a load of a global from two instructions into one, but it is a separate
1905 /// question about addressing modes and issue #282 is it. Until then the address is in a
1906 /// register before anything uses it, which is correct and one instruction longer.
1907 ///
1908 /// What this does not do is give the name anything to refer to. A module carries its globals
1909 /// and nothing writes them out, so a file that defines the variable it reads compiles to a
1910 /// reference the linker cannot resolve. Issue #293 is the other half.
1911 ///
1912 /// A thread-local variable is neither of the two above and is [`Self::thread_address`].
1913 fn address_of(&mut self, inst: Inst) -> Result<(), Unsupported> {
1914 let data = &self.source[inst];
1915 let Extra::Symbol(symbol) = data.extra else { return Err(self.unsupported(inst)) };
1916 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1917 if self.elsewhere.thread(symbol) {
1918 return self.thread_address(inst, symbol, result);
1919 }
1920
1921 let block = self.at.expect("a block is being filled");
1922 let reg = self.new_reg(result);
1923 let span = self.source.span(inst);
1924 let (mnemonic, mem) = if self.elsewhere.holds(symbol) {
1925 (GOT_LOAD, mir::Mem::got(symbol))
1926 } else {
1927 (x86_64::FRAME.lea, mir::Mem::of(symbol))
1928 };
1929 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{mnemonic}")));
1930 self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
1931 Ok(())
1932 }
1933
1934 /// The address of a thread-local variable, which is this thread's copy of it.
1935 ///
1936 /// Neither instruction the ordinary case writes would mean anything here. There is no distance
1937 /// to the variable for a `lea` to add, because there is no variable: there is one copy of it per
1938 /// thread and they are at different addresses, so a link asked for the distance to the name
1939 /// refuses rather than picking one. And there is no address for a table slot to hold either, for
1940 /// the same reason.
1941 ///
1942 /// What is the same in every thread is where the variable sits inside the block of storage a
1943 /// thread gets, so that offset is what the link writes down, and the address of the running
1944 /// thread's block is what turns it into an address. x86-64 keeps that address in `%fs`, at the
1945 /// front of the block, so the whole of this is three instructions:
1946 ///
1947 /// ```text
1948 /// movq x@gottpoff(%rip), %off # how far into the block x sits, which the link fills in
1949 /// movq %fs:0, %tp # where this thread's block is, which only the machine knows
1950 /// addq %tp, %off # this thread's copy of x
1951 /// ```
1952 ///
1953 /// That is the initial exec model. It is one instruction longer than what gcc writes at `-O2`
1954 /// in an executable, which folds the addition into the instruction that uses the address, and
1955 /// the difference is issue #282 rather than anything about threads: nothing here folds an
1956 /// address into its reader yet. The link relaxes the first instruction into an immediate when it
1957 /// is making an executable, since it lays the blocks out and therefore knows the number, so the
1958 /// table slot costs nothing in the case that is common.
1959 ///
1960 /// It is not the most general model. A library loaded by `dlopen` gets its storage after the
1961 /// program is already running, and the block this reaches was laid out before it started, so
1962 /// the loader has to find room in that block for the library's variables. glibc keeps a little
1963 /// spare room for exactly this and a library that fits in it loads and runs; one that does not
1964 /// fails to load, with a message saying so. The model with no such limit calls `__tls_get_addr`
1965 /// and is what gcc writes under `-fPIC` by default, and it is issue #1104.
1966 ///
1967 /// So this is the model gcc writes under `-ftls-model=initial-exec`: right for an executable,
1968 /// right for a library the program is linked against, and a load that either works or is
1969 /// refused out loud for a library something opens later. What it is never is quietly wrong.
1970 fn thread_address(
1971 &mut self,
1972 inst: Inst,
1973 symbol: Symbol,
1974 result: Value,
1975 ) -> Result<(), Unsupported> {
1976 let block = self.at.expect("a block is being filled");
1977 let span = self.source.span(inst);
1978 let gpr = self.gpr;
1979 let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{GOT_LOAD}")));
1980
1981 let offset = self.out.new_vreg(gpr);
1982 self.out
1983 .build(block, load)
1984 .at(span)
1985 .def(offset, gpr)
1986 .mem(mir::Mem::thread(symbol))
1987 .finish();
1988 // The front of the block, which is the one thing on this machine that no instruction can
1989 // work out: `%fs` is not a register a program can read, and what it points at is a word
1990 // holding its own address, so reading through it at zero is how the address is come by.
1991 let pointer = self.out.new_vreg(gpr);
1992 let at = mir::Mem::in_segment(Segment::Fs, 0);
1993 self.out.build(block, load).at(span).def(pointer, gpr).mem(at).finish();
1994
1995 // Two address, spelled out for the reason `x87_to_int` gives: this machine adds into the
1996 // register it read, and only the constraint says the two are the same one.
1997 let reg = self.new_reg(result);
1998 let add = mir::Opcode::new(self.names.intern(&format!("{PREFIX}add_rr_64")));
1999 self.out
2000 .build(block, add)
2001 .at(span)
2002 .operand(mir::Operand::write(reg, gpr).with(Constraint::Reuse(1)))
2003 .operand(mir::Operand::read(offset, gpr))
2004 .operand(mir::Operand::read(pointer, gpr))
2005 .finish();
2006 Ok(())
2007 }
2008
2009 /// `&&label`, GNU's address of a label, which is the same `lea` a global gets against a place
2010 /// in this same function.
2011 ///
2012 /// What the two have in common is the whole of the instruction: an address worked out from
2013 /// where the instruction is, which is what `(%rip)` means and is the only way this compiler
2014 /// reaches anything. What they do not have in common is what fills the four bytes in. A
2015 /// global is a name, so the number is a relocation and the linker writes it. A block is a
2016 /// place in this function, so both ends are in one section and the number is known as soon as
2017 /// the blocks have been laid out, which is why `rucc_asm` fills it in the way it fills in a
2018 /// jump rather than leaving a relocation behind.
2019 ///
2020 /// Nothing here says the block is one control can arrive at. That is said by the
2021 /// [`Opcode::IndirectBr`] that reads the address, which lists every block it can arrive at,
2022 /// and by nothing else: an address on its own is a number.
2023 fn block_address(&mut self, inst: Inst) -> Result<(), Unsupported> {
2024 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2025 let Some(call) = self.source.successors(inst).next() else {
2026 return Err(self.unsupported(inst));
2027 };
2028 let block = self.at.expect("a block is being filled");
2029 let reg = self.new_reg(result);
2030 let span = self.source.span(inst);
2031 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
2032 let mem = mir::Mem::block(self.out_block(call.block));
2033 self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
2034 Ok(())
2035 }
2036
2037 /// `goto *p`, GNU's computed goto, which is a jump through a register.
2038 ///
2039 /// Where it goes is not written here and cannot be. Every block it can arrive at is on the
2040 /// block this ends, the way every other arm is, and which of them the address holds is decided
2041 /// while the program runs. So this is one instruction with one operand, and the arms are
2042 /// copied across by [`Self::edges`] like anybody else's.
2043 fn indirect_branch(&mut self, inst: Inst) -> Result<(), Unsupported> {
2044 let data = &self.source[inst];
2045 let &address = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
2046 let reg = self.reg_of(address)?;
2047 let block = self.at.expect("a block is being filled");
2048 let span = self.source.span(inst);
2049 let name = x86_64::BRANCH.indirect;
2050 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
2051 self.out.build(block, opcode).at(span).operand(mir::Operand::read(reg, self.gpr)).finish();
2052 Ok(())
2053 }
2054
2055 /// `__builtin_frame_address` and `__builtin_return_address`, which are a walk up the chain of
2056 /// saved frame pointers and then one thing read at the end of it.
2057 ///
2058 /// Every frame that kept a frame pointer holds the caller's at the address the register points
2059 /// at, and the address that frame returns to one word above that, which is where the call
2060 /// instruction put it and where the prologue's push left it. So the walk is a load through the
2061 /// register for each link, the frame address is wherever the walk stopped, and the return
2062 /// address is one more load from a word above it. gcc 16.2.0 writes exactly this, measured on
2063 /// x86-64 at `-O2` for depths zero to three of both builtins.
2064 ///
2065 /// The function is given a frame pointer because of this, which is what [`Stack::walks_frames`]
2066 /// carries out to the layout. A depth of zero needs it as the answer and every depth above zero
2067 /// needs it as the start, so there is no case here where it is not wanted.
2068 ///
2069 /// How far the chain actually reaches is the program's business and not this one's. A caller
2070 /// compiled without a frame pointer has no link in it for the walk to follow, so a depth above
2071 /// zero is a promise about how the whole program was built. That is why gcc documents a nonzero
2072 /// depth as unsafe rather than as an answer, and why the depth is refused above a limit in
2073 /// `check/builtin/frame.rs` rather than walked as far as it says.
2074 fn frames(&mut self, inst: Inst) -> Result<(), Unsupported> {
2075 let data = &self.source[inst];
2076 let Extra::Depth(depth) = data.extra else { return Err(self.unsupported(inst)) };
2077 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2078 let returning = data.opcode == Opcode::ReturnAddress;
2079 let block = self.at.expect("a block is being filled");
2080 let span = self.source.span(inst);
2081 let moves = x86_64::FRAME.moves(self.gpr).expect("a class the target says how to move");
2082 let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", moves.load)));
2083 self.stack.walks_frames = true;
2084
2085 // Where the walk is up to. The frame pointer to begin with, and the register the last load
2086 // wrote after that.
2087 let reg = self.new_reg(result);
2088 let mut base = mir::Reg::physical(self.conv.frame_pointer);
2089 for link in 0..depth {
2090 // The last load of a walk that is looking for a frame writes the answer itself, which
2091 // is what keeps a walk of so many links that many instructions and not one more.
2092 let ends_here = link + 1 == depth && !returning;
2093 let next = if ends_here { reg } else { self.out.new_vreg(self.gpr) };
2094 let at = mir::Mem::at(mir::Operand::read(base, self.gpr));
2095 self.out.build(block, load).at(span).def(next, self.gpr).mem(at).finish();
2096 base = next;
2097 }
2098
2099 if returning {
2100 let up = i32::try_from(self.conv.return_address).expect("a word above the frame");
2101 let at = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
2102 self.out.build(block, load).at(span).def(reg, self.gpr).mem(at).finish();
2103 } else if depth == 0 {
2104 // The one case with no load in it at all: the frame this function is running in is the
2105 // register itself, and a physical register is not one the allocator hands out, so the
2106 // answer is a copy of it.
2107 let mov = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", moves.mov)));
2108 self.out
2109 .build(block, mov)
2110 .at(span)
2111 .operand(mir::Operand::write(reg, self.gpr))
2112 .operand(mir::Operand::read(base, self.gpr))
2113 .finish();
2114 }
2115 Ok(())
2116 }
2117
2118 /// `__builtin_thread_pointer`, which is the front of the block [`Self::thread_address`] adds
2119 /// an offset to.
2120 ///
2121 /// The same one instruction, on its own this time and with nothing to add to it. A program
2122 /// writes this when what it wants is a number that is different in every thread and cheap to
2123 /// come by, rather than a variable of its own in the block, so there is no relocation here and
2124 /// no name for the link to resolve.
2125 fn thread_pointer(&mut self, inst: Inst) -> Result<(), Unsupported> {
2126 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2127 let block = self.at.expect("a block is being filled");
2128 let span = self.source.span(inst);
2129 let reg = self.new_reg(result);
2130 let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{GOT_LOAD}")));
2131 let at = mir::Mem::in_segment(Segment::Fs, 0);
2132 self.out.build(block, load).at(span).def(reg, self.gpr).mem(at).finish();
2133 Ok(())
2134 }
2135
2136 /// A conversion that converts nothing: the result is the operand under another type.
2137 ///
2138 /// `ptrtoint` and `inttoptr` at one width are the whole of this. An address on this machine is
2139 /// an integer as wide as the machine addresses, so a cast between the two changes what the
2140 /// type system calls the value and changes nothing about the value, and the register holding
2141 /// it is the register that already held it. The front end never writes either of them at any
2142 /// other width, because it widens or narrows around the cast rather than through it, so the
2143 /// two widths disagreeing here means the IR came from somewhere else and is refused rather
2144 /// than guessed at.
2145 ///
2146 /// Reading the operand first is what materializes it when it is a constant, which is the case
2147 /// that matters: a null pointer is an `inttoptr` of zero, and that zero has to reach a
2148 /// register before anything can call it an address.
2149 fn rename(&mut self, inst: Inst) -> Result<(), Unsupported> {
2150 let data = &self.source[inst];
2151 let [arg] = self.source[data.args] else { return Err(self.unsupported(inst)) };
2152 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2153 if !self.is_address_width(self.source[arg].ty)
2154 || !self.is_address_width(self.source[result].ty)
2155 {
2156 return Err(self.unsupported(inst));
2157 }
2158 let reg = self.reg_of(arg)?;
2159 self.regs[result.index()] = Some(reg);
2160 Ok(())
2161 }
2162
2163 /// One barrier, which on this machine is one instruction at the strongest ordering and no
2164 /// instruction at all at every other one.
2165 ///
2166 /// x86-64 is total store order, so the only reordering the machine does is a store followed by
2167 /// a load of a different address, and the only ordering that forbids that is sequential
2168 /// consistency. An acquire, a release and an acquire release fence are therefore already true
2169 /// of every program running here, and what a program wanted from writing one is that the
2170 /// compiler not move memory accesses across it. The optimizer has finished by the time this
2171 /// runs and nothing below reorders one access past another, so the constraint is already
2172 /// discharged and there is nothing to write.
2173 ///
2174 /// The strongest one is `mfence`, which is what gcc 16.2.0 writes for
2175 /// `__atomic_thread_fence(__ATOMIC_SEQ_CST)` and for `__sync_synchronize`. A locked instruction
2176 /// on the stack is faster on most parts and is what some compilers write instead; it is also a
2177 /// write to memory the program did not ask for, and the plain barrier is the one that says what
2178 /// it means.
2179 ///
2180 /// Written here by name rather than by a rule, for the same reason a `lea` of a symbol is:
2181 /// there is nothing in a barrier that a proof over bitvectors could discharge. It computes
2182 /// nothing, so there is no equality to state, and what makes it the right answer is the memory
2183 /// model, which the rule language cannot talk about.
2184 fn barrier(&mut self, inst: Inst) -> Result<(), Unsupported> {
2185 let Extra::Order(order) = self.source[inst].extra else {
2186 return Err(self.unsupported(inst));
2187 };
2188 if order != MemOrder::SeqCst {
2189 return Ok(());
2190 }
2191 let block = self.at.expect("a block is being filled");
2192 let span = self.source.span(inst);
2193 let fence = mir::Opcode::new(self.names.intern("x64.mfence"));
2194 self.out.build(block, fence).at(span).finish();
2195 Ok(())
2196 }
2197
2198 /// The instruction a program stops on, which is one byte pair and no operands.
2199 ///
2200 /// `ud2` is an opcode the manual promises will never be given a meaning, so a processor that
2201 /// reaches it raises the fault for an instruction it does not know, and on Linux that arrives
2202 /// at the program as `SIGILL`. That is what `__builtin_trap` is for: a stop that cannot be
2203 /// caught by anything the program installed for an ordinary error, cannot be returned from,
2204 /// and leaves the address of the fault in the core file.
2205 ///
2206 /// Why not a call to `abort`. It is two bytes against a call and a relocation, it needs no
2207 /// library, and it works in the places this one is written most, which are a kernel and a
2208 /// freestanding program that has no `abort` to call. gcc 16.2.0 writes `ud2` here too.
2209 fn trap(&mut self, inst: Inst) {
2210 let block = self.at.expect("a block is being filled");
2211 let span = self.source.span(inst);
2212 let stop = mir::Opcode::new(self.names.intern("x64.ud2"));
2213 self.out.build(block, stop).at(span).finish();
2214 }
2215
2216 /// One hint that an address is about to be used, which is one instruction and no promise.
2217 ///
2218 /// Four instructions on this machine and the locality picks between them, which is what the
2219 /// number means: how much of the data will still be wanted after the access. None of it wanted
2220 /// is `prefetchnta`, which brings the line in without keeping it, and all of it wanted is
2221 /// `prefetcht0`, which brings it as close as the machine can. The two in between are the levels
2222 /// between those. Measured against gcc 16.2.0 on x86-64 rather than read off the manual: zero
2223 /// gives `prefetchnta`, one `prefetcht2`, two `prefetcht1` and three `prefetcht0`.
2224 ///
2225 /// Whether the access will write is not read here, and that is this machine rather than an
2226 /// omission. The write hint is `prefetchw`, which is not in the base instruction set, and gcc
2227 /// writes it only when the command line said the part has it. So a prefetch for a write is the
2228 /// same instruction as a prefetch for a read, which is what gcc 16.2.0 writes without
2229 /// `-mprfchw`, and the difference is carried in the IR for a target that can use it.
2230 ///
2231 /// The address goes in the addressing mode rather than in an operand, the way a store's does.
2232 /// It is built here as the plainest one there is, a register and nothing else, because what
2233 /// arrives is a value and folding an addition into the mode is a rule's job and no rule reaches
2234 /// this instruction. An address the program computed is therefore one `lea` or one add in front
2235 /// of this, which is what it would have been for the load the hint is about anyway.
2236 fn hint(&mut self, inst: Inst) -> Result<(), Unsupported> {
2237 let Extra::Prefetch(hint) = self.source[inst].extra else {
2238 return Err(self.unsupported(inst));
2239 };
2240 let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
2241 let [address] = args[..] else { return Err(self.unsupported(inst)) };
2242 let name = match hint.locality {
2243 0 => "prefetch_nta",
2244 1 => "prefetch_t2",
2245 2 => "prefetch_t1",
2246 PrefetchHint::MOST => "prefetch_t0",
2247 // Nothing else exists. The checker reads a locality outside the range as zero and the
2248 // verifier refuses one that got here another way, so this is a hint that was built
2249 // rather than checked, and the safe answer for a hint is to write no instruction.
2250 _ => return Err(self.unsupported(inst)),
2251 };
2252 let base = self.reg_of(address)?;
2253 let block = self.at.expect("a block is being filled");
2254 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
2255 self.out
2256 .build(block, opcode)
2257 .at(self.source.span(inst))
2258 .mem(mir::Mem::at(mir::Operand::read(base, self.gpr)))
2259 .finish();
2260 Ok(())
2261 }
2262
2263 /// One compare and exchange, which is the instruction every other atomic on this machine is
2264 /// built out of.
2265 ///
2266 /// What the IR asks for is: read what is at an address, compare it against a value the program
2267 /// expected, put a second value there if the two were equal, and say both what was read and
2268 /// whether the exchange happened. The machine has exactly that instruction, and the `lock` in
2269 /// front of it is what makes the whole of it one step as far as every other processor is
2270 /// concerned.
2271 ///
2272 /// The ordering is not read here, and that is the memory model rather than an omission. A
2273 /// locked instruction on x86-64 is a full barrier whatever the program asked for, so a relaxed
2274 /// compare and exchange and a sequentially consistent one are the same instruction, and there
2275 /// is nothing weaker to emit for the weaker orderings. The failure ordering is not read for the
2276 /// same reason.
2277 ///
2278 /// The two values it produces are why this is written by name. The one the program compares
2279 /// against and the one it gets back are both `rax`, which the instruction reads and writes
2280 /// without being told, and the table says so with a fixed constraint at each end rather than
2281 /// leaving the allocator to find out. The second value is the byte behind it, which is the zero
2282 /// flag read out by a `sete`, and it is a definition of the same instruction so that the
2283 /// allocator knows the two are live together and never gives the byte the register the answer
2284 /// is in.
2285 fn exchange(&mut self, inst: Inst) -> Result<(), Unsupported> {
2286 let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
2287 let results: Vec<Value> = self.source[inst].results().collect();
2288 let [addr, expected, desired] = args[..] else { return Err(self.unsupported(inst)) };
2289 let [old, exchanged] = results[..] else { return Err(self.unsupported(inst)) };
2290
2291 // A value the machine can compare in one instruction, which is an integer or an address at
2292 // one of the four widths it has a compare and exchange for. Anything else is a type this
2293 // has no instruction for rather than a program that is wrong, and the front end refuses it
2294 // before ever getting here.
2295 let ty = self.source[old].ty;
2296 let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
2297 if (!ty.is_int() && !ty.is_ptr()) || !matches!(bits, 8 | 16 | 32 | 64) {
2298 return Err(self.unsupported(inst));
2299 }
2300
2301 let base = self.reg_of(addr)?;
2302 let want = self.reg_of(expected)?;
2303 let put = self.reg_of(desired)?;
2304 let got = self.new_reg(old);
2305 let flag = self.new_reg(exchanged);
2306
2307 let name = format!("cmpxchg_{bits}");
2308 let form = x86_64::form(&name).ok_or_else(|| self.unsupported(inst))?;
2309 let block = self.at.expect("a block is being filled");
2310 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
2311 let mut build = self.out.build(block, opcode).at(self.source.span(inst));
2312 for (desc, reg) in form.operands().iter().zip([got, flag, want, put]) {
2313 let operand = mir::Operand {
2314 reg,
2315 class: desc.class,
2316 role: desc.role,
2317 constraint: desc.constraint,
2318 };
2319 build = build.operand(operand);
2320 }
2321 build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
2322 Ok(())
2323 }
2324
2325 /// One read modify write, for the three operations this machine does in a single instruction.
2326 ///
2327 /// What the IR asks for is: read what is at an address, do something to it, put the answer back,
2328 /// say what was there before, and let nothing get between the three steps. The machine has
2329 /// `xchg` for putting a value there and `lock xadd` for adding one, and both leave what they
2330 /// found in the register the operand arrived in, which is why the value that comes back and the
2331 /// value that went in are one register here.
2332 ///
2333 /// A subtraction is the add over the negated operand, which is right at every width because the
2334 /// machine's arithmetic wraps and negating then adding is subtracting in two's complement
2335 /// whatever the operands were. The negate is a separate instruction in front, over a register of
2336 /// its own, so that the value the program handed over is not the one written on: an operand may
2337 /// be live after this and a program that read it again would read the negation.
2338 ///
2339 /// The ordering is not read, for the reason the compare and exchange beside this does not read
2340 /// it. `xchg` with memory locks the bus whether it is asked to or not and `lock xadd` is asked
2341 /// to, so both are full barriers on this machine and there is nothing weaker to fall to.
2342 ///
2343 /// Eight of the other ten never arrive, because `crate::retry` turned each of them into a loop
2344 /// around a compare and exchange before anything here saw it. The two that do arrive are the
2345 /// ones on floating values, and they are refused: a compare and exchange of a float wants the
2346 /// value carried through an integer of the same width, and an eighty bit float has no such
2347 /// width. Neither family of builtins can write one yet either, so a program that reaches this
2348 /// refusal is a program that reached an unimplemented builtin first.
2349 fn modify(&mut self, inst: Inst) -> Result<(), Unsupported> {
2350 let Extra::Rmw(op, _) = self.source[inst].extra else {
2351 return Err(self.unsupported(inst));
2352 };
2353 let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
2354 let [addr, operand] = args[..] else { return Err(self.unsupported(inst)) };
2355 let old = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2356
2357 // A value the machine can exchange in one instruction, which is an integer at one of the
2358 // four widths it has these for. A pointer arrives as an address, so it is an integer by the
2359 // time it is here, and anything else is a type this has no instruction for.
2360 let ty = self.source[old].ty;
2361 if !ty.is_int() || !matches!(ty.bits(), 8 | 16 | 32 | 64) {
2362 return Err(self.unsupported(inst));
2363 }
2364 let name = match op {
2365 RmwOp::Xchg => format!("xchg_{}", ty.bits()),
2366 RmwOp::Add | RmwOp::Sub => format!("xadd_{}", ty.bits()),
2367 _ => return Err(self.unsupported(inst)),
2368 };
2369
2370 let base = self.reg_of(addr)?;
2371 let mut put = self.reg_of(operand)?;
2372 let block = self.at.expect("a block is being filled");
2373 let span = self.source.span(inst);
2374 if op == RmwOp::Sub {
2375 let negated = self.out.new_vreg(self.gpr);
2376 let negate =
2377 mir::Opcode::new(self.names.intern(&format!("{PREFIX}neg_r_{}", ty.bits())));
2378 let form = x86_64::form(&format!("neg_r_{}", ty.bits()))
2379 .ok_or_else(|| self.unsupported(inst))?;
2380 let mut build = self.out.build(block, negate).at(span);
2381 for (desc, reg) in form.operands().iter().zip([negated, put]) {
2382 build = build.operand(mir::Operand {
2383 reg,
2384 class: desc.class,
2385 role: desc.role,
2386 constraint: desc.constraint,
2387 });
2388 }
2389 build.finish();
2390 put = negated;
2391 }
2392
2393 let got = self.new_reg(old);
2394 let form = x86_64::form(&name).ok_or_else(|| self.unsupported(inst))?;
2395 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
2396 let mut build = self.out.build(block, opcode).at(span);
2397 for (desc, reg) in form.operands().iter().zip([got, put]) {
2398 build = build.operand(mir::Operand {
2399 reg,
2400 class: desc.class,
2401 role: desc.role,
2402 constraint: desc.constraint,
2403 });
2404 }
2405 build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
2406 Ok(())
2407 }
2408
2409 /// One `asm` statement.
2410 ///
2411 /// An empty template is most of the inline assembly in a test suite, and it is not a corner
2412 /// case somebody wrote by accident. A program that wants a value computed where it stands, or a
2413 /// loop the optimizer must not touch, writes `asm volatile ("" : : : "memory")`, and forty
2414 /// years of bug reports about optimizers are full of them. What such a statement asks for is
2415 /// the barrier and the operand places, and no instructions at all.
2416 ///
2417 /// So the operands are the half that is always real: a constraint says where a value has to be,
2418 /// and where it has to be is still true when the template between them is empty.
2419 ///
2420 /// What the constraints ask for, on an empty template, is only ever that two operands share a
2421 /// place. Nothing reads a register no text names, so `"r"` on its own asks for a register and
2422 /// no particular one, and any register at all answers it. A matching constraint is different,
2423 /// because it says the output the assembly leaves is the place the input arrived in, and with
2424 /// no instructions between them that is the input unchanged. So it is a rename and not a move:
2425 /// the value is already in a register and the result is that register.
2426 ///
2427 /// An output nothing is tied to and no instruction writes is whatever the assembly left there,
2428 /// which for a template that writes nothing is whatever was in the register. That is a value
2429 /// the program is not entitled to, and this writes a zero rather than reading one, because the
2430 /// allocator has to be given a definition before a use whatever the program is entitled to.
2431 ///
2432 /// # A template with instructions in it
2433 ///
2434 /// [`x86_64::read`] turns the text into the opcodes this backend already has, which is what
2435 /// `spec/11-asm-objects-debug.md` section 11.1 asks for: the machine is described once, and an
2436 /// instruction a program wrote is looked up in that description rather than copied through to
2437 /// an assembler that has one of its own. So nothing here assembles anything. What it does is
2438 /// put the statement's operands where the opcode holds them, and from there an `asm` statement
2439 /// is ordinary machine code: the allocator picks the registers, the listing and the object file
2440 /// are written from the same table as every other instruction, and a spill around one works
2441 /// because there is nothing left about it for a spill to get wrong.
2442 ///
2443 /// Three things are refused, all for one reason, which is that placing them by a guess gives a
2444 /// program that assembles into something other than what it says.
2445 ///
2446 /// A register the template named itself. The registers an instruction here names are the ones
2447 /// the allocator handed out, and a name in the text is a claim on a register nobody told the
2448 /// allocator about. A register a constraint letter names is a different thing and is placed,
2449 /// which the paragraph below is about: there the statement said which of its own operands is
2450 /// in the register, and a name in the middle of a template says no such thing.
2451 ///
2452 /// An output the template writes more than once, and an output that is tied to an input and
2453 /// written. Both are one place with two definitions in it, and the machine IR between here and
2454 /// the allocator has one definition per register by construction.
2455 ///
2456 /// An operand read where the opcode writes, or written where it reads. An output that has not
2457 /// been written yet is not a value, and an input the assembly writes over is a value something
2458 /// else may still be using.
2459 ///
2460 /// # A register the instruction uses without being told
2461 ///
2462 /// An instruction may reach a register its text does not name, and `cpuid` is all of them at
2463 /// once: the leaf goes in `eax`, the subleaf in `ecx`, and the answer comes back in all four
2464 /// registers. The description holds every bit of that already, so what is left is to say which
2465 /// of the statement's operands is in each of those registers, and the constraint letter is the
2466 /// one thing in an assembly statement that says it. `"=a"` is an output in `rax` and `"c"` is
2467 /// an input in `rcx`, which is why a program writing `cpuid` writes its constraints that way
2468 /// and has no choice about it.
2469 ///
2470 /// A register no letter named is one the statement put nothing in, and that is the usual case
2471 /// rather than an unusual one, since an instruction that answers four questions is written by
2472 /// programs that asked one. A write of one is the register being destroyed and gets a register
2473 /// of its own, which is what tells the allocator to keep everything else out of it. A read of
2474 /// one is a register the instruction looks at and the program never filled, which gets a zero
2475 /// for the reason [`Self::undefined`] gives.
2476 ///
2477 /// # The clobber list
2478 ///
2479 /// Read now, as the registers it names being written by every instruction of the template. By
2480 /// every one rather than by one of them, because the list says the assembly as a whole leaves
2481 /// them ruined and nothing here knows which line did it. Every entry has to be a register this
2482 /// machine has a name for or the statement is refused, since a name nobody read is a register
2483 /// nobody is keeping out of.
2484 ///
2485 /// `memory` and `cc` are the two entries that are not registers and both are skipped. `memory`
2486 /// says the assembly touches storage, which is already true of every `asm` this writes and is
2487 /// nothing a register list could hold. `cc` says it ruins the condition flags, and the flag
2488 /// tracking already has that from the instructions the template was read into, since it takes
2489 /// every instruction it does not recognize as writing them and every instruction here is one
2490 /// this machine describes.
2491 ///
2492 /// A clobber the instruction already writes is left off it. `cpuid` writes all four registers
2493 /// by description, and a statement listing three of them as clobbers as well is saying the
2494 /// same thing twice, which the allocator would read as one register with two definitions.
2495 ///
2496 /// On a template with nothing in it the list is ignored, as it was before, since a template
2497 /// with no instructions ruins nothing whatever it said about what it ruins.
2498 fn assembly(&mut self, inst: Inst) -> Result<(), Unsupported> {
2499 let data = &self.source[inst];
2500 let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
2501 let info = self.source[asm];
2502 if !self.source[info.targets].is_empty() {
2503 return Err(Unsupported::Assembly { inst, refused: Written::Goto });
2504 }
2505 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
2506
2507 let template = self.names.resolve(info.template).to_string();
2508 let lines = if template.trim().is_empty() {
2509 Vec::new()
2510 } else {
2511 x86_64::read(&template)
2512 .ok_or(Unsupported::Assembly { inst, refused: Written::Template })?
2513 };
2514
2515 let constraints = self.names.resolve(info.constraints).to_string();
2516 let results: Vec<Value> = data.results().collect();
2517 let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
2518 .ok_or_else(refused)?;
2519 let list: Vec<AsmOperand> = operands.iter().copied().collect();
2520
2521 // Which operands the template writes, counted before anything is placed, because the answer
2522 // decides where each of the three below comes from and one instruction may name an operand
2523 // that a later one writes.
2524 let mut writes = vec![0usize; list.len()];
2525 for line in &lines {
2526 let form = x86_64::form(line.opcode).ok_or_else(refused)?;
2527 for (desc, piece) in form.operands().iter().zip(&line.operands) {
2528 // An operand the instruction reaches without its text saying so is the statement's
2529 // only when a constraint letter put something there. One that is nobody's writes
2530 // nothing of the program's, so it is counted nowhere and is dealt with where it is
2531 // placed.
2532 let index = match *piece {
2533 x86_64::Piece::Operand { index, .. } => index,
2534 x86_64::Piece::Implicit { reg } => match bound(&list, reg, desc.role) {
2535 Some(index) => index,
2536 None => continue,
2537 },
2538 x86_64::Piece::Reg { .. } => continue,
2539 };
2540 if matches!(desc.role, Role::Def | Role::EarlyDef) {
2541 *writes.get_mut(index).ok_or_else(refused)? += 1;
2542 }
2543 }
2544 }
2545
2546 // Where every operand is. Worked out in full before the first instruction is written, since
2547 // reading a value may be what puts it in a register in the first place, and that has to
2548 // happen in front of the assembly rather than in the middle of it.
2549 let mut places: Vec<Option<mir::Reg>> = vec![None; list.len()];
2550 for (index, operand) in list.iter().copied().enumerate() {
2551 let Some(result) = operand.result else {
2552 // An input, or an output the assembly was handed the address of, and both are a
2553 // value that arrives in a register and is read out of it.
2554 places[index] = Some(self.reg_of(operand.value.ok_or_else(refused)?)?);
2555 continue;
2556 };
2557 let ty = self.source[result].ty;
2558 if on_x87(ty) || writes[index] > 1 {
2559 return Err(refused());
2560 }
2561 match operands.tied_to(index) {
2562 // The place the input arrived in, which the assembly wrote nothing over.
2563 Some(from) => {
2564 if writes[index] > 0 || self.class_of(self.source[from].ty) != self.class_of(ty)
2565 {
2566 return Err(refused());
2567 }
2568 let reg = self.reg_of(from)?;
2569 self.regs[result.index()] = Some(reg);
2570 places[index] = Some(reg);
2571 }
2572 None if writes[index] == 1 => places[index] = Some(self.new_reg(result)),
2573 None => {
2574 self.undefined(inst, result)?;
2575 places[index] = self.regs[result.index()];
2576 }
2577 }
2578 }
2579
2580 // Worked out once for the whole template, since the list is one list and every instruction
2581 // of the template gets it. Not worked out at all for a template with no instructions, which
2582 // is where there is nothing for it to go on.
2583 let clobbers = self.names.resolve(info.clobbers).to_string();
2584 let clobbered =
2585 if lines.is_empty() { Vec::new() } else { Self::clobbered(inst, &clobbers)? };
2586
2587 for line in &lines {
2588 self.instruction(inst, line, &places, &list, &clobbered)?;
2589 }
2590 Ok(())
2591 }
2592
2593 /// The registers a clobber list names, in the order it named them.
2594 ///
2595 /// Nothing is dropped. A name this has no register for is refused, because the list is the
2596 /// program telling the compiler which registers it may not leave anything in, and an entry
2597 /// nobody read is a register something may still be left in. See [`Self::assembly`] for the
2598 /// two entries that are not registers and for why they are skipped rather than refused.
2599 fn clobbered(inst: Inst, clobbers: &str) -> Result<Vec<PhysReg>, Unsupported> {
2600 let refused = || Unsupported::Assembly { inst, refused: Written::Clobber };
2601 let mut named = Vec::new();
2602 for entry in clobbers.split(',') {
2603 let entry = entry.trim().trim_matches('"');
2604 // The sigil is optional in a clobber list and means nothing when it is there, unlike
2605 // in a template, where it is what tells a register from an operand.
2606 let entry = entry.strip_prefix('%').unwrap_or(entry);
2607 if entry.is_empty() || entry == "memory" || entry == "cc" {
2608 continue;
2609 }
2610 let (reg, _) = x86_64::gpr_named(entry).ok_or_else(refused)?;
2611 if !named.contains(®) {
2612 named.push(reg);
2613 }
2614 }
2615 Ok(named)
2616 }
2617
2618 /// One instruction of a template, as the machine instruction it was read back into.
2619 fn instruction(
2620 &mut self,
2621 inst: Inst,
2622 line: &x86_64::Line,
2623 places: &[Option<mir::Reg>],
2624 list: &[AsmOperand],
2625 clobbered: &[PhysReg],
2626 ) -> Result<(), Unsupported> {
2627 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
2628 let form = x86_64::form(line.opcode).ok_or_else(refused)?;
2629 let mut built = Vec::with_capacity(line.operands.len() + clobbered.len());
2630 for (desc, piece) in form.operands().iter().zip(&line.operands) {
2631 built.push(self.placed(inst, *desc, *piece, places, list)?);
2632 }
2633 // The clobbers go in among the definitions rather than behind the reads, because an operand
2634 // vector in the machine IR is every definition and then every use and what counts them
2635 // reads that order rather than each operand's role.
2636 let defs = built.iter().take_while(|operand| operand.role.is_def()).count();
2637 for ® in clobbered {
2638 if form.operands().iter().any(|desc| desc.constraint == Constraint::Fixed(reg)) {
2639 continue;
2640 }
2641 built.insert(defs, mir::Operand::write(mir::Reg::physical(reg), self.gpr));
2642 }
2643 let at = match line.at {
2644 Some(at) => Some(self.addressed(inst, at, places)?),
2645 None => None,
2646 };
2647
2648 let block = self.at.expect("a block is being filled");
2649 let span = self.source.span(inst);
2650 let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", line.opcode)));
2651 let mut build = self.out.build(block, opcode).at(span);
2652 for operand in built {
2653 build = build.operand(operand);
2654 }
2655 if let Some(value) = line.imm {
2656 build = build.imm(value);
2657 }
2658 if let Some(mem) = at {
2659 build = build.mem(mem);
2660 }
2661 build.finish();
2662 Ok(())
2663 }
2664
2665 /// One operand of one instruction of a template, in the register the statement put it in.
2666 fn placed(
2667 &mut self,
2668 inst: Inst,
2669 desc: OperandDesc,
2670 piece: x86_64::Piece,
2671 places: &[Option<mir::Reg>],
2672 list: &[AsmOperand],
2673 ) -> Result<mir::Operand, Unsupported> {
2674 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
2675 // A register the instruction reaches without its text naming it belongs to whichever of the
2676 // statement's operands a constraint letter put there, and to nobody when no letter did.
2677 // There is no width to check in that case: the operand is the register the letter named and
2678 // the instruction does what it does to it, which is what a program writing `"=a"` asked for.
2679 let (index, width) = match piece {
2680 x86_64::Piece::Operand { index, width } => (index, Some(width)),
2681 x86_64::Piece::Implicit { reg } => match bound(list, reg, desc.role) {
2682 Some(index) => (index, None),
2683 None => return self.spare(inst, desc),
2684 },
2685 x86_64::Piece::Reg { .. } => return Err(refused()),
2686 };
2687 let operand = list.get(index).copied().ok_or_else(refused)?;
2688 let reg = places.get(index).copied().flatten().ok_or_else(refused)?;
2689
2690 // Read where the opcode reads and written where it writes, which is what the first half of
2691 // this asks. An output has a result and an input has a value, and an output written `+` has
2692 // both, because it is read before it is written.
2693 let placeable = match desc.role {
2694 Role::Use => operand.value.is_some(),
2695 Role::Def | Role::EarlyDef => operand.result.is_some(),
2696 };
2697 let ty = match (operand.result, operand.value) {
2698 (Some(result), _) => self.source[result].ty,
2699 (None, Some(value)) => self.source[value].ty,
2700 (None, None) => return Err(refused()),
2701 };
2702 let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
2703 if !placeable || self.class_of(ty) != desc.class {
2704 return Err(refused());
2705 }
2706 if width.is_some_and(|width| bits != width.bits()) {
2707 return Err(refused());
2708 }
2709 Ok(mir::Operand { reg, class: desc.class, role: desc.role, constraint: desc.constraint })
2710 }
2711
2712 /// A register an instruction of a template uses and the statement put nothing in.
2713 ///
2714 /// A write of one is the register being destroyed, which is what a clobber list is usually
2715 /// written to say and what an instruction with more answers than the program asked for does
2716 /// anyway: `cpuid` writes all four registers whether or not the statement wanted all four. A
2717 /// register of its own is the whole of what that needs, since a value nothing reads is one the
2718 /// allocator may put anywhere and is told about so that nothing else is put there.
2719 ///
2720 /// A read of one is a register the instruction looks at and the program never filled, which
2721 /// gcc leaves as whatever happened to be there. A zero is written instead, for the reason
2722 /// [`Self::undefined`] gives: the allocator has to be given a definition before a use, and a
2723 /// zero is the one answer that reads the same on every run.
2724 fn spare(&mut self, inst: Inst, desc: OperandDesc) -> Result<mir::Operand, Unsupported> {
2725 let refused = Unsupported::Assembly { inst, refused: Written::Operand };
2726 if desc.class != self.gpr {
2727 return Err(refused);
2728 }
2729 let reg = self.out.new_vreg(desc.class);
2730 if !desc.role.is_def() {
2731 let block = self.at.expect("a block is being filled");
2732 let span = self.source.span(inst);
2733 let put = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_ri_64")));
2734 self.out.build(block, put).at(span).def(reg, desc.class).imm(0).finish();
2735 }
2736 Ok(mir::Operand { reg, class: desc.class, role: desc.role, constraint: desc.constraint })
2737 }
2738
2739 /// The address one instruction of a template reads or writes.
2740 fn addressed(
2741 &mut self,
2742 inst: Inst,
2743 at: x86_64::At,
2744 places: &[Option<mir::Reg>],
2745 ) -> Result<mir::Mem, Unsupported> {
2746 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
2747 let base = match at.base {
2748 None => None,
2749 Some(x86_64::Piece::Operand { index, .. }) => {
2750 let reg = places.get(index).copied().flatten().ok_or_else(refused)?;
2751 Some(mir::Operand::read(reg, self.gpr))
2752 }
2753 // An address counted from a register the instruction reaches without being told is
2754 // not something this machine has: every addressing mode is written out in the text it
2755 // is part of, so a base that got here another way is a base nothing wrote down.
2756 Some(x86_64::Piece::Reg { .. } | x86_64::Piece::Implicit { .. }) => {
2757 return Err(refused());
2758 }
2759 };
2760 Ok(mir::Mem { base, scale: 1, disp: at.disp, segment: at.segment, ..mir::Mem::default() })
2761 }
2762
2763 /// A register holding a value the program has no claim on, written as a zero.
2764 ///
2765 /// Every other way of saying it costs the same instruction or needs a word the machine IR does
2766 /// not have, and a zero is the one that reads the same on every run.
2767 fn undefined(&mut self, inst: Inst, result: Value) -> Result<(), Unsupported> {
2768 let ty = self.source[result].ty;
2769 let refused = Unsupported::Assembly { inst, refused: Written::Operand };
2770 if self.class_of(ty) != self.gpr || !matches!(ty.bits(), 8 | 16 | 32 | 64) {
2771 return Err(refused);
2772 }
2773 let block = self.at.expect("a block is being filled");
2774 let span = self.source.span(inst);
2775 let reg = self.new_reg(result);
2776 let put = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_ri_{}", ty.bits())));
2777 self.out.build(block, put).at(span).def(reg, self.gpr).imm(0).finish();
2778 Ok(())
2779 }
2780
2781 /// Whether a type is the width an address is, which is what makes a cast to or from one free.
2782 fn is_address_width(&self, ty: Type) -> bool {
2783 ty.is_ptr() || (ty.is_int() && ty.bits() == ADDRESS_BITS)
2784 }
2785
2786 /// Where a block goes, which in machine IR is on the block rather than on its terminator.
2787 ///
2788 /// That is why no rule ever names a block: a branch is selected for what it reads and the
2789 /// edges are copied across here, arguments and all. The arguments are read last, after every
2790 /// instruction of the block is written, because an argument that is a constant is
2791 /// materialized where it is first wanted and the end of the block is where an edge wants it.
2792 ///
2793 /// Which is not quite the end. A block that leaves two ways has the branch as its last
2794 /// instruction, and a block that leaves through a register has the indirect jump as its last,
2795 /// and anything appended after either is something it has already jumped past, so a constant
2796 /// materialized here would be a register the block below reads and nothing ever writes. The
2797 /// one that was there is put back on the end when that happened, which is the only reordering
2798 /// anything in this crate does and is why it is remembered before a single argument is read.
2799 fn edges(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
2800 let Some(term) = self.source.terminator(block) else { return Ok(()) };
2801 let leaves = matches!(self.source[term].opcode, Opcode::BrIf | Opcode::IndirectBr);
2802 let branch = if leaves { self.out.terminator(out) } else { None };
2803
2804 let calls: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
2805 let mut succs = Vec::with_capacity(calls.len());
2806 for call in calls {
2807 let args: Vec<Value> = self.source[call.args].to_vec();
2808 let mut regs = Vec::with_capacity(args.len());
2809 for value in args {
2810 // The address of where the value is rather than the value, for the one type a
2811 // register holds none of. The block on the other side copies the bytes out of it
2812 // into a slot of its own, which is what makes a second edge into the same block
2813 // safe.
2814 let reg = if on_x87(self.source[value].ty) {
2815 self.x87_slot(value)
2816 } else {
2817 self.reg_of(value)?
2818 };
2819 regs.push(reg);
2820 }
2821 succs.push(mir::BlockCall::with(self.out_block(call.block), regs));
2822 }
2823 if let Some(branch) = branch {
2824 if self.out.terminator(out) != Some(branch) {
2825 self.out.remove_inst(branch);
2826 self.out.append_inst(out, branch);
2827 }
2828 }
2829 *self.out.succs_mut(out) = succs;
2830 Ok(())
2831 }
2832
2833 /// The machine IR block an IR block became.
2834 fn out_block(&self, block: Block) -> mir::Block {
2835 self.blocks[block.index()].expect("every block was created before any was filled")
2836 }
2837
2838 /// The parameters of the entry block, which are the function's arguments.
2839 ///
2840 /// They are not block parameters in the machine IR and they cannot be. A block parameter is
2841 /// given its value by a move on the edge into the block, and there is no edge into an entry
2842 /// block, so what arrives in a function is the convention's to say. [`crate::abi`] is what
2843 /// says it.
2844 ///
2845 /// The ones past the last register arrived in the caller's memory and are read out of it, and
2846 /// the loads that read them come back here so that the frame can finish them the way it
2847 /// finishes an `alloca`.
2848 fn arrive(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
2849 let params = self.source[block].params.clone();
2850 // The type of each is the block's answer and what the ABI asks of it is the signature's,
2851 // and the two lists are the same list: a parameter the classification turned into a
2852 // pointer is a pointer in the block too. A block with more parameters than the signature
2853 // names is not one the front end writes, and each of those is taken as a plain value.
2854 let asked: Vec<Abi> = self.source.signature().params.iter().map(|it| it.abi).collect();
2855 let types: Vec<Param> = params
2856 .iter()
2857 .enumerate()
2858 .map(|(index, &value)| {
2859 let abi = asked.get(index).copied().unwrap_or_default();
2860 Param { ty: self.source[value].ty, abi }
2861 })
2862 .collect();
2863 // A save area for a function that takes arguments its signature does not name, on a
2864 // convention whose list is the four field one. Windows is the other kind and has no area at
2865 // all, so a `va_start` in one is refused rather than built wrong.
2866 let variadic = self.source.signature().variadic && !self.conv.shared_positions;
2867 let area = variadic.then(|| varargs::Area::of(self.conv));
2868 let arrived = abi::entry(&mut self.out, out, &types, self.conv, self.names, area)
2869 .map_err(|(index, missing)| Unsupported::Argument { index, missing })?;
2870 for (¶m, reg) in params.iter().zip(&arrived.regs) {
2871 self.regs[param.index()] = Some(*reg);
2872 }
2873 if let Some(area) = area {
2874 self.save_area(out, &arrived, area);
2875 }
2876 self.stack.arguments.extend(arrived.stack);
2877 Ok(())
2878 }
2879
2880 /// The prologue of a variadic function, which is every argument register it was handed written
2881 /// into the frame.
2882 ///
2883 /// Every one the signature did not name, that is. Which of those hold anything is a thing only
2884 /// the caller knew and there is nothing here to ask, so all of them are written, and the ones a
2885 /// named parameter took are not, because `va_start` sets the two offsets past them and nothing
2886 /// ever reads their slots.
2887 ///
2888 /// What that costs is up to fourteen stores in the prologue of a function that may read none of
2889 /// them, and the convention's answer to that is the count of vector registers in `%al`, which
2890 /// lets a callee skip the eight vector stores when the call passed no floats. Skipping them is a
2891 /// branch in a prologue, and a prologue is written long after this by [`crate::finish`], which
2892 /// has no blocks to branch between. So they are all written every time, which is correct and is
2893 /// what `-O0` costs. Issue #323 is the branch.
2894 ///
2895 /// A vector register is written all sixteen bytes at a time, because a `_Float128` fills one and
2896 /// a `va_arg` of a quad reads the slot back whole. gcc writes the same sixteen with the same
2897 /// instruction, which is what [`crate::varargs`] says a list has to be built out of.
2898 ///
2899 /// The address is computed once into a register rather than written as a displacement off the
2900 /// stack pointer, because a displacement into a frame is not known until after allocation and
2901 /// one `lea` costs less than a fixup list for a dozen stores. It is the same `lea` an `alloca`
2902 /// gets and [`crate::finish`] fills it in the same way.
2903 fn save_area(&mut self, out: mir::Block, arrived: &abi::Arrived, area: varargs::Area) {
2904 let save = self.stack.locals.len();
2905 self.stack.locals.push(Local { size: area.size, align: varargs::VECTOR_SLOT });
2906 self.varargs = Some(Varargs {
2907 save,
2908 incoming: arrived.used,
2909 integers: u32::try_from(arrived.took.0).unwrap_or(0) * area.stride(false),
2910 floats: area.starts_at(true)
2911 + u32::try_from(arrived.took.1).unwrap_or(0) * area.stride(true),
2912 });
2913
2914 let base = self.frame_address(out, save);
2915 for &(reg, class, at) in &arrived.spare {
2916 let name = if class == self.gpr { "x64.mov_mr_64" } else { "x64.movaps_mr" };
2917 let store = mir::Opcode::new(self.names.intern(name));
2918 let up = i32::try_from(at).expect("a register save area under two gigabytes");
2919 let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
2920 self.out.build(out, store).uses(reg, class).mem(mem).finish();
2921 }
2922 }
2923
2924 /// The address of one of the function's stack objects, in a fresh register.
2925 ///
2926 /// Written with nothing in its displacement, because where an object is in a frame is not known
2927 /// until after allocation, and given to [`crate::finish`] to fill in the way an `alloca` is.
2928 fn frame_address(&mut self, out: mir::Block, local: usize) -> mir::Reg {
2929 let reg = self.out.new_vreg(self.gpr);
2930 let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
2931 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
2932 let made = self.out.build(out, lea).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
2933 self.stack.addresses.push((made, local));
2934 reg
2935 }
2936
2937 /// Whether an instruction is one no machine instruction is written for where it stands.
2938 ///
2939 /// Four of them, and none is a lowering decision, which is why none is a rule. A constant is
2940 /// written where a register for it is first wanted rather than where the IR put it, and every
2941 /// reader of one may have folded it into an immediate, in which case nowhere is the right
2942 /// place. A return of nothing has nothing to put anywhere: the epilogue gives the frame back
2943 /// and leaves, and it is appended to every block with no successors long after this has
2944 /// finished, so a return with a value is one instruction here and a return without one is
2945 /// none. Unless the value went back through memory, in which case there is something to put
2946 /// somewhere after all and the IR does not carry it: the address the caller handed over has
2947 /// to be in `rax` on the way out, and [`Lowering::returned`] is what writes that.
2948 ///
2949 /// An unconditional jump is the third, and there is even less of it: the edge is on the
2950 /// block, and whether the block it goes to is the next one and needs no jump at all is the
2951 /// block layout's answer rather than this one's.
2952 ///
2953 /// The fourth is a point control does not arrive at, in both of the forms the IR has for it:
2954 /// the `unreachable` terminator the front end puts at the end of a function whose body can run
2955 /// off the bottom, and the `unreachable_hint` a call to `__builtin_unreachable` becomes. What
2956 /// to write for a place nothing reaches is a question with no wrong answer, and nothing is the
2957 /// smallest one and the one gcc 16.2.0 gives at `-O0`. The terminator leaves the block with no
2958 /// successors, so the epilogue lands at the end of it the way it does on any other block that
2959 /// goes nowhere, and the function cannot fall out of its own last instruction into whatever
2960 /// the assembler puts next.
2961 fn writes_nothing(&self, inst: Inst) -> bool {
2962 let data = &self.source[inst];
2963 match data.opcode {
2964 Opcode::IConst | Opcode::Jump | Opcode::Unreachable | Opcode::UnreachableHint => true,
2965 Opcode::Return => self.source[data.args].is_empty() && self.sret().is_none(),
2966 _ => false,
2967 }
2968 }
2969
2970 /// What every instruction in one block matched, with a set of values nobody may take.
2971 ///
2972 /// Backwards, because an instruction that has been folded into a later one does not get to
2973 /// fold anything into itself: the rule that took it only reached one level down, so what is
2974 /// under it is not in the term the matcher saw and cannot be replaced.
2975 fn decide(&self, insts: &[Inst], refused: &HashSet<Value>) -> Decided {
2976 let mut found: Vec<Option<Match<Term>>> = (0..insts.len()).map(|_| None).collect();
2977 let mut plans: Vec<Option<Plan>> = vec![None; insts.len()];
2978 let mut folded: Vec<Inst> = Vec::new();
2979 for (index, &inst) in insts.iter().enumerate().rev() {
2980 if folded.contains(&inst) {
2981 continue;
2982 }
2983 if let Some((plan, matched)) = self.select(inst, refused) {
2984 folded.extend(self.folds(inst, plan));
2985 found[index] = Some(matched);
2986 plans[index] = Some(plan);
2987 }
2988 }
2989 Decided { found, plans, folded }
2990 }
2991
2992 /// A value some of its readers took and some of them did not, which is the one case folding
2993 /// buys nothing.
2994 ///
2995 /// Folding does not delete the instruction that computed a value for anybody else, so a
2996 /// reader that did not take it still needs it in a register and the instruction stays. The
2997 /// reader that did take it now does that work again. Either all of them take it, in which
2998 /// case nothing is left to read it and the instruction goes, or none of them do.
2999 ///
3000 /// The count is over the whole function rather than over the block, since a value read from
3001 /// another block is read from a register there whatever this block decides. An instruction
3002 /// built by name rather than matched, a call being the one that matters, has no plan and so
3003 /// takes nothing, which is the right answer for it as well.
3004 fn left_alive(&self, insts: &[Inst], plans: &[Option<Plan>]) -> Option<Value> {
3005 let mut taken = vec![0u32; self.uses.len()];
3006 for (&inst, plan) in insts.iter().zip(plans) {
3007 let Some(plan) = plan else { continue };
3008 let args = &self.source[self.source[inst].args];
3009 for (index, &arg) in args.iter().take(MAX_ARGS).enumerate() {
3010 if plan[index] == Shown::Expand {
3011 taken[arg.index()] += 1;
3012 }
3013 }
3014 }
3015 for (&inst, plan) in insts.iter().zip(plans) {
3016 let Some(plan) = plan else { continue };
3017 let args = &self.source[self.source[inst].args];
3018 for (index, &arg) in args.iter().take(MAX_ARGS).enumerate() {
3019 if plan[index] == Shown::Expand && taken[arg.index()] < self.uses[arg.index()] {
3020 return Some(arg);
3021 }
3022 }
3023 }
3024 None
3025 }
3026
3027 /// The rule that fires on an instruction, and what it bound.
3028 ///
3029 /// The plans are tried in order and the first that matches wins, which is the maximal munch
3030 /// `spec/10-backend.md` asks for: a plan that offers more to the matcher is tried before one
3031 /// that offers less.
3032 fn select(&self, inst: Inst, refused: &HashSet<Value>) -> Option<(Plan, Match<Term>)> {
3033 for plan in self.plans(inst, refused) {
3034 let terms = Terms::new(self.source, inst, plan);
3035 if let Some(matched) = TABLE.find(&terms, Term::Root) {
3036 return Some((plan, matched));
3037 }
3038 }
3039 None
3040 }
3041
3042 /// Every way this instruction can be shown to the matcher, most offered first.
3043 fn plans(&self, inst: Inst, refused: &HashSet<Value>) -> Vec<Plan> {
3044 let args = &self.source[self.source[inst].args];
3045 let mut plans = vec![PLAIN];
3046 for (index, &arg) in args.iter().enumerate().take(MAX_ARGS) {
3047 let mut ways = Vec::new();
3048 if self.foldable(inst, arg, refused) {
3049 ways.push(Shown::Expand);
3050 }
3051 if Terms::new(self.source, inst, PLAIN).constant(arg).is_some() {
3052 ways.push(Shown::Const);
3053 }
3054 ways.push(Shown::Reg);
3055 plans = plans
3056 .into_iter()
3057 .flat_map(|plan| {
3058 ways.iter().map(move |&way| {
3059 let mut next = plan;
3060 next[index] = way;
3061 next
3062 })
3063 })
3064 .collect();
3065 }
3066 plans
3067 }
3068
3069 /// Whether an operand may be shown as the instruction that computed it.
3070 ///
3071 /// It has to be in the same block, because a rule that folds one instruction into another
3072 /// moves the work to where the second one is. It has to be something rather than a block
3073 /// parameter, and not a constant, which is shown as a constant instead. And it has to be a
3074 /// value [`Lowering::left_alive`] has not put back, which is how the one reader at a time
3075 /// question is asked here: this says yes to a value with any number of readers, and a value
3076 /// only some of them could take is refused after the fact and asked again.
3077 ///
3078 /// A value with several readers used to be refused outright, on the reasoning that folding
3079 /// does not delete the instruction for anybody else. That reasoning is about the set of
3080 /// readers and was being applied to one reader at a time, which is stricter than it needs to
3081 /// be: when every reader takes it there is nobody left to read it and the instruction goes.
3082 /// An address a store and a load share is the shape that matters, since a memory operand has
3083 /// room for the whole of it and both readers have a memory operand.
3084 fn foldable(&self, into: Inst, value: Value, refused: &HashSet<Value>) -> bool {
3085 let Def::Result { inst, .. } = self.source[value].def else { return false };
3086 if self.source[inst].opcode == Opcode::IConst || refused.contains(&value) {
3087 return false;
3088 }
3089 self.source.block_of(inst).is_some()
3090 && self.source.block_of(inst) == self.source.block_of(into)
3091 }
3092
3093 /// The instructions a match folded into the one it matched.
3094 ///
3095 /// The plan is what says this, not the bindings: a binding is a register or a number either
3096 /// way, and an operand shown as the instruction that computed it is one no rule could have
3097 /// matched without taking that instruction, because the plan offered the matcher nothing
3098 /// else to call it.
3099 fn folds(&self, inst: Inst, plan: Plan) -> Vec<Inst> {
3100 let args = &self.source[self.source[inst].args];
3101 args.iter()
3102 .take(MAX_ARGS)
3103 .enumerate()
3104 .filter(|&(index, _)| plan[index] == Shown::Expand)
3105 .filter_map(|(_, &arg)| match self.source[arg].def {
3106 Def::Result { inst, .. } => Some(inst),
3107 Def::Param { .. } => None,
3108 })
3109 .collect()
3110 }
3111
3112 /// Build the machine instruction a match calls for.
3113 fn emit(&mut self, inst: Inst, matched: &Match<Term>) -> Result<(), Unsupported> {
3114 let rule: &Rule = TABLE.rule(matched);
3115 let pieces = rule.replacement;
3116 let Some(Piece::App { head, arity }) = pieces.first() else {
3117 return Err(self.unsupported(inst));
3118 };
3119 let opcode = head.strip_prefix(PREFIX).ok_or_else(|| self.unsupported(inst))?;
3120 let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
3121
3122 let mut read = Read::default();
3123 let mut at = 1;
3124 for _ in 0..*arity {
3125 at = self.read(inst, pieces, at, &matched.bindings, &mut read)?;
3126 }
3127
3128 let descs = form.operands();
3129 let writes = descs.iter().take_while(|desc| desc.role.is_def()).count();
3130 if descs.len() - writes != read.regs.len() {
3131 return Err(self.unsupported(inst));
3132 }
3133
3134 // The first thing the instruction writes is what it computes, and any others are
3135 // registers the machine destroys on the way, which are fresh because nothing else is in
3136 // them and nothing reads them. An instruction that writes nothing at all is one whose
3137 // whole purpose is its effect, which is what a store is, and there is no result to put
3138 // anywhere.
3139 let mut regs = Vec::new();
3140 if writes > 0 {
3141 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3142 regs.push(self.new_reg(result));
3143 // The rest are the registers the machine destroys on the way, and the class each is in
3144 // is the one the instruction's description gives it rather than a guess, so that an
3145 // instruction that wrecks a register in the other file says so.
3146 regs.extend(descs[1..writes].iter().map(|desc| self.out.new_vreg(desc.class)));
3147 } else if self.source[inst].first_result.is_some() {
3148 // A rule that throws away a value the IR gave a name to would leave every reader of
3149 // that name with nothing to read, so it is a rule this and the target disagree about.
3150 return Err(self.unsupported(inst));
3151 }
3152 regs.extend(read.regs.iter().copied());
3153
3154 let block = self.at.expect("a block is being filled");
3155 let opcode = mir::Opcode::new(self.names.intern(head));
3156 let mut build = self.out.build(block, opcode).at(self.source.span(inst));
3157 for (desc, reg) in descs.iter().zip(regs) {
3158 let operand = mir::Operand {
3159 reg,
3160 class: desc.class,
3161 role: desc.role,
3162 constraint: desc.constraint,
3163 };
3164 build = build.operand(operand);
3165 }
3166 if let Some(mem) = read.mem {
3167 build = build.mem(mem);
3168 }
3169 if let Some(imm) = read.imm {
3170 build = build.imm(imm);
3171 }
3172 build.finish();
3173 Ok(())
3174 }
3175
3176 /// Read one argument of a replacement, which is a register, a number or an address.
3177 ///
3178 /// Gives back the position after it, because a replacement is flat and an address takes
3179 /// arguments of its own.
3180 fn read(
3181 &mut self,
3182 inst: Inst,
3183 pieces: &'static [Piece],
3184 at: usize,
3185 bindings: &[Term],
3186 out: &mut Read,
3187 ) -> Result<usize, Unsupported> {
3188 match pieces.get(at) {
3189 Some(Piece::Int(value)) => {
3190 out.imm = i64::try_from(*value).ok();
3191 Ok(at + 1)
3192 }
3193 Some(Piece::Var { index, .. }) => {
3194 match bindings.get(*index) {
3195 Some(&Term::Reg(value)) => {
3196 let reg = self.reg_of(value)?;
3197 out.regs.push(reg);
3198 }
3199 Some(&Term::Num(value)) => out.imm = i64::try_from(value).ok(),
3200 // A pattern binds a register or a number and nothing else, so this is a
3201 // rule the matcher and this file disagree about.
3202 _ => return Err(self.unsupported(inst)),
3203 }
3204 Ok(at + 1)
3205 }
3206 Some(Piece::App { head, arity }) => {
3207 let kind = x86_64::address(head).ok_or_else(|| self.unsupported(inst))?;
3208 let mut inner = Read::default();
3209 let mut next = at + 1;
3210 for _ in 0..*arity {
3211 next = self.read(inst, pieces, next, bindings, &mut inner)?;
3212 }
3213 let mem = address(kind, &inner, self.gpr).ok_or_else(|| self.unsupported(inst))?;
3214 out.mem = Some(mem);
3215 Ok(next)
3216 }
3217 None => Err(self.unsupported(inst)),
3218 }
3219 }
3220
3221 /// The register a value is in, materializing it if it is a constant that has not been put in
3222 /// one yet.
3223 ///
3224 /// A constant is written where it is wanted rather than where the IR defined it, and where it
3225 /// is wanted is a block that need not be the one the IR defined it in. So the register holding
3226 /// one is only good inside the block it was written into, and a second block that wants the
3227 /// same constant gets its own. Anything else is a register read where nothing wrote it: the
3228 /// IR guarantees a definition dominates its uses, and this moved the definition.
3229 ///
3230 /// Writing the number again is also the right answer and not merely the safe one. It is one
3231 /// instruction that reads nothing, which is cheaper than holding a register live across a
3232 /// branch for it, and it is what a rematerializing allocator would do with the value anyway.
3233 fn reg_of(&mut self, value: Value) -> Result<mir::Reg, Unsupported> {
3234 let constant = match self.source[value].def {
3235 Def::Result { inst, .. } => {
3236 (self.source[inst].opcode == Opcode::IConst).then_some(inst)
3237 }
3238 Def::Param { .. } => None,
3239 };
3240 let here = self.at.expect("a block is being filled");
3241 if let Some(reg) = self.regs[value.index()] {
3242 if constant.is_none() || self.written[value.index()] == Some(here) {
3243 return Ok(reg);
3244 }
3245 }
3246 if let Some(inst) = constant {
3247 // Cleared so that the register the constant is written into is a new one rather than
3248 // the one the block above wrote, which is still being read up there.
3249 self.regs[value.index()] = None;
3250 // Nothing is refused here. A constant is written on its own, out of the loop over the
3251 // block, and the operands of the rule that writes one are the number and nothing else.
3252 let matched = self
3253 .select(inst, &HashSet::new())
3254 .map(|(_, matched)| matched)
3255 .ok_or_else(|| self.unsupported(inst))?;
3256 self.emit(inst, &matched)?;
3257 // The same mark the loop over the instructions makes, and it has to be made here as
3258 // well because this is the only place a constant is ever selected: the loop skips one
3259 // where the IR wrote it, so a rule that lowers a constant fires from nowhere else and
3260 // would be reported as a rule nothing reaches.
3261 self.fired.mark(matched.rule);
3262 self.written[value.index()] = Some(here);
3263 return Ok(self.regs[value.index()].expect("a constant is written into a register"));
3264 }
3265 Ok(self.new_reg(value))
3266 }
3267
3268 /// Which register file a value of that type lives in.
3269 ///
3270 /// The vector one for the two float widths the machine has scalar instructions for and for the
3271 /// one it only moves, and the general purpose one for everything else. An eighty bit `long
3272 /// double` is in neither, and it is here rather than in the vector class on purpose: it would
3273 /// be put in a register that cannot hold it, and there is no rule that names one, so the
3274 /// instruction computing it is reported. The wrong class would make that a wrong program
3275 /// instead of a refused one.
3276 ///
3277 /// A hundred and twenty eight bit float is in the vector class and fits it exactly, which is
3278 /// the difference. Nothing computes in it, so every arithmetic on one is still reported, and
3279 /// what the class buys is the moves: a register that holds the whole value is a register a
3280 /// spill, a reload and a copy are each one instruction for.
3281 fn class_of(&self, ty: Type) -> RegClass {
3282 if crate::term::in_vector_file(ty) { self.conv.sse_class } else { self.gpr }
3283 }
3284
3285 /// A fresh register for a value, which is what the instruction computing it writes.
3286 fn new_reg(&mut self, value: Value) -> mir::Reg {
3287 if let Some(reg) = self.regs[value.index()] {
3288 return reg;
3289 }
3290 let reg = self.out.new_vreg(self.class_of(self.source[value].ty));
3291 self.regs[value.index()] = Some(reg);
3292 reg
3293 }
3294
3295 fn unsupported(&self, inst: Inst) -> Unsupported {
3296 let data = &self.source[inst];
3297 Unsupported::Inst {
3298 inst,
3299 term: Terms::new(self.source, inst, PLAIN).name(inst),
3300 opcode: data.opcode,
3301 ty: data.first_result.map(|result| self.source[result].ty),
3302 }
3303 }
3304}
3305
3306/// What the arguments of one replacement came to.
3307#[derive(Debug, Default)]
3308struct Read {
3309 regs: Vec<mir::Reg>,
3310 imm: Option<i64>,
3311 mem: Option<mir::Mem>,
3312}
3313
3314/// The addressing mode an address constructor's arguments make.
3315///
3316/// One arm per constructor rather than a question asked of the kind, because what the arguments
3317/// mean is the whole of what tells the four apart: the same register is a base in one and an
3318/// index in another, and the same constant is a scale in one and a displacement in another.
3319fn address(kind: x86_64::Address, read: &Read, gpr: RegClass) -> Option<mir::Mem> {
3320 let mut regs = read.regs.iter().copied().map(|reg| mir::Operand::read(reg, gpr));
3321 match kind {
3322 x86_64::Address::BaseIndexScale => {
3323 let base = regs.next()?;
3324 let index = regs.next()?;
3325 Some(mir::Mem::at(base).indexed(index, u8::try_from(read.imm?).ok()?))
3326 }
3327 x86_64::Address::IndexScale => Some(mir::Mem {
3328 base: None,
3329 index: Some(regs.next()?),
3330 scale: u8::try_from(read.imm?).ok()?,
3331 disp: 0,
3332 symbol: None,
3333 block: None,
3334 reach: mir::Reach::Itself,
3335 segment: None,
3336 }),
3337 x86_64::Address::Base => Some(mir::Mem::at(regs.next()?)),
3338 // The rule that writes this has a guard saying the constant fits, so a displacement that
3339 // does not is a rule and a target that disagree rather than a program this cannot compile.
3340 x86_64::Address::BaseOffset => {
3341 Some(mir::Mem { disp: i32::try_from(read.imm?).ok()?, ..mir::Mem::at(regs.next()?) })
3342 }
3343 }
3344}
3345
3346/// The table this selector matches with.
3347///
3348/// One target for now, because one target has a rule file. Which table to use becomes a question
3349/// the moment a second one does, and the answer will be the target the session was given rather
3350/// than a constant here.
3351static TABLE: &Table = &crate::select::x86_64::TABLE;
3352
3353#[cfg(test)]
3354mod tests {
3355 use rucc_ir::{
3356 AsmInfo, Builder, CallInfo, Flags, InstData, MemInfo, MemOrder, Restrict, Signature, Type,
3357 };
3358 use rucc_regalloc::assign::Env;
3359 use rucc_target::x86_64::{FRAME, REGS, SYSV};
3360
3361 use super::*;
3362 use crate::finish::{Convention, finish};
3363 use crate::frame::{Frame, Incoming, Layout};
3364
3365 /// A function of as many 64 bit parameters as the test wants, and the block they are in.
3366 fn blank(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
3367 let mut names = Interner::new();
3368 let mut func = Func::new(names.intern("f"), Signature::new());
3369 let block = func.create_block();
3370 let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
3371 (names, func, block, values)
3372 }
3373
3374 /// An ordinary access: not atomic, and aligned enough that nothing here has an opinion.
3375 /// Neither field reaches selection, which is the point of saying it once here.
3376 fn plain() -> MemInfo {
3377 MemInfo {
3378 size: 0,
3379 align: 1,
3380 order: MemOrder::NotAtomic,
3381 tbaa: None,
3382 owns: 0,
3383 restrict: Restrict::NONE,
3384 }
3385 }
3386
3387 /// What the allocator is given: every integer register the convention offers except two, held
3388 /// back so that a move on an edge has somewhere to break a cycle and a spilled value has
3389 /// somewhere to be read into. Which two does not matter, and holding back the last two the
3390 /// convention would reach for leaves every expectation below unchanged.
3391 fn env() -> Env {
3392 const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
3393 let order: Vec<PhysReg> =
3394 SYSV.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
3395 Env::new().with(x86_64::GPR, &order, &SCRATCH)
3396 }
3397
3398 /// The machine IR text a function lowers to.
3399 fn lower(names: &mut Interner, source: &Func) -> String {
3400 let out = func(source, names, &SYSV, &Elsewhere::default())
3401 .expect("every instruction has a rule");
3402 mir::print_func(&out.func, names, ®S)
3403 }
3404
3405 #[test]
3406 fn an_addition_of_two_registers_is_one_instruction() {
3407 let i32 = Type::int(32);
3408 let (mut names, mut func, block, args) = blank(&[i32, i32]);
3409 let mut build = Builder::new(&mut func, block);
3410 build.binary(Opcode::Add, args[0], args[1], Flags::default());
3411
3412 assert_eq!(
3413 lower(&mut names, &func),
3414 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
3415 %1:gpr($rsi) = x64.arg_val_32\n %2:gpr(reuse 1) = x64.add_rr_32 %0, %1\n}\n"
3416 );
3417 }
3418
3419 #[test]
3420 fn a_constant_operand_becomes_an_immediate() {
3421 let i32 = Type::int(32);
3422 let (mut names, mut func, block, args) = blank(&[i32]);
3423 let mut build = Builder::new(&mut func, block);
3424 let seven = build.iconst(i32, 7);
3425 build.binary(Opcode::Add, args[0], seven, Flags::default());
3426
3427 // The constant is in the instruction and nothing was written to hold it, which is what
3428 // materializing one where a register for it is wanted buys.
3429 assert_eq!(
3430 lower(&mut names, &func),
3431 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
3432 %1:gpr(reuse 1) = x64.add_ri_32 %0, 7\n}\n"
3433 );
3434 }
3435
3436 #[test]
3437 fn a_constant_too_wide_for_an_immediate_goes_into_a_register() {
3438 let i64 = Type::int(64);
3439 let (mut names, mut func, block, args) = blank(&[i64]);
3440 let mut build = Builder::new(&mut func, block);
3441 let big = build.iconst(i64, i128::from(i32::MAX) + 1);
3442 build.binary(Opcode::Add, args[0], big, Flags::default());
3443
3444 // Nobody wrote this fallback down. The rule that takes an immediate has a guard that
3445 // turns a number this wide down, so it does not fire, and the next way of showing the
3446 // operand puts it in a register.
3447 assert_eq!(
3448 lower(&mut names, &func),
3449 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
3450 %1:gpr = x64.mov_ri_64 2147483648\n %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n}\n"
3451 );
3452 }
3453
3454 #[test]
3455 fn an_index_calculation_folds_into_an_address() {
3456 let i64 = Type::int(64);
3457 let (mut names, mut func, block, args) = blank(&[i64, i64]);
3458 let mut build = Builder::new(&mut func, block);
3459 let four = build.iconst(i64, 4);
3460 let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
3461 build.binary(Opcode::Add, args[0], scaled, Flags::default());
3462
3463 // Three IR instructions and one machine instruction. The multiply is gone because the
3464 // rule that matched reached down and took it.
3465 assert_eq!(
3466 lower(&mut names, &func),
3467 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
3468 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr = x64.lea_64 [%0 + %1*4]\n}\n"
3469 );
3470 }
3471
3472 #[test]
3473 fn an_instruction_every_reader_can_take_is_folded_into_all_of_them() {
3474 let i64 = Type::int(64);
3475 let (mut names, mut func, block, args) = blank(&[i64, i64]);
3476 let mut build = Builder::new(&mut func, block);
3477 let four = build.iconst(i64, 4);
3478 let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
3479 let first = build.binary(Opcode::Add, args[0], scaled, Flags::default());
3480 build.binary(Opcode::Add, first, scaled, Flags::default());
3481
3482 // Both readers have room for a scaled index, so both of them take it and nothing is left
3483 // to read the multiply. Three IR instructions become two machine ones, where refusing to
3484 // fold into either reader would have left three.
3485 assert_eq!(
3486 lower(&mut names, &func),
3487 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
3488 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr = x64.lea_64 [%0 + %1*4]\n \
3489 %3:gpr = x64.lea_64 [%2 + %1*4]\n}\n"
3490 );
3491 }
3492
3493 #[test]
3494 fn an_instruction_one_of_its_readers_cannot_take_is_folded_into_none_of_them() {
3495 let i64 = Type::int(64);
3496 let (mut names, mut func, block, args) = blank(&[i64, i64]);
3497 let mut build = Builder::new(&mut func, block);
3498 let four = build.iconst(i64, 4);
3499 let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
3500 build.binary(Opcode::Add, args[0], scaled, Flags::default());
3501 build.store(scaled, args[0], plain(), Flags::default());
3502
3503 // The addition has room for the multiply and the store does not: what a store writes is
3504 // a register, and no rule reaches through it. Folding into the addition alone would
3505 // leave the multiply where it is for the store to read and do the work twice, so the
3506 // multiply is put back and both readers read the register it wrote.
3507 let text = lower(&mut names, &func);
3508 assert!(text.contains("x64.lea_64 [%1*4]"), "{text}");
3509 assert!(text.contains("x64.add_rr_64"), "{text}");
3510 }
3511
3512 #[test]
3513 fn a_shift_by_a_register_asks_for_it_in_cl() {
3514 let i32 = Type::int(32);
3515 let (mut names, mut func, block, args) = blank(&[i32, i32]);
3516 let mut build = Builder::new(&mut func, block);
3517 build.binary(Opcode::Shl, args[0], args[1], Flags::default());
3518
3519 // The fixed register is not in the rule. It is what the target says the instruction does
3520 // with its operands, and the allocator is what will act on it.
3521 let text = lower(&mut names, &func);
3522 assert!(text.contains("x64.shl_rcl_32 %0, %1($rcx)"), "{text}");
3523 }
3524
3525 #[test]
3526 fn a_division_names_the_registers_and_the_register_it_destroys() {
3527 let i32 = Type::int(32);
3528 let (mut names, mut func, block, args) = blank(&[i32, i32]);
3529 let mut build = Builder::new(&mut func, block);
3530 build.binary(Opcode::SDiv, args[0], args[1], Flags::default());
3531
3532 // Two definitions, because a division writes the remainder whether anybody wanted it or
3533 // not, and the second one is early because it is destroyed before the operands are read.
3534 let text = lower(&mut names, &func);
3535 assert!(
3536 text.contains("%2:gpr($rax), early %3:gpr($rdx) = x64.idiv_quo_32 %0($rax), %1"),
3537 "{text}"
3538 );
3539 }
3540
3541 #[test]
3542 fn a_load_reads_through_the_register_the_address_is_in() {
3543 let i64 = Type::int(64);
3544 let (mut names, mut func, block, args) = blank(&[i64]);
3545 let mut build = Builder::new(&mut func, block);
3546 build.load(Type::int(32), args[0], plain(), Flags::default());
3547
3548 assert_eq!(
3549 lower(&mut names, &func),
3550 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
3551 %1:gpr = x64.mov_rm_32 [%0]\n}\n"
3552 );
3553 }
3554
3555 #[test]
3556 fn a_store_writes_no_register_and_the_value_it_writes_is_the_one_the_ir_gave_it() {
3557 let (mut names, mut func, block, args) = blank(&[Type::int(32), Type::int(64)]);
3558 let mut build = Builder::new(&mut func, block);
3559 build.store(args[0], args[1], plain(), Flags::default());
3560
3561 // The value is the first parameter and the address is the second, and the instruction
3562 // takes them the other way round. Getting that backwards would compile to a store of the
3563 // address into the value, which is a program that runs and does the wrong thing.
3564 assert_eq!(
3565 lower(&mut names, &func),
3566 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
3567 %1:gpr($rsi) = x64.arg_val_64\n x64.mov_mr_32 %0, [%1]\n}\n"
3568 );
3569 }
3570
3571 #[test]
3572 fn an_address_with_a_constant_added_folds_into_the_access() {
3573 let i64 = Type::int(64);
3574 let (mut names, mut func, block, args) = blank(&[i64]);
3575 let mut build = Builder::new(&mut func, block);
3576 let twelve = build.iconst(i64, 12);
3577 let field = build.binary(Opcode::Add, args[0], twelve, Flags::default());
3578 build.load(Type::int(64), field, plain(), Flags::default());
3579
3580 // Two IR instructions and one machine instruction, which is what every read of a field
3581 // of a structure comes to.
3582 assert_eq!(
3583 lower(&mut names, &func),
3584 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
3585 %1:gpr = x64.mov_rm_64 [%0 + 12]\n}\n"
3586 );
3587 }
3588
3589 #[test]
3590 fn a_displacement_too_wide_to_encode_leaves_the_addition_where_it_is() {
3591 let i64 = Type::int(64);
3592 let (mut names, mut func, block, args) = blank(&[i64]);
3593 let mut build = Builder::new(&mut func, block);
3594 let big = build.iconst(i64, i128::from(i32::MAX) + 1);
3595 let far = build.binary(Opcode::Add, args[0], big, Flags::default());
3596 build.load(Type::int(32), far, plain(), Flags::default());
3597
3598 // A displacement is signed and 32 bits. The rule that folds one has a guard that turns
3599 // this down, so the addition stays and the load reads through what it produced. Nobody
3600 // wrote that fallback: it is the next way of showing the operand.
3601 let text = lower(&mut names, &func);
3602 assert!(text.contains("x64.mov_rm_32 [%2]"), "{text}");
3603 assert!(text.contains("x64.add_rr_64"), "{text}");
3604 }
3605
3606 #[test]
3607 fn a_store_of_a_value_that_was_loaded_is_two_instructions_and_no_arithmetic() {
3608 let i64 = Type::int(64);
3609 let (mut names, mut func, block, args) = blank(&[i64, i64]);
3610 let mut build = Builder::new(&mut func, block);
3611 let got = build.load(Type::int(8), args[0], plain(), Flags::default());
3612 build.store(got, args[1], plain(), Flags::default());
3613
3614 // A load feeding a store is the one place folding would be wrong: an x86-64 `mov` has at
3615 // most one memory operand, and there is no rule that takes two, so the load is left where
3616 // it is and the store reads the register it wrote.
3617 assert_eq!(
3618 lower(&mut names, &func),
3619 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
3620 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr = x64.mov_rm_8 [%0]\n \
3621 x64.mov_mr_8 %2, [%1]\n}\n"
3622 );
3623 }
3624
3625 #[test]
3626 fn an_access_at_a_width_no_rule_is_written_at_is_reported() {
3627 let i64 = Type::int(64);
3628 let (mut names, mut source, block, args) = blank(&[i64]);
3629 let mut build = Builder::new(&mut source, block);
3630 build.load(Type::int(128), args[0], plain(), Flags::default());
3631
3632 // The width is the whole of what is wrong here, so the width is in the message: `load`
3633 // on its own is written about at every other width and would send a reader looking in
3634 // the wrong place.
3635 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
3636 .expect_err("nothing loads 128 bits");
3637 assert_eq!(failed.to_string(), "no rule lowers a `load` producing a `i128`");
3638 }
3639
3640 #[test]
3641 fn a_return_asks_for_the_value_in_the_register_the_caller_reads() {
3642 let (mut names, mut func, block, args) = blank(&[Type::int(32)]);
3643 let mut build = Builder::new(&mut func, block);
3644 build.ret(&[args[0]]);
3645
3646 // The register is not in the rule, the same way `cl` is not in the rule for a shift. It
3647 // is what the target says the instruction does with its operand, and the allocator is
3648 // what will act on it. There is no `ret` here, because giving the frame back has to
3649 // happen between this and leaving and the frame is not worked out yet.
3650 assert_eq!(
3651 lower(&mut names, &func),
3652 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
3653 x64.ret_val_32 %0($rax)\n}\n"
3654 );
3655 }
3656
3657 #[test]
3658 fn a_return_of_two_values_asks_for_the_second_register_as_well() {
3659 let i64 = Type::int(64);
3660 let (mut names, mut func, block, args) = blank(&[i64, i64]);
3661 let mut build = Builder::new(&mut func, block);
3662 build.ret(&[args[0], args[1]]);
3663
3664 // `struct { long a, b; } f(long a, long b)`, after the front end has classified it. Both
3665 // halves are integers, so the second is in the second integer return register, and both
3666 // pseudos say so the same way the one for a single value does.
3667 assert_eq!(
3668 lower(&mut names, &func),
3669 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
3670 %1:gpr($rsi) = x64.arg_val_64\n x64.ret_val_64 %0($rax)\n \
3671 x64.ret_val2_64 %1($rdx)\n}\n"
3672 );
3673 }
3674
3675 #[test]
3676 fn two_values_back_in_different_files_are_both_the_first_of_their_own() {
3677 let f64 = Type::float(rucc_ir::Float::F64);
3678 let (mut names, mut func, block, args) = blank(&[f64, Type::int(64)]);
3679 let mut build = Builder::new(&mut func, block);
3680 build.ret(&[args[0], args[1]]);
3681
3682 // `struct { double a; long b; } f(double a, long b)`. The two files are counted apart, so
3683 // neither half is the second of anything and the `double` is in `xmm0` rather than in the
3684 // register a second `double` would have been in. Getting this wrong is not a crash: the
3685 // caller reads a register nobody wrote, and this is where that is ruled out.
3686 assert_eq!(
3687 lower(&mut names, &func),
3688 "mfunc @f {\nblock0:\n %0:xmm($xmm0) = x64.arg_val_f64\n \
3689 %1:gpr($rdi) = x64.arg_val_64\n x64.ret_val_f64 %0($xmm0)\n \
3690 x64.ret_val_64 %1($rax)\n}\n"
3691 );
3692 }
3693
3694 #[test]
3695 fn two_of_the_same_file_back_take_the_first_two_of_it() {
3696 let f64 = Type::float(rucc_ir::Float::F64);
3697 let (mut names, mut func, block, args) = blank(&[f64, f64]);
3698 let mut build = Builder::new(&mut func, block);
3699 build.ret(&[args[0], args[1]]);
3700
3701 // `struct { double x, y; } f(double x, double y)`, which is the vector half of the pair
3702 // above and counts in its own file the same way.
3703 assert_eq!(
3704 lower(&mut names, &func),
3705 "mfunc @f {\nblock0:\n %0:xmm($xmm0) = x64.arg_val_f64\n \
3706 %1:xmm($xmm1) = x64.arg_val_f64\n x64.ret_val_f64 %0($xmm0)\n \
3707 x64.ret_val2_f64 %1($xmm1)\n}\n"
3708 );
3709 }
3710
3711 /// A function whose answer goes back through memory, with the pointer to the space for it in
3712 /// front of whatever else it takes. Only the signature says it is one.
3713 fn returning_through_memory(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
3714 let mut names = Interner::new();
3715 let sret = Abi::Sret { size: 32, align: 8 };
3716 let mut signature = Signature::new().and_param(Param::with_abi(Type::PTR, sret));
3717 signature.params.extend(params.iter().copied().map(Param::new));
3718 let mut func = Func::new(names.intern("f"), signature);
3719 let block = func.create_block();
3720 let space = func.append_param(block, Type::PTR);
3721 let values = std::iter::once(space)
3722 .chain(params.iter().map(|&ty| func.append_param(block, ty)))
3723 .collect();
3724 (names, func, block, values)
3725 }
3726
3727 #[test]
3728 fn the_space_a_return_through_memory_was_given_goes_back_in_the_first_return_register() {
3729 let (mut names, mut func, block, _) = returning_through_memory(&[]);
3730 Builder::new(&mut func, block).ret(&[]);
3731
3732 // `struct big f(void)`, where `big` is too large to come back in registers. The `return`
3733 // carries nothing, because the value went into the space the caller handed over, and the
3734 // document still says that address comes back in `rax`. Nothing in the IR says it, so the
3735 // convention says it, and the pseudo is the one any other pointer return would use.
3736 assert_eq!(
3737 lower(&mut names, &func),
3738 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
3739 x64.ret_val_64 %0($rax)\n}\n"
3740 );
3741 }
3742
3743 #[test]
3744 fn what_the_function_did_in_between_does_not_take_the_register_off_it() {
3745 let (mut names, mut func, block, args) = returning_through_memory(&[Type::int(32)]);
3746 let mut build = Builder::new(&mut func, block);
3747 build.store(args[1], args[0], plain(), Flags::default());
3748 build.ret(&[]);
3749
3750 // The register is a read at the end and not a move at the start, so it is live across
3751 // everything between the two and the allocator has to keep it somewhere. In a function
3752 // with a call in it that somewhere is a callee saved register, and the address comes back
3753 // into `rax` here rather than whatever the last instruction happened to leave there. That
3754 // is issue #333, and a store is enough to show the value outlives the entry block.
3755 let text = lower(&mut names, &func);
3756 assert!(text.contains("x64.mov_mr_32 %1, [%0]"), "{text}");
3757 assert!(text.ends_with(" x64.ret_val_64 %0($rax)\n}\n"), "{text}");
3758 }
3759
3760 #[test]
3761 fn a_pointer_that_is_only_a_pointer_is_not_given_back() {
3762 let (mut names, mut func, block, args) = blank(&[Type::PTR]);
3763 let mut build = Builder::new(&mut func, block);
3764 build.store(args[0], args[0], plain(), Flags::default());
3765 build.ret(&[]);
3766
3767 // `void f(void **p)`. It takes a pointer first and returns nothing, which is the shape of
3768 // the one above and none of its meaning, and what tells them apart is the signature. A
3769 // `void` function leaves `rax` alone.
3770 assert!(!lower(&mut names, &func).contains("ret_val"));
3771 }
3772
3773 #[test]
3774 fn a_return_of_a_constant_puts_it_in_a_register_first() {
3775 let (mut names, mut func, block, _) = blank(&[]);
3776 let mut build = Builder::new(&mut func, block);
3777 let zero = build.iconst(Type::int(32), 0);
3778 build.ret(&[zero]);
3779
3780 // No rule returns an immediate, so the plan that offers one is turned down and the next
3781 // one materializes it. That is `int main(void) { return 0; }` in full, once the epilogue
3782 // is appended to it.
3783 assert_eq!(
3784 lower(&mut names, &func),
3785 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_32 0\n x64.ret_val_32 %0($rax)\n}\n"
3786 );
3787 }
3788
3789 #[test]
3790 fn the_rule_that_writes_a_constant_down_is_recorded_as_a_rule_that_fired() {
3791 let (mut names, mut func, block, _) = blank(&[]);
3792 let mut build = Builder::new(&mut func, block);
3793 let zero = build.iconst(Type::int(32), 0);
3794 build.ret(&[zero]);
3795
3796 // The loop over the instructions passes a constant by, because a constant is written where
3797 // a register for it is first wanted rather than where the IR put it. So the only place a
3798 // rule about one is ever selected is the materialization, and a mark made in the loop
3799 // alone would report every rule about a constant as a rule nothing reaches.
3800 let out = super::func(&func, &mut names, &SYSV, &Elsewhere::default())
3801 .expect("every instruction has a rule");
3802 let rules = &crate::select::x86_64::TABLE.rules;
3803 let fired: Vec<&str> = rules
3804 .iter()
3805 .enumerate()
3806 .filter(|(index, _)| out.fired.has(*index))
3807 .map(|(_, rule)| rule.pattern)
3808 .collect();
3809 assert!(fired.contains(&"(iconst.i32 k)"), "{fired:?}");
3810 }
3811
3812 #[test]
3813 fn a_return_of_nothing_is_no_instruction_at_all() {
3814 let (mut names, mut func, block, _) = blank(&[]);
3815 let mut build = Builder::new(&mut func, block);
3816 build.ret(&[]);
3817
3818 // Every part of leaving a function that returns nothing is the epilogue's, and the
3819 // epilogue goes in after allocation. A block with nothing in it is the right answer here
3820 // rather than a function that could not be lowered.
3821 assert_eq!(lower(&mut names, &func), "mfunc @f {\nblock0:\n}\n");
3822 }
3823
3824 #[test]
3825 fn the_allocator_is_what_moves_the_answer_into_the_return_register() {
3826 let (mut names, mut source, block, _) = blank(&[]);
3827 let mut build = Builder::new(&mut source, block);
3828 let zero = build.iconst(Type::int(32), 0);
3829 build.ret(&[zero]);
3830
3831 let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
3832 .expect("every instruction has a rule")
3833 .func;
3834 let env = env();
3835 let allocation = rucc_regalloc::run(&mut out, &env, "test");
3836 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
3837 finish(
3838 &mut out,
3839 &allocation,
3840 &frame,
3841 &Stack::default(),
3842 Convention::new(&SYSV, &FRAME),
3843 &mut names,
3844 );
3845
3846 // `int main(void) { return 0; }` end to end. Nothing here asked for `rax`: the rule said
3847 // the value goes back, the target said where, and the allocator is what made it true. The
3848 // epilogue is what leaves, and this function needs no frame, so it is the return alone.
3849 //
3850 // Two instructions and no copy, which is what a hint buys. The return insists on `rax`,
3851 // so `rax` is the register the allocator tries first for the value the return reads, and
3852 // the constant is written straight into it.
3853 assert_eq!(
3854 mir::print_func(&out, &names, ®S),
3855 "mfunc @f {\nblock0:\n $rax = x64.mov_ri_32 0\n \
3856 x64.ret_val_32 $rax($rax)\n x64.ret\n}\n"
3857 );
3858 }
3859
3860 #[test]
3861 fn a_function_of_two_arguments_is_a_whole_function_now() {
3862 let i32 = Type::int(32);
3863 let (mut names, mut source, block, args) = blank(&[i32, i32]);
3864 let mut build = Builder::new(&mut source, block);
3865 let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
3866 build.ret(&[sum]);
3867
3868 let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
3869 .expect("every instruction has a rule")
3870 .func;
3871 let env = env();
3872 let allocation = rucc_regalloc::run(&mut out, &env, "test");
3873 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
3874 finish(
3875 &mut out,
3876 &allocation,
3877 &frame,
3878 &Stack::default(),
3879 Convention::new(&SYSV, &FRAME),
3880 &mut names,
3881 );
3882
3883 // `int f(int a, int b) { return a + b; }` end to end, and this is the test the argument
3884 // side exists for. Before it there was no way to write one: the allocator refuses a
3885 // function whose entry block takes parameters, because there is no edge into an entry
3886 // block for the moves that give a block parameter its value to go on.
3887 //
3888 // One move, and it is the one the machine's addition needs rather than one the allocator
3889 // owes anybody. Each argument stays in the register it arrived in, because the pseudo
3890 // that defines it insists on that register and the allocator now tries it first, and the
3891 // sum stays in the register the addition wrote it to until the return reads it out. The
3892 // copy in front of a two address instruction is what makes its destination one of the
3893 // registers it reads, and the source operand keeps its own name because the destination
3894 // is what the encoder writes.
3895 assert_eq!(
3896 mir::print_func(&out, &names, ®S),
3897 "mfunc @f {\nblock0:\n $rdi($rdi) = x64.arg_val_32\n \
3898 $rsi($rsi) = x64.arg_val_32\n \
3899 $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n $rax = x64.mov_rr_64 $rdi\n \
3900 x64.ret_val_32 $rax($rax)\n x64.ret\n}\n"
3901 );
3902 }
3903
3904 #[test]
3905 fn an_argument_with_no_register_left_for_it_is_read_out_of_the_caller_s_stack() {
3906 let i64 = Type::int(64);
3907 let (mut names, mut source, block, args) = blank(&[i64; 7]);
3908 let mut build = Builder::new(&mut source, block);
3909 build.ret(&[args[6]]);
3910
3911 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3912 .expect("the seventh is read from memory");
3913
3914 // SysV passes six integers in registers and the seventh in the caller's memory, so six of
3915 // these are pseudos that encode to nothing and the seventh is a load that encodes to real
3916 // bytes. Its displacement is nothing here for the reason a local's is: there is no frame
3917 // yet. What the walk hands on is which instruction is waiting, and for how far up the
3918 // caller's argument area, which is the bottom of it because it is the first one there.
3919 assert_eq!(lowered.stack.arguments.len(), 1);
3920 assert_eq!(lowered.stack.arguments[0].1, 0);
3921 let text = mir::print_func(&lowered.func, &names, ®S);
3922 assert!(text.contains("%6:gpr = x64.mov_rm_64 [$rsp]"), "{text}");
3923 assert_eq!(text.matches("x64.arg_val_64").count(), 6, "{text}");
3924 }
3925
3926 #[test]
3927 fn the_frame_is_what_says_how_far_up_the_caller_s_stack_an_argument_is() {
3928 let i64 = Type::int(64);
3929 let (mut names, mut source, block, args) = blank(&[i64; 8]);
3930 let mut build = Builder::new(&mut source, block);
3931 let sum = build.binary(Opcode::Add, args[6], args[7], Flags::default());
3932 build.ret(&[sum]);
3933
3934 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3935 .expect("both are read from memory");
3936 let stack = lowered.stack;
3937 let mut out = lowered.func;
3938 let env = env();
3939 let allocation = rucc_regalloc::run(&mut out, &env, "test");
3940 let layout = stack.layout(Layout::new(&SYSV, REGS));
3941 let frame = Frame::of(&out, &allocation, &layout);
3942 finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
3943
3944 // A leaf that takes no frame, so the stack pointer never moves and the only thing between
3945 // it and the caller's arguments is the return address the call pushed. The seventh
3946 // parameter is at the bottom of the caller's argument area and the eighth is one word
3947 // further up, which is the eight bytes between the two offsets.
3948 let text = mir::print_func(&out, &names, ®S);
3949 assert_eq!(frame.size(), 0);
3950 assert_eq!(frame.incoming(), Incoming::from_stack(8));
3951 assert!(text.contains("x64.mov_rm_64 [$rsp + 8]"), "{text}");
3952 assert!(text.contains("x64.mov_rm_64 [$rsp + 16]"), "{text}");
3953 }
3954
3955 #[test]
3956 fn a_realigned_frame_reaches_the_caller_s_arguments_through_the_frame_pointer() {
3957 let i64 = Type::int(64);
3958 let (mut names, mut source, block, args) = blank(&[i64; 7]);
3959 let wide = slot(&mut source, block, 64, 32);
3960 let mut build = Builder::new(&mut source, block);
3961 build.store(args[6], wide, plain(), Flags::default());
3962 build.ret(&[args[6]]);
3963
3964 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3965 .expect("every instruction has a rule");
3966 let stack = lowered.stack;
3967 let mut out = lowered.func;
3968 let env = env();
3969 let allocation = rucc_regalloc::run(&mut out, &env, "test");
3970 let layout = stack.layout(Layout::new(&SYSV, REGS));
3971 let frame = Frame::of(&out, &allocation, &layout);
3972 finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
3973
3974 // A local wanting thirty two byte alignment makes the prologue force the stack pointer,
3975 // which throws away how far the caller's stack was. So the load the lowering wrote off the
3976 // stack pointer is rewritten to read through the frame pointer, at the one distance that
3977 // survives: the word the prologue pushed the frame pointer into, and the return address
3978 // above it.
3979 let text = mir::print_func(&out, &names, ®S);
3980 assert_eq!(frame.realign(), Some(32));
3981 assert_eq!(frame.incoming(), Incoming::from_frame(16));
3982 assert!(text.contains("x64.mov_rm_64 [$rbp + 16]"), "{text}");
3983 assert!(!text.contains("x64.mov_rm_64 [$rsp"), "{text}");
3984 }
3985
3986 #[test]
3987 fn a_jump_is_the_edge_and_nothing_else() {
3988 let i32 = Type::int(32);
3989 let (mut names, mut source, entry, args) = blank(&[i32]);
3990 let next = source.create_block();
3991 let got = source.append_param(next, i32);
3992 Builder::new(&mut source, entry).jump(next, &[args[0]]);
3993 Builder::new(&mut source, next).ret(&[got]);
3994
3995 // Two blocks and two instructions, and the jump is neither of them. What it was is the
3996 // arm on the first block, and what the arm carries is the argument it was called with.
3997 assert_eq!(
3998 lower(&mut names, &source),
3999 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32 block1(%0)\n\n\
4000 block1(%1:gpr):\n x64.ret_val_32 %1($rax)\n}\n"
4001 );
4002 }
4003
4004 /// A block that reads what a block below it writes is filled after it, not before it.
4005 ///
4006 /// The blocks are written entry, `early`, `late`, `exit`, and the entry jumps straight past
4007 /// `early` to `late`, so `late` dominates `early` while sitting below it in the function.
4008 /// Filling them in the order they are written reaches the read in `early` first, and reading
4009 /// a value with no register yet mints one. The cast in `late` is no instruction at all, so
4010 /// what it does is give its answer the register its operand is already in, and that is not
4011 /// the register the read minted. Nothing writes the register the read minted. The printer
4012 /// says `%?` for a register nothing defines, which is what this looks for, and what came out
4013 /// of the real bug was SQLite loading a stack slot no store ever reached.
4014 #[test]
4015 fn a_block_that_reads_what_a_block_below_it_writes_is_filled_after_it() {
4016 let i64 = Type::int(64);
4017 let (mut names, mut source, entry, args) = blank(&[i64, i64]);
4018 let early = source.create_block();
4019 let late = source.create_block();
4020 let exit = source.create_block();
4021
4022 Builder::new(&mut source, entry).jump(late, &[]);
4023 let ptr = cast(&mut source, late, Opcode::IntToPtr, args[0], Type::PTR);
4024 Builder::new(&mut source, early).ret(&[ptr]);
4025 let mut build = Builder::new(&mut source, late);
4026 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
4027 build.br_if(cond, early, &[], exit, &[]);
4028 Builder::new(&mut source, exit).ret(&[args[1]]);
4029
4030 let text = lower(&mut names, &source);
4031 assert!(!text.contains("%?"), "every register has something that writes it: {text}");
4032 }
4033
4034 /// A constant is written where it is wanted rather than where the IR defined it, and two
4035 /// blocks wanting the same one is two places. Writing it once and reading it in both is a
4036 /// register read where nothing wrote it, unless the block it was written in happens to
4037 /// dominate the other, which nothing here checks and which the second arm of a branch never
4038 /// does. Each block gets its own copy of the number instead.
4039 #[test]
4040 fn a_constant_two_blocks_want_is_written_in_both_of_them() {
4041 let i32 = Type::int(32);
4042 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
4043 let then = source.create_block();
4044 let other = source.create_block();
4045 let join = source.create_block();
4046 let got = source.append_param(join, i32);
4047
4048 let mut build = Builder::new(&mut source, entry);
4049 let seven = build.iconst(i32, 7);
4050 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
4051 build.br_if(cond, then, &[], other, &[]);
4052 // Both arms want the seven in a register, because a block argument is never an immediate,
4053 // and neither arm dominates the other.
4054 Builder::new(&mut source, then).jump(join, &[seven]);
4055 Builder::new(&mut source, other).jump(join, &[seven]);
4056 Builder::new(&mut source, join).ret(&[got]);
4057
4058 let text = lower(&mut names, &source);
4059 assert_eq!(text.matches("x64.mov_ri_32 7").count(), 2, "one seven per block: {text}");
4060 }
4061
4062 /// An argument on an edge out of a block that leaves two ways is read after every instruction
4063 /// of the block is written, and reading one can write an instruction, which would land after
4064 /// the branch that has already jumped past it. The branch goes back on the end.
4065 #[test]
4066 fn a_constant_an_edge_wants_is_written_before_the_branch_and_not_after_it() {
4067 let i32 = Type::int(32);
4068 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
4069 let then = source.create_block();
4070 let join = source.create_block();
4071 let got = source.append_param(join, i32);
4072
4073 let mut build = Builder::new(&mut source, entry);
4074 let nine = build.iconst(i32, 9);
4075 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
4076 build.br_if(cond, then, &[], join, &[nine]);
4077 Builder::new(&mut source, then).jump(join, &[args[0]]);
4078 Builder::new(&mut source, join).ret(&[got]);
4079
4080 let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
4081 .expect("every instruction has a rule")
4082 .func;
4083 let entry = out.entry().expect("an entry block");
4084 let last = out.terminator(entry).expect("a block that leaves two ways has a branch");
4085 let branch = names.intern("x64.br_cond_8");
4086 assert_eq!(
4087 out[last].opcode,
4088 mir::Opcode::new(branch),
4089 "the branch is last: {}",
4090 mir::print_func(&out, &names, ®S)
4091 );
4092 }
4093
4094 #[test]
4095 fn a_conditional_branch_is_lowered_to_the_condition_and_nothing_about_where_it_goes() {
4096 let i32 = Type::int(32);
4097 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
4098 let then = source.create_block();
4099 let other = source.create_block();
4100 let mut build = Builder::new(&mut source, entry);
4101 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
4102 build.br_if(cond, then, &[], other, &[]);
4103 Builder::new(&mut source, then).ret(&[args[0]]);
4104 Builder::new(&mut source, other).ret(&[args[1]]);
4105
4106 // The comparison writes a byte and the branch reads it, and neither says a block. Both
4107 // arms are on the entry block, in the order the branch took them, so the arm that runs
4108 // when the condition holds is the first.
4109 assert_eq!(
4110 lower(&mut names, &source),
4111 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
4112 %1:gpr($rsi) = x64.arg_val_32\n %2:gpr = x64.cmp_set_l_32 %0, %1\n \
4113 x64.br_cond_8 %2, block1, block2\n\n\
4114 block1:\n x64.ret_val_32 %0($rax)\n\n\
4115 block2:\n x64.ret_val_32 %1($rax)\n}\n"
4116 );
4117 }
4118
4119 /// A choice between two values, which is one instruction and no blocks at all.
4120 ///
4121 /// The arms come out the other way round from the IR, because a conditional move overwrites its
4122 /// destination and the destination is the arm taken when the condition does not hold. The
4123 /// condition arrives last for the same reason: it is read by the test in front of the move
4124 /// rather than by the move.
4125 #[test]
4126 fn a_select_is_lowered_to_a_test_and_a_conditional_move() {
4127 let i32 = Type::int(32);
4128 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
4129 let mut build = Builder::new(&mut source, entry);
4130 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
4131 let picked = build.select(cond, args[0], args[1]);
4132 build.ret(&[picked]);
4133
4134 assert_eq!(
4135 lower(&mut names, &source),
4136 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
4137 %1:gpr($rsi) = x64.arg_val_32\n %2:gpr = x64.cmp_set_l_32 %0, %1\n \
4138 %3:gpr(reuse 1) = x64.test_cmov_ne_32 %1, %0, %2\n \
4139 x64.ret_val_32 %3($rax)\n}\n"
4140 );
4141 }
4142
4143 #[test]
4144 fn a_branch_over_a_block_is_a_whole_function_now() {
4145 let i32 = Type::int(32);
4146 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
4147 let then = source.create_block();
4148 let other = source.create_block();
4149 let join = source.create_block();
4150 let got = source.append_param(join, i32);
4151 let mut build = Builder::new(&mut source, entry);
4152 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
4153 build.br_if(cond, then, &[], other, &[]);
4154 let mut build = Builder::new(&mut source, then);
4155 let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
4156 build.jump(join, &[sum]);
4157 Builder::new(&mut source, other).jump(join, &[args[1]]);
4158 Builder::new(&mut source, join).ret(&[got]);
4159
4160 // `int f(int a, int b) { if (a < b) return a + b; else return b; }` end to end, written
4161 // the way a front end writes it: both arms of the branch are blocks of their own and the
4162 // return is the block they meet at. No edge here is critical, because the two arms out of
4163 // the entry carry nothing and the two arms into the join each leave a block that goes
4164 // nowhere else, so each has its own end to put its move at.
4165 let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
4166 .expect("every instruction has a rule")
4167 .func;
4168 assert_eq!(crate::split::critical(&mut out), 0, "no edge here is critical");
4169 let env = env();
4170 let allocation = rucc_regalloc::run(&mut out, &env, "test");
4171 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
4172 finish(
4173 &mut out,
4174 &allocation,
4175 &frame,
4176 &Stack::default(),
4177 Convention::new(&SYSV, &FRAME),
4178 &mut names,
4179 );
4180
4181 // One epilogue, on the join, which is the one block the function leaves from, and the
4182 // moves that give the join its parameter are at the end of each arm. Every register is
4183 // physical and the branch is still a branch on a register, because turning it into a
4184 // `test` and a `jcc` is the block layout's and there is no block layout yet.
4185 let text = mir::print_func(&out, &names, ®S);
4186 assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
4187 assert!(text.contains("x64.br_cond_8"), "{text}");
4188 assert!(text.contains("x64.add_rr_32"), "{text}");
4189 assert!(!text.contains('%'), "{text}");
4190 }
4191
4192 #[test]
4193 fn a_critical_edge_is_split_before_the_allocator_ever_sees_it() {
4194 let i32 = Type::int(32);
4195 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
4196 let then = source.create_block();
4197 let join = source.create_block();
4198 let got = source.append_param(join, i32);
4199 let mut build = Builder::new(&mut source, entry);
4200 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
4201 build.br_if(cond, then, &[], join, &[args[1]]);
4202 Builder::new(&mut source, then).jump(join, &[args[0]]);
4203 let mut build = Builder::new(&mut source, join);
4204 let twice = build.binary(Opcode::Add, got, got, Flags::default());
4205 build.ret(&[twice]);
4206
4207 // The else arm is critical: the entry block leaves two ways and the join is arrived at
4208 // two ways, and the arm carries a value. Without splitting it the allocator asserts,
4209 // because the move that gives the join its parameter would have to run at the end of a
4210 // block that also goes to the other arm.
4211 let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
4212 .expect("every instruction has a rule")
4213 .func;
4214 assert_eq!(crate::split::critical(&mut out), 1);
4215 let env = env();
4216 let allocation = rucc_regalloc::run(&mut out, &env, "test");
4217 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
4218 finish(
4219 &mut out,
4220 &allocation,
4221 &frame,
4222 &Stack::default(),
4223 Convention::new(&SYSV, &FRAME),
4224 &mut names,
4225 );
4226
4227 // The block the split added is where the move went, and it is the whole of that block.
4228 let text = mir::print_func(&out, &names, ®S);
4229 assert_eq!(out.block_count(), 4, "{text}");
4230 assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
4231 }
4232
4233 #[test]
4234 fn a_call_passes_what_the_convention_says_and_takes_back_what_it_says() {
4235 let i32 = Type::int(32);
4236 let (mut names, mut source, block, args) = blank(&[i32, i32]);
4237 let sig =
4238 source.add_signature(Signature::new().with_params(&[i32, i32]).with_returns(&[i32]));
4239 let callee = names.intern("g");
4240 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0], args[1]]);
4241 let got = source[call].first_result.expect("an integer comes back");
4242 Builder::new(&mut source, block).ret(&[got]);
4243
4244 // `int f(int a, int b) { return g(a, b); }`. The arguments arrived where the call wants
4245 // them, so what the call reads is what arrived, and the whole of the convention is in the
4246 // constraints rather than in a move.
4247 let text = lower(&mut names, &source);
4248 assert!(text.contains("= x64.call %0($rdi), %1($rsi), @g"), "{text}");
4249 assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
4250 // What the call writes is the value that comes back and then every register the callee is
4251 // free to destroy, in both classes, which is the whole of what stops the allocator from
4252 // leaving something in one of them.
4253 assert!(text.contains("%2:gpr($rax), $rcx, $rdx, $r8, $r9, $r10, $r11, $xmm0,"), "{text}");
4254 assert!(text.contains("$xmm15 = x64.call"), "{text}");
4255 }
4256
4257 #[test]
4258 fn what_the_frame_owes_a_call_comes_back_with_the_function() {
4259 let i32 = Type::int(32);
4260 let sig = |source: &mut Func| source.add_signature(Signature::new().with_params(&[i32]));
4261
4262 let (mut names, mut source, block, args) = blank(&[i32]);
4263 let sig = sig(&mut source);
4264 let callee = names.intern("g");
4265 Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
4266 let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
4267 .expect("every instruction has a rule");
4268
4269 // Nothing on the stack, so nothing owed, but not a leaf either: a function that calls
4270 // owes the callee an aligned stack pointer and may not use the red zone.
4271 assert_eq!(out.stack.calls, Some(0));
4272 let layout = out.stack.layout(Layout::new(&SYSV, REGS));
4273 assert!(!layout.leaf);
4274 assert_eq!(layout.outgoing, 0);
4275
4276 // The same call under the other convention owes thirty two bytes for the callee to spill
4277 // its register arguments into, which is a fact about the convention and not about the call.
4278 let out = func(&source, &mut names, &x86_64::WIN64, &Elsewhere::default())
4279 .expect("every instruction has a rule");
4280 assert_eq!(out.stack.calls, Some(32));
4281
4282 // And a function that calls nothing is a leaf, which is what says it may use the red zone.
4283 let (mut names, mut source, block, args) = blank(&[i32]);
4284 Builder::new(&mut source, block).ret(&[args[0]]);
4285 let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
4286 .expect("every instruction has a rule");
4287 assert_eq!(out.stack.calls, None);
4288 assert!(out.stack.layout(Layout::new(&SYSV, REGS)).leaf);
4289 }
4290
4291 #[test]
4292 fn a_value_that_outlives_a_call_is_not_left_where_the_call_destroys_it() {
4293 let i32 = Type::int(32);
4294 let (mut names, mut source, block, args) = blank(&[i32]);
4295 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
4296 let callee = names.intern("g");
4297 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
4298 let got = source[call].first_result.expect("an integer comes back");
4299 let mut build = Builder::new(&mut source, block);
4300 let sum = build.binary(Opcode::Add, got, args[0], Flags::default());
4301 build.ret(&[sum]);
4302
4303 // `int f(int a) { return g(a) + a; }`, which is the smallest program that asks the
4304 // question: `a` is read after the call and `rdi` is a register the call destroys.
4305 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
4306 .expect("every instruction has a rule");
4307 let layout = lowered.stack.layout(Layout::new(&SYSV, REGS));
4308 let mut out = lowered.func;
4309 let env = env();
4310 let allocation = rucc_regalloc::run(&mut out, &env, "test");
4311 let frame = Frame::of(&out, &allocation, &layout);
4312 finish(
4313 &mut out,
4314 &allocation,
4315 &frame,
4316 &Stack::default(),
4317 Convention::new(&SYSV, &FRAME),
4318 &mut names,
4319 );
4320
4321 // It went to a register the callee has to put back, and the prologue and epilogue are what
4322 // put it back, which is the whole bargain the two halves of a convention make.
4323 let text = mir::print_func(&out, &names, ®S);
4324 assert!(text.contains("$rbx"), "{text}");
4325 assert!(!text.contains('%'), "{text}");
4326 assert_eq!(text.matches("x64.call").count(), 1, "{text}");
4327 }
4328
4329 #[test]
4330 fn a_call_with_more_arguments_than_registers_writes_the_rest_into_the_outgoing_area() {
4331 let i64 = Type::int(64);
4332 let (mut names, mut source, block, args) = blank(&[i64]);
4333 let seven = vec![i64; 7];
4334 let sig = source.add_signature(Signature::new().with_params(&seven));
4335 let callee = names.intern("g");
4336 let passed = vec![args[0]; 7];
4337 Builder::new(&mut source, block).call(callee, sig, &passed);
4338
4339 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
4340 .expect("the seventh goes to memory");
4341 // The bytes the call needs are on the layout the frame is worked out from, so that the
4342 // frame reserves as many as the widest call in the function asked for.
4343 assert_eq!(lowered.stack.calls, Some(8));
4344 let text = mir::print_func(&lowered.func, &names, ®S);
4345 assert!(text.contains("x64.mov_mr_64 %0, [$rsp]\n"), "{text}");
4346 }
4347
4348 #[test]
4349 fn a_call_this_cannot_make_is_reported_rather_than_made() {
4350 let (mut names, mut source, block, _) = blank(&[]);
4351 let returns = [Type::float(rucc_ir::Float::F80), Type::int(64)];
4352 let sig = source.add_signature(Signature::new().with_returns(&returns));
4353 let callee = names.intern("g");
4354 Builder::new(&mut source, block).call(callee, sig, &[]);
4355 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
4356 .expect_err("a long double is on the x87");
4357 assert_eq!(failed.to_string(), "what this call gives back is on the x87 stack");
4358 }
4359
4360 /// A `long double` on its own is a different answer, because on its own it comes back on the
4361 /// x87 stack rather than in a register, which is somewhere the call cannot be said to write.
4362 ///
4363 /// So the call gives back nothing at all and the value is taken off the stack by the `fstp`
4364 /// straight after it. That instruction has to be straight after it: the stack is one place and
4365 /// anything else that touched it before this ran would be looking at the value still on it.
4366 #[test]
4367 fn a_call_that_gives_back_a_long_double_takes_it_off_the_stack_at_once() {
4368 let (mut names, mut source, block, _) = blank(&[]);
4369 let long_double = Type::float(rucc_ir::Float::F80);
4370 let sig = source.add_signature(Signature::new().with_returns(&[long_double]));
4371 let callee = names.intern("g");
4372 Builder::new(&mut source, block).call(callee, sig, &[]);
4373
4374 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
4375 .expect("the value comes back in st0");
4376 let text = mir::print_func(&lowered.func, &names, ®S);
4377 let after: Vec<&str> =
4378 text.lines().skip_while(|line| !line.contains("x64.call")).skip(1).collect();
4379 assert_eq!(after[0].trim(), "%0:gpr = x64.lea_64 [$rsp]", "{text}");
4380 assert_eq!(after[1].trim(), "x64.fstp_t [%0]", "{text}");
4381 // And the slot it went into is the sixteen bytes the type takes, like every other one.
4382 assert_eq!(lowered.stack.locals.len(), 1, "{text}");
4383 assert_eq!(lowered.stack.locals[0].size, X87_BYTES);
4384 }
4385
4386 #[test]
4387 fn a_call_through_an_address_goes_through_the_register_the_address_is_in() {
4388 let i32 = Type::int(32);
4389 let (mut names, mut source, block, args) = blank(&[Type::PTR, i32]);
4390 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
4391 let varargs = source.push_abis(&[]);
4392 let info = source.add_call(CallInfo { callee: None, signature: sig, varargs });
4393 let mut build = Builder::new(&mut source, block);
4394 let inst = InstData {
4395 args: build.func().push_values(&[args[0], args[1]]),
4396 extra: Extra::Call(info),
4397 ..InstData::new(Opcode::CallIndirect)
4398 };
4399 let called = build.inst(inst, &[i32]);
4400 let got = source[called].first_result.expect("an integer comes back");
4401 Builder::new(&mut source, block).ret(&[got]);
4402
4403 // `int f(int (*g)(int), int a) { return g(a); }`. The first operand is the address and
4404 // the arguments are the ones behind it, and everything else about the call is what a call
4405 // to a name would have been.
4406 let text = lower(&mut names, &source);
4407 assert!(text.contains("= x64.call_reg %0, %1($rdi)"), "{text}");
4408 assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
4409 assert!(!text.contains("@g"), "a call through an address names nobody: {text}");
4410 }
4411
4412 #[test]
4413 fn an_instruction_no_rule_covers_is_reported() {
4414 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
4415 let mut build = Builder::new(&mut source, block);
4416 let operands = build.func().push_values(&[args[0]]);
4417 build.inst(InstData { args: operands, ..InstData::new(Opcode::LongjmpMarker) }, &[]);
4418
4419 // The mark that a jump goes back through here, which nothing writes an instruction for
4420 // yet: what it needs is for the allocator to be told a block can be arrived at twice, and
4421 // that is `tamnd/rucc#223`. Nothing about it is a width or a register, so there is nothing
4422 // for the message to add beyond the name.
4423 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
4424 .expect_err("no rule writes a longjmp marker");
4425 assert_eq!(failed.to_string(), "no rule lowers a `longjmp_marker`");
4426
4427 // It produces nothing, so there is no type in the message and nothing invents one, and the
4428 // instruction comes back so a caller can ask the function where it was.
4429 let inst = failed.inst().expect("the instruction it is about");
4430 assert_eq!(source[inst].opcode, Opcode::LongjmpMarker);
4431 }
4432
4433 /// A barrier is written by name here, and what it is depends on the ordering and on nothing
4434 /// else. `crate::expand` is where the reasoning about this machine's memory model lives.
4435 #[test]
4436 fn a_barrier_is_one_instruction_at_the_strongest_ordering_and_none_below_it() {
4437 for order in MemOrder::all().filter(|&order| order != MemOrder::NotAtomic) {
4438 let (mut names, mut source, block, _) = blank(&[]);
4439 let mut build = Builder::new(&mut source, block);
4440 build
4441 .inst(InstData { extra: Extra::Order(order), ..InstData::new(Opcode::Fence) }, &[]);
4442
4443 let text = lower(&mut names, &source);
4444 assert_eq!(text.contains("x64.mfence"), order == MemOrder::SeqCst, "{order:?}: {text}");
4445 }
4446 }
4447
4448 /// A compare and exchange is written by name too, and at the width of the value rather than at
4449 /// the width of the address, which is the mistake worth pinning: everything here is a pointer
4450 /// and only the value says how many bytes the instruction touches.
4451 #[test]
4452 fn a_compare_and_exchange_is_one_instruction_at_the_width_of_the_value() {
4453 for bits in [8, 16, 32, 64] {
4454 let ty = Type::int(bits);
4455 let (mut names, mut source, block, args) = blank(&[Type::PTR, ty, ty]);
4456 let mut build = Builder::new(&mut source, block);
4457 let mem = build.func().add_mem(MemInfo {
4458 size: u64::from(bits / 8),
4459 align: bits / 8,
4460 order: MemOrder::SeqCst,
4461 ..plain()
4462 });
4463 let operands = build.func().push_values(&[args[0], args[1], args[2]]);
4464 build.inst(
4465 InstData {
4466 args: operands,
4467 extra: Extra::Mem(mem),
4468 ..InstData::new(Opcode::Cmpxchg)
4469 },
4470 &[ty, Type::I1],
4471 );
4472
4473 // Two values out of one instruction, the first of them in the register the machine
4474 // reads the expected value out of, the second free for the allocator to place. The
4475 // address is the memory operand and neither of the two values is.
4476 let text = lower(&mut names, &source);
4477 let written = format!("%3:gpr($rax), %4:gpr = x64.cmpxchg_{bits} %1($rax), %2, [%0]");
4478 assert!(text.contains(&written), "{bits}: {text}");
4479 }
4480 }
4481
4482 #[test]
4483 fn more_values_back_than_the_convention_has_registers_for_is_reported() {
4484 let i64 = Type::int(64);
4485 let (mut names, mut source, block, args) = blank(&[i64, i64, i64]);
4486 let mut build = Builder::new(&mut source, block);
4487 build.ret(&[args[0], args[1], args[2]]);
4488
4489 // Two integers come back in `rax` and `rdx` and a third has nowhere to go, which is not a
4490 // gap in the rules but the convention saying no. The front end classifies before it gets
4491 // here, so this is the shape that would mean the classification went wrong.
4492 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
4493 .expect_err("only two come back");
4494 assert_eq!(
4495 failed.to_string(),
4496 "what this function gives back takes more registers than this convention has for it"
4497 );
4498
4499 let inst = failed.inst().expect("the instruction it is about");
4500 assert_eq!(source[inst].opcode, Opcode::Return);
4501 }
4502
4503 /// A refusal about a signature has no instruction, which is what makes it the one arm apart.
4504 ///
4505 /// Everything else is about something written somewhere in the body and hands it back so a
4506 /// caller can ask the function where it came from. A parameter arrives before the first
4507 /// instruction runs, so there is nothing in the body to point at and the message is about
4508 /// the function.
4509 #[test]
4510 fn a_refusal_about_a_parameter_has_no_instruction_to_point_at() {
4511 let missing = Unsupported::Argument { index: 0, missing: Missing::OnX87 };
4512 assert_eq!(missing.inst(), None);
4513 }
4514
4515 /// An `alloca` of a fixed size, which is what every local whose address is taken becomes.
4516 fn slot(source: &mut Func, block: Block, size: u64, align: u32) -> Value {
4517 let info = MemInfo { size, align, ..plain() };
4518 let mut build = Builder::new(source, block);
4519 let mem = build.func().add_mem(info);
4520 build.value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR)
4521 }
4522
4523 #[test]
4524 fn a_local_is_memory_in_the_frame_and_one_instruction_that_says_where() {
4525 let (mut names, mut source, block, _) = blank(&[]);
4526 let slot = slot(&mut source, block, 4, 4);
4527 let mut build = Builder::new(&mut source, block);
4528 let nine = build.iconst(Type::int(32), 9);
4529 build.store(nine, slot, plain(), Flags::default());
4530 let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
4531 build.ret(&[loaded]);
4532
4533 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
4534 .expect("every instruction has a rule");
4535
4536 // Four bytes on the list the frame is laid out from, and the one instruction that reads
4537 // where they went. Its displacement is nothing here because there is no frame yet, and
4538 // which instruction is waiting for which local is what `finish` is handed.
4539 assert_eq!(lowered.stack.locals, vec![Local { size: 4, align: 4 }]);
4540 assert_eq!(lowered.stack.addresses.len(), 1);
4541 assert_eq!(lowered.stack.addresses[0].1, 0);
4542 assert_eq!(
4543 mir::print_func(&lowered.func, &names, ®S),
4544 "mfunc @f {\nblock0:\n %0:gpr = x64.lea_64 [$rsp]\n \
4545 %1:gpr = x64.mov_ri_32 9\n x64.mov_mr_32 %1, [%0]\n \
4546 %2:gpr = x64.mov_rm_32 [%0]\n x64.ret_val_32 %2($rax)\n}\n"
4547 );
4548 }
4549
4550 #[test]
4551 fn the_frame_is_what_fills_the_address_of_a_local_in() {
4552 let (mut names, mut source, block, _) = blank(&[]);
4553 let slot = slot(&mut source, block, 4, 4);
4554 let mut build = Builder::new(&mut source, block);
4555 let nine = build.iconst(Type::int(32), 9);
4556 build.store(nine, slot, plain(), Flags::default());
4557 let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
4558 build.ret(&[loaded]);
4559
4560 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
4561 .expect("every instruction has a rule");
4562 let stack = lowered.stack;
4563 let mut out = lowered.func;
4564 let env = env();
4565 let allocation = rucc_regalloc::run(&mut out, &env, "test");
4566 let layout = stack.layout(Layout::new(&SYSV, REGS));
4567 let frame = Frame::of(&out, &allocation, &layout);
4568 finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
4569
4570 // `int f(void) { int x; x = 9; return x; }` with the address of `x` taken, end to end.
4571 // A leaf small enough to live in the red zone takes no frame at all, so the stack pointer
4572 // never moves and the four bytes are below it, which is what the negative offset is. The
4573 // instruction the lowering left with nothing in its displacement now has the answer in it.
4574 let text = mir::print_func(&out, &names, ®S);
4575 assert!(text.contains("$rax = x64.lea_64 [$rsp - 8]"), "{text}");
4576 assert!(!text.contains("x64.sub_ri_64"), "{text}");
4577 assert_eq!(frame.size(), 0);
4578 assert_eq!(frame.local(0), Some(-8));
4579 }
4580
4581 /// An `alloca` whose size is an operand, which is a variable length array.
4582 fn growing(source: &mut Func, block: Block, size: Value, align: u32) -> Value {
4583 let info = MemInfo { size: 0, align, ..plain() };
4584 let mut build = Builder::new(source, block);
4585 let mem = build.func().add_mem(info);
4586 let args = build.func().push_values(&[size]);
4587 build.value(
4588 InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) },
4589 Type::PTR,
4590 )
4591 }
4592
4593 #[test]
4594 fn a_stack_slot_whose_size_is_not_known_until_it_runs_takes_the_bytes_off_the_stack_pointer() {
4595 let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
4596 let slot = growing(&mut source, block, args[0], 16);
4597 Builder::new(&mut source, block).ret(&[slot]);
4598
4599 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
4600 .expect("every instruction has a rule");
4601
4602 // The bytes come off the stack pointer where the declaration stands and the address is
4603 // where the stack pointer then is, which is one subtraction and one `lea` rather than a
4604 // slot the frame laid out. Nothing is on the list of locals, because there is nothing
4605 // about this the frame could place.
4606 let text = mir::print_func(&lowered.func, &names, ®S);
4607 assert!(text.contains("$rsp = x64.sub_rr_64 $rsp, %0"), "{text}");
4608 assert!(text.contains("x64.lea_64 [$rsp]"), "{text}");
4609 assert!(lowered.stack.locals.is_empty(), "{text}");
4610 assert_eq!(lowered.stack.dynamic.len(), 1);
4611 assert!(lowered.stack.grown_at.is_some());
4612 }
4613
4614 #[test]
4615 fn a_growing_slot_wanting_more_alignment_than_the_stack_pointer_has_is_reported() {
4616 let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
4617 let slot = growing(&mut source, block, args[0], 32);
4618 Builder::new(&mut source, block).ret(&[slot]);
4619
4620 // Thirty two is more than a call leaves the stack pointer on, so giving it what it asked
4621 // for means masking the stack pointer after moving it, and after that no constant reaches
4622 // the rest of the frame from the frame pointer either. A second pointer held for the
4623 // purpose is what fixes it and there is not one yet.
4624 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
4625 .expect_err("nothing realigns a frame that grows");
4626 assert_eq!(
4627 failed.to_string(),
4628 "this local wants more alignment than the stack pointer is left on, which needs a \
4629 base register nothing here keeps"
4630 );
4631 }
4632
4633 #[test]
4634 fn a_frame_that_grows_reaches_its_own_locals_through_the_frame_pointer() {
4635 let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
4636 let fixed = slot(&mut source, block, 4, 4);
4637 let mut build = Builder::new(&mut source, block);
4638 let nine = build.iconst(Type::int(32), 9);
4639 build.store(nine, fixed, plain(), Flags::default());
4640 let grown = growing(&mut source, block, args[0], 16);
4641 Builder::new(&mut source, block).ret(&[grown]);
4642
4643 let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
4644 .expect("every instruction has a rule");
4645 let stack = lowered.stack;
4646 let mut out = lowered.func;
4647 let env = env();
4648 let allocation = rucc_regalloc::run(&mut out, &env, "test");
4649 let layout = stack.layout(Layout::new(&SYSV, REGS));
4650 let frame = Frame::of(&out, &allocation, &layout);
4651 finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
4652
4653 // The stack pointer moves in the middle of the function, so the four bytes of the fixed
4654 // local are not a constant away from it any more and the frame pointer is what reaches
4655 // them. The frame keeps one whatever the flags asked for, takes its bytes rather than
4656 // living in the red zone, and the address of the growing slot is off the stack pointer as
4657 // it stands after the subtraction rather than off anything the prologue left.
4658 let text = mir::print_func(&out, &names, ®S);
4659 assert!(frame.grows());
4660 assert!(frame.frame_pointer());
4661 assert!(frame.size() > 0, "{text}");
4662 assert!(text.contains("x64.lea_64 [$rbp"), "{text}");
4663 assert!(text.contains("$rsp = x64.sub_rr_64 $rsp"), "{text}");
4664 assert!(text.contains("x64.lea_64 [$rsp]"), "{text}");
4665 }
4666
4667 #[test]
4668 fn an_address_is_read_written_and_added_to_like_the_integer_it_is() {
4669 let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
4670 let mut build = Builder::new(&mut source, block);
4671 let stepped = build.func().push_values(&[args[0], args[1]]);
4672 let next =
4673 build.value(InstData { args: stepped, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
4674 let loaded = build.load(Type::int(32), next, plain(), Flags::default());
4675 build.ret(&[loaded]);
4676
4677 // `int f(int *p, long i) { return *(int *)((char *)p + i); }`. Nothing about this is new
4678 // in the rule set, which is the point: the two addresses arrive in registers because an
4679 // address is an integer as wide as one, and the arithmetic on them is the add it always
4680 // was, so every rule written about an add reaches it.
4681 //
4682 // The add stays its own instruction rather than folding into the address the load reads
4683 // from. Two registers with no scale on either is the one addressing mode the rules have no
4684 // load through, because the folds that exist are the displacement one and the scaled ones,
4685 // and this is neither. That is a peephole worth having and not a thing this changes.
4686 assert_eq!(
4687 lower(&mut names, &source),
4688 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
4689 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n \
4690 %3:gpr = x64.mov_rm_32 [%2]\n x64.ret_val_32 %3($rax)\n}\n"
4691 );
4692 }
4693
4694 /// The address of a file scope name, which is what every use of a global and every string
4695 /// literal starts from.
4696 fn address_of(source: &mut Func, block: Block, names: &mut Interner, name: &str) -> Value {
4697 let symbol = names.intern(name);
4698 let mut build = Builder::new(source, block);
4699 build.value(
4700 InstData { extra: Extra::Symbol(symbol), ..InstData::new(Opcode::GlobalAddr) },
4701 Type::PTR,
4702 )
4703 }
4704
4705 #[test]
4706 fn the_address_of_a_name_is_one_instruction_carrying_the_name() {
4707 let (mut names, mut source, block, _) = blank(&[]);
4708 let counter = address_of(&mut source, block, &mut names, "counter");
4709 let mut build = Builder::new(&mut source, block);
4710 let loaded = build.load(Type::int(32), counter, plain(), Flags::default());
4711 build.ret(&[loaded]);
4712
4713 // `extern int counter; int f(void) { return counter; }`. The address is an addressing mode
4714 // that names no register and carries the symbol, which is what the assembler writes
4715 // relative to `%rip` and what the object writer leaves a relocation for.
4716 assert_eq!(
4717 lower(&mut names, &source),
4718 "mfunc @f {\nblock0:\n %0:gpr = x64.lea_64 [@counter]\n \
4719 %1:gpr = x64.mov_rm_32 [%0]\n x64.ret_val_32 %1($rax)\n}\n"
4720 );
4721 }
4722
4723 #[test]
4724 fn the_address_of_a_name_outside_the_file_is_read_out_of_the_offset_table() {
4725 let (mut names, mut source, block, _) = blank(&[]);
4726 let away = address_of(&mut source, block, &mut names, "away");
4727 Builder::new(&mut source, block).ret(&[away]);
4728 let elsewhere: Elsewhere = [names.intern("away")].into_iter().collect();
4729
4730 // `extern void away(void); void *f(void) { return away; }`. A load and not an address
4731 // computation, because the distance from here to a name a shared library may be the one
4732 // that defines is not a number any link can work out, and the slot the linker fills in is
4733 // in this program and so is a distance it has.
4734 let out =
4735 func(&source, &mut names, &SYSV, &elsewhere).expect("every instruction has a rule");
4736 assert_eq!(
4737 mir::print_func(&out.func, &names, ®S),
4738 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rm_64 [got @away]\n \
4739 x64.ret_val_64 %0($rax)\n}\n"
4740 );
4741 }
4742
4743 #[test]
4744 fn the_address_of_a_thread_local_is_an_offset_out_of_the_table_plus_where_this_thread_starts() {
4745 let (mut names, mut source, block, _) = blank(&[]);
4746 let own = address_of(&mut source, block, &mut names, "own");
4747 Builder::new(&mut source, block).ret(&[own]);
4748 let elsewhere = Elsewhere::default().with_threads([names.intern("own")]);
4749
4750 // `extern _Thread_local int own; void *f(void) { return &own; }`. Three instructions where
4751 // the two cases above are one, because there is no address to load or to work out: the
4752 // slot holds how far into a thread's block the variable sits, `%fs:0` is where this
4753 // thread's block starts, and the sum of the two is this thread's copy.
4754 let out =
4755 func(&source, &mut names, &SYSV, &elsewhere).expect("every instruction has a rule");
4756 assert_eq!(
4757 mir::print_func(&out.func, &names, ®S),
4758 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rm_64 [thread @own]\n \
4759 %1:gpr = x64.mov_rm_64 [fs:0]\n %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n \
4760 x64.ret_val_64 %2($rax)\n}\n"
4761 );
4762 }
4763
4764 /// The same load with nothing added to it, which is the whole of `__builtin_thread_pointer`.
4765 #[test]
4766 fn the_start_of_this_thread_s_own_storage_is_the_one_load_and_no_arithmetic() {
4767 let (mut names, mut source, block, _) = blank(&[]);
4768 let here =
4769 Builder::new(&mut source, block).value(InstData::new(Opcode::ThreadPointer), Type::PTR);
4770 Builder::new(&mut source, block).ret(&[here]);
4771
4772 let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
4773 .expect("every instruction has a rule");
4774 assert_eq!(
4775 mir::print_func(&out.func, &names, ®S),
4776 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rm_64 [fs:0]\n \
4777 x64.ret_val_64 %0($rax)\n}\n"
4778 );
4779 }
4780
4781 /// One `asm` statement, with its template and its constraint list written as a program does.
4782 fn assembly(
4783 source: &mut Func,
4784 block: Block,
4785 names: &mut Interner,
4786 template: &str,
4787 constraints: &str,
4788 args: &[Value],
4789 results: &[Type],
4790 ) -> Inst {
4791 clobbering(source, block, names, template, constraints, "memory", args, results)
4792 }
4793
4794 /// The same with a clobber list of its own, for the statements that are about one.
4795 #[allow(clippy::too_many_arguments)]
4796 fn clobbering(
4797 source: &mut Func,
4798 block: Block,
4799 names: &mut Interner,
4800 template: &str,
4801 constraints: &str,
4802 clobbers: &str,
4803 args: &[Value],
4804 results: &[Type],
4805 ) -> Inst {
4806 let info = AsmInfo {
4807 template: names.intern(template),
4808 constraints: names.intern(constraints),
4809 clobbers: names.intern(clobbers),
4810 targets: rucc_ir::BlockCallList::EMPTY,
4811 };
4812 Builder::new(source, block).inline_asm(info, args, results, Flags::VOLATILE)
4813 }
4814
4815 /// What a program asking the processor what it can do writes, which is the instruction whose
4816 /// every operand is a register its text does not name.
4817 #[test]
4818 fn a_template_whose_registers_are_named_by_the_constraints_places_them_from_the_letters() {
4819 let u32 = Type::int(32);
4820 let (mut names, mut source, block, _) = blank(&[]);
4821 let zero = Builder::new(&mut source, block).iconst(u32, 0);
4822 let out = clobbering(
4823 &mut source,
4824 block,
4825 &mut names,
4826 "cpuid",
4827 "=a,a",
4828 "ebx,ecx,edx",
4829 &[zero],
4830 &[u32],
4831 );
4832 let produced = source[out].results().next().expect("one result");
4833 Builder::new(&mut source, block).ret(&[produced]);
4834
4835 // `asm ("cpuid" : "=a" (n) : "a" (0) : "ebx", "ecx", "edx")`, which is the first thing
4836 // every program that has a faster path on some machines writes. Four registers written and
4837 // two read, none of them in the template, all of them out of the description, and the two
4838 // that the letters named are the statement's own. The subleaf is a zero because the
4839 // instruction reads `ecx` and the program said nothing about what is in it. The three
4840 // clobbers are gone because `cpuid` writes those three anyway, and saying it twice is one
4841 // register with two definitions.
4842 assert_eq!(
4843 lower(&mut names, &source),
4844 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_32 0\n \
4845 %1:gpr = x64.mov_ri_64 0\n \
4846 %2:gpr($rax), %3:gpr($rbx), %4:gpr($rcx), %5:gpr($rdx) = x64.cpuid %0($rax), \
4847 %1($rcx)\n x64.ret_val_32 %2($rax)\n}\n"
4848 );
4849 }
4850
4851 /// A clobber the instruction does not write itself, which is the case the list is there for.
4852 /// It goes on as a definition of the register, in among the other definitions, because that is
4853 /// the whole of how a machine function says a register is not worth anything after this.
4854 #[test]
4855 fn a_clobber_the_instruction_does_not_write_itself_is_a_definition_of_that_register() {
4856 let (mut names, mut source, block, _) = blank(&[]);
4857 clobbering(&mut source, block, &mut names, "pause", "", "rsi,cc,memory", &[], &[]);
4858 Builder::new(&mut source, block).ret(&[]);
4859
4860 assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n $rsi = x64.pause\n}\n");
4861 }
4862
4863 /// A clobber naming something this has no register for. Refused rather than dropped, since the
4864 /// list is the program saying which registers it may not leave anything in, and an entry
4865 /// nobody read is a register something may still be left in.
4866 #[test]
4867 fn a_clobber_this_has_no_register_for_is_refused() {
4868 let (mut names, mut source, block, _) = blank(&[]);
4869 clobbering(&mut source, block, &mut names, "pause", "", "zmm0", &[], &[]);
4870 Builder::new(&mut source, block).ret(&[]);
4871
4872 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
4873 .expect_err("there is no such register here");
4874 assert_eq!(
4875 failed.to_string(),
4876 "this `asm` says it destroys a register this has no name for"
4877 );
4878 }
4879
4880 #[test]
4881 fn an_asm_with_an_empty_template_and_no_operands_is_no_instructions() {
4882 let (mut names, mut source, block, _) = blank(&[]);
4883 assembly(&mut source, block, &mut names, "", "", &[], &[]);
4884 Builder::new(&mut source, block).ret(&[]);
4885
4886 // `asm volatile ("" : : : "memory")`, which is a barrier and nothing else. The barrier was
4887 // spent on the optimizer, which has finished by now, so what is left is nothing.
4888 assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n}\n");
4889 }
4890
4891 #[test]
4892 fn an_output_an_input_is_tied_to_is_the_register_that_input_arrived_in() {
4893 let i32 = Type::int(32);
4894 let (mut names, mut source, block, args) = blank(&[i32]);
4895 let out = assembly(&mut source, block, &mut names, "", "=r,0", &args, &[i32]);
4896 let produced = source[out].results().next().expect("one result");
4897 Builder::new(&mut source, block).ret(&[produced]);
4898
4899 // `asm ("" : "=r" (x) : "0" (x))`, which is how a program stops the optimizer following a
4900 // value without changing it. The two share a place and the template writes nothing over
4901 // it, so the value comes back out of the register it went in.
4902 assert_eq!(
4903 lower(&mut names, &source),
4904 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
4905 x64.ret_val_32 %0($rax)\n}\n"
4906 );
4907 }
4908
4909 #[test]
4910 fn an_output_written_plus_is_the_same_rename() {
4911 let i32 = Type::int(32);
4912 let (mut names, mut source, block, args) = blank(&[i32]);
4913 let out = assembly(&mut source, block, &mut names, "", "+r", &args, &[i32]);
4914 let produced = source[out].results().next().expect("one result");
4915 Builder::new(&mut source, block).ret(&[produced]);
4916
4917 // `asm ("" : "+r" (x))`, which says the same thing in one operand instead of two.
4918 assert_eq!(
4919 lower(&mut names, &source),
4920 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
4921 x64.ret_val_32 %0($rax)\n}\n"
4922 );
4923 }
4924
4925 #[test]
4926 fn an_output_nothing_is_tied_to_is_a_zero() {
4927 let i32 = Type::int(32);
4928 let (mut names, mut source, block, _) = blank(&[]);
4929 let out = assembly(&mut source, block, &mut names, "", "=r", &[], &[i32]);
4930 let produced = source[out].results().next().expect("one result");
4931 Builder::new(&mut source, block).ret(&[produced]);
4932
4933 // `asm ("" : "=r" (y))`, whose answer is whatever the assembly left in the register, and
4934 // an empty template leaves nothing. A definite value rather than a register nothing wrote,
4935 // because the allocator is owed a definition before the use however little the program is.
4936 assert_eq!(
4937 lower(&mut names, &source),
4938 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_32 0\n x64.ret_val_32 %0($rax)\n}\n"
4939 );
4940 }
4941
4942 #[test]
4943 fn a_template_that_is_one_instruction_becomes_that_instruction() {
4944 let (mut names, mut source, block, _) = blank(&[]);
4945 assembly(&mut source, block, &mut names, "pause", "", &[], &[]);
4946 Builder::new(&mut source, block).ret(&[]);
4947
4948 // `asm volatile ("pause")`, which is what every spin lock in every allocator writes. One
4949 // instruction, no operands, and nothing between the template and the machine but the table
4950 // that already says what a `pause` is.
4951 assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n x64.pause\n}\n");
4952 }
4953
4954 #[test]
4955 fn a_template_that_reads_a_segment_becomes_the_load_it_already_was() {
4956 let i64 = Type::int(64);
4957 let (mut names, mut source, block, _) = blank(&[]);
4958 let out = assembly(&mut source, block, &mut names, "movq %%fs:0, %0", "=r", &[], &[i64]);
4959 let produced = source[out].results().next().expect("one result");
4960 Builder::new(&mut source, block).ret(&[produced]);
4961
4962 // `asm ("movq %%fs:0, %0" : "=r" (tid))`, which is how a program finds the block its own
4963 // thread owns. The same instruction `crate::lower` already writes for a thread-local
4964 // variable, reached this time because a program wrote it out by hand.
4965 assert_eq!(
4966 lower(&mut names, &source),
4967 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rm_64 [fs:0]\n \
4968 x64.ret_val_64 %0($rax)\n}\n"
4969 );
4970 }
4971
4972 #[test]
4973 fn a_template_naming_an_instruction_this_machine_has_not_got_is_refused() {
4974 let (mut names, mut source, block, _) = blank(&[]);
4975 assembly(&mut source, block, &mut names, "hcf", "", &[], &[]);
4976 Builder::new(&mut source, block).ret(&[]);
4977
4978 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
4979 .expect_err("there is no such instruction");
4980 assert_eq!(
4981 failed.to_string(),
4982 "this `asm` has instructions in its template, which nothing here assembles"
4983 );
4984 }
4985
4986 /// A register the template named is a claim on a register nobody told the allocator about.
4987 /// Refused rather than placed, because a register two things believe they own is a wrong
4988 /// program that nothing reports. A register a constraint letter names is a different thing and
4989 /// is placed, which the test above is about: there the statement said which of its own operands
4990 /// is in the register, and a name in the middle of a template says no such thing.
4991 #[test]
4992 fn a_template_naming_a_register_the_allocator_did_not_hand_out_is_refused() {
4993 let i64 = Type::int(64);
4994 let (mut names, mut source, block, _) = blank(&[]);
4995 let out = assembly(&mut source, block, &mut names, "movq %%rax, %0", "=r", &[], &[i64]);
4996 let produced = source[out].results().next().expect("one result");
4997 Builder::new(&mut source, block).ret(&[produced]);
4998
4999 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
5000 .expect_err("the template named a register");
5001 assert_eq!(failed.to_string(), "this `asm` has an operand this cannot place");
5002 }
5003
5004 #[test]
5005 fn a_constraint_list_that_does_not_describe_the_operands_is_refused() {
5006 let i32 = Type::int(32);
5007 let (mut names, mut source, block, args) = blank(&[i32]);
5008 assembly(&mut source, block, &mut names, "", "=r", &args, &[]);
5009 Builder::new(&mut source, block).ret(&[]);
5010
5011 // An output with no result to be, which is what the front end never writes and what a
5012 // hand written module can. Refused rather than placed by a guess.
5013 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
5014 .expect_err("the list and the instruction disagree");
5015 assert_eq!(failed.to_string(), "this `asm` has an operand this cannot place");
5016 }
5017
5018 /// A cast between a pointer and an integer, at whatever width the result is asked for.
5019 fn cast(source: &mut Func, block: Block, opcode: Opcode, from: Value, to: Type) -> Value {
5020 let mut build = Builder::new(source, block);
5021 let args = build.func().push_values(&[from]);
5022 build.value(InstData { args, ..InstData::new(opcode) }, to)
5023 }
5024
5025 #[test]
5026 fn a_cast_between_a_pointer_and_an_integer_as_wide_is_no_instruction_at_all() {
5027 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
5028 let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(64));
5029 Builder::new(&mut source, block).ret(&[number]);
5030
5031 // `long f(void *p) { return (long)p; }`. An address on this machine is an integer as wide
5032 // as the machine addresses, so the cast changes what the type system calls the value and
5033 // changes nothing about the value, and the register holding it is the one that held it.
5034 assert_eq!(
5035 lower(&mut names, &source),
5036 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
5037 x64.ret_val_64 %0($rax)\n}\n"
5038 );
5039 }
5040
5041 #[test]
5042 fn a_null_pointer_is_a_constant_that_reaches_a_register_before_anything_reads_it() {
5043 let (mut names, mut source, block, _) = blank(&[]);
5044 let mut build = Builder::new(&mut source, block);
5045 let zero = build.iconst(Type::int(64), 0);
5046 let null = cast(&mut source, block, Opcode::IntToPtr, zero, Type::PTR);
5047 Builder::new(&mut source, block).ret(&[null]);
5048
5049 // `void *f(void) { return 0; }`. The cast is nothing, and reading its operand is what
5050 // writes the zero down: a constant is materialized where it is wanted rather than where
5051 // the IR defined it, and without the read there would be no instruction at all.
5052 assert_eq!(
5053 lower(&mut names, &source),
5054 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_64 0\n x64.ret_val_64 %0($rax)\n}\n"
5055 );
5056 }
5057
5058 #[test]
5059 fn the_five_linkages_the_ir_has_narrow_to_the_three_an_object_file_can_say() {
5060 let readings = [
5061 (Linkage::External, mir::Binding::Global),
5062 (Linkage::Common, mir::Binding::Global),
5063 (Linkage::Internal, mir::Binding::Local),
5064 (Linkage::Weak, mir::Binding::Weak),
5065 (Linkage::LinkOnce, mir::Binding::Weak),
5066 ];
5067 for (linkage, wanted) in readings {
5068 let (mut names, mut source, block, _) = blank(&[]);
5069 source.linkage = linkage;
5070 Builder::new(&mut source, block).ret(&[]);
5071 let out = func(&source, &mut names, &SYSV, &Elsewhere::default()).expect("a return");
5072 // The narrowing is done here rather than where the object is written, because a
5073 // machine function is all the assembler and the writer are ever handed.
5074 assert_eq!(out.func.binding, wanted, "{linkage:?}");
5075 }
5076 }
5077
5078 /// The visibility makes the same trip and is not narrowed on the way, because ELF says all
5079 /// three of them.
5080 ///
5081 /// Here for the reason the linkage above is here. A machine function is the whole of what the
5082 /// assembler and the object writer are handed, so a fact about the symbol that does not get
5083 /// onto one is a fact that is gone by the time anything could write it down, and the way that
5084 /// shows up is a shared library exporting the wrong set of names with nothing said anywhere.
5085 #[test]
5086 fn the_visibility_survives_the_trip_from_the_ir_to_a_machine_function() {
5087 let readings = [
5088 (Visibility::Default, mir::Visibility::Default),
5089 (Visibility::Hidden, mir::Visibility::Hidden),
5090 (Visibility::Protected, mir::Visibility::Protected),
5091 ];
5092 for (visibility, wanted) in readings {
5093 let (mut names, mut source, block, _) = blank(&[]);
5094 source.visibility = visibility;
5095 Builder::new(&mut source, block).ret(&[]);
5096 let out = func(&source, &mut names, &SYSV, &Elsewhere::default()).expect("a return");
5097 assert_eq!(out.func.visibility, wanted, "{visibility:?}");
5098 }
5099 }
5100
5101 #[test]
5102 fn a_cast_between_a_pointer_and_a_narrower_integer_is_reported() {
5103 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
5104 let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(32));
5105 Builder::new(&mut source, block).ret(&[number]);
5106
5107 // The front end never writes one: it casts at the address width and truncates or extends
5108 // around it, so both of those are the rules they always were. IR from somewhere else that
5109 // does write one is refused rather than compiled to a move that keeps the high half.
5110 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
5111 .expect_err("no rule narrows an address");
5112 assert_eq!(failed.to_string(), "no rule lowers a `ptrtoint` producing a `i32`");
5113 }
5114
5115 /// The type this machine has no register for.
5116 fn long_double() -> Type {
5117 Type::float(rucc_ir::Float::F80)
5118 }
5119
5120 #[test]
5121 fn a_double_widened_and_narrowed_again_goes_out_through_the_frame_and_back() {
5122 let f64 = Type::float(rucc_ir::Float::F64);
5123 let (mut names, mut source, block, args) = blank(&[f64]);
5124 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
5125 let back = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
5126 Builder::new(&mut source, block).ret(&[back]);
5127
5128 // `double f(double d) { long double x = d; return x; }`. The x87 reads memory and nothing
5129 // else, so the value is written to the crossing slot, loaded at the format that widens it
5130 // and put in the slot the eighty bit value lives in. Coming back is the same three the
5131 // other way. Both slots are addressed by a `lea` with nothing in it yet, which is what
5132 // every address in a frame looks like here until `finish` has the numbers.
5133 assert_eq!(
5134 lower(&mut names, &source),
5135 "mfunc @f {\nblock0:\n \
5136 %0:xmm($xmm0) = x64.arg_val_f64\n \
5137 %1:gpr = x64.lea_64 [$rsp]\n \
5138 %2:gpr = x64.lea_64 [$rsp]\n \
5139 x64.movsd_mr %0, [%1]\n \
5140 x64.fld_l [%1]\n \
5141 x64.fstp_t [%2]\n \
5142 %3:gpr = x64.lea_64 [$rsp]\n \
5143 %4:gpr = x64.lea_64 [$rsp]\n \
5144 x64.fld_t [%3]\n \
5145 x64.fstp_l [%4]\n \
5146 %5:xmm = x64.movsd_rm [%4]\n \
5147 x64.ret_val_f64 %5($xmm0)\n}\n"
5148 );
5149 }
5150
5151 #[test]
5152 fn a_long_double_has_sixteen_bytes_of_its_own_and_keeps_them() {
5153 let f64 = Type::float(rucc_ir::Float::F64);
5154 let (mut names, mut source, block, args) = blank(&[f64]);
5155 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
5156 let once = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
5157 let twice = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
5158 let mut build = Builder::new(&mut source, block);
5159 let sum = build.binary(Opcode::FAdd, once, twice, Flags::default());
5160 build.ret(&[sum]);
5161
5162 let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
5163 .expect("every instruction is written");
5164
5165 // Two slots and not four: sixteen bytes for the one eighty bit value, which is what the
5166 // psABI says one takes and is aligned to, and eight for the crossing, which every group
5167 // in the function shares because nothing is ever left in it. The value's slot is its own
5168 // for the whole function, so reading it twice reads the same sixteen bytes.
5169 assert_eq!(
5170 out.stack.locals,
5171 vec![Local { size: 8, align: 8 }, Local { size: 16, align: 16 }]
5172 );
5173 }
5174
5175 #[test]
5176 fn an_integer_becomes_a_long_double_by_being_loaded_as_one() {
5177 let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
5178 let wide = cast(&mut source, block, Opcode::SIToFP, args[0], long_double());
5179 let back =
5180 cast(&mut source, block, Opcode::FPTrunc, wide, Type::float(rucc_ir::Float::F64));
5181 Builder::new(&mut source, block).ret(&[back]);
5182
5183 // `double f(long n) { long double x = n; return x; }`. `fild` is the same push at another
5184 // format, so the conversion is the load and there is no instruction that converts.
5185 let text = lower(&mut names, &source);
5186 assert!(text.contains("x64.mov_mr_64 %0, [%1]"), "{text}");
5187 assert!(text.contains("x64.fild_ll [%1]"), "{text}");
5188 }
5189
5190 #[test]
5191 fn a_long_double_becoming_an_integer_cuts_towards_zero_with_the_control_word() {
5192 let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
5193 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
5194 let whole = cast(&mut source, block, Opcode::FPToSI, wide, Type::int(32));
5195 Builder::new(&mut source, block).ret(&[whole]);
5196
5197 // The one conversion here with no single instruction behind it. C cuts towards zero and
5198 // the unit rounds the way its control word says, so the word is saved, ORed with the two
5199 // bits that mean truncate, loaded, used and put back. Nine instructions for what `fisttp`
5200 // does in one, and `spec/10-backend.md` section 10.8 says why that one is not used.
5201 let text = lower(&mut names, &source);
5202 let group: Vec<&str> = text
5203 .lines()
5204 .map(str::trim)
5205 .filter(|line| line.starts_with("x64.f") || line.contains("_16"))
5206 .collect();
5207 assert_eq!(
5208 group,
5209 [
5210 "x64.fld_l [%1]",
5211 "x64.fstp_t [%2]",
5212 "x64.fnstcw [%5]",
5213 "%6:gpr = x64.mov_rm_16 [%5]",
5214 "%7:gpr(reuse 1) = x64.or_ri_16 %6, 3072",
5215 "x64.mov_mr_16 %7, [%5 + 2]",
5216 "x64.fldcw [%5 + 2]",
5217 "x64.fld_t [%3]",
5218 "x64.fistp_l [%4]",
5219 "x64.fldcw [%5]",
5220 ],
5221 "{text}"
5222 );
5223 }
5224
5225 #[test]
5226 fn a_long_double_is_read_and_written_as_the_bits_it_already_is() {
5227 let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::PTR]);
5228 let mut build = Builder::new(&mut source, block);
5229 let value = build.load(long_double(), args[0], plain(), Flags::default());
5230 build.store(value, args[1], plain(), Flags::default());
5231 build.ret(&[]);
5232
5233 // `void f(long double *a, long double *b) { *b = *a; }`. A copy is a push and a pop at the
5234 // format the value is already in, which neither converts nor looks: a signalling NaN stays
5235 // one and nothing is raised, which is the whole of what makes it a copy.
5236 let text = lower(&mut names, &source);
5237 let group: Vec<&str> =
5238 text.lines().map(str::trim).filter(|line| line.starts_with("x64.f")).collect();
5239 assert_eq!(
5240 group,
5241 ["x64.fld_t [%0]", "x64.fstp_t [%2]", "x64.fld_t [%3]", "x64.fstp_t [%1]"],
5242 "{text}"
5243 );
5244 }
5245
5246 /// Two `long double` values, from two `double` parameters, and the instructions that made
5247 /// them, which every test below this one throws away.
5248 fn two_long_doubles(source: &mut Func, block: Block, args: &[Value]) -> (Value, Value) {
5249 let left = cast(source, block, Opcode::FPExt, args[0], long_double());
5250 let right = cast(source, block, Opcode::FPExt, args[1], long_double());
5251 (left, right)
5252 }
5253
5254 /// The x87 instructions of a function, in order, with everything else dropped.
5255 fn stack_only(text: &str) -> Vec<&str> {
5256 text.lines().map(str::trim).filter(|line| line.contains("x64.f")).collect()
5257 }
5258
5259 /// The two frame slots the last two addresses of a function were taken of, which in a
5260 /// comparison are the two operands in the order they go on the stack.
5261 fn pushed(out: &Lowered) -> Vec<usize> {
5262 let taken: Vec<usize> = out.stack.addresses.iter().map(|&(_, local)| local).collect();
5263 taken[taken.len() - 2..].to_vec()
5264 }
5265
5266 #[test]
5267 fn adding_two_long_doubles_pushes_both_and_leaves_the_answer_in_a_slot() {
5268 let f64 = Type::float(rucc_ir::Float::F64);
5269 let (mut names, mut source, block, args) = blank(&[f64, f64]);
5270 let (left, right) = two_long_doubles(&mut source, block, &args);
5271 let sum =
5272 Builder::new(&mut source, block).binary(Opcode::FAdd, left, right, Flags::default());
5273 let back = cast(&mut source, block, Opcode::FPTrunc, sum, f64);
5274 Builder::new(&mut source, block).ret(&[back]);
5275
5276 // `double f(double a, double b) { return (long double) a + (long double) b; }`. The last
5277 // four lines are the add: both operands pushed, the instruction that names neither of
5278 // them because they are the top two of a stack, and the answer taken off into its slot.
5279 let text = lower(&mut names, &source);
5280 assert_eq!(
5281 stack_only(&text),
5282 [
5283 "x64.fld_l [%2]",
5284 "x64.fstp_t [%3]",
5285 "x64.fld_l [%4]",
5286 "x64.fstp_t [%5]",
5287 "x64.fld_t [%6]",
5288 "x64.fld_t [%7]",
5289 "x64.fadd_p",
5290 "x64.fstp_t [%8]",
5291 "x64.fld_t [%9]",
5292 "x64.fstp_l [%10]",
5293 ],
5294 "{text}"
5295 );
5296 }
5297
5298 #[test]
5299 fn a_subtraction_pushes_the_left_operand_first_and_asks_for_the_att_spelling() {
5300 let f64 = Type::float(rucc_ir::Float::F64);
5301 let (mut names, mut source, block, args) = blank(&[f64, f64]);
5302 let (left, right) = two_long_doubles(&mut source, block, &args);
5303 let less =
5304 Builder::new(&mut source, block).binary(Opcode::FSub, left, right, Flags::default());
5305 let back = cast(&mut source, block, Opcode::FPTrunc, less, f64);
5306 Builder::new(&mut source, block).ret(&[back]);
5307
5308 // The left one goes on first, so it ends up under the right one, and the answer wanted is
5309 // the one below minus the top. In AT&T that is `fsubrp`, since `fsubp` there is `DE E0+i`
5310 // and computes the other one. The `r` says which spelling this is and not which order the
5311 // pushes were in. `crates/rucc/tests/x87.rs` is what says the answer is right, because a
5312 // name is what got this wrong the first time.
5313 let text = lower(&mut names, &source);
5314 assert_eq!(
5315 &stack_only(&text)[4..8],
5316 ["x64.fld_t [%6]", "x64.fld_t [%7]", "x64.fsubr_p", "x64.fstp_t [%8]"],
5317 "{text}"
5318 );
5319 }
5320
5321 #[test]
5322 fn negating_a_long_double_turns_the_sign_over_and_reads_nothing() {
5323 let f64 = Type::float(rucc_ir::Float::F64);
5324 let (mut names, mut source, block, args) = blank(&[f64]);
5325 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
5326 let flipped = Builder::new(&mut source, block).unary(Opcode::FNeg, wide, long_double());
5327 let back = cast(&mut source, block, Opcode::FPTrunc, flipped, f64);
5328 Builder::new(&mut source, block).ret(&[back]);
5329
5330 // `fchs` and not a subtraction from zero, which would give a different answer at a negative
5331 // zero and would signal at a NaN. It does not read the value as a number at all.
5332 let text = lower(&mut names, &source);
5333 assert_eq!(
5334 &stack_only(&text)[2..5],
5335 ["x64.fld_t [%3]", "x64.fchs", "x64.fstp_t [%4]"],
5336 "{text}"
5337 );
5338 }
5339
5340 #[test]
5341 fn comparing_two_long_doubles_puts_the_left_one_on_top() {
5342 let f64 = Type::float(rucc_ir::Float::F64);
5343 let (mut names, mut source, block, args) = blank(&[f64, f64]);
5344 let (left, right) = two_long_doubles(&mut source, block, &args);
5345 let mut build = Builder::new(&mut source, block);
5346 build.fcmp(FloatPred::Ogt, left, right, Flags::default());
5347 build.ret(&[]);
5348
5349 // `a > b`. `fucomip` asks about the top of the stack against what is under it, so the
5350 // operand the predicate is about has to go on last, which is the other way round from the
5351 // arithmetic above. The pop that clears the loser and the byte that reads the flags are
5352 // both inside the one opcode.
5353 let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
5354 .expect("every instruction is written");
5355 let slots = pushed(&out);
5356 assert_eq!(slots, [2, 1], "the right operand goes on first and the left one on top");
5357 let text = mir::print_func(&out.func, &names, ®S);
5358 assert_eq!(
5359 &stack_only(&text)[4..],
5360 ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
5361 "{text}"
5362 );
5363 }
5364
5365 #[test]
5366 fn a_comparison_that_the_machine_has_backwards_swaps_the_two_pushes() {
5367 let f64 = Type::float(rucc_ir::Float::F64);
5368 let (mut names, mut source, block, args) = blank(&[f64, f64]);
5369 let (left, right) = two_long_doubles(&mut source, block, &args);
5370 let mut build = Builder::new(&mut source, block);
5371 build.fcmp(FloatPred::Olt, left, right, Flags::default());
5372 build.ret(&[]);
5373
5374 // `a < b` is `b > a` and this machine has the one condition, so the same opcode runs with
5375 // the operands the other way round. The same trade the vector rules make, and it has to
5376 // be the same one: a `long double` comparison that picked a different condition from the
5377 // `double` comparison of the same two numbers would be wrong at exactly the unordered
5378 // cases the two conditions differ on.
5379 //
5380 // Which slot each push names is the whole of the difference from the test above, and the
5381 // text does not show it, since an address in a frame is a `lea` with nothing in it until
5382 // `finish` has the numbers. So the slots are what is read here.
5383 let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
5384 .expect("every instruction is written");
5385 let slots = pushed(&out);
5386 assert_eq!(slots, [1, 2], "the left operand goes on first and the right one on top");
5387 let text = mir::print_func(&out.func, &names, ®S);
5388 assert_eq!(
5389 &stack_only(&text)[4..],
5390 ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
5391 "{text}"
5392 );
5393 }
5394
5395 #[test]
5396 fn an_ordered_equal_needs_a_second_byte_to_put_the_two_conditions_together() {
5397 let f64 = Type::float(rucc_ir::Float::F64);
5398 let (mut names, mut source, block, args) = blank(&[f64, f64]);
5399 let (left, right) = two_long_doubles(&mut source, block, &args);
5400 let mut build = Builder::new(&mut source, block);
5401 build.fcmp(FloatPred::Oeq, left, right, Flags::default());
5402 build.ret(&[]);
5403
5404 // Equal and ordered are two conditions and the flags carry both, so the opcode writes a
5405 // second register as well as the one the value is in and ANDs them together. Said here by
5406 // handing it a spare, since an instruction that wrote a register nothing knew about would
5407 // be an instruction the allocator could put a live value in the way of.
5408 let text = lower(&mut names, &source);
5409 assert!(text.contains("%8:gpr, %9:gpr = x64.fucomip_set_e_and_np"), "{text}");
5410 }
5411
5412 #[test]
5413 fn a_comparison_that_is_never_asked_is_reported() {
5414 let f64 = Type::float(rucc_ir::Float::F64);
5415 let (mut names, mut source, block, args) = blank(&[f64, f64]);
5416 let (left, right) = two_long_doubles(&mut source, block, &args);
5417 let mut build = Builder::new(&mut source, block);
5418 build.fcmp(FloatPred::False, left, right, Flags::default());
5419 build.ret(&[]);
5420
5421 // Always false is a constant and not a comparison, so there is no condition to pick and
5422 // nothing here folds it into one: an instruction that quietly agreed with it would hide
5423 // that the optimizer left a comparison in that it should have taken out.
5424 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
5425 .expect_err("no condition is always false");
5426 assert_eq!(failed.to_string(), "no rule lowers a `fcmp` producing a `i1`");
5427 }
5428
5429 #[test]
5430 fn a_long_double_constant_is_the_bits_of_it_put_where_the_value_lives() {
5431 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
5432 let mut build = Builder::new(&mut source, block);
5433 // `1.5L`, which is the leading bit and one more of significand, and an exponent of zero.
5434 let one_and_a_half = build.fconst(long_double(), 0x3fff_c000_0000_0000_0000);
5435 build.store(one_and_a_half, args[0], plain(), Flags::default());
5436 build.ret(&[]);
5437
5438 // No x87 instruction at all. A slot holding one of these is the value, so a constant is
5439 // its ten bytes written where the value lives, and whatever reads it does the `fld`.
5440 let text = lower(&mut names, &source);
5441 assert!(text.contains("x64.mov_ri_64 -4611686018427387904"), "{text}");
5442 assert!(text.contains("x64.mov_ri_16 16383"), "{text}");
5443 assert!(text.contains("x64.mov_mr_16 %3, [%1 + 8]"), "{text}");
5444 // The six bytes above the ten are the padding that makes the type sixteen wide, and they
5445 // are unspecified rather than zero, so nothing writes them.
5446 assert_eq!(text.matches("x64.mov_mr").count(), 2, "{text}");
5447 }
5448
5449 #[test]
5450 fn a_negative_long_double_constant_keeps_the_bit_above_its_exponent() {
5451 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
5452 let mut build = Builder::new(&mut source, block);
5453 let minus = build.fconst(long_double(), 0xbfff_c000_0000_0000_0000);
5454 build.store(minus, args[0], plain(), Flags::default());
5455 build.ret(&[]);
5456
5457 // `-1.5L`. The sign is the top bit of the two byte half, so the immediate that half is put
5458 // in a register with is above the signed range of sixteen bits and has to stay there: read
5459 // as a number it would be negative, and it is not a number, it is two bytes.
5460 let text = lower(&mut names, &source);
5461 assert!(text.contains("x64.mov_ri_16 49151"), "{text}");
5462 }
5463
5464 #[test]
5465 fn a_long_double_crosses_an_edge_as_an_address_and_is_copied_where_it_lands() {
5466 let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
5467 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
5468 let next = source.create_block();
5469 let param = source.append_param(next, long_double());
5470 Builder::new(&mut source, block).jump(next, &[wide]);
5471 Builder::new(&mut source, next).ret(&[param]);
5472
5473 // What the edge carries is the address of the slot the value is already in, which is an
5474 // ordinary register the allocator has an opinion about. The block on the other side copies
5475 // the sixteen bytes into a slot of its own before anything reads them, so a second edge
5476 // handing over a second address would still leave one place for a reader to look.
5477 let text = lower(&mut names, &source);
5478 let second: Vec<&str> = text
5479 .lines()
5480 .skip_while(|line| !line.starts_with("block1"))
5481 .skip(1)
5482 .take(3)
5483 .map(str::trim)
5484 .collect();
5485 assert_eq!(
5486 second,
5487 ["x64.fld_t [%4]", "%5:gpr = x64.lea_64 [$rsp]", "x64.fstp_t [%5]"],
5488 "{text}"
5489 );
5490 }
5491
5492 #[test]
5493 fn more_long_doubles_at_a_block_than_the_stack_is_deep_are_reported() {
5494 let f64 = Type::float(rucc_ir::Float::F64);
5495 let (mut names, mut source, block, args) = blank(&[f64]);
5496 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
5497 let next = source.create_block();
5498 let params: Vec<Value> =
5499 (0..=X87_DEPTH).map(|_| source.append_param(next, long_double())).collect();
5500 let carried: Vec<Value> = params.iter().map(|_| wide).collect();
5501 Builder::new(&mut source, block).jump(next, &carried);
5502 Builder::new(&mut source, next).ret(&[params[0]]);
5503
5504 // The copies go through the x87 stack so that every one of them is read before any of them
5505 // is written, which is what makes a block that swaps two of these right. Nine of them do
5506 // not fit on the stack, and copying the ninth before or after the rest is the order that
5507 // could be wrong, so it is refused instead.
5508 let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
5509 .expect_err("nine do not fit on the stack");
5510 assert_eq!(
5511 failed.to_string(),
5512 "block1 takes 9 parameters of type `f80` and only 8 can cross an edge at once"
5513 );
5514 assert_eq!(failed.inst(), None);
5515 }
5516}