Skip to main content

offlineasm_backend/
registers.rs

1use offlineasm_ir::regs::{self, fpr_id, gpr_id};
2pub use offlineasm_ir::regs::{FPRS, GPRS, VECS};
3
4/// Reports whether `name` is a portable GPR spelling.
5pub fn is_gpr(name: &str) -> bool {
6    GPRS.contains(&name)
7}
8
9/// Reports whether `name` is a portable FPR spelling.
10pub fn is_fpr(name: &str) -> bool {
11    FPRS.contains(&name)
12}
13
14/// Reports whether `name` is a portable vector spelling.
15pub fn is_vec(name: &str) -> bool {
16    VECS.contains(&name)
17}
18
19/// Reports whether `name` is any portable register spelling.
20pub fn is_register_name(name: &str) -> bool {
21    is_gpr(name) || is_fpr(name) || is_vec(name)
22}
23
24use crate::ast::Node;
25
26/// Names whether a register survives a call.
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum SaveClass {
29    /// Holds a value the caller must spill around a call.
30    CallerSaved,
31    /// Holds a value that survives a call.
32    CalleeSaved,
33    /// Names no register on this target.
34    Unmapped,
35}
36
37/// Names the calling convention for callee-saved queries.
38#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
39pub enum Abi {
40    /// Selects the System V AMD64 ABI.
41    ///
42    /// ARM64 and RISC-V always use this ABI.
43    #[default]
44    SysV,
45    /// Selects the Microsoft x64 calling convention.
46    Windows,
47}
48
49impl Abi {
50    /// Returns `sysv` or `windows`.
51    pub fn as_str(self) -> &'static str {
52        match self {
53            Abi::SysV => "sysv",
54            Abi::Windows => "windows",
55        }
56    }
57}
58
59/// Holds one row of the callee-saved table.
60///
61/// Each row lists the portable `csr*`/`csfr*` ids that survive a call for one
62/// target and ABI. A new ABI is one entry.
63struct CalleeSaved {
64    backend: &'static str,
65    abi: Abi,
66    gprs: &'static [u16],
67    fprs: &'static [u16],
68}
69
70/// Holds the callee-saved sets per target and ABI.
71///
72/// Only x86-64 distinguishes ABIs here. The RISC-V and AArch64 rows use
73/// `SysV`, the only ABI those targets run under in this crate.
74const CALLEE_SAVED: &[CalleeSaved] = &[
75    CalleeSaved {
76        backend: "X86_64",
77        abi: Abi::SysV,
78        gprs: &[
79            regs::csr0.id(),
80            regs::csr1.id(),
81            regs::csr2.id(),
82            regs::csr3.id(),
83            regs::csr4.id(),
84        ],
85        fprs: &[],
86    },
87    CalleeSaved {
88        backend: "X86_64",
89        abi: Abi::Windows,
90        gprs: &[
91            regs::csr0.id(),
92            regs::csr1.id(),
93            regs::csr2.id(),
94            regs::csr3.id(),
95            regs::csr4.id(),
96            regs::csr5.id(),
97            regs::csr6.id(),
98        ],
99        fprs: &[],
100    },
101    CalleeSaved {
102        backend: "ARM64",
103        abi: Abi::SysV,
104        gprs: &[
105            regs::csr0.id(),
106            regs::csr1.id(),
107            regs::csr2.id(),
108            regs::csr3.id(),
109            regs::csr4.id(),
110            regs::csr5.id(),
111            regs::csr6.id(),
112            regs::csr7.id(),
113            regs::csr8.id(),
114            regs::csr9.id(),
115        ],
116        fprs: &[
117            regs::csfr0.id(),
118            regs::csfr1.id(),
119            regs::csfr2.id(),
120            regs::csfr3.id(),
121            regs::csfr4.id(),
122            regs::csfr5.id(),
123            regs::csfr6.id(),
124            regs::csfr7.id(),
125        ],
126    },
127    CalleeSaved {
128        backend: "RISCV64",
129        abi: Abi::SysV,
130        gprs: &[
131            regs::csr0.id(),
132            regs::csr1.id(),
133            regs::csr2.id(),
134            regs::csr3.id(),
135            regs::csr4.id(),
136            regs::csr5.id(),
137            regs::csr6.id(),
138            regs::csr7.id(),
139            regs::csr8.id(),
140            regs::csr9.id(),
141            regs::csr10.id(),
142        ],
143        fprs: &[
144            regs::csfr0.id(),
145            regs::csfr1.id(),
146            regs::csfr2.id(),
147            regs::csfr3.id(),
148            regs::csfr4.id(),
149            regs::csfr5.id(),
150            regs::csfr6.id(),
151            regs::csfr7.id(),
152            regs::csfr8.id(),
153            regs::csfr9.id(),
154            regs::csfr10.id(),
155            regs::csfr11.id(),
156        ],
157    },
158];
159
160/// Returns the `CALLEE_SAVED` row for `backend`.
161///
162/// Matches `abi` only where a backend has more than one row.
163fn callee_saved_row(backend: &str, abi: Abi) -> Option<&'static CalleeSaved> {
164    CALLEE_SAVED
165        .iter()
166        .find(|row| row.backend == backend && (row.backend != "X86_64" || row.abi == abi))
167}
168
169/// Returns the ABI label for `backend`.
170///
171/// Returns `None` for unknown backends.
172pub fn backend_abi(backend: &str, abi: Abi) -> Option<&'static str> {
173    match backend {
174        "X86_64" => Some(abi.as_str()),
175        "ARM64" | "ARM64E" => Some("aapcs64"),
176        "RISCV64" => Some("riscv"),
177        _ => None,
178    }
179}
180
181/// Lists the physical callee-saved GPR names for an ABI label.
182pub fn abi_callee_saved_gprs(abi: &str) -> &'static [&'static str] {
183    match abi {
184        "sysv" => &["rbx", "rsp", "rbp", "r12", "r13", "r14", "r15"],
185        "windows" => &[
186            "rbx", "rsp", "rbp", "rsi", "rdi", "r12", "r13", "r14", "r15",
187        ],
188        "aapcs64" => &[
189            "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28", "x29", "sp",
190        ],
191        "riscv" => &[
192            "x2", "x8", "x9", "x18", "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27",
193        ],
194        _ => &[],
195    }
196}
197
198/// Lists the physical callee-saved FPR names for an ABI label.
199pub fn abi_callee_saved_fprs(abi: &str) -> &'static [&'static str] {
200    match abi {
201        "windows" => &[
202            "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15",
203        ],
204        "aapcs64" => &["d8", "d9", "d10", "d11", "d12", "d13", "d14", "d15"],
205        "riscv" => &[
206            "f8", "f9", "f18", "f19", "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27",
207        ],
208        _ => &[],
209    }
210}
211
212/// Returns the stack alignment in bytes for an ABI label.
213pub fn abi_stack_align(abi: &str) -> Option<u32> {
214    match abi {
215        "sysv" | "windows" | "aapcs64" | "riscv" => Some(16),
216        _ => None,
217    }
218}
219
220/// Returns the portable callee-saved GPR ids for `backend` and `abi`.
221pub fn callee_saved_gprs(backend: &str, abi: Abi) -> &'static [u16] {
222    let backend = if backend == "ARM64E" {
223        "ARM64"
224    } else {
225        backend
226    };
227    callee_saved_row(backend, abi).map_or(&[], |row| row.gprs)
228}
229
230/// Returns the portable callee-saved FPR ids for `backend` and `abi`.
231pub fn callee_saved_fprs(backend: &str, abi: Abi) -> &'static [u16] {
232    let backend = if backend == "ARM64E" {
233        "ARM64"
234    } else {
235        backend
236    };
237    callee_saved_row(backend, abi).map_or(&[], |row| row.fprs)
238}
239
240/// Lists the portable GPR ids the RLOOP interpreter maps.
241const RLOOP_GPR_IDS: &[u16] = &[
242    regs::t0.id(),
243    regs::t1.id(),
244    regs::t2.id(),
245    regs::t3.id(),
246    regs::t4.id(),
247    regs::t5.id(),
248    regs::t6.id(),
249    regs::t7.id(),
250    regs::csr0.id(),
251    regs::csr1.id(),
252    regs::csr2.id(),
253    regs::csr3.id(),
254    regs::cfr.id(),
255    regs::lr.id(),
256    regs::sp.id(),
257];
258
259/// Lists the portable FPR ids the RLOOP interpreter maps.
260const RLOOP_FPR_IDS: &[u16] = &[
261    regs::ft0.id(),
262    regs::ft1.id(),
263    regs::ft2.id(),
264    regs::ft3.id(),
265    regs::ft4.id(),
266    regs::ft5.id(),
267    regs::ft6.id(),
268    regs::ft7.id(),
269];
270
271fn gpr_mapped(backend: &str, name: &str) -> bool {
272    if let Some(t) = target_regs(backend) {
273        return t.resolve_gpr_name(name).is_some();
274    }
275    match backend {
276        "RLOOP" => gpr_id(name).is_some_and(|id| RLOOP_GPR_IDS.contains(&id)),
277        _ => false,
278    }
279}
280
281fn fpr_mapped(backend: &str, name: &str) -> bool {
282    if let Some(t) = target_regs(backend) {
283        return t.resolve_fpr_name(name).is_some();
284    }
285    match backend {
286        "RLOOP" => fpr_id(name).is_some_and(|id| RLOOP_FPR_IDS.contains(&id)),
287        _ => false,
288    }
289}
290
291/// Returns the IR register table for `backend`.
292///
293/// Returns `None` for `RLOOP` and unknown backends.
294pub fn target_regs(backend: &str) -> Option<&'static offlineasm_ir::regs::TargetRegs> {
295    match backend {
296        "X86_64" => Some(&offlineasm_ir::regs::X86),
297        "ARM64" | "ARM64E" => Some(&offlineasm_ir::regs::AARCH64),
298        "RISCV64" => Some(&offlineasm_ir::regs::RISCV64),
299        _ => None,
300    }
301}
302
303/// Returns the physical callee-saved GPR numbers for `backend` and `abi`.
304pub fn callee_saved_gpr_ids(backend: &str, abi: Abi) -> Vec<u8> {
305    let Some(t) = target_regs(backend) else {
306        return Vec::new();
307    };
308    callee_saved_gprs(backend, abi)
309        .iter()
310        .filter_map(|&id| t.resolve_gpr(id).map(|g| g.0))
311        .collect()
312}
313
314/// Returns the save class of GPR `name` on `backend` and `abi`.
315pub fn gpr_save_class(backend: &str, abi: Abi, name: &str) -> SaveClass {
316    if let Some(id) = gpr_id(name) {
317        if callee_saved_gprs(backend, abi).contains(&id) {
318            return SaveClass::CalleeSaved;
319        }
320    }
321    if gpr_mapped(backend, name) {
322        return SaveClass::CallerSaved;
323    }
324    SaveClass::Unmapped
325}
326
327/// Returns the save class of FPR `name` on `backend` and `abi`.
328pub fn fpr_save_class(backend: &str, abi: Abi, name: &str) -> SaveClass {
329    if let Some(id) = fpr_id(name) {
330        if callee_saved_fprs(backend, abi).contains(&id) {
331            return SaveClass::CalleeSaved;
332        }
333    }
334    if fpr_mapped(backend, name) {
335        return SaveClass::CallerSaved;
336    }
337    SaveClass::Unmapped
338}
339
340/// Checks that every operand is a GPR callee-saved on `backend` under `abi`.
341///
342/// # Errors
343///
344/// Returns an error if any operand is not a `Node::Register`, or names a
345/// register that is not callee-saved on `backend`.
346pub fn check_callee_saved_gprs(backend: &str, abi: Abi, operands: &[Node]) -> Result<(), String> {
347    for op in operands {
348        match op {
349            Node::Register { name, .. } => {
350                if gpr_save_class(backend, abi, name) != SaveClass::CalleeSaved {
351                    return Err(format!("{name} is not callee-saved on {backend}"));
352                }
353            }
354            _ => return Err("callee-save helpers take GPRs only".to_string()),
355        }
356    }
357    Ok(())
358}