cranelift_codegen/machinst/abi.rs
1//! Implementation of a vanilla ABI, shared between several machines. The
2//! implementation here assumes that arguments will be passed in registers
3//! first, then additional args on the stack; that the stack grows downward,
4//! contains a standard frame (return address and frame pointer), and the
5//! compiler is otherwise free to allocate space below that with its choice of
6//! layout; and that the machine has some notion of caller- and callee-save
7//! registers. Most modern machines, e.g. x86-64 and AArch64, should fit this
8//! mold and thus both of these backends use this shared implementation.
9//!
10//! See the documentation in specific machine backends for the "instantiation"
11//! of this generic ABI, i.e., which registers are caller/callee-save, arguments
12//! and return values, and any other special requirements.
13//!
14//! For now the implementation here assumes a 64-bit machine, but we intend to
15//! make this 32/64-bit-generic shortly.
16//!
17//! # Vanilla ABI
18//!
19//! First, arguments and return values are passed in registers up to a certain
20//! fixed count, after which they overflow onto the stack. Multiple return
21//! values either fit in registers, or are returned in a separate return-value
22//! area on the stack, given by a hidden extra parameter.
23//!
24//! Note that the exact stack layout is up to us. We settled on the
25//! below design based on several requirements. In particular, we need
26//! to be able to generate instructions (or instruction sequences) to
27//! access arguments, stack slots, and spill slots before we know how
28//! many spill slots or clobber-saves there will be, because of our
29//! pass structure. We also prefer positive offsets to negative
30//! offsets because of an asymmetry in some machines' addressing modes
31//! (e.g., on AArch64, positive offsets have a larger possible range
32//! without a long-form sequence to synthesize an arbitrary
33//! offset). We also need clobber-save registers to be "near" the
34//! frame pointer: Windows unwind information requires it to be within
35//! 240 bytes of RBP. Finally, it is not allowed to access memory
36//! below the current SP value.
37//!
38//! We assume that a prologue first pushes the frame pointer (and
39//! return address above that, if the machine does not do that in
40//! hardware). We set FP to point to this two-word frame record. We
41//! store all other frame slots below this two-word frame record, as
42//! well as enough space for arguments to the largest possible
43//! function call. The stack pointer then remains at this position
44//! for the duration of the function, allowing us to address all
45//! frame storage at positive offsets from SP.
46//!
47//! Note that if we ever support dynamic stack-space allocation (for
48//! `alloca`), we will need a way to reference spill slots and stack
49//! slots relative to a dynamic SP, because we will no longer be able
50//! to know a static offset from SP to the slots at any particular
51//! program point. Probably the best solution at that point will be to
52//! revert to using the frame pointer as the reference for all slots,
53//! to allow generating spill/reload and stackslot accesses before we
54//! know how large the clobber-saves will be.
55//!
56//! # Stack Layout
57//!
58//! The stack looks like:
59//!
60//! ```plain
61//! (high address)
62//! | ... |
63//! | caller frames |
64//! | ... |
65//! +===========================+
66//! | ... |
67//! | stack args |
68//! Canonical Frame Address --> | (accessed via FP) |
69//! +---------------------------+
70//! SP at function entry -----> | return address |
71//! +---------------------------+
72//! FP after prologue --------> | FP (pushed by prologue) |
73//! +---------------------------+ -----
74//! | ... | |
75//! | clobbered callee-saves | |
76//! unwind-frame base --------> | (pushed by prologue) | |
77//! +---------------------------+ ----- |
78//! | ... | | |
79//! | spill slots | | |
80//! | (accessed via SP) | fixed active
81//! | ... | frame size
82//! | stack slots | storage |
83//! | (accessed via SP) | size |
84//! | (alloc'd by prologue) | | |
85//! +---------------------------+ ----- |
86//! | [alignment as needed] | |
87//! | ... | |
88//! | args for largest call | |
89//! SP -----------------------> | (alloc'd by prologue) | |
90//! +===========================+ -----
91//!
92//! (low address)
93//! ```
94//!
95//! # Multi-value Returns
96//!
97//! We support multi-value returns by using multiple return-value
98//! registers. In some cases this is an extension of the base system
99//! ABI. See each platform's `abi.rs` implementation for details.
100
101use crate::CodegenError;
102use crate::entity::SecondaryMap;
103use crate::ir::types::*;
104use crate::ir::{ArgumentExtension, ArgumentPurpose, ExceptionTag, Signature};
105use crate::isa::TargetIsa;
106use crate::settings::ProbestackStrategy;
107use crate::{ir, isa};
108use crate::{machinst::*, trace};
109use alloc::boxed::Box;
110use regalloc2::{MachineEnv, PReg, PRegSet};
111use rustc_hash::FxHashMap;
112use smallvec::smallvec;
113use std::collections::HashMap;
114use std::marker::PhantomData;
115
116/// A small vector of instructions (with some reasonable size); appropriate for
117/// a small fixed sequence implementing one operation.
118pub type SmallInstVec<I> = SmallVec<[I; 4]>;
119
120/// A type used by backends to track argument-binding info in the "args"
121/// pseudoinst. The pseudoinst holds a vec of `ArgPair` structs.
122#[derive(Clone, Debug)]
123pub struct ArgPair {
124 /// The vreg that is defined by this args pseudoinst.
125 pub vreg: Writable<Reg>,
126 /// The preg that the arg arrives in; this constrains the vreg's
127 /// placement at the pseudoinst.
128 pub preg: Reg,
129}
130
131/// A type used by backends to track return register binding info in the "ret"
132/// pseudoinst. The pseudoinst holds a vec of `RetPair` structs.
133#[derive(Clone, Debug)]
134pub struct RetPair {
135 /// The vreg that is returned by this pseudionst.
136 pub vreg: Reg,
137 /// The preg that the arg is returned through; this constrains the vreg's
138 /// placement at the pseudoinst.
139 pub preg: Reg,
140}
141
142/// A location for (part of) an argument or return value. These "storage slots"
143/// are specified for each register-sized part of an argument.
144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145pub enum ABIArgSlot {
146 /// In a real register.
147 Reg {
148 /// Register that holds this arg.
149 reg: RealReg,
150 /// Value type of this arg.
151 ty: ir::Type,
152 /// Should this arg be zero- or sign-extended?
153 extension: ir::ArgumentExtension,
154 },
155 /// Arguments only: on stack, at given offset from SP at entry.
156 Stack {
157 /// Offset of this arg relative to the base of stack args.
158 offset: i64,
159 /// Value type of this arg.
160 ty: ir::Type,
161 /// Should this arg be zero- or sign-extended?
162 extension: ir::ArgumentExtension,
163 },
164}
165
166impl ABIArgSlot {
167 /// The type of the value that will be stored in this slot.
168 pub fn get_type(&self) -> ir::Type {
169 match self {
170 ABIArgSlot::Reg { ty, .. } => *ty,
171 ABIArgSlot::Stack { ty, .. } => *ty,
172 }
173 }
174}
175
176/// A vector of `ABIArgSlot`s. Inline capacity for one element because basically
177/// 100% of values use one slot. Only `i128`s need multiple slots, and they are
178/// super rare (and never happen with Wasm).
179pub type ABIArgSlotVec = SmallVec<[ABIArgSlot; 1]>;
180
181/// An ABIArg is composed of one or more parts. This allows for a CLIF-level
182/// Value to be passed with its parts in more than one location at the ABI
183/// level. For example, a 128-bit integer may be passed in two 64-bit registers,
184/// or even a 64-bit register and a 64-bit stack slot, on a 64-bit machine. The
185/// number of "parts" should correspond to the number of registers used to store
186/// this type according to the machine backend.
187///
188/// As an invariant, the `purpose` for every part must match. As a further
189/// invariant, a `StructArg` part cannot appear with any other part.
190#[derive(Clone, Debug)]
191pub enum ABIArg {
192 /// Storage slots (registers or stack locations) for each part of the
193 /// argument value. The number of slots must equal the number of register
194 /// parts used to store a value of this type.
195 Slots {
196 /// Slots, one per register part.
197 slots: ABIArgSlotVec,
198 /// Purpose of this arg.
199 purpose: ir::ArgumentPurpose,
200 },
201 /// Structure argument. We reserve stack space for it, but the CLIF-level
202 /// semantics are a little weird: the value passed to the call instruction,
203 /// and received in the corresponding block param, is a *pointer*. On the
204 /// caller side, we memcpy the data from the passed-in pointer to the stack
205 /// area; on the callee side, we compute a pointer to this stack area and
206 /// provide that as the argument's value.
207 StructArg {
208 /// Offset of this arg relative to base of stack args.
209 offset: i64,
210 /// Size of this arg on the stack.
211 size: u64,
212 /// Purpose of this arg.
213 purpose: ir::ArgumentPurpose,
214 },
215 /// Implicit argument. Similar to a StructArg, except that we have the
216 /// target type, not a pointer type, at the CLIF-level. This argument is
217 /// still being passed via reference implicitly.
218 ImplicitPtrArg {
219 /// Register or stack slot holding a pointer to the buffer.
220 pointer: ABIArgSlot,
221 /// Offset of the argument buffer.
222 offset: i64,
223 /// Type of the implicit argument.
224 ty: Type,
225 /// Purpose of this arg.
226 purpose: ir::ArgumentPurpose,
227 },
228}
229
230impl ABIArg {
231 /// Create an ABIArg from one register.
232 pub fn reg(
233 reg: RealReg,
234 ty: ir::Type,
235 extension: ir::ArgumentExtension,
236 purpose: ir::ArgumentPurpose,
237 ) -> ABIArg {
238 ABIArg::Slots {
239 slots: smallvec![ABIArgSlot::Reg { reg, ty, extension }],
240 purpose,
241 }
242 }
243
244 /// Create an ABIArg from one stack slot.
245 pub fn stack(
246 offset: i64,
247 ty: ir::Type,
248 extension: ir::ArgumentExtension,
249 purpose: ir::ArgumentPurpose,
250 ) -> ABIArg {
251 ABIArg::Slots {
252 slots: smallvec![ABIArgSlot::Stack {
253 offset,
254 ty,
255 extension,
256 }],
257 purpose,
258 }
259 }
260}
261
262/// Are we computing information about arguments or return values? Much of the
263/// handling is factored out into common routines; this enum allows us to
264/// distinguish which case we're handling.
265#[derive(Clone, Copy, Debug, PartialEq, Eq)]
266pub enum ArgsOrRets {
267 /// Arguments.
268 Args,
269 /// Return values.
270 Rets,
271}
272
273/// Abstract location for a machine-specific ABI impl to translate into the
274/// appropriate addressing mode.
275#[derive(Clone, Copy, Debug, PartialEq, Eq)]
276pub enum StackAMode {
277 /// Offset into the current frame's argument area.
278 IncomingArg(i64, u32),
279 /// Offset within the stack slots in the current frame.
280 Slot(i64),
281 /// Offset into the callee frame's argument area.
282 OutgoingArg(i64),
283}
284
285impl StackAMode {
286 fn offset_by(&self, offset: u32) -> Self {
287 match self {
288 StackAMode::IncomingArg(off, size) => {
289 StackAMode::IncomingArg(off.checked_add(i64::from(offset)).unwrap(), *size)
290 }
291 StackAMode::Slot(off) => StackAMode::Slot(off.checked_add(i64::from(offset)).unwrap()),
292 StackAMode::OutgoingArg(off) => {
293 StackAMode::OutgoingArg(off.checked_add(i64::from(offset)).unwrap())
294 }
295 }
296 }
297}
298
299/// Trait implemented by machine-specific backend to represent ISA flags.
300pub trait IsaFlags: Clone {
301 /// Get a flag indicating whether forward-edge CFI is enabled.
302 fn is_forward_edge_cfi_enabled(&self) -> bool {
303 false
304 }
305}
306
307/// Used as an out-parameter to accumulate a sequence of `ABIArg`s in
308/// `ABIMachineSpec::compute_arg_locs`. Wraps the shared allocation for all
309/// `ABIArg`s in `SigSet` and exposes just the args for the current
310/// `compute_arg_locs` call.
311pub struct ArgsAccumulator<'a> {
312 sig_set_abi_args: &'a mut Vec<ABIArg>,
313 start: usize,
314 non_formal_flag: bool,
315}
316
317impl<'a> ArgsAccumulator<'a> {
318 fn new(sig_set_abi_args: &'a mut Vec<ABIArg>) -> Self {
319 let start = sig_set_abi_args.len();
320 ArgsAccumulator {
321 sig_set_abi_args,
322 start,
323 non_formal_flag: false,
324 }
325 }
326
327 #[inline]
328 pub fn push(&mut self, arg: ABIArg) {
329 debug_assert!(!self.non_formal_flag);
330 self.sig_set_abi_args.push(arg)
331 }
332
333 #[inline]
334 pub fn push_non_formal(&mut self, arg: ABIArg) {
335 self.non_formal_flag = true;
336 self.sig_set_abi_args.push(arg)
337 }
338
339 #[inline]
340 pub fn args(&self) -> &[ABIArg] {
341 &self.sig_set_abi_args[self.start..]
342 }
343
344 #[inline]
345 pub fn args_mut(&mut self) -> &mut [ABIArg] {
346 &mut self.sig_set_abi_args[self.start..]
347 }
348}
349
350/// Trait implemented by machine-specific backend to provide information about
351/// register assignments and to allow generating the specific instructions for
352/// stack loads/saves, prologues/epilogues, etc.
353pub trait ABIMachineSpec {
354 /// The instruction type.
355 type I: VCodeInst;
356
357 /// The ISA flags type.
358 type F: IsaFlags;
359
360 /// This is the limit for the size of argument and return-value areas on the
361 /// stack. We place a reasonable limit here to avoid integer overflow issues
362 /// with 32-bit arithmetic.
363 const STACK_ARG_RET_SIZE_LIMIT: u32;
364
365 /// Returns the number of bits in a word, that is 32/64 for 32/64-bit architecture.
366 fn word_bits() -> u32;
367
368 /// Returns the number of bytes in a word.
369 fn word_bytes() -> u32 {
370 return Self::word_bits() / 8;
371 }
372
373 /// Returns word-size integer type.
374 fn word_type() -> Type {
375 match Self::word_bits() {
376 32 => I32,
377 64 => I64,
378 _ => unreachable!(),
379 }
380 }
381
382 /// Returns word register class.
383 fn word_reg_class() -> RegClass {
384 RegClass::Int
385 }
386
387 /// Returns required stack alignment in bytes.
388 fn stack_align(call_conv: isa::CallConv) -> u32;
389
390 /// Process a list of parameters or return values and allocate them to registers
391 /// and stack slots.
392 ///
393 /// The argument locations should be pushed onto the given `ArgsAccumulator`
394 /// in order. Any extra arguments added (such as return area pointers)
395 /// should come at the end of the list so that the first N lowered
396 /// parameters align with the N clif parameters.
397 ///
398 /// Returns the stack-space used (rounded up to as alignment requires), and
399 /// if `add_ret_area_ptr` was passed, the index of the extra synthetic arg
400 /// that was added.
401 fn compute_arg_locs(
402 call_conv: isa::CallConv,
403 flags: &settings::Flags,
404 params: &[ir::AbiParam],
405 args_or_rets: ArgsOrRets,
406 add_ret_area_ptr: bool,
407 args: ArgsAccumulator,
408 ) -> CodegenResult<(u32, Option<usize>)>;
409
410 /// Generate a load from the stack.
411 fn gen_load_stack(mem: StackAMode, into_reg: Writable<Reg>, ty: Type) -> Self::I;
412
413 /// Generate a store to the stack.
414 fn gen_store_stack(mem: StackAMode, from_reg: Reg, ty: Type) -> Self::I;
415
416 /// Generate a move.
417 fn gen_move(to_reg: Writable<Reg>, from_reg: Reg, ty: Type) -> Self::I;
418
419 /// Generate an integer-extend operation.
420 fn gen_extend(
421 to_reg: Writable<Reg>,
422 from_reg: Reg,
423 is_signed: bool,
424 from_bits: u8,
425 to_bits: u8,
426 ) -> Self::I;
427
428 /// Generate an "args" pseudo-instruction to capture input args in
429 /// registers.
430 fn gen_args(args: Vec<ArgPair>) -> Self::I;
431
432 /// Generate a "rets" pseudo-instruction that moves vregs to return
433 /// registers.
434 fn gen_rets(rets: Vec<RetPair>) -> Self::I;
435
436 /// Generate an add-with-immediate. Note that even if this uses a scratch
437 /// register, it must satisfy two requirements:
438 ///
439 /// - The add-imm sequence must only clobber caller-save registers that are
440 /// not used for arguments, because it will be placed in the prologue
441 /// before the clobbered callee-save registers are saved.
442 ///
443 /// - The add-imm sequence must work correctly when `from_reg` and/or
444 /// `into_reg` are the register returned by `get_stacklimit_reg()`.
445 fn gen_add_imm(
446 call_conv: isa::CallConv,
447 into_reg: Writable<Reg>,
448 from_reg: Reg,
449 imm: u32,
450 ) -> SmallInstVec<Self::I>;
451
452 /// Generate a sequence that traps with a `TrapCode::StackOverflow` code if
453 /// the stack pointer is less than the given limit register (assuming the
454 /// stack grows downward).
455 fn gen_stack_lower_bound_trap(limit_reg: Reg) -> SmallInstVec<Self::I>;
456
457 /// Generate an instruction to compute an address of a stack slot (FP- or
458 /// SP-based offset).
459 fn gen_get_stack_addr(mem: StackAMode, into_reg: Writable<Reg>) -> Self::I;
460
461 /// Get a fixed register to use to compute a stack limit. This is needed for
462 /// certain sequences generated after the register allocator has already
463 /// run. This must satisfy two requirements:
464 ///
465 /// - It must be a caller-save register that is not used for arguments,
466 /// because it will be clobbered in the prologue before the clobbered
467 /// callee-save registers are saved.
468 ///
469 /// - It must be safe to pass as an argument and/or destination to
470 /// `gen_add_imm()`. This is relevant when an addition with a large
471 /// immediate needs its own temporary; it cannot use the same fixed
472 /// temporary as this one.
473 fn get_stacklimit_reg(call_conv: isa::CallConv) -> Reg;
474
475 /// Generate a load to the given [base+offset] address.
476 fn gen_load_base_offset(into_reg: Writable<Reg>, base: Reg, offset: i32, ty: Type) -> Self::I;
477
478 /// Generate a store from the given [base+offset] address.
479 fn gen_store_base_offset(base: Reg, offset: i32, from_reg: Reg, ty: Type) -> Self::I;
480
481 /// Adjust the stack pointer up or down.
482 fn gen_sp_reg_adjust(amount: i32) -> SmallInstVec<Self::I>;
483
484 /// Compute a FrameLayout structure containing a sorted list of all clobbered
485 /// registers that are callee-saved according to the ABI, as well as the sizes
486 /// of all parts of the stack frame. The result is used to emit the prologue
487 /// and epilogue routines.
488 fn compute_frame_layout(
489 call_conv: isa::CallConv,
490 flags: &settings::Flags,
491 sig: &Signature,
492 regs: &[Writable<RealReg>],
493 is_leaf: bool,
494 incoming_args_size: u32,
495 tail_args_size: u32,
496 stackslots_size: u32,
497 fixed_frame_storage_size: u32,
498 outgoing_args_size: u32,
499 ) -> FrameLayout;
500
501 /// Generate the usual frame-setup sequence for this architecture: e.g.,
502 /// `push rbp / mov rbp, rsp` on x86-64, or `stp fp, lr, [sp, #-16]!` on
503 /// AArch64.
504 fn gen_prologue_frame_setup(
505 call_conv: isa::CallConv,
506 flags: &settings::Flags,
507 isa_flags: &Self::F,
508 frame_layout: &FrameLayout,
509 ) -> SmallInstVec<Self::I>;
510
511 /// Generate the usual frame-restore sequence for this architecture.
512 fn gen_epilogue_frame_restore(
513 call_conv: isa::CallConv,
514 flags: &settings::Flags,
515 isa_flags: &Self::F,
516 frame_layout: &FrameLayout,
517 ) -> SmallInstVec<Self::I>;
518
519 /// Generate a return instruction.
520 fn gen_return(
521 call_conv: isa::CallConv,
522 isa_flags: &Self::F,
523 frame_layout: &FrameLayout,
524 ) -> SmallInstVec<Self::I>;
525
526 /// Generate a probestack call.
527 fn gen_probestack(insts: &mut SmallInstVec<Self::I>, frame_size: u32);
528
529 /// Generate a inline stack probe.
530 fn gen_inline_probestack(
531 insts: &mut SmallInstVec<Self::I>,
532 call_conv: isa::CallConv,
533 frame_size: u32,
534 guard_size: u32,
535 );
536
537 /// Generate a clobber-save sequence. The implementation here should return
538 /// a sequence of instructions that "push" or otherwise save to the stack all
539 /// registers written/modified by the function body that are callee-saved.
540 /// The sequence of instructions should adjust the stack pointer downward,
541 /// and should align as necessary according to ABI requirements.
542 fn gen_clobber_save(
543 call_conv: isa::CallConv,
544 flags: &settings::Flags,
545 frame_layout: &FrameLayout,
546 ) -> SmallVec<[Self::I; 16]>;
547
548 /// Generate a clobber-restore sequence. This sequence should perform the
549 /// opposite of the clobber-save sequence generated above, assuming that SP
550 /// going into the sequence is at the same point that it was left when the
551 /// clobber-save sequence finished.
552 fn gen_clobber_restore(
553 call_conv: isa::CallConv,
554 flags: &settings::Flags,
555 frame_layout: &FrameLayout,
556 ) -> SmallVec<[Self::I; 16]>;
557
558 /// Generate a memcpy invocation. Used to set up struct
559 /// args. Takes `src`, `dst` as read-only inputs and passes a temporary
560 /// allocator.
561 fn gen_memcpy<F: FnMut(Type) -> Writable<Reg>>(
562 call_conv: isa::CallConv,
563 dst: Reg,
564 src: Reg,
565 size: usize,
566 alloc_tmp: F,
567 ) -> SmallVec<[Self::I; 8]>;
568
569 /// Get the number of spillslots required for the given register-class.
570 fn get_number_of_spillslots_for_value(
571 rc: RegClass,
572 target_vector_bytes: u32,
573 isa_flags: &Self::F,
574 ) -> u32;
575
576 /// Get the ABI-dependent MachineEnv for managing register allocation.
577 fn get_machine_env(flags: &settings::Flags, call_conv: isa::CallConv) -> &MachineEnv;
578
579 /// Get all caller-save registers, that is, registers that we expect
580 /// not to be saved across a call to a callee with the given ABI.
581 fn get_regs_clobbered_by_call(
582 call_conv_of_callee: isa::CallConv,
583 is_exception: bool,
584 ) -> PRegSet;
585
586 /// Get the needed extension mode, given the mode attached to the argument
587 /// in the signature and the calling convention. The input (the attribute in
588 /// the signature) specifies what extension type should be done *if* the ABI
589 /// requires extension to the full register; this method's return value
590 /// indicates whether the extension actually *will* be done.
591 fn get_ext_mode(
592 call_conv: isa::CallConv,
593 specified: ir::ArgumentExtension,
594 ) -> ir::ArgumentExtension;
595
596 /// Get a temporary register that is available to use after a call
597 /// completes and that does not interfere with register-carried
598 /// return values. This is used to move stack-carried return
599 /// values directly into spillslots if needed.
600 fn retval_temp_reg(call_conv_of_callee: isa::CallConv) -> Writable<Reg>;
601
602 /// Get the exception payload registers, if any, for a calling
603 /// convention.
604 fn exception_payload_regs(_call_conv: isa::CallConv) -> &'static [Reg] {
605 &[]
606 }
607}
608
609/// Out-of-line data for calls, to keep the size of `Inst` down.
610#[derive(Clone, Debug)]
611pub struct CallInfo<T> {
612 /// Receiver of this call
613 pub dest: T,
614 /// Register uses of this call.
615 pub uses: CallArgList,
616 /// Register defs of this call.
617 pub defs: CallRetList,
618 /// Registers clobbered by this call, as per its calling convention.
619 pub clobbers: PRegSet,
620 /// The calling convention of the callee.
621 pub callee_conv: isa::CallConv,
622 /// The calling convention of the caller.
623 pub caller_conv: isa::CallConv,
624 /// The number of bytes that the callee will pop from the stack for the
625 /// caller, if any. (Used for popping stack arguments with the `tail`
626 /// calling convention.)
627 pub callee_pop_size: u32,
628 /// Information for a try-call, if this is one. We combine
629 /// handling of calls and try-calls as much as possible to share
630 /// argument/return logic; they mostly differ in the metadata that
631 /// they emit, which this information feeds into.
632 pub try_call_info: Option<TryCallInfo>,
633}
634
635/// Out-of-line information present on `try_call` instructions only:
636/// information that is used to generate exception-handling tables and
637/// link up to destination blocks properly.
638#[derive(Clone, Debug)]
639pub struct TryCallInfo {
640 /// The target to jump to on a normal returhn.
641 pub continuation: MachLabel,
642 /// Exception tags to catch and corresponding destination labels.
643 pub exception_handlers: Box<[TryCallHandler]>,
644}
645
646/// Information about an individual handler at a try-call site.
647#[derive(Clone, Debug)]
648pub enum TryCallHandler {
649 /// If the tag matches (given the current context), recover at the
650 /// label.
651 Tag(ExceptionTag, MachLabel),
652 /// Recover at the label unconditionally.
653 Default(MachLabel),
654 /// Set the dynamic context for interpreting tags at this point in
655 /// the handler list.
656 Context(Reg),
657}
658
659impl<T> CallInfo<T> {
660 /// Creates an empty set of info with no clobbers/uses/etc with the
661 /// specified ABI
662 pub fn empty(dest: T, call_conv: isa::CallConv) -> CallInfo<T> {
663 CallInfo {
664 dest,
665 uses: smallvec![],
666 defs: smallvec![],
667 clobbers: PRegSet::empty(),
668 caller_conv: call_conv,
669 callee_conv: call_conv,
670 callee_pop_size: 0,
671 try_call_info: None,
672 }
673 }
674}
675
676/// The id of an ABI signature within the `SigSet`.
677#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
678pub struct Sig(u32);
679cranelift_entity::entity_impl!(Sig);
680
681impl Sig {
682 fn prev(self) -> Option<Sig> {
683 self.0.checked_sub(1).map(Sig)
684 }
685}
686
687/// ABI information shared between body (callee) and caller.
688#[derive(Clone, Debug)]
689pub struct SigData {
690 /// Currently both return values and arguments are stored in a continuous space vector
691 /// in `SigSet::abi_args`.
692 ///
693 /// ```plain
694 /// +----------------------------------------------+
695 /// | return values |
696 /// | ... |
697 /// rets_end --> +----------------------------------------------+
698 /// | arguments |
699 /// | ... |
700 /// args_end --> +----------------------------------------------+
701 ///
702 /// ```
703 ///
704 /// Note we only store two offsets as rets_end == args_start, and rets_start == prev.args_end.
705 ///
706 /// Argument location ending offset (regs or stack slots). Stack offsets are relative to
707 /// SP on entry to function.
708 ///
709 /// This is a index into the `SigSet::abi_args`.
710 args_end: u32,
711
712 /// Return-value location ending offset. Stack offsets are relative to the return-area
713 /// pointer.
714 ///
715 /// This is a index into the `SigSet::abi_args`.
716 rets_end: u32,
717
718 /// Space on stack used to store arguments. We're storing the size in u32 to
719 /// reduce the size of the struct.
720 sized_stack_arg_space: u32,
721
722 /// Space on stack used to store return values. We're storing the size in u32 to
723 /// reduce the size of the struct.
724 sized_stack_ret_space: u32,
725
726 /// Index in `args` of the stack-return-value-area argument.
727 stack_ret_arg: Option<u16>,
728
729 /// Calling convention used.
730 call_conv: isa::CallConv,
731}
732
733impl SigData {
734 /// Get total stack space required for arguments.
735 pub fn sized_stack_arg_space(&self) -> u32 {
736 self.sized_stack_arg_space
737 }
738
739 /// Get total stack space required for return values.
740 pub fn sized_stack_ret_space(&self) -> u32 {
741 self.sized_stack_ret_space
742 }
743
744 /// Get calling convention used.
745 pub fn call_conv(&self) -> isa::CallConv {
746 self.call_conv
747 }
748
749 /// The index of the stack-return-value-area argument, if any.
750 pub fn stack_ret_arg(&self) -> Option<u16> {
751 self.stack_ret_arg
752 }
753}
754
755/// A (mostly) deduplicated set of ABI signatures.
756///
757/// We say "mostly" because we do not dedupe between signatures interned via
758/// `ir::SigRef` (direct and indirect calls; the vast majority of signatures in
759/// this set) vs via `ir::Signature` (the callee itself and libcalls). Doing
760/// this final bit of deduplication would require filling out the
761/// `ir_signature_to_abi_sig`, which is a bunch of allocations (not just the
762/// hash map itself but params and returns vecs in each signature) that we want
763/// to avoid.
764///
765/// In general, prefer using the `ir::SigRef`-taking methods to the
766/// `ir::Signature`-taking methods when you can get away with it, as they don't
767/// require cloning non-copy types that will trigger heap allocations.
768///
769/// This type can be indexed by `Sig` to access its associated `SigData`.
770pub struct SigSet {
771 /// Interned `ir::Signature`s that we already have an ABI signature for.
772 ir_signature_to_abi_sig: FxHashMap<ir::Signature, Sig>,
773
774 /// Interned `ir::SigRef`s that we already have an ABI signature for.
775 ir_sig_ref_to_abi_sig: SecondaryMap<ir::SigRef, Option<Sig>>,
776
777 /// A single, shared allocation for all `ABIArg`s used by all
778 /// `SigData`s. Each `SigData` references its args/rets via indices into
779 /// this allocation.
780 abi_args: Vec<ABIArg>,
781
782 /// The actual ABI signatures, keyed by `Sig`.
783 sigs: PrimaryMap<Sig, SigData>,
784}
785
786impl SigSet {
787 /// Construct a new `SigSet`, interning all of the signatures used by the
788 /// given function.
789 pub fn new<M>(func: &ir::Function, flags: &settings::Flags) -> CodegenResult<Self>
790 where
791 M: ABIMachineSpec,
792 {
793 let arg_estimate = func.dfg.signatures.len() * 6;
794
795 let mut sigs = SigSet {
796 ir_signature_to_abi_sig: FxHashMap::default(),
797 ir_sig_ref_to_abi_sig: SecondaryMap::with_capacity(func.dfg.signatures.len()),
798 abi_args: Vec::with_capacity(arg_estimate),
799 sigs: PrimaryMap::with_capacity(1 + func.dfg.signatures.len()),
800 };
801
802 sigs.make_abi_sig_from_ir_signature::<M>(func.signature.clone(), flags)?;
803 for sig_ref in func.dfg.signatures.keys() {
804 sigs.make_abi_sig_from_ir_sig_ref::<M>(sig_ref, &func.dfg, flags)?;
805 }
806
807 Ok(sigs)
808 }
809
810 /// Have we already interned an ABI signature for the given `ir::Signature`?
811 pub fn have_abi_sig_for_signature(&self, signature: &ir::Signature) -> bool {
812 self.ir_signature_to_abi_sig.contains_key(signature)
813 }
814
815 /// Construct and intern an ABI signature for the given `ir::Signature`.
816 pub fn make_abi_sig_from_ir_signature<M>(
817 &mut self,
818 signature: ir::Signature,
819 flags: &settings::Flags,
820 ) -> CodegenResult<Sig>
821 where
822 M: ABIMachineSpec,
823 {
824 // Because the `HashMap` entry API requires taking ownership of the
825 // lookup key -- and we want to avoid unnecessary clones of
826 // `ir::Signature`s, even at the cost of duplicate lookups -- we can't
827 // have a single, get-or-create-style method for interning
828 // `ir::Signature`s into ABI signatures. So at least (debug) assert that
829 // we aren't creating duplicate ABI signatures for the same
830 // `ir::Signature`.
831 debug_assert!(!self.have_abi_sig_for_signature(&signature));
832
833 let sig_data = self.from_func_sig::<M>(&signature, flags)?;
834 let sig = self.sigs.push(sig_data);
835 self.ir_signature_to_abi_sig.insert(signature, sig);
836 Ok(sig)
837 }
838
839 fn make_abi_sig_from_ir_sig_ref<M>(
840 &mut self,
841 sig_ref: ir::SigRef,
842 dfg: &ir::DataFlowGraph,
843 flags: &settings::Flags,
844 ) -> CodegenResult<Sig>
845 where
846 M: ABIMachineSpec,
847 {
848 if let Some(sig) = self.ir_sig_ref_to_abi_sig[sig_ref] {
849 return Ok(sig);
850 }
851 let signature = &dfg.signatures[sig_ref];
852 let sig_data = self.from_func_sig::<M>(signature, flags)?;
853 let sig = self.sigs.push(sig_data);
854 self.ir_sig_ref_to_abi_sig[sig_ref] = Some(sig);
855 Ok(sig)
856 }
857
858 /// Get the already-interned ABI signature id for the given `ir::SigRef`.
859 pub fn abi_sig_for_sig_ref(&self, sig_ref: ir::SigRef) -> Sig {
860 self.ir_sig_ref_to_abi_sig[sig_ref]
861 .expect("must call `make_abi_sig_from_ir_sig_ref` before `get_abi_sig_for_sig_ref`")
862 }
863
864 /// Get the already-interned ABI signature id for the given `ir::Signature`.
865 pub fn abi_sig_for_signature(&self, signature: &ir::Signature) -> Sig {
866 self.ir_signature_to_abi_sig
867 .get(signature)
868 .copied()
869 .expect("must call `make_abi_sig_from_ir_signature` before `get_abi_sig_for_signature`")
870 }
871
872 pub fn from_func_sig<M: ABIMachineSpec>(
873 &mut self,
874 sig: &ir::Signature,
875 flags: &settings::Flags,
876 ) -> CodegenResult<SigData> {
877 // Keep in sync with ensure_struct_return_ptr_is_returned
878 if sig.uses_special_return(ArgumentPurpose::StructReturn) {
879 panic!("Explicit StructReturn return value not allowed: {sig:?}")
880 }
881 let tmp;
882 let returns = if let Some(struct_ret_index) =
883 sig.special_param_index(ArgumentPurpose::StructReturn)
884 {
885 if !sig.returns.is_empty() {
886 panic!("No return values are allowed when using StructReturn: {sig:?}");
887 }
888 tmp = [sig.params[struct_ret_index]];
889 &tmp
890 } else {
891 sig.returns.as_slice()
892 };
893
894 // Compute args and retvals from signature. Handle retvals first,
895 // because we may need to add a return-area arg to the args.
896
897 // NOTE: We rely on the order of the args (rets -> args) inserted to compute the offsets in
898 // `SigSet::args()` and `SigSet::rets()`. Therefore, we cannot change the two
899 // compute_arg_locs order.
900 let (sized_stack_ret_space, _) = M::compute_arg_locs(
901 sig.call_conv,
902 flags,
903 &returns,
904 ArgsOrRets::Rets,
905 /* extra ret-area ptr = */ false,
906 ArgsAccumulator::new(&mut self.abi_args),
907 )?;
908 if !flags.enable_multi_ret_implicit_sret() {
909 assert_eq!(sized_stack_ret_space, 0);
910 }
911 let rets_end = u32::try_from(self.abi_args.len()).unwrap();
912
913 // To avoid overflow issues, limit the return size to something reasonable.
914 if sized_stack_ret_space > M::STACK_ARG_RET_SIZE_LIMIT {
915 return Err(CodegenError::ImplLimitExceeded);
916 }
917
918 let need_stack_return_area = sized_stack_ret_space > 0;
919 if need_stack_return_area {
920 assert!(!sig.uses_special_param(ir::ArgumentPurpose::StructReturn));
921 }
922
923 let (sized_stack_arg_space, stack_ret_arg) = M::compute_arg_locs(
924 sig.call_conv,
925 flags,
926 &sig.params,
927 ArgsOrRets::Args,
928 need_stack_return_area,
929 ArgsAccumulator::new(&mut self.abi_args),
930 )?;
931 let args_end = u32::try_from(self.abi_args.len()).unwrap();
932
933 // To avoid overflow issues, limit the arg size to something reasonable.
934 if sized_stack_arg_space > M::STACK_ARG_RET_SIZE_LIMIT {
935 return Err(CodegenError::ImplLimitExceeded);
936 }
937
938 trace!(
939 "ABISig: sig {:?} => args end = {} rets end = {}
940 arg stack = {} ret stack = {} stack_ret_arg = {:?}",
941 sig,
942 args_end,
943 rets_end,
944 sized_stack_arg_space,
945 sized_stack_ret_space,
946 need_stack_return_area,
947 );
948
949 let stack_ret_arg = stack_ret_arg.map(|s| u16::try_from(s).unwrap());
950 Ok(SigData {
951 args_end,
952 rets_end,
953 sized_stack_arg_space,
954 sized_stack_ret_space,
955 stack_ret_arg,
956 call_conv: sig.call_conv,
957 })
958 }
959
960 /// Get this signature's ABI arguments.
961 pub fn args(&self, sig: Sig) -> &[ABIArg] {
962 let sig_data = &self.sigs[sig];
963 // Please see comments in `SigSet::from_func_sig` of how we store the offsets.
964 let start = usize::try_from(sig_data.rets_end).unwrap();
965 let end = usize::try_from(sig_data.args_end).unwrap();
966 &self.abi_args[start..end]
967 }
968
969 /// Get information specifying how to pass the implicit pointer
970 /// to the return-value area on the stack, if required.
971 pub fn get_ret_arg(&self, sig: Sig) -> Option<ABIArg> {
972 let sig_data = &self.sigs[sig];
973 if let Some(i) = sig_data.stack_ret_arg {
974 Some(self.args(sig)[usize::from(i)].clone())
975 } else {
976 None
977 }
978 }
979
980 /// Get information specifying how to pass one argument.
981 pub fn get_arg(&self, sig: Sig, idx: usize) -> ABIArg {
982 self.args(sig)[idx].clone()
983 }
984
985 /// Get this signature's ABI returns.
986 pub fn rets(&self, sig: Sig) -> &[ABIArg] {
987 let sig_data = &self.sigs[sig];
988 // Please see comments in `SigSet::from_func_sig` of how we store the offsets.
989 let start = usize::try_from(sig.prev().map_or(0, |prev| self.sigs[prev].args_end)).unwrap();
990 let end = usize::try_from(sig_data.rets_end).unwrap();
991 &self.abi_args[start..end]
992 }
993
994 /// Get information specifying how to pass one return value.
995 pub fn get_ret(&self, sig: Sig, idx: usize) -> ABIArg {
996 self.rets(sig)[idx].clone()
997 }
998
999 /// Get the number of arguments expected.
1000 pub fn num_args(&self, sig: Sig) -> usize {
1001 let len = self.args(sig).len();
1002 if self.sigs[sig].stack_ret_arg.is_some() {
1003 len - 1
1004 } else {
1005 len
1006 }
1007 }
1008
1009 /// Get the number of return values expected.
1010 pub fn num_rets(&self, sig: Sig) -> usize {
1011 self.rets(sig).len()
1012 }
1013}
1014
1015// NB: we do _not_ implement `IndexMut` because these signatures are
1016// deduplicated and shared!
1017impl std::ops::Index<Sig> for SigSet {
1018 type Output = SigData;
1019
1020 fn index(&self, sig: Sig) -> &Self::Output {
1021 &self.sigs[sig]
1022 }
1023}
1024
1025/// Structure describing the layout of a function's stack frame.
1026#[derive(Clone, Debug, Default)]
1027pub struct FrameLayout {
1028 /// Word size in bytes, so this struct can be
1029 /// monomorphic/independent of `ABIMachineSpec`.
1030 pub word_bytes: u32,
1031
1032 /// N.B. The areas whose sizes are given in this structure fully
1033 /// cover the current function's stack frame, from high to low
1034 /// stack addresses in the sequence below. Each size contains
1035 /// any alignment padding that may be required by the ABI.
1036
1037 /// Size of incoming arguments on the stack. This is not technically
1038 /// part of this function's frame, but code in the function will still
1039 /// need to access it. Depending on the ABI, we may need to set up a
1040 /// frame pointer to do so; we also may need to pop this area from the
1041 /// stack upon return.
1042 pub incoming_args_size: u32,
1043
1044 /// The size of the incoming argument area, taking into account any
1045 /// potential increase in size required for tail calls present in the
1046 /// function. In the case that no tail calls are present, this value
1047 /// will be the same as [`Self::incoming_args_size`].
1048 pub tail_args_size: u32,
1049
1050 /// Size of the "setup area", typically holding the return address
1051 /// and/or the saved frame pointer. This may be written either during
1052 /// the call itself (e.g. a pushed return address) or by code emitted
1053 /// from gen_prologue_frame_setup. In any case, after that code has
1054 /// completed execution, the stack pointer is expected to point to the
1055 /// bottom of this area. The same holds at the start of code emitted
1056 /// by gen_epilogue_frame_restore.
1057 pub setup_area_size: u32,
1058
1059 /// Size of the area used to save callee-saved clobbered registers.
1060 /// This area is accessed by code emitted from gen_clobber_save and
1061 /// gen_clobber_restore.
1062 pub clobber_size: u32,
1063
1064 /// Storage allocated for the fixed part of the stack frame.
1065 /// This contains stack slots and spill slots.
1066 pub fixed_frame_storage_size: u32,
1067
1068 /// The size of all stackslots.
1069 pub stackslots_size: u32,
1070
1071 /// Stack size to be reserved for outgoing arguments, if used by
1072 /// the current ABI, or 0 otherwise. After gen_clobber_save and
1073 /// before gen_clobber_restore, the stack pointer points to the
1074 /// bottom of this area.
1075 pub outgoing_args_size: u32,
1076
1077 /// Sorted list of callee-saved registers that are clobbered
1078 /// according to the ABI. These registers will be saved and
1079 /// restored by gen_clobber_save and gen_clobber_restore.
1080 pub clobbered_callee_saves: Vec<Writable<RealReg>>,
1081}
1082
1083impl FrameLayout {
1084 /// Split the clobbered callee-save registers into integer-class and
1085 /// float-class groups.
1086 ///
1087 /// This method does not currently support vector-class callee-save
1088 /// registers because no current backend has them.
1089 pub fn clobbered_callee_saves_by_class(&self) -> (&[Writable<RealReg>], &[Writable<RealReg>]) {
1090 let (ints, floats) = self.clobbered_callee_saves.split_at(
1091 self.clobbered_callee_saves
1092 .partition_point(|r| r.to_reg().class() == RegClass::Int),
1093 );
1094 debug_assert!(floats.iter().all(|r| r.to_reg().class() == RegClass::Float));
1095 (ints, floats)
1096 }
1097
1098 /// The size of FP to SP while the frame is active (not during prologue
1099 /// setup or epilogue tear down).
1100 pub fn active_size(&self) -> u32 {
1101 self.outgoing_args_size + self.fixed_frame_storage_size + self.clobber_size
1102 }
1103
1104 /// Get the offset from the SP to the sized stack slots area.
1105 pub fn sp_to_sized_stack_slots(&self) -> u32 {
1106 self.outgoing_args_size
1107 }
1108
1109 /// Get the offset of a spill slot from SP.
1110 pub fn spillslot_offset(&self, spillslot: SpillSlot) -> i64 {
1111 // Offset from beginning of spillslot area.
1112 let islot = spillslot.index() as i64;
1113 let spill_off = islot * self.word_bytes as i64;
1114 let sp_off = self.stackslots_size as i64 + spill_off;
1115
1116 sp_off
1117 }
1118}
1119
1120/// ABI object for a function body.
1121pub struct Callee<M: ABIMachineSpec> {
1122 /// CLIF-level signature, possibly normalized.
1123 ir_sig: ir::Signature,
1124 /// Signature: arg and retval regs.
1125 sig: Sig,
1126 /// Defined dynamic types.
1127 dynamic_type_sizes: HashMap<Type, u32>,
1128 /// Offsets to each dynamic stackslot.
1129 dynamic_stackslots: PrimaryMap<DynamicStackSlot, u32>,
1130 /// Offsets to each sized stackslot.
1131 sized_stackslots: PrimaryMap<StackSlot, u32>,
1132 /// Total stack size of all stackslots
1133 stackslots_size: u32,
1134 /// Stack size to be reserved for outgoing arguments.
1135 outgoing_args_size: u32,
1136 /// Initially the number of bytes originating in the callers frame where stack arguments will
1137 /// live. After lowering this number may be larger than the size expected by the function being
1138 /// compiled, as tail calls potentially require more space for stack arguments.
1139 tail_args_size: u32,
1140 /// Register-argument defs, to be provided to the `args`
1141 /// pseudo-inst, and pregs to constrain them to.
1142 reg_args: Vec<ArgPair>,
1143 /// Finalized frame layout for this function.
1144 frame_layout: Option<FrameLayout>,
1145 /// The register holding the return-area pointer, if needed.
1146 ret_area_ptr: Option<Reg>,
1147 /// Calling convention this function expects.
1148 call_conv: isa::CallConv,
1149 /// The settings controlling this function's compilation.
1150 flags: settings::Flags,
1151 /// The ISA-specific flag values controlling this function's compilation.
1152 isa_flags: M::F,
1153 /// Whether or not this function is a "leaf", meaning it calls no other
1154 /// functions
1155 is_leaf: bool,
1156 /// If this function has a stack limit specified, then `Reg` is where the
1157 /// stack limit will be located after the instructions specified have been
1158 /// executed.
1159 ///
1160 /// Note that this is intended for insertion into the prologue, if
1161 /// present. Also note that because the instructions here execute in the
1162 /// prologue this happens after legalization/register allocation/etc so we
1163 /// need to be extremely careful with each instruction. The instructions are
1164 /// manually register-allocated and carefully only use caller-saved
1165 /// registers and keep nothing live after this sequence of instructions.
1166 stack_limit: Option<(Reg, SmallInstVec<M::I>)>,
1167
1168 _mach: PhantomData<M>,
1169}
1170
1171fn get_special_purpose_param_register(
1172 f: &ir::Function,
1173 sigs: &SigSet,
1174 sig: Sig,
1175 purpose: ir::ArgumentPurpose,
1176) -> Option<Reg> {
1177 let idx = f.signature.special_param_index(purpose)?;
1178 match &sigs.args(sig)[idx] {
1179 &ABIArg::Slots { ref slots, .. } => match &slots[0] {
1180 &ABIArgSlot::Reg { reg, .. } => Some(reg.into()),
1181 _ => None,
1182 },
1183 _ => None,
1184 }
1185}
1186
1187fn checked_round_up(val: u32, mask: u32) -> Option<u32> {
1188 Some(val.checked_add(mask)? & !mask)
1189}
1190
1191impl<M: ABIMachineSpec> Callee<M> {
1192 /// Create a new body ABI instance.
1193 pub fn new(
1194 f: &ir::Function,
1195 isa: &dyn TargetIsa,
1196 isa_flags: &M::F,
1197 sigs: &SigSet,
1198 ) -> CodegenResult<Self> {
1199 trace!("ABI: func signature {:?}", f.signature);
1200
1201 let flags = isa.flags().clone();
1202 let sig = sigs.abi_sig_for_signature(&f.signature);
1203
1204 let call_conv = f.signature.call_conv;
1205 // Only these calling conventions are supported.
1206 debug_assert!(
1207 call_conv == isa::CallConv::SystemV
1208 || call_conv == isa::CallConv::Tail
1209 || call_conv == isa::CallConv::Fast
1210 || call_conv == isa::CallConv::Cold
1211 || call_conv == isa::CallConv::WindowsFastcall
1212 || call_conv == isa::CallConv::AppleAarch64
1213 || call_conv == isa::CallConv::Winch,
1214 "Unsupported calling convention: {call_conv:?}"
1215 );
1216
1217 // Compute sized stackslot locations and total stackslot size.
1218 let mut end_offset: u32 = 0;
1219 let mut sized_stackslots = PrimaryMap::new();
1220
1221 for (stackslot, data) in f.sized_stack_slots.iter() {
1222 // We start our computation possibly unaligned where the previous
1223 // stackslot left off.
1224 let unaligned_start_offset = end_offset;
1225
1226 // The start of the stackslot must be aligned.
1227 //
1228 // We always at least machine-word-align slots, but also
1229 // satisfy the user's requested alignment.
1230 debug_assert!(data.align_shift < 32);
1231 let align = std::cmp::max(M::word_bytes(), 1u32 << data.align_shift);
1232 let mask = align - 1;
1233 let start_offset = checked_round_up(unaligned_start_offset, mask)
1234 .ok_or(CodegenError::ImplLimitExceeded)?;
1235
1236 // The end offset is the start offset increased by the size
1237 end_offset = start_offset
1238 .checked_add(data.size)
1239 .ok_or(CodegenError::ImplLimitExceeded)?;
1240
1241 debug_assert_eq!(stackslot.as_u32() as usize, sized_stackslots.len());
1242 sized_stackslots.push(start_offset);
1243 }
1244
1245 // Compute dynamic stackslot locations and total stackslot size.
1246 let mut dynamic_stackslots = PrimaryMap::new();
1247 for (stackslot, data) in f.dynamic_stack_slots.iter() {
1248 debug_assert_eq!(stackslot.as_u32() as usize, dynamic_stackslots.len());
1249
1250 // This computation is similar to the stackslots above
1251 let unaligned_start_offset = end_offset;
1252
1253 let mask = M::word_bytes() - 1;
1254 let start_offset = checked_round_up(unaligned_start_offset, mask)
1255 .ok_or(CodegenError::ImplLimitExceeded)?;
1256
1257 let ty = f.get_concrete_dynamic_ty(data.dyn_ty).ok_or_else(|| {
1258 CodegenError::Unsupported(format!("invalid dynamic vector type: {}", data.dyn_ty))
1259 })?;
1260
1261 end_offset = start_offset
1262 .checked_add(isa.dynamic_vector_bytes(ty))
1263 .ok_or(CodegenError::ImplLimitExceeded)?;
1264
1265 dynamic_stackslots.push(start_offset);
1266 }
1267
1268 // The size of the stackslots needs to be word aligned
1269 let stackslots_size = checked_round_up(end_offset, M::word_bytes() - 1)
1270 .ok_or(CodegenError::ImplLimitExceeded)?;
1271
1272 let mut dynamic_type_sizes = HashMap::with_capacity(f.dfg.dynamic_types.len());
1273 for (dyn_ty, _data) in f.dfg.dynamic_types.iter() {
1274 let ty = f
1275 .get_concrete_dynamic_ty(dyn_ty)
1276 .unwrap_or_else(|| panic!("invalid dynamic vector type: {dyn_ty}"));
1277 let size = isa.dynamic_vector_bytes(ty);
1278 dynamic_type_sizes.insert(ty, size);
1279 }
1280
1281 // Figure out what instructions, if any, will be needed to check the
1282 // stack limit. This can either be specified as a special-purpose
1283 // argument or as a global value which often calculates the stack limit
1284 // from the arguments.
1285 let stack_limit = f
1286 .stack_limit
1287 .map(|gv| gen_stack_limit::<M>(f, sigs, sig, gv));
1288
1289 let tail_args_size = sigs[sig].sized_stack_arg_space;
1290
1291 Ok(Self {
1292 ir_sig: ensure_struct_return_ptr_is_returned(&f.signature),
1293 sig,
1294 dynamic_stackslots,
1295 dynamic_type_sizes,
1296 sized_stackslots,
1297 stackslots_size,
1298 outgoing_args_size: 0,
1299 tail_args_size,
1300 reg_args: vec![],
1301 frame_layout: None,
1302 ret_area_ptr: None,
1303 call_conv,
1304 flags,
1305 isa_flags: isa_flags.clone(),
1306 is_leaf: f.is_leaf(),
1307 stack_limit,
1308 _mach: PhantomData,
1309 })
1310 }
1311
1312 /// Inserts instructions necessary for checking the stack limit into the
1313 /// prologue.
1314 ///
1315 /// This function will generate instructions necessary for perform a stack
1316 /// check at the header of a function. The stack check is intended to trap
1317 /// if the stack pointer goes below a particular threshold, preventing stack
1318 /// overflow in wasm or other code. The `stack_limit` argument here is the
1319 /// register which holds the threshold below which we're supposed to trap.
1320 /// This function is known to allocate `stack_size` bytes and we'll push
1321 /// instructions onto `insts`.
1322 ///
1323 /// Note that the instructions generated here are special because this is
1324 /// happening so late in the pipeline (e.g. after register allocation). This
1325 /// means that we need to do manual register allocation here and also be
1326 /// careful to not clobber any callee-saved or argument registers. For now
1327 /// this routine makes do with the `spilltmp_reg` as one temporary
1328 /// register, and a second register of `tmp2` which is caller-saved. This
1329 /// should be fine for us since no spills should happen in this sequence of
1330 /// instructions, so our register won't get accidentally clobbered.
1331 ///
1332 /// No values can be live after the prologue, but in this case that's ok
1333 /// because we just need to perform a stack check before progressing with
1334 /// the rest of the function.
1335 fn insert_stack_check(
1336 &self,
1337 stack_limit: Reg,
1338 stack_size: u32,
1339 insts: &mut SmallInstVec<M::I>,
1340 ) {
1341 // With no explicit stack allocated we can just emit the simple check of
1342 // the stack registers against the stack limit register, and trap if
1343 // it's out of bounds.
1344 if stack_size == 0 {
1345 insts.extend(M::gen_stack_lower_bound_trap(stack_limit));
1346 return;
1347 }
1348
1349 // Note that the 32k stack size here is pretty special. See the
1350 // documentation in x86/abi.rs for why this is here. The general idea is
1351 // that we're protecting against overflow in the addition that happens
1352 // below.
1353 if stack_size >= 32 * 1024 {
1354 insts.extend(M::gen_stack_lower_bound_trap(stack_limit));
1355 }
1356
1357 // Add the `stack_size` to `stack_limit`, placing the result in
1358 // `scratch`.
1359 //
1360 // Note though that `stack_limit`'s register may be the same as
1361 // `scratch`. If our stack size doesn't fit into an immediate this
1362 // means we need a second scratch register for loading the stack size
1363 // into a register.
1364 let scratch = Writable::from_reg(M::get_stacklimit_reg(self.call_conv));
1365 insts.extend(M::gen_add_imm(
1366 self.call_conv,
1367 scratch,
1368 stack_limit,
1369 stack_size,
1370 ));
1371 insts.extend(M::gen_stack_lower_bound_trap(scratch.to_reg()));
1372 }
1373}
1374
1375/// Generates the instructions necessary for the `gv` to be materialized into a
1376/// register.
1377///
1378/// This function will return a register that will contain the result of
1379/// evaluating `gv`. It will also return any instructions necessary to calculate
1380/// the value of the register.
1381///
1382/// Note that global values are typically lowered to instructions via the
1383/// standard legalization pass. Unfortunately though prologue generation happens
1384/// so late in the pipeline that we can't use these legalization passes to
1385/// generate the instructions for `gv`. As a result we duplicate some lowering
1386/// of `gv` here and support only some global values. This is similar to what
1387/// the x86 backend does for now, and hopefully this can be somewhat cleaned up
1388/// in the future too!
1389///
1390/// Also note that this function will make use of `writable_spilltmp_reg()` as a
1391/// temporary register to store values in if necessary. Currently after we write
1392/// to this register there's guaranteed to be no spilled values between where
1393/// it's used, because we're not participating in register allocation anyway!
1394fn gen_stack_limit<M: ABIMachineSpec>(
1395 f: &ir::Function,
1396 sigs: &SigSet,
1397 sig: Sig,
1398 gv: ir::GlobalValue,
1399) -> (Reg, SmallInstVec<M::I>) {
1400 let mut insts = smallvec![];
1401 let reg = generate_gv::<M>(f, sigs, sig, gv, &mut insts);
1402 return (reg, insts);
1403}
1404
1405fn generate_gv<M: ABIMachineSpec>(
1406 f: &ir::Function,
1407 sigs: &SigSet,
1408 sig: Sig,
1409 gv: ir::GlobalValue,
1410 insts: &mut SmallInstVec<M::I>,
1411) -> Reg {
1412 match f.global_values[gv] {
1413 // Return the direct register the vmcontext is in
1414 ir::GlobalValueData::VMContext => {
1415 get_special_purpose_param_register(f, sigs, sig, ir::ArgumentPurpose::VMContext)
1416 .expect("no vmcontext parameter found")
1417 }
1418 // Load our base value into a register, then load from that register
1419 // in to a temporary register.
1420 ir::GlobalValueData::Load {
1421 base,
1422 offset,
1423 global_type: _,
1424 flags: _,
1425 } => {
1426 let base = generate_gv::<M>(f, sigs, sig, base, insts);
1427 let into_reg = Writable::from_reg(M::get_stacklimit_reg(f.stencil.signature.call_conv));
1428 insts.push(M::gen_load_base_offset(
1429 into_reg,
1430 base,
1431 offset.into(),
1432 M::word_type(),
1433 ));
1434 return into_reg.to_reg();
1435 }
1436 ref other => panic!("global value for stack limit not supported: {other}"),
1437 }
1438}
1439
1440/// Returns true if the signature needs to be legalized.
1441fn missing_struct_return(sig: &ir::Signature) -> bool {
1442 sig.uses_special_param(ArgumentPurpose::StructReturn)
1443 && !sig.uses_special_return(ArgumentPurpose::StructReturn)
1444}
1445
1446fn ensure_struct_return_ptr_is_returned(sig: &ir::Signature) -> ir::Signature {
1447 // Keep in sync with Callee::new
1448 let mut sig = sig.clone();
1449 if sig.uses_special_return(ArgumentPurpose::StructReturn) {
1450 panic!("Explicit StructReturn return value not allowed: {sig:?}")
1451 }
1452 if let Some(struct_ret_index) = sig.special_param_index(ArgumentPurpose::StructReturn) {
1453 if !sig.returns.is_empty() {
1454 panic!("No return values are allowed when using StructReturn: {sig:?}");
1455 }
1456 sig.returns.insert(0, sig.params[struct_ret_index]);
1457 }
1458 sig
1459}
1460
1461/// ### Pre-Regalloc Functions
1462///
1463/// These methods of `Callee` may only be called before regalloc.
1464impl<M: ABIMachineSpec> Callee<M> {
1465 /// Access the (possibly legalized) signature.
1466 pub fn signature(&self) -> &ir::Signature {
1467 debug_assert!(
1468 !missing_struct_return(&self.ir_sig),
1469 "`Callee::ir_sig` is always legalized"
1470 );
1471 &self.ir_sig
1472 }
1473
1474 /// Initialize. This is called after the Callee is constructed because it
1475 /// may allocate a temp vreg, which can only be allocated once the lowering
1476 /// context exists.
1477 pub fn init_retval_area(
1478 &mut self,
1479 sigs: &SigSet,
1480 vregs: &mut VRegAllocator<M::I>,
1481 ) -> CodegenResult<()> {
1482 if sigs[self.sig].stack_ret_arg.is_some() {
1483 let ret_area_ptr = vregs.alloc(M::word_type())?;
1484 self.ret_area_ptr = Some(ret_area_ptr.only_reg().unwrap());
1485 }
1486 Ok(())
1487 }
1488
1489 /// Get the return area pointer register, if any.
1490 pub fn ret_area_ptr(&self) -> Option<Reg> {
1491 self.ret_area_ptr
1492 }
1493
1494 /// Accumulate outgoing arguments.
1495 ///
1496 /// This ensures that at least `size` bytes are allocated in the prologue to
1497 /// be available for use in function calls to hold arguments and/or return
1498 /// values. If this function is called multiple times, the maximum of all
1499 /// `size` values will be available.
1500 pub fn accumulate_outgoing_args_size(&mut self, size: u32) {
1501 if size > self.outgoing_args_size {
1502 self.outgoing_args_size = size;
1503 }
1504 }
1505
1506 /// Accumulate the incoming argument area size requirements for a tail call,
1507 /// as it could be larger than the incoming arguments of the function
1508 /// currently being compiled.
1509 pub fn accumulate_tail_args_size(&mut self, size: u32) {
1510 if size > self.tail_args_size {
1511 self.tail_args_size = size;
1512 }
1513 }
1514
1515 pub fn is_forward_edge_cfi_enabled(&self) -> bool {
1516 self.isa_flags.is_forward_edge_cfi_enabled()
1517 }
1518
1519 /// Get the calling convention implemented by this ABI object.
1520 pub fn call_conv(&self) -> isa::CallConv {
1521 self.call_conv
1522 }
1523
1524 /// Get the ABI-dependent MachineEnv for managing register allocation.
1525 pub fn machine_env(&self) -> &MachineEnv {
1526 M::get_machine_env(&self.flags, self.call_conv)
1527 }
1528
1529 /// The offsets of all sized stack slots (not spill slots) for debuginfo purposes.
1530 pub fn sized_stackslot_offsets(&self) -> &PrimaryMap<StackSlot, u32> {
1531 &self.sized_stackslots
1532 }
1533
1534 /// The offsets of all dynamic stack slots (not spill slots) for debuginfo purposes.
1535 pub fn dynamic_stackslot_offsets(&self) -> &PrimaryMap<DynamicStackSlot, u32> {
1536 &self.dynamic_stackslots
1537 }
1538
1539 /// Generate an instruction which copies an argument to a destination
1540 /// register.
1541 pub fn gen_copy_arg_to_regs(
1542 &mut self,
1543 sigs: &SigSet,
1544 idx: usize,
1545 into_regs: ValueRegs<Writable<Reg>>,
1546 vregs: &mut VRegAllocator<M::I>,
1547 ) -> SmallInstVec<M::I> {
1548 let mut insts = smallvec![];
1549 let mut copy_arg_slot_to_reg = |slot: &ABIArgSlot, into_reg: &Writable<Reg>| {
1550 match slot {
1551 &ABIArgSlot::Reg { reg, .. } => {
1552 // Add a preg -> def pair to the eventual `args`
1553 // instruction. Extension mode doesn't matter
1554 // (we're copying out, not in; we ignore high bits
1555 // by convention).
1556 let arg = ArgPair {
1557 vreg: *into_reg,
1558 preg: reg.into(),
1559 };
1560 self.reg_args.push(arg);
1561 }
1562 &ABIArgSlot::Stack {
1563 offset,
1564 ty,
1565 extension,
1566 ..
1567 } => {
1568 // However, we have to respect the extension mode for stack
1569 // slots, or else we grab the wrong bytes on big-endian.
1570 let ext = M::get_ext_mode(sigs[self.sig].call_conv, extension);
1571 let ty =
1572 if ext != ArgumentExtension::None && M::word_bits() > ty_bits(ty) as u32 {
1573 M::word_type()
1574 } else {
1575 ty
1576 };
1577 insts.push(M::gen_load_stack(
1578 StackAMode::IncomingArg(offset, sigs[self.sig].sized_stack_arg_space),
1579 *into_reg,
1580 ty,
1581 ));
1582 }
1583 }
1584 };
1585
1586 match &sigs.args(self.sig)[idx] {
1587 &ABIArg::Slots { ref slots, .. } => {
1588 assert_eq!(into_regs.len(), slots.len());
1589 for (slot, into_reg) in slots.iter().zip(into_regs.regs().iter()) {
1590 copy_arg_slot_to_reg(&slot, &into_reg);
1591 }
1592 }
1593 &ABIArg::StructArg { offset, .. } => {
1594 let into_reg = into_regs.only_reg().unwrap();
1595 // Buffer address is implicitly defined by the ABI.
1596 insts.push(M::gen_get_stack_addr(
1597 StackAMode::IncomingArg(offset, sigs[self.sig].sized_stack_arg_space),
1598 into_reg,
1599 ));
1600 }
1601 &ABIArg::ImplicitPtrArg { pointer, ty, .. } => {
1602 let into_reg = into_regs.only_reg().unwrap();
1603 // We need to dereference the pointer.
1604 let base = match &pointer {
1605 &ABIArgSlot::Reg { reg, ty, .. } => {
1606 let tmp = vregs.alloc_with_deferred_error(ty).only_reg().unwrap();
1607 self.reg_args.push(ArgPair {
1608 vreg: Writable::from_reg(tmp),
1609 preg: reg.into(),
1610 });
1611 tmp
1612 }
1613 &ABIArgSlot::Stack { offset, ty, .. } => {
1614 let addr_reg = writable_value_regs(vregs.alloc_with_deferred_error(ty))
1615 .only_reg()
1616 .unwrap();
1617 insts.push(M::gen_load_stack(
1618 StackAMode::IncomingArg(offset, sigs[self.sig].sized_stack_arg_space),
1619 addr_reg,
1620 ty,
1621 ));
1622 addr_reg.to_reg()
1623 }
1624 };
1625 insts.push(M::gen_load_base_offset(into_reg, base, 0, ty));
1626 }
1627 }
1628 insts
1629 }
1630
1631 /// Generate an instruction which copies a source register to a return value slot.
1632 pub fn gen_copy_regs_to_retval(
1633 &self,
1634 sigs: &SigSet,
1635 idx: usize,
1636 from_regs: ValueRegs<Reg>,
1637 vregs: &mut VRegAllocator<M::I>,
1638 ) -> (SmallVec<[RetPair; 2]>, SmallInstVec<M::I>) {
1639 let mut reg_pairs = smallvec![];
1640 let mut ret = smallvec![];
1641 let word_bits = M::word_bits() as u8;
1642 match &sigs.rets(self.sig)[idx] {
1643 &ABIArg::Slots { ref slots, .. } => {
1644 assert_eq!(from_regs.len(), slots.len());
1645 for (slot, &from_reg) in slots.iter().zip(from_regs.regs().iter()) {
1646 match slot {
1647 &ABIArgSlot::Reg {
1648 reg, ty, extension, ..
1649 } => {
1650 let from_bits = ty_bits(ty) as u8;
1651 let ext = M::get_ext_mode(sigs[self.sig].call_conv, extension);
1652 let vreg = match (ext, from_bits) {
1653 (ir::ArgumentExtension::Uext, n)
1654 | (ir::ArgumentExtension::Sext, n)
1655 if n < word_bits =>
1656 {
1657 let signed = ext == ir::ArgumentExtension::Sext;
1658 let dst =
1659 writable_value_regs(vregs.alloc_with_deferred_error(ty))
1660 .only_reg()
1661 .unwrap();
1662 ret.push(M::gen_extend(
1663 dst, from_reg, signed, from_bits,
1664 /* to_bits = */ word_bits,
1665 ));
1666 dst.to_reg()
1667 }
1668 _ => {
1669 // No move needed, regalloc2 will emit it using the constraint
1670 // added by the RetPair.
1671 from_reg
1672 }
1673 };
1674 reg_pairs.push(RetPair {
1675 vreg,
1676 preg: Reg::from(reg),
1677 });
1678 }
1679 &ABIArgSlot::Stack {
1680 offset,
1681 ty,
1682 extension,
1683 ..
1684 } => {
1685 let mut ty = ty;
1686 let from_bits = ty_bits(ty) as u8;
1687 // A machine ABI implementation should ensure that stack frames
1688 // have "reasonable" size. All current ABIs for machinst
1689 // backends (aarch64 and x64) enforce a 128MB limit.
1690 let off = i32::try_from(offset).expect(
1691 "Argument stack offset greater than 2GB; should hit impl limit first",
1692 );
1693 let ext = M::get_ext_mode(sigs[self.sig].call_conv, extension);
1694 // Trash the from_reg; it should be its last use.
1695 match (ext, from_bits) {
1696 (ir::ArgumentExtension::Uext, n)
1697 | (ir::ArgumentExtension::Sext, n)
1698 if n < word_bits =>
1699 {
1700 assert_eq!(M::word_reg_class(), from_reg.class());
1701 let signed = ext == ir::ArgumentExtension::Sext;
1702 let dst =
1703 writable_value_regs(vregs.alloc_with_deferred_error(ty))
1704 .only_reg()
1705 .unwrap();
1706 ret.push(M::gen_extend(
1707 dst, from_reg, signed, from_bits,
1708 /* to_bits = */ word_bits,
1709 ));
1710 // Store the extended version.
1711 ty = M::word_type();
1712 }
1713 _ => {}
1714 };
1715 ret.push(M::gen_store_base_offset(
1716 self.ret_area_ptr.unwrap(),
1717 off,
1718 from_reg,
1719 ty,
1720 ));
1721 }
1722 }
1723 }
1724 }
1725 ABIArg::StructArg { .. } => {
1726 panic!("StructArg in return position is unsupported");
1727 }
1728 ABIArg::ImplicitPtrArg { .. } => {
1729 panic!("ImplicitPtrArg in return position is unsupported");
1730 }
1731 }
1732 (reg_pairs, ret)
1733 }
1734
1735 /// Generate any setup instruction needed to save values to the
1736 /// return-value area. This is usually used when were are multiple return
1737 /// values or an otherwise large return value that must be passed on the
1738 /// stack; typically the ABI specifies an extra hidden argument that is a
1739 /// pointer to that memory.
1740 pub fn gen_retval_area_setup(
1741 &mut self,
1742 sigs: &SigSet,
1743 vregs: &mut VRegAllocator<M::I>,
1744 ) -> Option<M::I> {
1745 if let Some(i) = sigs[self.sig].stack_ret_arg {
1746 let ret_area_ptr = Writable::from_reg(self.ret_area_ptr.unwrap());
1747 let insts =
1748 self.gen_copy_arg_to_regs(sigs, i.into(), ValueRegs::one(ret_area_ptr), vregs);
1749 insts.into_iter().next().map(|inst| {
1750 trace!(
1751 "gen_retval_area_setup: inst {:?}; ptr reg is {:?}",
1752 inst,
1753 ret_area_ptr.to_reg()
1754 );
1755 inst
1756 })
1757 } else {
1758 trace!("gen_retval_area_setup: not needed");
1759 None
1760 }
1761 }
1762
1763 /// Generate a return instruction.
1764 pub fn gen_rets(&self, rets: Vec<RetPair>) -> M::I {
1765 M::gen_rets(rets)
1766 }
1767
1768 /// Set up arguments values `args` for a call with signature `sig`.
1769 /// This will return a series of instructions to be emitted to set
1770 /// up all arguments, as well as a `CallArgList` list representing
1771 /// the arguments passed in registers. The latter need to be added
1772 /// as constraints to the actual call instruction.
1773 pub fn gen_call_args(
1774 &self,
1775 sigs: &SigSet,
1776 sig: Sig,
1777 args: &[ValueRegs<Reg>],
1778 is_tail_call: bool,
1779 flags: &settings::Flags,
1780 vregs: &mut VRegAllocator<M::I>,
1781 ) -> (CallArgList, SmallInstVec<M::I>) {
1782 let mut uses: CallArgList = smallvec![];
1783 let mut insts = smallvec![];
1784
1785 assert_eq!(args.len(), sigs.num_args(sig));
1786
1787 let call_conv = sigs[sig].call_conv;
1788 let stack_arg_space = sigs[sig].sized_stack_arg_space;
1789 let stack_arg = |offset| {
1790 if is_tail_call {
1791 StackAMode::IncomingArg(offset, stack_arg_space)
1792 } else {
1793 StackAMode::OutgoingArg(offset)
1794 }
1795 };
1796
1797 let word_ty = M::word_type();
1798 let word_rc = M::word_reg_class();
1799 let word_bits = M::word_bits() as usize;
1800
1801 if is_tail_call {
1802 debug_assert_eq!(
1803 self.call_conv,
1804 isa::CallConv::Tail,
1805 "Can only do `return_call`s from within a `tail` calling convention function"
1806 );
1807 }
1808
1809 // Helper to process a single argument slot (register or stack slot).
1810 // This will either add the register to the `uses` list or write the
1811 // value to the stack slot in the outgoing argument area (or for tail
1812 // calls, the incoming argument area).
1813 let mut process_arg_slot = |insts: &mut SmallInstVec<M::I>, slot, vreg, ty| {
1814 match &slot {
1815 &ABIArgSlot::Reg { reg, .. } => {
1816 uses.push(CallArgPair {
1817 vreg,
1818 preg: reg.into(),
1819 });
1820 }
1821 &ABIArgSlot::Stack { offset, .. } => {
1822 insts.push(M::gen_store_stack(stack_arg(offset), vreg, ty));
1823 }
1824 };
1825 };
1826
1827 // First pass: Handle `StructArg` arguments. These need to be copied
1828 // into their associated stack buffers. This should happen before any
1829 // of the other arguments are processed, as the `memcpy` call might
1830 // clobber registers used by other arguments.
1831 for (idx, from_regs) in args.iter().enumerate() {
1832 match &sigs.args(sig)[idx] {
1833 &ABIArg::Slots { .. } | &ABIArg::ImplicitPtrArg { .. } => {}
1834 &ABIArg::StructArg { offset, size, .. } => {
1835 let tmp = vregs.alloc_with_deferred_error(word_ty).only_reg().unwrap();
1836 insts.push(M::gen_get_stack_addr(
1837 stack_arg(offset),
1838 Writable::from_reg(tmp),
1839 ));
1840 insts.extend(M::gen_memcpy(
1841 isa::CallConv::for_libcall(flags, call_conv),
1842 tmp,
1843 from_regs.only_reg().unwrap(),
1844 size as usize,
1845 |ty| {
1846 Writable::from_reg(
1847 vregs.alloc_with_deferred_error(ty).only_reg().unwrap(),
1848 )
1849 },
1850 ));
1851 }
1852 }
1853 }
1854
1855 // Second pass: Handle everything except `StructArg` arguments.
1856 for (idx, from_regs) in args.iter().enumerate() {
1857 match sigs.args(sig)[idx] {
1858 ABIArg::Slots { ref slots, .. } => {
1859 assert_eq!(from_regs.len(), slots.len());
1860 for (slot, from_reg) in slots.iter().zip(from_regs.regs().iter()) {
1861 // Load argument slot value from `from_reg`, and perform any zero-
1862 // or sign-extension that is required by the ABI.
1863 let (ty, extension) = match *slot {
1864 ABIArgSlot::Reg { ty, extension, .. } => (ty, extension),
1865 ABIArgSlot::Stack { ty, extension, .. } => (ty, extension),
1866 };
1867 let ext = M::get_ext_mode(call_conv, extension);
1868 let (vreg, ty) = if ext != ir::ArgumentExtension::None
1869 && ty_bits(ty) < word_bits
1870 {
1871 assert_eq!(word_rc, from_reg.class());
1872 let signed = match ext {
1873 ir::ArgumentExtension::Uext => false,
1874 ir::ArgumentExtension::Sext => true,
1875 _ => unreachable!(),
1876 };
1877 let tmp = vregs.alloc_with_deferred_error(word_ty).only_reg().unwrap();
1878 insts.push(M::gen_extend(
1879 Writable::from_reg(tmp),
1880 *from_reg,
1881 signed,
1882 ty_bits(ty) as u8,
1883 word_bits as u8,
1884 ));
1885 (tmp, word_ty)
1886 } else {
1887 (*from_reg, ty)
1888 };
1889 process_arg_slot(&mut insts, *slot, vreg, ty);
1890 }
1891 }
1892 ABIArg::ImplicitPtrArg {
1893 offset,
1894 pointer,
1895 ty,
1896 ..
1897 } => {
1898 let vreg = from_regs.only_reg().unwrap();
1899 let tmp = vregs.alloc_with_deferred_error(word_ty).only_reg().unwrap();
1900 insts.push(M::gen_get_stack_addr(
1901 stack_arg(offset),
1902 Writable::from_reg(tmp),
1903 ));
1904 insts.push(M::gen_store_base_offset(tmp, 0, vreg, ty));
1905 process_arg_slot(&mut insts, pointer, tmp, word_ty);
1906 }
1907 ABIArg::StructArg { .. } => {}
1908 }
1909 }
1910
1911 // Finally, set the stack-return pointer to the return argument area.
1912 // For tail calls, this means forwarding the incoming stack-return pointer.
1913 if let Some(ret_arg) = sigs.get_ret_arg(sig) {
1914 let ret_area = if is_tail_call {
1915 self.ret_area_ptr.expect(
1916 "if the tail callee has a return pointer, then the tail caller must as well",
1917 )
1918 } else {
1919 let tmp = vregs.alloc_with_deferred_error(word_ty).only_reg().unwrap();
1920 let amode = StackAMode::OutgoingArg(stack_arg_space.into());
1921 insts.push(M::gen_get_stack_addr(amode, Writable::from_reg(tmp)));
1922 tmp
1923 };
1924 match ret_arg {
1925 // The return pointer must occupy a single slot.
1926 ABIArg::Slots { slots, .. } => {
1927 assert_eq!(slots.len(), 1);
1928 process_arg_slot(&mut insts, slots[0], ret_area, word_ty);
1929 }
1930 _ => unreachable!(),
1931 }
1932 }
1933
1934 (uses, insts)
1935 }
1936
1937 /// Set up return values `outputs` for a call with signature `sig`.
1938 /// This does not emit (or return) any instructions, but returns a
1939 /// `CallRetList` representing the return value constraints. This
1940 /// needs to be added to the actual call instruction.
1941 ///
1942 /// If `try_call_payloads` is non-zero, it is expected to hold
1943 /// exception payload registers for try_call instructions. These
1944 /// will be added as needed to the `CallRetList` as well.
1945 pub fn gen_call_rets(
1946 &self,
1947 sigs: &SigSet,
1948 sig: Sig,
1949 outputs: &[ValueRegs<Reg>],
1950 try_call_payloads: Option<&[Writable<Reg>]>,
1951 vregs: &mut VRegAllocator<M::I>,
1952 ) -> CallRetList {
1953 let callee_conv = sigs[sig].call_conv;
1954 let stack_arg_space = sigs[sig].sized_stack_arg_space;
1955
1956 let word_ty = M::word_type();
1957 let word_bits = M::word_bits() as usize;
1958
1959 let mut defs: CallRetList = smallvec![];
1960 let mut outputs = outputs.into_iter();
1961 let num_rets = sigs.num_rets(sig);
1962 for idx in 0..num_rets {
1963 let ret = sigs.rets(sig)[idx].clone();
1964 match ret {
1965 ABIArg::Slots {
1966 ref slots, purpose, ..
1967 } => {
1968 // We do not use the returned copy of the return buffer pointer,
1969 // so skip any StructReturn returns that may be present.
1970 if purpose == ArgumentPurpose::StructReturn {
1971 continue;
1972 }
1973 let retval_regs = outputs.next().unwrap();
1974 assert_eq!(retval_regs.len(), slots.len());
1975 for (slot, retval_reg) in slots.iter().zip(retval_regs.regs().iter()) {
1976 // We do not perform any extension because we're copying out, not in,
1977 // and we ignore high bits in our own registers by convention. However,
1978 // we still need to use the proper extended type to access stack slots
1979 // (this is critical on big-endian systems).
1980 let (ty, extension) = match *slot {
1981 ABIArgSlot::Reg { ty, extension, .. } => (ty, extension),
1982 ABIArgSlot::Stack { ty, extension, .. } => (ty, extension),
1983 };
1984 let ext = M::get_ext_mode(callee_conv, extension);
1985 let ty = if ext != ir::ArgumentExtension::None && ty_bits(ty) < word_bits {
1986 word_ty
1987 } else {
1988 ty
1989 };
1990
1991 match slot {
1992 &ABIArgSlot::Reg { reg, .. } => {
1993 defs.push(CallRetPair {
1994 vreg: Writable::from_reg(*retval_reg),
1995 location: RetLocation::Reg(reg.into(), ty),
1996 });
1997 }
1998 &ABIArgSlot::Stack { offset, .. } => {
1999 let amode =
2000 StackAMode::OutgoingArg(offset + i64::from(stack_arg_space));
2001 defs.push(CallRetPair {
2002 vreg: Writable::from_reg(*retval_reg),
2003 location: RetLocation::Stack(amode, ty),
2004 });
2005 }
2006 }
2007 }
2008 }
2009 ABIArg::StructArg { .. } => {
2010 panic!("StructArg not supported in return position");
2011 }
2012 ABIArg::ImplicitPtrArg { .. } => {
2013 panic!("ImplicitPtrArg not supported in return position");
2014 }
2015 }
2016 }
2017 assert!(outputs.next().is_none());
2018
2019 if let Some(try_call_payloads) = try_call_payloads {
2020 // We need to update `defs` to contain the exception
2021 // payload regs as well. We have two sources of info that
2022 // we join:
2023 //
2024 // - The machine-specific ABI implementation `M`, which
2025 // tells us the particular registers that payload values
2026 // must be in
2027 // - The passed-in lowering context, which gives us the
2028 // vregs we must define.
2029 //
2030 // Note that payload values may need to end up in the same
2031 // physical registers as ordinary return values; this is
2032 // not a conflict, because we either get one or the
2033 // other. For regalloc's purposes, we define both starting
2034 // here at the callsite, but we can share one def in the
2035 // `defs` list and alias one vreg to another. Thus we
2036 // handle the two cases below for each payload register:
2037 // overlaps a return value (and we alias to it) or not
2038 // (and we add a def).
2039 let pregs = M::exception_payload_regs(callee_conv);
2040 for (i, &preg) in pregs.iter().enumerate() {
2041 let vreg = try_call_payloads[i];
2042 if let Some(existing) = defs.iter().find(|def| match def.location {
2043 RetLocation::Reg(r, _) => r == preg,
2044 _ => false,
2045 }) {
2046 vregs.set_vreg_alias(vreg.to_reg(), existing.vreg.to_reg());
2047 } else {
2048 defs.push(CallRetPair {
2049 vreg,
2050 location: RetLocation::Reg(preg, word_ty),
2051 });
2052 }
2053 }
2054 }
2055
2056 defs
2057 }
2058
2059 /// Populate a `CallInfo` for a call with signature `sig`.
2060 ///
2061 /// `dest` is the target-specific call destination value
2062 /// `uses` is the `CallArgList` describing argument constraints
2063 /// `defs` is the `CallRetList` describing return constraints
2064 /// `try_call_info` describes exception targets for try_call instructions
2065 ///
2066 /// The clobber list is computed here from the above data.
2067 pub fn gen_call_info<T>(
2068 &self,
2069 sigs: &SigSet,
2070 sig: Sig,
2071 dest: T,
2072 uses: CallArgList,
2073 defs: CallRetList,
2074 try_call_info: Option<TryCallInfo>,
2075 ) -> CallInfo<T> {
2076 let caller_conv = self.call_conv;
2077 let callee_conv = sigs[sig].call_conv;
2078 let stack_arg_space = sigs[sig].sized_stack_arg_space;
2079
2080 let clobbers = {
2081 // Get clobbers: all caller-saves. These may include return value
2082 // regs, which we will remove from the clobber set below.
2083 let mut clobbers =
2084 <M>::get_regs_clobbered_by_call(callee_conv, try_call_info.is_some());
2085
2086 // Remove retval regs from clobbers.
2087 for def in &defs {
2088 if let RetLocation::Reg(preg, _) = def.location {
2089 clobbers.remove(PReg::from(preg.to_real_reg().unwrap()));
2090 }
2091 }
2092
2093 clobbers
2094 };
2095
2096 // Any adjustment to SP to account for required outgoing arguments/stack return values must
2097 // be done inside of the call pseudo-op, to ensure that SP is always in a consistent
2098 // state for all other instructions. For example, if a tail-call abi function is called
2099 // here, the reclamation of the outgoing argument area must be done inside of the call
2100 // pseudo-op's emission to ensure that SP is consistent at all other points in the lowered
2101 // function. (Except the prologue and epilogue, but those are fairly special parts of the
2102 // function that establish the SP invariants that are relied on elsewhere and are generated
2103 // after the register allocator has run and thus cannot have register allocator-inserted
2104 // references to SP offsets.)
2105
2106 let callee_pop_size = if callee_conv == isa::CallConv::Tail {
2107 // The tail calling convention has callees pop stack arguments.
2108 stack_arg_space
2109 } else {
2110 0
2111 };
2112
2113 CallInfo {
2114 dest,
2115 uses,
2116 defs,
2117 clobbers,
2118 callee_conv,
2119 caller_conv,
2120 callee_pop_size,
2121 try_call_info,
2122 }
2123 }
2124
2125 /// Produce an instruction that computes a sized stackslot address.
2126 pub fn sized_stackslot_addr(
2127 &self,
2128 slot: StackSlot,
2129 offset: u32,
2130 into_reg: Writable<Reg>,
2131 ) -> M::I {
2132 // Offset from beginning of stackslot area.
2133 let stack_off = self.sized_stackslots[slot] as i64;
2134 let sp_off: i64 = stack_off + (offset as i64);
2135 M::gen_get_stack_addr(StackAMode::Slot(sp_off), into_reg)
2136 }
2137
2138 /// Produce an instruction that computes a dynamic stackslot address.
2139 pub fn dynamic_stackslot_addr(&self, slot: DynamicStackSlot, into_reg: Writable<Reg>) -> M::I {
2140 let stack_off = self.dynamic_stackslots[slot] as i64;
2141 M::gen_get_stack_addr(StackAMode::Slot(stack_off), into_reg)
2142 }
2143
2144 /// Get an `args` pseudo-inst, if any, that should appear at the
2145 /// very top of the function body prior to regalloc.
2146 pub fn take_args(&mut self) -> Option<M::I> {
2147 if self.reg_args.len() > 0 {
2148 // Very first instruction is an `args` pseudo-inst that
2149 // establishes live-ranges for in-register arguments and
2150 // constrains them at the start of the function to the
2151 // locations defined by the ABI.
2152 Some(M::gen_args(std::mem::take(&mut self.reg_args)))
2153 } else {
2154 None
2155 }
2156 }
2157}
2158
2159/// ### Post-Regalloc Functions
2160///
2161/// These methods of `Callee` may only be called after
2162/// regalloc.
2163impl<M: ABIMachineSpec> Callee<M> {
2164 /// Compute the final frame layout, post-regalloc.
2165 ///
2166 /// This must be called before gen_prologue or gen_epilogue.
2167 pub fn compute_frame_layout(
2168 &mut self,
2169 sigs: &SigSet,
2170 spillslots: usize,
2171 clobbered: Vec<Writable<RealReg>>,
2172 ) {
2173 let bytes = M::word_bytes();
2174 let total_stacksize = self.stackslots_size + bytes * spillslots as u32;
2175 let mask = M::stack_align(self.call_conv) - 1;
2176 let total_stacksize = (total_stacksize + mask) & !mask; // 16-align the stack.
2177 self.frame_layout = Some(M::compute_frame_layout(
2178 self.call_conv,
2179 &self.flags,
2180 self.signature(),
2181 &clobbered,
2182 self.is_leaf,
2183 self.stack_args_size(sigs),
2184 self.tail_args_size,
2185 self.stackslots_size,
2186 total_stacksize,
2187 self.outgoing_args_size,
2188 ));
2189 }
2190
2191 /// Generate a prologue, post-regalloc.
2192 ///
2193 /// This should include any stack frame or other setup necessary to use the
2194 /// other methods (`load_arg`, `store_retval`, and spillslot accesses.)
2195 pub fn gen_prologue(&self) -> SmallInstVec<M::I> {
2196 let frame_layout = self.frame_layout();
2197 let mut insts = smallvec![];
2198
2199 // Set up frame.
2200 insts.extend(M::gen_prologue_frame_setup(
2201 self.call_conv,
2202 &self.flags,
2203 &self.isa_flags,
2204 &frame_layout,
2205 ));
2206
2207 // The stack limit check needs to cover all the stack adjustments we
2208 // might make, up to the next stack limit check in any function we
2209 // call. Since this happens after frame setup, the current function's
2210 // setup area needs to be accounted for in the caller's stack limit
2211 // check, but we need to account for any setup area that our callees
2212 // might need. Note that s390x may also use the outgoing args area for
2213 // backtrace support even in leaf functions, so that should be accounted
2214 // for unconditionally.
2215 let total_stacksize = (frame_layout.tail_args_size - frame_layout.incoming_args_size)
2216 + frame_layout.clobber_size
2217 + frame_layout.fixed_frame_storage_size
2218 + frame_layout.outgoing_args_size
2219 + if self.is_leaf {
2220 0
2221 } else {
2222 frame_layout.setup_area_size
2223 };
2224
2225 // Leaf functions with zero stack don't need a stack check if one's
2226 // specified, otherwise always insert the stack check.
2227 if total_stacksize > 0 || !self.is_leaf {
2228 if let Some((reg, stack_limit_load)) = &self.stack_limit {
2229 insts.extend(stack_limit_load.clone());
2230 self.insert_stack_check(*reg, total_stacksize, &mut insts);
2231 }
2232
2233 if self.flags.enable_probestack() {
2234 let guard_size = 1 << self.flags.probestack_size_log2();
2235 match self.flags.probestack_strategy() {
2236 ProbestackStrategy::Inline => M::gen_inline_probestack(
2237 &mut insts,
2238 self.call_conv,
2239 total_stacksize,
2240 guard_size,
2241 ),
2242 ProbestackStrategy::Outline => {
2243 if total_stacksize >= guard_size {
2244 M::gen_probestack(&mut insts, total_stacksize);
2245 }
2246 }
2247 }
2248 }
2249 }
2250
2251 // Save clobbered registers.
2252 insts.extend(M::gen_clobber_save(
2253 self.call_conv,
2254 &self.flags,
2255 &frame_layout,
2256 ));
2257
2258 insts
2259 }
2260
2261 /// Generate an epilogue, post-regalloc.
2262 ///
2263 /// Note that this must generate the actual return instruction (rather than
2264 /// emitting this in the lowering logic), because the epilogue code comes
2265 /// before the return and the two are likely closely related.
2266 pub fn gen_epilogue(&self) -> SmallInstVec<M::I> {
2267 let frame_layout = self.frame_layout();
2268 let mut insts = smallvec![];
2269
2270 // Restore clobbered registers.
2271 insts.extend(M::gen_clobber_restore(
2272 self.call_conv,
2273 &self.flags,
2274 &frame_layout,
2275 ));
2276
2277 // Tear down frame.
2278 insts.extend(M::gen_epilogue_frame_restore(
2279 self.call_conv,
2280 &self.flags,
2281 &self.isa_flags,
2282 &frame_layout,
2283 ));
2284
2285 // And return.
2286 insts.extend(M::gen_return(
2287 self.call_conv,
2288 &self.isa_flags,
2289 &frame_layout,
2290 ));
2291
2292 trace!("Epilogue: {:?}", insts);
2293 insts
2294 }
2295
2296 /// Return a reference to the computed frame layout information. This
2297 /// function will panic if it's called before [`Self::compute_frame_layout`].
2298 pub fn frame_layout(&self) -> &FrameLayout {
2299 self.frame_layout
2300 .as_ref()
2301 .expect("frame layout not computed before prologue generation")
2302 }
2303
2304 /// Returns the full frame size for the given function, after prologue
2305 /// emission has run. This comprises the spill slots and stack-storage
2306 /// slots as well as storage for clobbered callee-save registers, but
2307 /// not arguments arguments pushed at callsites within this function,
2308 /// or other ephemeral pushes.
2309 pub fn frame_size(&self) -> u32 {
2310 let frame_layout = self.frame_layout();
2311 frame_layout.clobber_size + frame_layout.fixed_frame_storage_size
2312 }
2313
2314 /// Returns offset from the slot base in the current frame to the caller's SP.
2315 pub fn slot_base_to_caller_sp_offset(&self) -> u32 {
2316 let frame_layout = self.frame_layout();
2317 frame_layout.clobber_size
2318 + frame_layout.fixed_frame_storage_size
2319 + frame_layout.setup_area_size
2320 }
2321
2322 /// Returns the size of arguments expected on the stack.
2323 pub fn stack_args_size(&self, sigs: &SigSet) -> u32 {
2324 sigs[self.sig].sized_stack_arg_space
2325 }
2326
2327 /// Get the spill-slot size.
2328 pub fn get_spillslot_size(&self, rc: RegClass) -> u32 {
2329 let max = if self.dynamic_type_sizes.len() == 0 {
2330 16
2331 } else {
2332 *self
2333 .dynamic_type_sizes
2334 .iter()
2335 .max_by(|x, y| x.1.cmp(&y.1))
2336 .map(|(_k, v)| v)
2337 .unwrap()
2338 };
2339 M::get_number_of_spillslots_for_value(rc, max, &self.isa_flags)
2340 }
2341
2342 /// Get the spill slot offset relative to the fixed allocation area start.
2343 pub fn get_spillslot_offset(&self, slot: SpillSlot) -> i64 {
2344 self.frame_layout().spillslot_offset(slot)
2345 }
2346
2347 /// Generate a spill.
2348 pub fn gen_spill(&self, to_slot: SpillSlot, from_reg: RealReg) -> M::I {
2349 let ty = M::I::canonical_type_for_rc(from_reg.class());
2350 debug_assert_eq!(<M>::I::rc_for_type(ty).unwrap().1, &[ty]);
2351
2352 let sp_off = self.get_spillslot_offset(to_slot);
2353 trace!("gen_spill: {from_reg:?} into slot {to_slot:?} at offset {sp_off}");
2354
2355 let from = StackAMode::Slot(sp_off);
2356 <M>::gen_store_stack(from, Reg::from(from_reg), ty)
2357 }
2358
2359 /// Generate a reload (fill).
2360 pub fn gen_reload(&self, to_reg: Writable<RealReg>, from_slot: SpillSlot) -> M::I {
2361 let ty = M::I::canonical_type_for_rc(to_reg.to_reg().class());
2362 debug_assert_eq!(<M>::I::rc_for_type(ty).unwrap().1, &[ty]);
2363
2364 let sp_off = self.get_spillslot_offset(from_slot);
2365 trace!("gen_reload: {to_reg:?} from slot {from_slot:?} at offset {sp_off}");
2366
2367 let from = StackAMode::Slot(sp_off);
2368 <M>::gen_load_stack(from, to_reg.map(Reg::from), ty)
2369 }
2370}
2371
2372/// An input argument to a call instruction: the vreg that is used,
2373/// and the preg it is constrained to (per the ABI).
2374#[derive(Clone, Debug)]
2375pub struct CallArgPair {
2376 /// The virtual register to use for the argument.
2377 pub vreg: Reg,
2378 /// The real register into which the arg goes.
2379 pub preg: Reg,
2380}
2381
2382/// An output return value from a call instruction: the vreg that is
2383/// defined, and the preg or stack location it is constrained to (per
2384/// the ABI).
2385#[derive(Clone, Debug)]
2386pub struct CallRetPair {
2387 /// The virtual register to define from this return value.
2388 pub vreg: Writable<Reg>,
2389 /// The real register from which the return value is read.
2390 pub location: RetLocation,
2391}
2392
2393/// A location to load a return-value from after a call completes.
2394#[derive(Clone, Debug, PartialEq, Eq)]
2395pub enum RetLocation {
2396 /// A physical register.
2397 Reg(Reg, Type),
2398 /// A stack location, identified by a `StackAMode`.
2399 Stack(StackAMode, Type),
2400}
2401
2402pub type CallArgList = SmallVec<[CallArgPair; 8]>;
2403pub type CallRetList = SmallVec<[CallRetPair; 8]>;
2404
2405impl<T> CallInfo<T> {
2406 /// Emit loads for any stack-carried return values using the call
2407 /// info and allocations.
2408 pub fn emit_retval_loads<
2409 M: ABIMachineSpec,
2410 EmitFn: FnMut(M::I),
2411 IslandFn: Fn(u32) -> Option<M::I>,
2412 >(
2413 &self,
2414 stackslots_size: u32,
2415 mut emit: EmitFn,
2416 emit_island: IslandFn,
2417 ) {
2418 // Count stack-ret locations and emit an island to account for
2419 // this space usage.
2420 let mut space_needed = 0;
2421 for CallRetPair { location, .. } in &self.defs {
2422 if let RetLocation::Stack(..) = location {
2423 // Assume up to ten instructions, semi-arbitrarily:
2424 // load from stack, store to spillslot, codegen of
2425 // large offsets on RISC ISAs.
2426 space_needed += 10 * M::I::worst_case_size();
2427 }
2428 }
2429 if space_needed > 0 {
2430 if let Some(island_inst) = emit_island(space_needed) {
2431 emit(island_inst);
2432 }
2433 }
2434
2435 let temp = M::retval_temp_reg(self.callee_conv);
2436 // The temporary must be noted as clobbered.
2437 debug_assert!(
2438 M::get_regs_clobbered_by_call(self.callee_conv, self.try_call_info.is_some())
2439 .contains(PReg::from(temp.to_reg().to_real_reg().unwrap()))
2440 );
2441
2442 for CallRetPair { vreg, location } in &self.defs {
2443 match location {
2444 RetLocation::Reg(preg, ..) => {
2445 // The temporary must not also be an actual return
2446 // value register.
2447 debug_assert!(*preg != temp.to_reg());
2448 }
2449 RetLocation::Stack(amode, ty) => {
2450 if let Some(spillslot) = vreg.to_reg().to_spillslot() {
2451 // `temp` is an integer register of machine word
2452 // width, but `ty` may be floating-point/vector,
2453 // which (i) may not be loadable directly into an
2454 // int reg, and (ii) may be wider than a machine
2455 // word. For simplicity, and because there are not
2456 // always easy choices for volatile float/vec regs
2457 // (see e.g. x86-64, where fastcall clobbers only
2458 // xmm0-xmm5, but tail uses xmm0-xmm7 for
2459 // returns), we use the integer temp register in
2460 // steps.
2461 let parts = (ty.bytes() + M::word_bytes() - 1) / M::word_bytes();
2462 for part in 0..parts {
2463 emit(M::gen_load_stack(
2464 amode.offset_by(part * M::word_bytes()),
2465 temp,
2466 M::word_type(),
2467 ));
2468 emit(M::gen_store_stack(
2469 StackAMode::Slot(
2470 i64::from(stackslots_size)
2471 + i64::from(M::word_bytes())
2472 * ((spillslot.index() as i64) + (part as i64)),
2473 ),
2474 temp.to_reg(),
2475 M::word_type(),
2476 ));
2477 }
2478 } else {
2479 assert_ne!(*vreg, temp);
2480 emit(M::gen_load_stack(*amode, *vreg, *ty));
2481 }
2482 }
2483 }
2484 }
2485 }
2486}
2487
2488impl TryCallInfo {
2489 pub(crate) fn exception_handlers(
2490 &self,
2491 layout: &FrameLayout,
2492 ) -> impl Iterator<Item = MachExceptionHandler> {
2493 self.exception_handlers.iter().map(|handler| match handler {
2494 TryCallHandler::Tag(tag, label) => MachExceptionHandler::Tag(*tag, *label),
2495 TryCallHandler::Default(label) => MachExceptionHandler::Default(*label),
2496 TryCallHandler::Context(reg) => {
2497 let loc = if let Some(spillslot) = reg.to_spillslot() {
2498 let offset = layout.spillslot_offset(spillslot);
2499 ExceptionContextLoc::SPOffset(u32::try_from(offset).expect("SP offset cannot be negative or larger than 4GiB"))
2500 } else if let Some(realreg) = reg.to_real_reg() {
2501 ExceptionContextLoc::GPR(realreg.hw_enc())
2502 } else {
2503 panic!("Virtual register present in try-call handler clause after register allocation");
2504 };
2505 MachExceptionHandler::Context(loc)
2506 }
2507 })
2508 }
2509
2510 pub(crate) fn pretty_print_dests(&self) -> String {
2511 self.exception_handlers
2512 .iter()
2513 .map(|handler| match handler {
2514 TryCallHandler::Tag(tag, label) => format!("{tag:?}: {label:?}"),
2515 TryCallHandler::Default(label) => format!("default: {label:?}"),
2516 TryCallHandler::Context(loc) => format!("context {loc:?}"),
2517 })
2518 .collect::<Vec<_>>()
2519 .join(", ")
2520 }
2521
2522 pub(crate) fn collect_operands(&mut self, collector: &mut impl OperandVisitor) {
2523 for handler in &mut self.exception_handlers {
2524 match handler {
2525 TryCallHandler::Context(ctx) => {
2526 collector.any_late_use(ctx);
2527 }
2528 TryCallHandler::Tag(_, _) | TryCallHandler::Default(_) => {}
2529 }
2530 }
2531 }
2532}
2533
2534#[cfg(test)]
2535mod tests {
2536 use super::SigData;
2537
2538 #[test]
2539 fn sig_data_size() {
2540 // The size of `SigData` is performance sensitive, so make sure
2541 // we don't regress it unintentionally.
2542 assert_eq!(std::mem::size_of::<SigData>(), 24);
2543 }
2544}