Skip to main content

rustc_target/callconv/
riscv.rs

1// Reference: RISC-V ELF psABI specification
2// https://github.com/riscv/riscv-elf-psabi-doc
3//
4// Reference: Clang RISC-V ELF psABI lowering code
5// https://github.com/llvm/llvm-project/blob/8e780252a7284be45cf1ba224cabd884847e8e92/clang/lib/CodeGen/TargetInfo.cpp#L9311-L9773
6
7use rustc_abi::{
8    BackendRepr, CanonAbi, FieldsShape, HasDataLayout, Primitive, Reg, RegKind, Size,
9    TyAbiInterface, TyAndLayout, Variants,
10};
11
12use crate::callconv::{
13    ArgAbi, ArgExtension, CastTarget, ComputeCallConv, FnAbi, PassMode, Uniform,
14};
15use crate::spec::{HasTargetSpec, LlvmAbi};
16
17#[derive(#[automatically_derived]impl ::core::marker::Copy for RegPassKind { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for RegPassKind {
}
#[automatically_derived]impl ::core::clone::Clone for RegPassKind {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Size>;
        let _: ::core::clone::AssertParamIsClone<Reg>;
        *self
    }
}Clone)]
18enum RegPassKind {
19    Float { offset_from_start: Size, ty: Reg },
20    Integer { offset_from_start: Size, ty: Reg },
21    Unknown,
22}
23
24#[derive(#[automatically_derived]impl ::core::marker::Copy for FloatConv { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for FloatConv {
}
#[automatically_derived]impl ::core::clone::Clone for FloatConv {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Reg>;
        let _: ::core::clone::AssertParamIsClone<Size>;
        *self
    }
}Clone)]
25enum FloatConv {
26    FloatPair { first_ty: Reg, second_ty_offset_from_start: Size, second_ty: Reg },
27    Float(Reg),
28    MixedPair { first_ty: Reg, second_ty_offset_from_start: Size, second_ty: Reg },
29}
30
31#[derive(#[automatically_derived]impl ::core::marker::Copy for CannotUseFpConv { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for CannotUseFpConv {
}
#[automatically_derived]impl ::core::clone::Clone for CannotUseFpConv {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone)]
32struct CannotUseFpConv;
33
34fn is_riscv_aggregate<Ty>(arg: &ArgAbi<'_, Ty>) -> bool {
35    match arg.layout.backend_repr {
36        BackendRepr::SimdVector { .. } => true,
37        _ => arg.layout.is_aggregate(),
38    }
39}
40
41fn should_use_fp_conv_helper<'a, Ty, C>(
42    cx: &C,
43    arg_layout: &TyAndLayout<'a, Ty>,
44    xlen: u64,
45    flen: u64,
46    field1_kind: &mut RegPassKind,
47    field2_kind: &mut RegPassKind,
48    offset_from_start: Size,
49) -> Result<(), CannotUseFpConv>
50where
51    Ty: TyAbiInterface<'a, C> + Copy,
52{
53    match arg_layout.backend_repr {
54        BackendRepr::Scalar(scalar) => match scalar.primitive() {
55            Primitive::Bool | Primitive::Int(..) | Primitive::Pointer(_) => {
56                if arg_layout.size.bits() > xlen {
57                    return Err(CannotUseFpConv);
58                }
59                match (*field1_kind, *field2_kind) {
60                    (RegPassKind::Unknown, _) => {
61                        *field1_kind = RegPassKind::Integer {
62                            offset_from_start,
63                            ty: Reg { kind: RegKind::Integer, size: arg_layout.size },
64                        };
65                    }
66                    (RegPassKind::Float { .. }, RegPassKind::Unknown) => {
67                        *field2_kind = RegPassKind::Integer {
68                            offset_from_start,
69                            ty: Reg { kind: RegKind::Integer, size: arg_layout.size },
70                        };
71                    }
72                    _ => return Err(CannotUseFpConv),
73                }
74            }
75            Primitive::Float(_) => {
76                if arg_layout.size.bits() > flen {
77                    return Err(CannotUseFpConv);
78                }
79                match (*field1_kind, *field2_kind) {
80                    (RegPassKind::Unknown, _) => {
81                        *field1_kind = RegPassKind::Float {
82                            offset_from_start,
83                            ty: Reg { kind: RegKind::Float, size: arg_layout.size },
84                        };
85                    }
86                    (_, RegPassKind::Unknown) => {
87                        *field2_kind = RegPassKind::Float {
88                            offset_from_start,
89                            ty: Reg { kind: RegKind::Float, size: arg_layout.size },
90                        };
91                    }
92                    _ => return Err(CannotUseFpConv),
93                }
94            }
95        },
96        BackendRepr::SimdVector { .. } | BackendRepr::SimdScalableVector { .. } => {
97            return Err(CannotUseFpConv);
98        }
99        BackendRepr::ScalarPair { .. } | BackendRepr::Memory { .. } => match arg_layout.fields {
100            FieldsShape::Primitive => {
101                {
    ::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`")
102            }
103            FieldsShape::Union(_) => {
104                if !arg_layout.is_zst() {
105                    if arg_layout.is_transparent() {
106                        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;
107                        return should_use_fp_conv_helper(
108                            cx,
109                            &non_1zst_elem,
110                            xlen,
111                            flen,
112                            field1_kind,
113                            field2_kind,
114                            offset_from_start,
115                        );
116                    }
117                    return Err(CannotUseFpConv);
118                }
119            }
120            FieldsShape::Array { count, .. } => {
121                for i in 0..count {
122                    let elem_layout = arg_layout.field(cx, 0);
123                    should_use_fp_conv_helper(
124                        cx,
125                        &elem_layout,
126                        xlen,
127                        flen,
128                        field1_kind,
129                        field2_kind,
130                        offset_from_start + elem_layout.size * i,
131                    )?;
132                }
133            }
134            FieldsShape::Arbitrary { .. } => {
135                match arg_layout.variants {
136                    Variants::Multiple { .. } => return Err(CannotUseFpConv),
137                    Variants::Single { .. } | Variants::Empty => (),
138                }
139                for i in arg_layout.fields.index_by_increasing_offset() {
140                    let field = arg_layout.field(cx, i);
141                    should_use_fp_conv_helper(
142                        cx,
143                        &field,
144                        xlen,
145                        flen,
146                        field1_kind,
147                        field2_kind,
148                        offset_from_start + arg_layout.fields.offset(i),
149                    )?;
150                }
151            }
152        },
153    }
154    Ok(())
155}
156
157fn should_use_fp_conv<'a, Ty, C>(
158    cx: &C,
159    arg: &TyAndLayout<'a, Ty>,
160    xlen: u64,
161    flen: u64,
162) -> Option<FloatConv>
163where
164    Ty: TyAbiInterface<'a, C> + Copy,
165{
166    let mut field1_kind = RegPassKind::Unknown;
167    let mut field2_kind = RegPassKind::Unknown;
168    if should_use_fp_conv_helper(
169        cx,
170        arg,
171        xlen,
172        flen,
173        &mut field1_kind,
174        &mut field2_kind,
175        Size::ZERO,
176    )
177    .is_err()
178    {
179        return None;
180    }
181    match (field1_kind, field2_kind) {
182        (
183            RegPassKind::Integer { offset_from_start, .. }
184            | RegPassKind::Float { offset_from_start, .. },
185            _,
186        ) if offset_from_start != Size::ZERO => {
187            {
    ::core::panicking::panic_fmt(format_args!("type {0:?} has a first field with non-zero offset {1:?}",
            arg.ty, offset_from_start));
}panic!("type {:?} has a first field with non-zero offset {offset_from_start:?}", arg.ty)
188        }
189        (
190            RegPassKind::Integer { ty: first_ty, .. },
191            RegPassKind::Float { offset_from_start, ty: second_ty },
192        ) => Some(FloatConv::MixedPair {
193            first_ty,
194            second_ty_offset_from_start: offset_from_start,
195            second_ty,
196        }),
197        (
198            RegPassKind::Float { ty: first_ty, .. },
199            RegPassKind::Integer { offset_from_start, ty: second_ty },
200        ) => Some(FloatConv::MixedPair {
201            first_ty,
202            second_ty_offset_from_start: offset_from_start,
203            second_ty,
204        }),
205        (
206            RegPassKind::Float { ty: first_ty, .. },
207            RegPassKind::Float { offset_from_start, ty: second_ty },
208        ) => Some(FloatConv::FloatPair {
209            first_ty,
210            second_ty_offset_from_start: offset_from_start,
211            second_ty,
212        }),
213        (RegPassKind::Float { ty, .. }, RegPassKind::Unknown) => Some(FloatConv::Float(ty)),
214        _ => None,
215    }
216}
217
218fn classify_ret<'a, Ty, C>(cx: &C, arg: &mut ArgAbi<'a, Ty>, xlen: u64, flen: u64) -> bool
219where
220    Ty: TyAbiInterface<'a, C> + Copy,
221{
222    if !arg.layout.is_sized() {
223        // Not touching this...
224        return false; // I guess? return value of this function is not documented
225    }
226    if let Some(conv) = should_use_fp_conv(cx, &arg.layout, xlen, flen) {
227        match conv {
228            FloatConv::Float(f) => {
229                arg.cast_to(f);
230            }
231            FloatConv::FloatPair { first_ty, second_ty_offset_from_start, second_ty } => {
232                arg.cast_to(CastTarget::offset_pair(
233                    first_ty,
234                    second_ty_offset_from_start,
235                    second_ty,
236                ));
237            }
238            FloatConv::MixedPair { first_ty, second_ty_offset_from_start, second_ty } => {
239                arg.cast_to(CastTarget::offset_pair(
240                    first_ty,
241                    second_ty_offset_from_start,
242                    second_ty,
243                ));
244            }
245        }
246        return false;
247    }
248
249    let total = arg.layout.size;
250
251    // "Scalars wider than 2✕XLEN are passed by reference and are replaced in
252    // the argument list with the address."
253    // "Aggregates larger than 2✕XLEN bits are passed by reference and are
254    // replaced in the argument list with the address, as are C++ aggregates
255    // with nontrivial copy constructors, destructors, or vtables."
256    if total.bits() > 2 * xlen {
257        // We rely on the LLVM backend lowering code to lower passing a scalar larger than 2*XLEN.
258        if is_riscv_aggregate(arg) {
259            arg.make_indirect();
260        }
261        return true;
262    }
263
264    let xlen_reg = match xlen {
265        32 => Reg::i32(),
266        64 => Reg::i64(),
267        _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Unsupported XLEN: {0}", xlen)));
}unreachable!("Unsupported XLEN: {}", xlen),
268    };
269    if is_riscv_aggregate(arg) {
270        if total.bits() <= xlen {
271            arg.cast_to(xlen_reg);
272        } else {
273            arg.cast_to(Uniform::new(xlen_reg, Size::from_bits(xlen * 2)));
274        }
275        return false;
276    }
277
278    // "When passed in registers, scalars narrower than XLEN bits are widened
279    // according to the sign of their type up to 32 bits, then sign-extended to
280    // XLEN bits."
281    extend_integer_width(arg, xlen);
282    false
283}
284
285fn classify_arg<'a, Ty, C>(
286    cx: &C,
287    arg: &mut ArgAbi<'a, Ty>,
288    xlen: u64,
289    flen: u64,
290    is_vararg: bool,
291    avail_gprs: &mut u64,
292    avail_fprs: &mut u64,
293) where
294    Ty: TyAbiInterface<'a, C> + Copy,
295{
296    if !arg.layout.is_sized() {
297        // FIXME: Update avail_gprs?
298        // Not touching this...
299        return;
300    }
301    if arg.layout.pass_indirectly_in_non_rustic_abis(cx) {
302        arg.make_indirect();
303        *avail_gprs = (*avail_gprs).saturating_sub(1);
304        return;
305    }
306    if !is_vararg {
307        match should_use_fp_conv(cx, &arg.layout, xlen, flen) {
308            Some(FloatConv::Float(f)) if *avail_fprs >= 1 => {
309                *avail_fprs -= 1;
310                arg.cast_to(f);
311                return;
312            }
313            Some(FloatConv::FloatPair { first_ty, second_ty_offset_from_start, second_ty })
314                if *avail_fprs >= 2 =>
315            {
316                *avail_fprs -= 2;
317                arg.cast_to(CastTarget::offset_pair(
318                    first_ty,
319                    second_ty_offset_from_start,
320                    second_ty,
321                ));
322                return;
323            }
324            Some(FloatConv::MixedPair { first_ty, second_ty_offset_from_start, second_ty })
325                if *avail_fprs >= 1 && *avail_gprs >= 1 =>
326            {
327                *avail_gprs -= 1;
328                *avail_fprs -= 1;
329                arg.cast_to(CastTarget::offset_pair(
330                    first_ty,
331                    second_ty_offset_from_start,
332                    second_ty,
333                ));
334                return;
335            }
336            _ => (),
337        }
338    }
339
340    let total = arg.layout.size;
341    let align = arg.layout.align.bits();
342
343    // "Scalars wider than 2✕XLEN are passed by reference and are replaced in
344    // the argument list with the address."
345    // "Aggregates larger than 2✕XLEN bits are passed by reference and are
346    // replaced in the argument list with the address, as are C++ aggregates
347    // with nontrivial copy constructors, destructors, or vtables."
348    if total.bits() > 2 * xlen {
349        // We rely on the LLVM backend lowering code to lower passing a scalar larger than 2*XLEN.
350        if is_riscv_aggregate(arg) {
351            arg.make_indirect();
352        }
353        if *avail_gprs >= 1 {
354            *avail_gprs -= 1;
355        }
356        return;
357    }
358
359    let double_xlen_reg = match xlen {
360        32 => Reg::i64(),
361        64 => Reg::i128(),
362        _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Unsupported XLEN: {0}", xlen)));
}unreachable!("Unsupported XLEN: {}", xlen),
363    };
364
365    let xlen_reg = match xlen {
366        32 => Reg::i32(),
367        64 => Reg::i64(),
368        _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Unsupported XLEN: {0}", xlen)));
}unreachable!("Unsupported XLEN: {}", xlen),
369    };
370
371    if total.bits() > xlen {
372        let align_regs = align > xlen;
373        if is_riscv_aggregate(arg) {
374            arg.cast_to(Uniform::new(
375                if align_regs { double_xlen_reg } else { xlen_reg },
376                Size::from_bits(xlen * 2),
377            ));
378        }
379        if align_regs && is_vararg {
380            *avail_gprs -= *avail_gprs % 2;
381        }
382        if *avail_gprs >= 2 {
383            *avail_gprs -= 2;
384        } else {
385            *avail_gprs = 0;
386        }
387        return;
388    } else if is_riscv_aggregate(arg) {
389        arg.cast_to(xlen_reg);
390        if *avail_gprs >= 1 {
391            *avail_gprs -= 1;
392        }
393        return;
394    }
395
396    // "When passed in registers, scalars narrower than XLEN bits are widened
397    // according to the sign of their type up to 32 bits, then sign-extended to
398    // XLEN bits."
399    if *avail_gprs >= 1 {
400        extend_integer_width(arg, xlen);
401        *avail_gprs -= 1;
402    }
403}
404
405fn extend_integer_width<Ty>(arg: &mut ArgAbi<'_, Ty>, xlen: u64) {
406    if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr
407        && let Primitive::Int(i, _) = scalar.primitive()
408        && i.size().bits() == 32
409        && xlen > 32
410        && let PassMode::Direct(ref mut attrs) = arg.mode
411    {
412        attrs.ext(ArgExtension::Sext);
413        return;
414    }
415
416    arg.extend_integer_width_to(xlen);
417}
418
419pub(crate) struct RiscvCallConv {
420    flen: u64,
421    xlen: u64,
422    avail_gprs: u64,
423    avail_fprs: u64,
424}
425
426impl<'a, Ty, C> ComputeCallConv<'a, Ty, C> for RiscvCallConv
427where
428    Ty: TyAbiInterface<'a, C> + Copy,
429    C: HasDataLayout + HasTargetSpec,
430{
431    fn new(cx: &C, _conv: CanonAbi, _c_variadic: bool) -> Self {
432        let flen = match &cx.target_spec().llvm_abiname {
433            LlvmAbi::Ilp32f | LlvmAbi::Lp64f => 32,
434            LlvmAbi::Ilp32d | LlvmAbi::Lp64d => 64,
435            _ => 0,
436        };
437        let xlen = cx.data_layout().pointer_size().bits();
438
439        let avail_gprs = 8;
440        let avail_fprs = 8;
441
442        Self { flen, xlen, avail_gprs, avail_fprs }
443    }
444
445    fn compute_ret_abi(&mut self, cx: &C, ret: &mut ArgAbi<'a, Ty>) {
446        if classify_ret(cx, ret, self.xlen, self.flen) {
447            self.avail_gprs -= 1;
448        }
449    }
450
451    fn compute_arg_abi(&mut self, cx: &C, arg: &mut ArgAbi<'a, Ty>, is_vararg: bool) {
452        classify_arg(
453            cx,
454            arg,
455            self.xlen,
456            self.flen,
457            is_vararg,
458            &mut self.avail_gprs,
459            &mut self.avail_fprs,
460        );
461    }
462}
463
464pub(crate) fn compute_rust_abi_info<'a, Ty, C>(cx: &C, fn_abi: &mut FnAbi<'a, Ty>)
465where
466    Ty: TyAbiInterface<'a, C> + Copy,
467    C: HasDataLayout + HasTargetSpec,
468{
469    let xlen = cx.data_layout().pointer_size().bits();
470
471    for arg in fn_abi.args.iter_mut() {
472        if arg.is_ignore() {
473            continue;
474        }
475
476        // LLVM integers types do not differentiate between signed or unsigned integers.
477        // Some RISC-V instructions do not have a `.w` suffix version, they use all the
478        // XLEN bits. By explicitly setting the `signext` or `zeroext` attribute
479        // according to signedness to avoid unnecessary integer extending instructions.
480        //
481        // See https://github.com/rust-lang/rust/issues/114508 for details.
482        extend_integer_width(arg, xlen);
483    }
484}