rustc_target/callconv/
wasm.rs

1use rustc_abi::{BackendRepr, Float, HasDataLayout, Integer, Primitive, TyAbiInterface};
2
3use crate::callconv::{ArgAbi, FnAbi};
4
5fn unwrap_trivial_aggregate<'a, Ty, C>(cx: &C, val: &mut ArgAbi<'a, Ty>) -> bool
6where
7    Ty: TyAbiInterface<'a, C> + Copy,
8    C: HasDataLayout,
9{
10    if val.layout.is_aggregate() {
11        if let Some(unit) = val.layout.homogeneous_aggregate(cx).ok().and_then(|ha| ha.unit()) {
12            let size = val.layout.size;
13            // This size check also catches over-aligned scalars as `size` will be rounded up to a
14            // multiple of the alignment, and the default alignment of all scalar types on wasm
15            // equals their size.
16            if unit.size == size {
17                val.cast_to(unit);
18                return true;
19            }
20        }
21    }
22    false
23}
24
25fn classify_ret<'a, Ty, C>(cx: &C, ret: &mut ArgAbi<'a, Ty>)
26where
27    Ty: TyAbiInterface<'a, C> + Copy,
28    C: HasDataLayout,
29{
30    ret.extend_integer_width_to(32);
31    if ret.layout.is_aggregate() && !unwrap_trivial_aggregate(cx, ret) {
32        ret.make_indirect();
33    }
34
35    // `long double`, `__int128_t` and `__uint128_t` use an indirect return
36    if let BackendRepr::Scalar(scalar) = ret.layout.backend_repr {
37        match scalar.primitive() {
38            Primitive::Int(Integer::I128, _) | Primitive::Float(Float::F128) => {
39                ret.make_indirect();
40            }
41            _ => {}
42        }
43    }
44}
45
46fn classify_arg<'a, Ty, C>(cx: &C, arg: &mut ArgAbi<'a, Ty>)
47where
48    Ty: TyAbiInterface<'a, C> + Copy,
49    C: HasDataLayout,
50{
51    if !arg.layout.is_sized() {
52        // Not touching this...
53        return;
54    }
55    arg.extend_integer_width_to(32);
56    if arg.layout.is_aggregate() && !unwrap_trivial_aggregate(cx, arg) {
57        arg.make_indirect();
58    }
59}
60
61/// The purpose of this ABI is to match the C ABI (aka clang) exactly.
62pub(crate) fn compute_abi_info<'a, Ty, C>(cx: &C, fn_abi: &mut FnAbi<'a, Ty>)
63where
64    Ty: TyAbiInterface<'a, C> + Copy,
65    C: HasDataLayout,
66{
67    if !fn_abi.ret.is_ignore() {
68        classify_ret(cx, &mut fn_abi.ret);
69    }
70
71    for arg in fn_abi.args.iter_mut() {
72        if arg.is_ignore() {
73            continue;
74        }
75        classify_arg(cx, arg);
76    }
77}