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