Skip to main content

rustc_target/callconv/
sparc64.rs

1use arrayvec::ArrayVec;
2use rustc_abi::{
3    Align, BackendRepr, FieldsShape, Float, HasDataLayout, Integer, Numeric, Primitive, Reg,
4    RegKind, Size, TyAbiInterface, TyAndLayout, Variants,
5};
6
7use crate::callconv::{ArgAbi, ArgAttribute, CastTarget, FnAbi, 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]
    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]
    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::panic("internal error: entered unreachable code")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                    }
63                } else {
64                    /* pass unaligned floats in integer registers */
65                }
66            }
67            Primitive::Int(_, _) | Primitive::Pointer(_) => { /* pass in integer registers */ }
68        },
69        BackendRepr::SimdVector { .. } => {}
70        BackendRepr::SimdScalableVector { .. } => {}
71        BackendRepr::ScalarPair { .. } | BackendRepr::Memory { .. } => match arg_layout.fields {
72            FieldsShape::Primitive => {
73                {
    ::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`")
74            }
75            FieldsShape::Union(_) => {
76                if !arg_layout.is_zst() {
77                    if arg_layout.is_transparent() {
78                        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;
79                        classify(cx, &non_1zst_elem, offset, double_words);
80                    }
81                }
82            }
83            FieldsShape::Array { .. } => {}
84            FieldsShape::Arbitrary { .. } => match arg_layout.variants {
85                Variants::Multiple { .. } => {}
86                Variants::Single { .. } | Variants::Empty => {
87                    // Match Clang by ignoring whether a struct is packed and just considering
88                    // whether individual fields are aligned. GCC currently uses only integer
89                    // registers when passing packed structs.
90                    for i in arg_layout.fields.index_by_increasing_offset() {
91                        classify(
92                            cx,
93                            &arg_layout.field(cx, i),
94                            offset + arg_layout.fields.offset(i),
95                            double_words,
96                        );
97                    }
98                }
99            },
100        },
101    }
102}
103
104fn classify_arg<'a, Ty, C>(
105    cx: &C,
106    arg: &mut ArgAbi<'a, Ty>,
107    in_registers_max: Size,
108    total_double_word_count: &mut usize,
109) where
110    Ty: TyAbiInterface<'a, C> + Copy,
111    C: HasDataLayout,
112{
113    // 64-bit SPARC allocates argument stack space in 64-bit chunks (double words), some of which
114    // are promoted to registers based on their position on the stack.
115
116    // Keep track of the total number of double words used by arguments so far. This allows padding
117    // arguments to be inserted where necessary to ensure that 16-aligned arguments are passed in an
118    // aligned set of registers.
119
120    let pad = !total_double_word_count.is_multiple_of(2) && arg.layout.align.abi.bytes() == 16;
121    // The number of double words used by this argument.
122    let double_word_count = arg.layout.size.bytes_usize().div_ceil(8);
123    // The number of double words before this argument, including any padding.
124    let start_double_word_count = *total_double_word_count + usize::from(pad);
125
126    if arg.layout.pass_indirectly_in_non_rustic_abis(cx) {
127        arg.make_indirect();
128        *total_double_word_count += 1;
129        return;
130    }
131
132    if !arg.layout.is_aggregate() {
133        arg.extend_integer_width_to(64);
134        *total_double_word_count = start_double_word_count + double_word_count;
135        return;
136    }
137
138    let total = arg.layout.size;
139    if total > in_registers_max {
140        arg.make_indirect();
141        *total_double_word_count += 1;
142        return;
143    }
144
145    *total_double_word_count = start_double_word_count + double_word_count;
146
147    // Compatible with GCC and Clang 24.
148    if let Some(Numeric::Int(Integer::I8 | Integer::I16, _)) = arg.layout.complex_number(cx) {
149        arg.cast_to(Reg { kind: RegKind::Integer, size: total });
150        return;
151    }
152
153    const ARGUMENT_REGISTERS: usize = 8;
154
155    let mut double_words = [DoubleWord::Words([Word::Integer; 2]); ARGUMENT_REGISTERS / 2];
156    classify(cx, &arg.layout, Size::ZERO, &mut double_words);
157
158    let mut regs = ArrayVec::new();
159    let mut attrs = ArgAttribute::empty();
160
161    for (index, double_word) in double_words.into_iter().enumerate() {
162        if arg.layout.size.bytes_usize() <= index * 8 {
163            break;
164        }
165        match double_word {
166            // `f128` must be aligned to be assigned a float register.
167            DoubleWord::F128Start if (start_double_word_count + index).is_multiple_of(2) => {
168                regs.push(Reg::f128());
169            }
170            DoubleWord::F128Start => {
171                // Clang currently handles this case nonsensically, always returning a packed
172                // `struct { long double x; }` in an aligned quad floating-point register even when
173                // the `long double` isn't aligned on the stack, which also makes all future
174                // arguments get passed in the wrong registers. This passes the `f128` in integer
175                // registers when it is unaligned, same as with `f32` and `f64`.
176                regs.push(Reg::i64());
177                regs.push(Reg::i64());
178            }
179            DoubleWord::F128End => {} // Already handled by `F128Start`
180            DoubleWord::F64 => regs.push(Reg::f64()),
181            DoubleWord::Words([Word::Integer, Word::Integer]) => regs.push(Reg::i64()),
182            DoubleWord::Words(words) => {
183                attrs |= ArgAttribute::InReg;
184                for word in words {
185                    match word {
186                        Word::F32 => regs.push(Reg::f32()),
187                        Word::Integer => regs.push(Reg::i32()),
188                    }
189                }
190            }
191        }
192    }
193
194    let cast_target = match regs.as_slice() {
195        // Just a single register is needed for this value.
196        [reg] => CastTarget::from(*reg),
197        _ => CastTarget::prefixed(regs, Uniform::new(Reg::i8(), Size::ZERO)),
198    };
199
200    arg.cast_to_and_pad_i32(cast_target.with_attrs(attrs.into()), u8::from(pad));
201}
202
203pub(crate) fn compute_abi_info<'a, Ty, C>(cx: &C, fn_abi: &mut FnAbi<'a, Ty>)
204where
205    Ty: TyAbiInterface<'a, C> + Copy,
206    C: HasDataLayout + HasTargetSpec,
207{
208    if !fn_abi.ret.is_ignore() && fn_abi.ret.layout.is_sized() {
209        // A return value of 32 bytes or smaller is passed via registers.
210        classify_arg(cx, &mut fn_abi.ret, Size::from_bytes(32), &mut 0);
211    }
212
213    // sparc64-unknown-linux-{gnu,musl,uclibc} doesn't ignore ZSTs.
214    let passes_zsts = #[allow(non_exhaustive_omitted_patterns)] match cx.target_spec().os {
    Os::Linux => true,
    _ => false,
}matches!(cx.target_spec().os, Os::Linux);
215
216    let mut double_word_count = 0;
217    for arg in fn_abi.args.iter_mut() {
218        if !arg.layout.is_sized() {
219            continue;
220        }
221        if arg.is_ignore() {
222            if passes_zsts && arg.layout.is_zst() {
223                arg.make_indirect_from_ignore();
224                double_word_count += 1;
225            }
226            continue;
227        }
228        // An argument of 16 bytes or smaller is passed via registers.
229        classify_arg(cx, arg, Size::from_bytes(16), &mut double_word_count);
230    }
231}