rucc_target/regs.rs
1//! The register file: what registers a target has, and what classes they fall into.
2//!
3//! Design: `spec/10-backend.md` section 10.8.
4//!
5//! A register file is data rather than code, which is the same claim the rest of this crate
6//! makes and the one `M10` puts a number on. A class is a set of registers that an operand of
7//! that class may be assigned to, and a physical register is its number inside its class, so
8//! the allocator works in dense small integers and only the printer and the parser ever deal in
9//! names.
10//!
11//! The file lives here rather than in `rucc-mir` because more than one thing reads it. The
12//! machine IR needs it to print, the allocator needs the set it may assign from, and the ABI
13//! description needs to name the registers arguments arrive in. All three are above this crate,
14//! and the alternative is the register file living in whichever of them happens to be lowest,
15//! which is how a layering ends up describing itself as historical.
16//!
17//! Names are unique across the whole file, not merely inside a class. That is what lets a
18//! register be written `$rax` in a dump rather than `$gpr.0`, and it is a real constraint on a
19//! target that gives one register two classes: it has to say which class it is in, or use two
20//! names. [`RegFile::duplicate`] is what a target's own test asks to find out.
21
22use std::fmt;
23
24/// One class of registers, and the registers in it.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub struct ClassInfo {
27 /// What the class is called in a dump, such as `gpr`.
28 pub name: &'static str,
29 /// How wide one of its registers is, in bits.
30 pub bits: u32,
31 /// The registers, in the order their numbers run, without the sigil a dump writes.
32 pub regs: &'static [&'static str],
33 /// Whether the allocator may put a value in one of these.
34 ///
35 /// True for every class a target means the allocator to use, which is nearly all of them.
36 /// False says the registers exist and are named and are not somewhere a value may be told to
37 /// live, so a virtual register of this class is a mistake at the point it was made rather than
38 /// a value the allocator has nowhere to put.
39 ///
40 /// The x87 stack is the case this exists for, and it is worth the sentence because it is not
41 /// the usual reason a register is unavailable. `rsp` is unavailable because it has a job;
42 /// `st0` is unavailable because the machine addresses it as a stack, so which register a name
43 /// means depends on how many values are on the stack at the time, and an allocator that hands
44 /// out a name has no way to say that. So nothing allocates from it, an eighty bit value lives
45 /// in a stack slot between one operation and the next, and the stack is empty on both sides of
46 /// every group of instructions that uses it. See `spec/10-backend.md` section 10.8, which says
47 /// what a group is and why nothing the allocator inserts can get into the middle of one, and
48 /// tamnd/rucc#540.
49 ///
50 /// A register in such a class can still be named, which is the whole reason the class is
51 /// described at all: a `long double` comes back from a call in `st0` and the convention has to
52 /// be able to say so.
53 pub allocatable: bool,
54}
55
56/// Which class a register or an operand belongs to.
57///
58/// A number into the file's classes rather than a name, because it is on every operand of every
59/// instruction and it is compared far more often than it is printed.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
61pub struct RegClass(u8);
62
63impl RegClass {
64 /// The class with that number.
65 #[must_use]
66 pub const fn new(number: u8) -> Self {
67 Self(number)
68 }
69
70 /// Its number, which is what indexes the file.
71 #[must_use]
72 pub const fn number(self) -> u8 {
73 self.0
74 }
75}
76
77/// One physical register, as its number inside its class.
78///
79/// The class is not in here. An operand carries its class already, and a fixed-register
80/// constraint is a constraint on an operand, so repeating the class would be a second copy of
81/// something that can disagree with the first.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
83pub struct PhysReg(u8);
84
85impl PhysReg {
86 /// The register with that number in its class.
87 #[must_use]
88 pub const fn new(number: u8) -> Self {
89 Self(number)
90 }
91
92 /// Its number inside its class.
93 #[must_use]
94 pub const fn number(self) -> u8 {
95 self.0
96 }
97}
98
99/// Every register a target has.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub struct RegFile {
102 classes: &'static [ClassInfo],
103}
104
105impl RegFile {
106 /// The file of a target whose registers nothing has described yet.
107 ///
108 /// A target reaches 1.0 with a real one. Until it has one, the honest answer to what
109 /// registers it has is that nobody has written them down, and that is a file with no
110 /// classes in it rather than a panic or a plausible guess.
111 pub const EMPTY: Self = Self::new(&[]);
112
113 /// A file made of those classes, numbered in the order they are given.
114 #[must_use]
115 pub const fn new(classes: &'static [ClassInfo]) -> Self {
116 Self { classes }
117 }
118
119 /// Its classes, each with the number it is known by.
120 pub fn classes(&self) -> impl Iterator<Item = (RegClass, &'static ClassInfo)> + use<> {
121 self.classes.iter().enumerate().map(|(number, info)| (RegClass::new(number as u8), info))
122 }
123
124 /// What is in one class.
125 #[must_use]
126 pub fn class(&self, class: RegClass) -> Option<&'static ClassInfo> {
127 self.classes.get(usize::from(class.number()))
128 }
129
130 /// The class of that name, such as `gpr`.
131 #[must_use]
132 pub fn class_named(&self, name: &str) -> Option<RegClass> {
133 self.classes().find(|(_, info)| info.name == name).map(|(class, _)| class)
134 }
135
136 /// Whether the allocator may put a value in that class, which is [`ClassInfo::allocatable`].
137 ///
138 /// A class the file does not have is not one either, which is the same answer as a class
139 /// nothing allocates from and is the one that keeps a caller from having to say what it means
140 /// by a class number the target never gave out.
141 #[must_use]
142 pub fn allocatable(&self, class: RegClass) -> bool {
143 self.class(class).is_some_and(|info| info.allocatable)
144 }
145
146 /// How many registers are in a class, which is one past the largest number in it.
147 #[must_use]
148 pub fn len(&self, class: RegClass) -> usize {
149 self.class(class).map_or(0, |info| info.regs.len())
150 }
151
152 /// Whether the file has no classes at all, which is a target that has not described one.
153 #[must_use]
154 pub fn is_empty(&self) -> bool {
155 self.classes.is_empty()
156 }
157
158 /// What one register is called.
159 #[must_use]
160 pub fn name(&self, class: RegClass, reg: PhysReg) -> Option<&'static str> {
161 self.class(class)?.regs.get(usize::from(reg.number())).copied()
162 }
163
164 /// The register of that name, and the class it is in.
165 ///
166 /// The name is written without the sigil, so `rax` rather than `$rax`.
167 #[must_use]
168 pub fn reg_named(&self, name: &str) -> Option<(RegClass, PhysReg)> {
169 for (class, info) in self.classes() {
170 if let Some(number) = info.regs.iter().position(|®| reg == name) {
171 return Some((class, PhysReg::new(number as u8)));
172 }
173 }
174 None
175 }
176
177 /// A name this file gives to two registers, if it gives one to two.
178 ///
179 /// Reading a dump back needs every name to say which register it means, and a target that
180 /// breaks that produces text that cannot be parsed rather than an error at the point of the
181 /// mistake. So every target's own test asks this, which is why it is here and public.
182 #[must_use]
183 pub fn duplicate(&self) -> Option<&'static str> {
184 let mut seen: Vec<&'static str> = Vec::new();
185 for (_, info) in self.classes() {
186 for ® in info.regs {
187 if seen.contains(®) {
188 return Some(reg);
189 }
190 seen.push(reg);
191 }
192 }
193 None
194 }
195}
196
197/// The storage an address is counted from, on a machine that has more than one.
198///
199/// x86 keeps a thread's own block of words at a fixed place reached through a segment register,
200/// and that block is the only thing anything here uses one for. The stack protector's canary lives
201/// in it, which is why `%fs:40` is an address a compiler writes and `%fs` is not a register any
202/// program names. Every other address this compiler writes is in the flat segment and says nothing
203/// at all, which is what `None` is.
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205pub enum Segment {
206 /// `%fs`, which is where a thread's own block is on x86-64 under System V.
207 Fs,
208 /// `%gs`, which is where it is on x86-64 under Windows and inside a kernel.
209 Gs,
210}
211
212/// Where a target keeps the word a stack protector's canary is a copy of.
213///
214/// Not a register and not a symbol either, on the conventions here. The word is in the block a
215/// thread has to itself, which is reached through a segment register and no other way, so the only
216/// way to name it is a distance into that block. That is why `%fs:40` appears in every protected
217/// function glibc has ever linked and why no object file carries a relocation for it.
218///
219/// A convention that answers `None` is one this compiler has no protector for, and a command line
220/// that asks for one on such a target is told so rather than quietly given an unprotected frame.
221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
222pub struct Guard {
223 /// The storage the word is in.
224 pub segment: Segment,
225 /// How far into it the word is.
226 pub at: i32,
227 /// The function called when the copy in the frame no longer matches it, which does not come
228 /// back.
229 pub fail: &'static str,
230}
231
232/// What a profiler's hook at the top of every function is called on this platform.
233///
234/// A profiler wants to know which function called which and how often, and the only place a
235/// compiler can tell it that is the moment a function is entered. So `-pg` puts a call there, and
236/// what it calls is a routine the runtime provides rather than anything the program wrote.
237///
238/// Two of them, because there are two conventions for the same job and they disagree about where
239/// the call goes as well as what it is called. The older one runs once the frame is taken, so the
240/// hook can walk back through the frame pointer, which is why it needs one. The newer one runs
241/// before the prologue has done anything at all, which is what makes the return address the top
242/// thing on the stack and the arguments still in the registers they arrived in, and that is what
243/// lets a tracer replace the call with something else while the program runs. Linux's ftrace is
244/// built on exactly that, and it is why every kernel is built with the newer one.
245///
246/// A convention that answers `None` is one this compiler has no hook for, and a command line that
247/// asks for one on such a target is told so rather than quietly given an unprofiled program.
248#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249pub struct Trace {
250 /// What is called in front of the prologue, which is what `-mfentry` asks for.
251 pub early: &'static str,
252 /// What is called once the frame is taken, which is what `-mno-fentry` asks for.
253 pub late: &'static str,
254 /// Which of the two a command line that named neither gets.
255 pub fentry: bool,
256}
257
258/// Which registers a calling convention gives which job.
259///
260/// This is the second half of a target description and it is separate from [`RegFile`] because
261/// the two do not vary together. x86-64 has one register file and two conventions over it, and
262/// they disagree about nearly everything below: `rdi` is where the first argument arrives on
263/// SysV and a register a callee has to preserve on Windows, and a Windows caller reserves
264/// thirty two bytes below the call that a SysV caller does not.
265///
266/// The allocation order is here rather than on a class because it is a consequence of what a
267/// call clobbers. A value that does not live across a call belongs in a register the callee is
268/// free to destroy, because putting it in a preserved one costs a push and a pop in the
269/// prologue of whichever function ends up owning it.
270///
271/// Every register named here is a register of the file the same target describes, and each list
272/// is in the order the convention uses them, so the fourth integer argument is `int_args[3]` and
273/// nothing has to count.
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275pub struct CallRegs {
276 /// The class the general purpose registers named here are in.
277 ///
278 /// A register is a number inside its class, so a list of them says nothing about which
279 /// registers they are without this. Everything else could get the class from the operand it
280 /// came off, and a frame cannot, because a saved register is not an operand of anything.
281 pub int_class: RegClass,
282 /// The class the vector registers named here are in.
283 pub sse_class: RegClass,
284 /// The general purpose registers integer arguments arrive in, in order.
285 pub int_args: &'static [PhysReg],
286 /// The vector registers floating point arguments arrive in, in order.
287 ///
288 /// Whether an argument's position counts against both lists or only against its own is
289 /// [`CallRegs::shared_positions`].
290 pub sse_args: &'static [PhysReg],
291 /// Whether an argument's position counts against both argument lists or only against its own.
292 ///
293 /// False on SysV, which counts each separately, so a `double` after six integers is still in
294 /// `xmm0`. True on Windows, which counts one position for both, so a `double` in the third
295 /// position is in `xmm2` and `r8` is skipped.
296 pub shared_positions: bool,
297 /// The general purpose registers an integer return value comes back in.
298 pub int_returns: &'static [PhysReg],
299 /// The vector registers a floating point return value comes back in.
300 pub sse_returns: &'static [PhysReg],
301 /// The x87 registers a `long double` comes back in, which is empty on a target whose
302 /// `long double` is a `double`.
303 pub x87_returns: &'static [PhysReg],
304 /// The general purpose registers a call leaves alone, so a value in one survives it.
305 pub int_saved: &'static [PhysReg],
306 /// The vector registers a call leaves alone, which is none of them on SysV.
307 pub sse_saved: &'static [PhysReg],
308 /// The general purpose registers the allocator may hand out, in the order it prefers them.
309 ///
310 /// The stack pointer is never in this list, and neither is the frame pointer, which a
311 /// target could allocate when nothing needs a frame and which nothing here does yet.
312 pub int_order: &'static [PhysReg],
313 /// The vector registers the allocator may hand out, in the order it prefers them.
314 pub sse_order: &'static [PhysReg],
315 /// The stack pointer.
316 pub stack_pointer: PhysReg,
317 /// The frame pointer, which is the register a prologue puts the old stack pointer in.
318 pub frame_pointer: PhysReg,
319 /// Where a variadic call says how many vector registers it passed arguments in, when the
320 /// convention makes it say.
321 ///
322 /// SysV puts the count in `al` and a variadic callee reads it to decide whether to save the
323 /// vector argument registers at all, which is what makes a call to `printf` with no
324 /// floating point argument cheap.
325 pub vector_count: Option<PhysReg>,
326 /// How many bytes below the stack pointer a leaf function may use without moving it.
327 ///
328 /// A hundred and twenty eight on SysV and nothing on Windows. It is nothing in kernel code
329 /// on either, because an interrupt handler runs on the interrupted stack and writes over
330 /// exactly this, which is what `-mno-red-zone` is for.
331 pub red_zone: u32,
332 /// How many bytes a caller reserves below the call for the callee to spill its register
333 /// arguments into, which is thirty two on Windows and nothing on SysV.
334 pub shadow: u32,
335 /// What the stack pointer has to be a multiple of at the instruction that makes a call.
336 ///
337 /// Sixteen on every convention here, and it is a real obligation rather than a preference,
338 /// because a callee is entitled to use an aligned vector store on its own frame and gets a
339 /// fault rather than a wrong answer when a caller got this wrong.
340 pub stack_align: u32,
341 /// How many bytes the call instruction itself pushes before the callee starts running.
342 ///
343 /// Eight on x86-64, where the return address is on the stack, and nothing on a machine that
344 /// leaves it in a register. It is what makes the stack pointer misaligned on entry by
345 /// exactly one word, which every frame layout has to undo.
346 pub return_address: u32,
347 /// How many bytes one general purpose register takes when it is saved on the stack.
348 pub word: u32,
349 /// What DWARF calls each register, one list per class in the order the file numbers the
350 /// classes, and inside a list in the order the class numbers its registers.
351 ///
352 /// The two numberings are a real difference and not a formality. On x86-64 the machine puts
353 /// `rcx` at one and DWARF puts `rdx` there, so a table written with the machine's numbers is
354 /// well formed and describes the wrong registers, which is a backtrace with plausible
355 /// nonsense in it rather than an error. Shorter than the file when the classes at the end are
356 /// ones DWARF has no column for, and empty on a target nobody has written this down for yet.
357 pub dwarf: &'static [&'static [u16]],
358 /// The column an unwind table files the return address under.
359 ///
360 /// Not a register on x86-64, where it is sixteen and `rip` is not a register anything can
361 /// name, and a real one on a machine that returns through a link register.
362 pub dwarf_return_address: u16,
363 /// Where the word a stack protector's canary is copied from lives, on a convention that has
364 /// somewhere to put one.
365 ///
366 /// Here rather than beside the frame instructions because it is a fact about the runtime the
367 /// code is linked against rather than about the machine. The two x86-64 conventions share
368 /// every instruction the check is made of and disagree about this.
369 pub guard: Option<Guard>,
370 /// What a profiler's hook is called on this platform, on one that has one.
371 ///
372 /// Here for the same reason [`CallRegs::guard`] is: the names are the runtime's rather than the
373 /// machine's, and the two x86-64 conventions write the same call instruction and disagree about
374 /// what goes in it.
375 pub trace: Option<Trace>,
376}
377
378impl CallRegs {
379 /// The number DWARF gives that register, or `None` for one it has no column for.
380 ///
381 /// The x87 stack is the case that answers `None` on x86-64, and it is not an omission: a
382 /// register whose name means whichever one is on top of the stack is not one a table can have
383 /// a column for. Nothing saves one across a call either, so nothing ever asks.
384 #[must_use]
385 pub fn dwarf(&self, class: RegClass, reg: PhysReg) -> Option<u16> {
386 self.dwarf.get(usize::from(class.number()))?.get(usize::from(reg.number())).copied()
387 }
388
389 /// Whether a call preserves that general purpose register.
390 #[must_use]
391 pub fn preserves_int(&self, reg: PhysReg) -> bool {
392 self.int_saved.contains(®)
393 }
394
395 /// Whether a call preserves that vector register.
396 #[must_use]
397 pub fn preserves_sse(&self, reg: PhysReg) -> bool {
398 self.sse_saved.contains(®)
399 }
400}
401
402/// Where one of the values a call passes is.
403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
404pub enum Where {
405 /// In that register.
406 Reg(PhysReg),
407 /// That many bytes up the argument area, which is where the stack pointer points at the
408 /// instruction that makes the call and is one word above the return address in the callee.
409 Stack(u32),
410}
411
412/// Where the values a call passes are, worked out one after another.
413///
414/// [`crate::abi::Call`] answers a different question: whether a value travels in registers at all
415/// and in how many, which is what decides the shape of a signature and is settled before the IR
416/// for a function exists. This answers the question after it. Given values in the order the
417/// signature holds them, it says which register each one is in and how far up the argument area
418/// the ones that got no register are. Both count registers, and they agree about how many fit
419/// because they read the same lists, but they run at opposite ends of the compiler and neither
420/// can be the other.
421///
422/// Ask about each value in the order the signature holds them. Asking out of order answers about
423/// a different signature, because where a value is depends on every value before it.
424#[derive(Debug, Clone)]
425pub struct Places<'a> {
426 regs: &'a CallRegs,
427 int: usize,
428 sse: usize,
429 stack: u32,
430}
431
432impl<'a> Places<'a> {
433 /// Where the first value is, for a call under that convention.
434 #[must_use]
435 pub fn new(regs: &'a CallRegs) -> Self {
436 Self { regs, int: 0, sse: 0, stack: regs.shadow }
437 }
438
439 /// Where the next value is, when it travels in a general purpose register.
440 pub fn integer(&mut self) -> Where {
441 match self.regs.int_args.get(self.position(false)) {
442 Some(®) => {
443 self.int += 1;
444 Where::Reg(reg)
445 }
446 None => self.on_stack(self.regs.word, self.regs.word),
447 }
448 }
449
450 /// Where the next value is, when it travels in a vector register.
451 pub fn float(&mut self) -> Where {
452 match self.regs.sse_args.get(self.position(true)) {
453 Some(®) => {
454 self.sse += 1;
455 Where::Reg(reg)
456 }
457 None => self.on_stack(self.regs.word, self.regs.word),
458 }
459 }
460
461 /// Where the next value is, when it travels in memory whatever is left.
462 ///
463 /// Every argument area is a run of whole words, so a value narrower than one still takes one
464 /// and a value that is not a whole number of them is rounded up. An alignment wider than a
465 /// word is respected, which is what a sixteen byte aligned structure passed by value needs.
466 pub fn on_stack(&mut self, size: u32, align: u32) -> Where {
467 let word = self.regs.word;
468 let at = self.stack.next_multiple_of(align.max(word));
469 self.stack = at.saturating_add(size.max(word).next_multiple_of(word));
470 Where::Stack(at)
471 }
472
473 /// How many bytes of argument area the values so far need, shadow space included.
474 #[must_use]
475 pub fn size(&self) -> u32 {
476 self.stack
477 }
478
479 /// How many general purpose argument registers the values so far took.
480 ///
481 /// What a variadic callee needs and nothing else does. `va_start` has to record how far into
482 /// each of the two register sequences the arguments the signature names got, because the first
483 /// argument it does not name is the one after them, and asking here is the only way to know
484 /// that is the same count the caller worked from.
485 #[must_use]
486 pub fn integers(&self) -> usize {
487 self.int
488 }
489
490 /// How many vector argument registers the values so far took.
491 #[must_use]
492 pub fn floats(&self) -> usize {
493 self.sse
494 }
495
496 /// The position the next value of a kind is at.
497 fn position(&self, sse: bool) -> usize {
498 if self.regs.shared_positions {
499 self.int + self.sse
500 } else if sse {
501 self.sse
502 } else {
503 self.int
504 }
505 }
506}
507
508impl fmt::Display for RegFile {
509 /// The file as a dump reads it, one class to a line.
510 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
511 for (_, info) in self.classes() {
512 writeln!(f, "class {} : i{} = {}", info.name, info.bits, info.regs.join(", "))?;
513 }
514 Ok(())
515 }
516}
517
518#[cfg(test)]
519mod tests {
520 use super::*;
521
522 static GPR: [&str; 3] = ["rax", "rcx", "rdx"];
523 static XMM: [&str; 2] = ["xmm0", "xmm1"];
524 static CLASSES: [ClassInfo; 2] = [
525 ClassInfo { name: "gpr", bits: 64, regs: &GPR, allocatable: true },
526 ClassInfo { name: "xmm", bits: 128, regs: &XMM, allocatable: true },
527 ];
528 static FILE: RegFile = RegFile::new(&CLASSES);
529
530 #[test]
531 fn a_class_is_found_by_its_name() {
532 let gpr = FILE.class_named("gpr").expect("the file has a gpr class");
533 assert_eq!(FILE.len(gpr), 3);
534 assert_eq!(FILE.class(gpr).map(|info| info.bits), Some(64));
535 assert_eq!(FILE.class_named("vec"), None);
536 }
537
538 #[test]
539 fn a_register_is_found_by_its_name_and_names_itself_back() {
540 let (class, reg) = FILE.reg_named("xmm1").expect("the file has xmm1");
541 assert_eq!(FILE.class(class).map(|info| info.name), Some("xmm"));
542 assert_eq!(reg.number(), 1);
543 assert_eq!(FILE.name(class, reg), Some("xmm1"));
544 assert_eq!(FILE.reg_named("r15"), None);
545 }
546
547 #[test]
548 fn a_number_past_the_end_of_a_class_has_no_name() {
549 let gpr = FILE.class_named("gpr").expect("the file has a gpr class");
550 assert_eq!(FILE.name(gpr, PhysReg::new(3)), None);
551 assert_eq!(FILE.name(RegClass::new(7), PhysReg::new(0)), None);
552 }
553
554 #[test]
555 fn a_file_that_names_two_registers_alike_says_so() {
556 assert_eq!(FILE.duplicate(), None);
557 static BOTH: [ClassInfo; 2] = [
558 ClassInfo { name: "gpr", bits: 64, regs: &GPR, allocatable: true },
559 ClassInfo { name: "shadow", bits: 64, regs: &GPR, allocatable: true },
560 ];
561 assert_eq!(RegFile::new(&BOTH).duplicate(), Some("rax"));
562 }
563
564 #[test]
565 fn a_class_nothing_allocates_from_is_still_a_class_in_every_other_way() {
566 static WITH_STACK: [ClassInfo; 2] = [
567 ClassInfo { name: "gpr", bits: 64, regs: &GPR, allocatable: true },
568 ClassInfo { name: "x87", bits: 80, regs: &XMM, allocatable: false },
569 ];
570 let file = RegFile::new(&WITH_STACK);
571 let stack = file.class_named("x87").expect("the file has an x87 class");
572
573 assert!(!file.allocatable(stack));
574 assert!(file.allocatable(file.class_named("gpr").expect("the file has a gpr class")));
575
576 // Everything else about it works, which is the point of describing a class the allocator
577 // will not touch: the registers are counted, are named, and name themselves back.
578 assert_eq!(file.len(stack), 2);
579 assert_eq!(file.name(stack, PhysReg::new(1)), Some("xmm1"));
580 assert_eq!(file.reg_named("xmm1"), Some((stack, PhysReg::new(1))));
581 }
582
583 #[test]
584 fn a_class_the_file_does_not_have_is_not_one_to_allocate_from_either() {
585 assert!(!FILE.allocatable(RegClass::new(7)));
586 }
587
588 #[test]
589 fn the_file_prints_one_class_to_a_line() {
590 assert_eq!(
591 FILE.to_string(),
592 "class gpr : i64 = rax, rcx, rdx\nclass xmm : i128 = xmm0, xmm1\n"
593 );
594 }
595
596 /// Two integer registers, two vector registers and nothing else, so running out of them takes
597 /// three arguments rather than seven and the interesting case is the one being tested.
598 fn convention(shared: bool, shadow: u32) -> CallRegs {
599 static INT: [PhysReg; 2] = [PhysReg::new(0), PhysReg::new(1)];
600 static SSE: [PhysReg; 2] = [PhysReg::new(10), PhysReg::new(11)];
601 static NONE: [PhysReg; 0] = [];
602 CallRegs {
603 int_class: RegClass::new(0),
604 sse_class: RegClass::new(1),
605 int_args: &INT,
606 sse_args: &SSE,
607 shared_positions: shared,
608 int_returns: &INT,
609 sse_returns: &SSE,
610 x87_returns: &NONE,
611 int_saved: &NONE,
612 sse_saved: &NONE,
613 int_order: &INT,
614 sse_order: &SSE,
615 stack_pointer: PhysReg::new(4),
616 frame_pointer: PhysReg::new(5),
617 vector_count: None,
618 red_zone: 0,
619 shadow,
620 stack_align: 16,
621 return_address: 8,
622 word: 8,
623 // Empty, which is all a convention made up for a test of argument placement needs to
624 // say about a question it never asks.
625 dwarf: &[],
626 dwarf_return_address: 16,
627 guard: None,
628 trace: None,
629 }
630 }
631
632 #[test]
633 fn counting_each_kind_separately_leaves_the_first_vector_register_to_the_first_float() {
634 let regs = convention(false, 0);
635 let mut places = Places::new(®s);
636 assert_eq!(places.integer(), Where::Reg(PhysReg::new(0)));
637 assert_eq!(places.integer(), Where::Reg(PhysReg::new(1)));
638 // Two integers went past, and a convention that counts separately has not spent a vector
639 // register on either of them.
640 assert_eq!(places.float(), Where::Reg(PhysReg::new(10)));
641 assert_eq!(places.size(), 0);
642 }
643
644 #[test]
645 fn counting_one_position_for_both_skips_the_register_the_other_kind_would_have_used() {
646 let regs = convention(true, 0);
647 let mut places = Places::new(®s);
648 assert_eq!(places.integer(), Where::Reg(PhysReg::new(0)));
649 // The second position, so the second vector register, and the second integer register is
650 // spent whether anything is in it or not.
651 assert_eq!(places.float(), Where::Reg(PhysReg::new(11)));
652 assert_eq!(places.integer(), Where::Stack(0));
653 }
654
655 #[test]
656 fn running_out_of_one_kind_of_register_does_not_touch_the_other() {
657 let regs = convention(false, 0);
658 let mut places = Places::new(®s);
659 assert_eq!(places.integer(), Where::Reg(PhysReg::new(0)));
660 assert_eq!(places.integer(), Where::Reg(PhysReg::new(1)));
661 assert_eq!(places.integer(), Where::Stack(0));
662 assert_eq!(places.float(), Where::Reg(PhysReg::new(10)));
663 assert_eq!(places.size(), 8);
664 }
665
666 #[test]
667 fn the_argument_area_starts_above_the_shadow_space_and_keeps_every_value_aligned() {
668 let regs = convention(false, 32);
669 let mut places = Places::new(®s);
670 // A Windows caller reserves this whether it passes anything on the stack or not, which is
671 // why an empty area is thirty two bytes rather than none.
672 assert_eq!(places.size(), 32);
673 assert_eq!(places.on_stack(4, 4), Where::Stack(32));
674 // Sixteen byte alignment skips the word at 40, which is what a vector or an over-aligned
675 // structure passed by value asks for. The four byte value before it still took a whole
676 // word, which is why the skipped word is there to skip.
677 assert_eq!(places.on_stack(16, 16), Where::Stack(48));
678 assert_eq!(places.on_stack(8, 8), Where::Stack(64));
679 assert_eq!(places.size(), 72);
680 }
681}