Skip to main content

rustc_target/callconv/
sparc64.rs

1use arrayvec::ArrayVec;
2use rustc_abi::{
3    Align, BackendRepr, CanonAbi, FieldsShape, Float, HasDataLayout, Integer, Numeric, Primitive,
4    Reg, RegKind, Size, TyAbiInterface, TyAndLayout, Variants,
5};
6
7use crate::callconv::{ArgAbi, ArgAttribute, CastTarget, ComputeCallConv, Uniform};
8use crate::spec::{HasTargetSpec, Os};
9
10// NOTE: GCC and Clang/LLVM have disagreements that the ABI doesn't resolve, we match the
11// Clang/LLVM behavior in these cases.
12
13#[derive(#[automatically_derived]impl ::core::marker::Copy for DoubleWord { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for DoubleWord {
}
#[automatically_derived]impl ::core::clone::Clone for DoubleWord {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<[Word; 2]>;
        *self
    }
}Clone)]
14enum DoubleWord {
15    F64,
16    F128Start,
17    F128End,
18    Words([Word; 2]),
19}
20
21#[derive(#[automatically_derived]impl ::core::marker::Copy for Word { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Word {
}
#[automatically_derived]impl ::core::clone::Clone for Word {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone)]
22enum Word {
23    F32,
24    Integer,
25}
26
27fn classify<'a, Ty, C>(
28    cx: &C,
29    arg_layout: &TyAndLayout<'a, Ty>,
30    offset: Size,
31    double_words: &mut [DoubleWord; 4],
32) where
33    Ty: TyAbiInterface<'a, C> + Copy,
34    C: HasDataLayout,
35{
36    // If this function does not update the `double_words` array, the value will be passed via
37    // integer registers. The array is initialized with `DoubleWord::Words([Word::Integer; 2])`.
38
39    match arg_layout.backend_repr {
40        BackendRepr::Scalar(scalar) => match scalar.primitive() {
41            Primitive::Float(float) => {
42                if offset.is_aligned(Ord::min(float.align(cx), Align::EIGHT)) {
43                    let index = offset.bytes_usize() / 8;
44                    match float {
45                        Float::F128 => {
46                            double_words[index] = DoubleWord::F128Start;
47                            double_words[index + 1] = DoubleWord::F128End;
48                        }
49                        Float::F64 => {
50                            double_words[index] = DoubleWord::F64;
51                        }
52                        Float::F32 => match &mut double_words[index] {
53                            DoubleWord::Words(words) => {
54                                words[(offset.bytes_usize() % 8) / 4] = Word::F32;
55                            }
56                            _ => ::core::panicking::unreachable_default_msg()unreachable!(),
57                        },
58                        Float::F16 => {
59                            // Match LLVM by passing `f16` in integer registers.
60                        }
61                        Float::F16B => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("`f16b` unsupported on sparc64")));
}unreachable!("`f16b` unsupported on sparc64"),
62                        Float::X87F80 => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("`x87_f80` unsupported on sparc64")));
}unreachable!("`x87_f80` unsupported on sparc64"),
63                        Float::PpcF128 => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("`ppcf128` unsupported on sparc64")));
}unreachable!("`ppcf128` unsupported on sparc64"),
64                    }
65                } else {
66                    /* pass unaligned floats in integer registers */
67                }
68            }
69            Primitive::Bool | Primitive::Int(_, _) | Primitive::Pointer(_) => {
70                /* pass in integer registers */
71            }
72        },
73        BackendRepr::SimdVector { .. } => {}
74        BackendRepr::SimdScalableVector { .. } => {}
75        BackendRepr::ScalarPair { .. } | BackendRepr::Memory { .. } => match arg_layout.fields {
76            FieldsShape::Primitive => {
77                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("aggregates can\'t have `FieldsShape::Primitive`")));
}unreachable!("aggregates can't have `FieldsShape::Primitive`")
78            }
79            FieldsShape::Union(_) => {
80                if !arg_layout.is_zst() {
81                    if arg_layout.is_transparent() {
82                        let non_1zst_elem = arg_layout.non_1zst_field(cx).expect("not exactly one non-1-ZST field in non-ZST repr(transparent) union").1;
83                        classify(cx, &non_1zst_elem, offset, double_words);
84                    }
85                }
86            }
87            FieldsShape::Array { .. } => {}
88            FieldsShape::Arbitrary { .. } => match arg_layout.variants {
89                Variants::Multiple { .. } => {}
90                Variants::Single { .. } | Variants::Empty => {
91                    // Match Clang by ignoring whether a struct is packed and just considering
92                    // whether individual fields are aligned. GCC currently uses only integer
93                    // registers when passing packed structs.
94                    for i in arg_layout.fields.index_by_increasing_offset() {
95                        classify(
96                            cx,
97                            &arg_layout.field(cx, i),
98                            offset + arg_layout.fields.offset(i),
99                            double_words,
100                        );
101                    }
102                }
103            },
104        },
105    }
106}
107
108fn classify_arg<'a, Ty, C>(
109    cx: &C,
110    arg: &mut ArgAbi<'a, Ty>,
111    in_registers_max: Size,
112    total_double_word_count: &mut usize,
113) where
114    Ty: TyAbiInterface<'a, C> + Copy,
115    C: HasDataLayout,
116{
117    // 64-bit SPARC allocates argument stack space in 64-bit chunks (double words), some of which
118    // are promoted to registers based on their position on the stack.
119
120    // Keep track of the total number of double words used by arguments so far. This allows padding
121    // arguments to be inserted where necessary to ensure that 16-aligned arguments are passed in an
122    // aligned set of registers.
123
124    let pad = !total_double_word_count.is_multiple_of(2) && arg.layout.align.bytes() == 16;
125    // The number of double words used by this argument.
126    let double_word_count = arg.layout.size.bytes_usize().div_ceil(8);
127    // The number of double words before this argument, including any padding.
128    let start_double_word_count = *total_double_word_count + usize::from(pad);
129
130    if arg.layout.pass_indirectly_in_non_rustic_abis(cx) {
131        arg.make_indirect();
132        *total_double_word_count += 1;
133        return;
134    }
135
136    if !arg.layout.is_aggregate() {
137        arg.extend_integer_width_to(64);
138        *total_double_word_count = start_double_word_count + double_word_count;
139        return;
140    }
141
142    let total = arg.layout.size;
143    if total > in_registers_max {
144        arg.make_indirect();
145        *total_double_word_count += 1;
146        return;
147    }
148
149    *total_double_word_count = start_double_word_count + double_word_count;
150
151    // Compatible with GCC and Clang 24.
152    if let Some(Numeric::Int(Integer::I8 | Integer::I16, _)) = arg.layout.complex_number(cx) {
153        arg.cast_to(Reg { kind: RegKind::Integer, size: total });
154        return;
155    }
156
157    const ARGUMENT_REGISTERS: usize = 8;
158
159    let mut double_words = [DoubleWord::Words([Word::Integer; 2]); ARGUMENT_REGISTERS / 2];
160    classify(cx, &arg.layout, Size::ZERO, &mut double_words);
161
162    let mut regs = ArrayVec::new();
163    let mut attrs = ArgAttribute::empty();
164
165    for (index, double_word) in double_words.into_iter().enumerate() {
166        if arg.layout.size.bytes_usize() <= index * 8 {
167            break;
168        }
169        match double_word {
170            // `f128` must be aligned to be assigned a float register.
171            DoubleWord::F128Start if (start_double_word_count + index).is_multiple_of(2) => {
172                regs.push(Reg::f128());
173            }
174            DoubleWord::F128Start => {
175                // Clang currently handles this case nonsensically, always returning a packed
176                // `struct { long double x; }` in an aligned quad floating-point register even when
177                // the `long double` isn't aligned on the stack, which also makes all future
178                // arguments get passed in the wrong registers. This passes the `f128` in integer
179                // registers when it is unaligned, same as with `f32` and `f64`.
180                regs.push(Reg::i64());
181                regs.push(Reg::i64());
182            }
183            DoubleWord::F128End => {} // Already handled by `F128Start`
184            DoubleWord::F64 => regs.push(Reg::f64()),
185            DoubleWord::Words([Word::Integer, Word::Integer]) => regs.push(Reg::i64()),
186            DoubleWord::Words(words) => {
187                attrs |= ArgAttribute::InReg;
188                for word in words {
189                    match word {
190                        Word::F32 => regs.push(Reg::f32()),
191                        Word::Integer => regs.push(Reg::i32()),
192                    }
193                }
194            }
195        }
196    }
197
198    let cast_target = match regs.as_slice() {
199        // Just a single register is needed for this value.
200        [reg] => CastTarget::from(*reg),
201        _ => CastTarget::prefixed(regs, Uniform::new(Reg::i8(), Size::ZERO)),
202    };
203
204    arg.cast_to_and_pad_i32(cast_target.with_attrs(attrs.into()), u8::from(pad));
205}
206
207pub(crate) struct Sparc64CallConv {
208    passes_zsts: bool,
209    double_word_count: usize,
210}
211
212impl<'a, Ty, C> ComputeCallConv<'a, Ty, C> for Sparc64CallConv
213where
214    Ty: TyAbiInterface<'a, C> + Copy,
215    C: HasDataLayout + HasTargetSpec,
216{
217    fn new(cx: &C, _conv: CanonAbi, _c_variadic: bool) -> Self {
218        // sparc64-unknown-linux-{gnu,musl,uclibc} doesn't ignore ZSTs.
219        let passes_zsts = #[allow(non_exhaustive_omitted_patterns)] match cx.target_spec().os {
    Os::Linux => true,
    _ => false,
}matches!(cx.target_spec().os, Os::Linux);
220
221        Self { passes_zsts, double_word_count: 0 }
222    }
223
224    fn passes_zsts(&self) -> bool {
225        self.passes_zsts
226    }
227
228    fn compute_ret_abi(&mut self, cx: &C, ret: &mut ArgAbi<'a, Ty>) {
229        if !ret.is_ignore() && ret.layout.is_sized() {
230            // A return value of 32 bytes or smaller is passed via registers.
231            classify_arg(cx, ret, Size::from_bytes(32), &mut 0);
232        }
233    }
234
235    fn compute_arg_abi(&mut self, cx: &C, arg: &mut ArgAbi<'a, Ty>, _is_vararg: bool) {
236        if !arg.layout.is_sized() {
237            return;
238        }
239        if arg.is_ignore() {
240            arg.make_indirect_from_ignore();
241            self.double_word_count += 1;
242            return;
243        }
244        // An argument of 16 bytes or smaller is passed via registers.
245        classify_arg(cx, arg, Size::from_bytes(16), &mut self.double_word_count);
246    }
247}