Skip to main content

cranelift_codegen/isa/
call_conv.rs

1use crate::ir::Type;
2use crate::ir::types;
3use crate::settings::{self, LibcallCallConv};
4use core::fmt;
5use core::str;
6use target_lexicon::{CallingConvention, Triple};
7
8#[cfg(feature = "enable-serde")]
9use serde_derive::{Deserialize, Serialize};
10
11/// Calling convention identifiers.
12#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
13#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
14pub enum CallConv {
15    /// Best performance, not ABI-stable.
16    Fast,
17    /// Supports tail calls, not ABI-stable except as stated here.
18    ///
19    /// On exception resume, a caller to a `tail`-convention function assumes
20    /// that the exception payload values are in the following registers (per
21    /// platform):
22    /// - x86-64: rax, rdx
23    /// - aarch64: x0, x1
24    /// - riscv64: a0, a1
25    /// - pulley{32,64}: x0, x1
26    ///
27    /// The `interrupt_poll` instruction uses registers as follows:
28    /// - x86-64: `context` in rdi, `load_ptr` and `next_load_ptr` in r11,
29    ///   scratch in r10
30    /// - aarch64: `context` in x0, `load_ptr` and `next_load_ptr` in x10,
31    ///   scratch in x9
32    //
33    // Currently, this is basically sys-v except that callees pop stack
34    // arguments, rather than callers. Expected to change even more in the
35    // future, however!
36    Tail,
37    /// System V-style convention used on many platforms.
38    SystemV,
39    /// Windows "fastcall" convention, also used for x64 and ARM.
40    WindowsFastcall,
41    /// Mac aarch64 calling convention, which is a tweaked aarch64 ABI.
42    AppleAarch64,
43    /// Specialized convention for the probestack function.
44    Probestack,
45    /// Internal calling convention for Winch-generated functions.
46    /// Cranelift-generated trampolines use the same convention to
47    /// interoperate with them. This convention is not ABI-stable.
48    ///
49    /// Callees reclaim their aligned incoming stack-argument area
50    /// before returning.
51    ///
52    /// Only the last result is returned in a register; any preceding
53    /// results are written to the return area in memory.
54    Winch,
55    /// Calling convention optimized for callsite efficiency, at the
56    /// cost of the callee. It does so by not clobbering any
57    /// registers.
58    ///
59    /// This is designed for a very specific need: we want callsites
60    /// that we can insert as instrumentation (perhaps patchable)
61    /// while affecting surrounding instructions' register allocation
62    /// as little as possible.
63    ///
64    /// The ABI is based on the native register-argument ABI on each
65    /// respective platform. It does not support tail-calls. It also
66    /// does not support return values.
67    PreserveAll,
68}
69
70impl CallConv {
71    /// Return the default calling convention for the given target triple.
72    pub fn triple_default(triple: &Triple) -> Self {
73        match triple.default_calling_convention() {
74            // Default to System V for unknown targets because most everything
75            // uses System V.
76            Ok(CallingConvention::SystemV) | Err(()) => Self::SystemV,
77            Ok(CallingConvention::AppleAarch64) => Self::AppleAarch64,
78            Ok(CallingConvention::WindowsFastcall) => Self::WindowsFastcall,
79            Ok(unimp) => unimplemented!("calling convention: {:?}", unimp),
80        }
81    }
82
83    /// Returns the calling convention used for libcalls according to the current flags.
84    pub fn for_libcall(flags: &settings::Flags, default_call_conv: CallConv) -> Self {
85        match flags.libcall_call_conv() {
86            LibcallCallConv::IsaDefault => default_call_conv,
87            LibcallCallConv::Fast => Self::Fast,
88            LibcallCallConv::SystemV => Self::SystemV,
89            LibcallCallConv::WindowsFastcall => Self::WindowsFastcall,
90            LibcallCallConv::AppleAarch64 => Self::AppleAarch64,
91            LibcallCallConv::PreserveAll => Self::PreserveAll,
92            LibcallCallConv::Probestack => Self::Probestack,
93        }
94    }
95
96    /// Does this calling convention support tail calls?
97    pub fn supports_tail_calls(&self) -> bool {
98        match self {
99            CallConv::Tail => true,
100            _ => false,
101        }
102    }
103
104    /// Does this calling convention support exceptions?
105    pub fn supports_exceptions(&self) -> bool {
106        match self {
107            CallConv::Tail
108            | CallConv::SystemV
109            | CallConv::Winch
110            | CallConv::PreserveAll
111            | CallConv::AppleAarch64 => true,
112            _ => false,
113        }
114    }
115
116    /// What types do the exception payload value(s) have?
117    ///
118    /// Note that this function applies to the *callee* of a `try_call`
119    /// instruction. The calling convention of the callee may differ from the
120    /// caller, but the exceptional payload types available are defined by the
121    /// callee calling convention.
122    ///
123    /// Also note that individual backends are responsible for reporting
124    /// register destinations for exceptional types. Internally Cranelift
125    /// asserts that the backend supports the exact same number of register
126    /// destinations as this return value.
127    pub fn exception_payload_types(&self, pointer_ty: Type) -> &[Type] {
128        match self {
129            CallConv::Tail | CallConv::SystemV | CallConv::PreserveAll | CallConv::AppleAarch64 => {
130                match pointer_ty {
131                    types::I32 => &[types::I32, types::I32],
132                    types::I64 => &[types::I64, types::I64],
133                    _ => unreachable!(),
134                }
135            }
136            _ => &[],
137        }
138    }
139}
140
141impl fmt::Display for CallConv {
142    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
143        f.write_str(match *self {
144            Self::Fast => "fast",
145            Self::Tail => "tail",
146            Self::SystemV => "system_v",
147            Self::WindowsFastcall => "windows_fastcall",
148            Self::AppleAarch64 => "apple_aarch64",
149            Self::Probestack => "probestack",
150            Self::Winch => "winch",
151            Self::PreserveAll => "preserve_all",
152        })
153    }
154}
155
156impl str::FromStr for CallConv {
157    type Err = ();
158    fn from_str(s: &str) -> Result<Self, Self::Err> {
159        match s {
160            "fast" => Ok(Self::Fast),
161            "tail" => Ok(Self::Tail),
162            "system_v" => Ok(Self::SystemV),
163            "windows_fastcall" => Ok(Self::WindowsFastcall),
164            "apple_aarch64" => Ok(Self::AppleAarch64),
165            "probestack" => Ok(Self::Probestack),
166            "winch" => Ok(Self::Winch),
167            "preserve_all" => Ok(Self::PreserveAll),
168            _ => Err(()),
169        }
170    }
171}