1 use crate::ir::Type;
2 use crate::ir::types;
3 use crate::settings::{self, LibcallCallConv};
4 use core::fmt;
5 use core::str;
6 use target_lexicon::{CallingConvention, Triple};
7 
8 #[cfg(feature = "enable-serde")]
9 use 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))]
14 pub enum CallConv {
15     /// Best performance, not ABI-stable.
16     Fast,
17     /// Smallest caller code size, not ABI-stable.
18     Cold,
19     /// Supports tail calls, not ABI-stable except for exception
20     /// payload registers.
21     ///
22     /// On exception resume, a caller to a `tail`-convention function
23     /// assumes that the exception payload values are in the following
24     /// registers (per platform):
25     /// - x86-64: rax, rdx
26     /// - aarch64: x0, x1
27     /// - riscv64: a0, a1
28     /// - pulley{32,64}: x0, x1
29     //
30     // Currently, this is basically sys-v except that callees pop stack
31     // arguments, rather than callers. Expected to change even more in the
32     // future, however!
33     Tail,
34     /// System V-style convention used on many platforms.
35     SystemV,
36     /// Windows "fastcall" convention, also used for x64 and ARM.
37     WindowsFastcall,
38     /// Mac aarch64 calling convention, which is a tweaked aarch64 ABI.
39     AppleAarch64,
40     /// Specialized convention for the probestack function.
41     Probestack,
42     /// The winch calling convention, not ABI-stable.
43     ///
44     /// The main difference to SystemV is that the winch calling convention
45     /// defines no callee-save registers, and restricts the number of return
46     /// registers to one integer, and one floating point.
47     Winch,
48     /// Calling convention for patchable-call instructions.
49     ///
50     /// This is designed for a very specific need: we want a *single*
51     /// call instruction at our callsite, with no other setup, and we
52     /// don't want any registers clobbered. This allows patchable
53     /// callsites to be as unobtrusive as possible.
54     ///
55     /// The ABI is based on the native register-argument ABI on each
56     /// respective platform, but puts severe restrictions on allowable
57     /// signatures: only up to four arguments of integer type, and no
58     /// return values. It does not support tail-calls, and disallows
59     /// any extension modes on arguments.
60     ///
61     /// The ABI specifies that *no* registers, not even argument
62     /// registers, are clobbered. This is pretty unique: it means that
63     /// the call instruction will constrain regalloc to have any args
64     /// in the right registers, but those registers will be preserved,
65     /// so multiple patchable callsites can reuse those values. This
66     /// further reduces the cost of the callsites.
67     Patchable,
68 }
69 
70 impl 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::Cold => Self::Cold,
89             LibcallCallConv::SystemV => Self::SystemV,
90             LibcallCallConv::WindowsFastcall => Self::WindowsFastcall,
91             LibcallCallConv::AppleAarch64 => Self::AppleAarch64,
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 | CallConv::SystemV | CallConv::Winch => true,
108             _ => false,
109         }
110     }
111 
112     /// What types do the exception payload value(s) have?
113     ///
114     /// Note that this function applies to the *callee* of a `try_call`
115     /// instruction. The calling convention of the callee may differ from the
116     /// caller, but the exceptional payload types available are defined by the
117     /// callee calling convention.
118     ///
119     /// Also note that individual backends are responsible for reporting
120     /// register destinations for exceptional types. Internally Cranelift
121     /// asserts that the backend supports the exact same number of register
122     /// destinations as this return value.
123     pub fn exception_payload_types(&self, pointer_ty: Type) -> &[Type] {
124         match self {
125             CallConv::Tail | CallConv::SystemV => match pointer_ty {
126                 types::I32 => &[types::I32, types::I32],
127                 types::I64 => &[types::I64, types::I64],
128                 _ => unreachable!(),
129             },
130             _ => &[],
131         }
132     }
133 }
134 
135 impl fmt::Display for CallConv {
136     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
137         f.write_str(match *self {
138             Self::Fast => "fast",
139             Self::Cold => "cold",
140             Self::Tail => "tail",
141             Self::SystemV => "system_v",
142             Self::WindowsFastcall => "windows_fastcall",
143             Self::AppleAarch64 => "apple_aarch64",
144             Self::Probestack => "probestack",
145             Self::Winch => "winch",
146             Self::Patchable => "patchable",
147         })
148     }
149 }
150 
151 impl str::FromStr for CallConv {
152     type Err = ();
153     fn from_str(s: &str) -> Result<Self, Self::Err> {
154         match s {
155             "fast" => Ok(Self::Fast),
156             "cold" => Ok(Self::Cold),
157             "tail" => Ok(Self::Tail),
158             "system_v" => Ok(Self::SystemV),
159             "windows_fastcall" => Ok(Self::WindowsFastcall),
160             "apple_aarch64" => Ok(Self::AppleAarch64),
161             "probestack" => Ok(Self::Probestack),
162             "winch" => Ok(Self::Winch),
163             "patchable" => Ok(Self::Patchable),
164             _ => Err(()),
165         }
166     }
167 }
168