Skip to main content

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