Skip to content

Commit a2f7f3c

Browse files
committed
ty_utils: lower tuples to ScalableVector repr
Instead of just using regular struct lowering for these types, which results in an incorrect ABI (e.g. returning indirectly), use `BackendRepr::ScalableVector` which will lower to the correct type and be passed in registers. This also enables some simplifications for generating alloca of scalable vectors and greater re-use of `scalable_vector_parts`. A LLVM codegen test demonstrating the changed IR this generates is included in the next commit alongside some intrinsics that make these tuples usable.
1 parent 5bbdeaa commit a2f7f3c

12 files changed

Lines changed: 161 additions & 69 deletions

File tree

compiler/rustc_abi/src/layout.rs

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ use tracing::{debug, trace};
1010

1111
use crate::{
1212
AbiAlign, Align, BackendRepr, FieldsShape, HasDataLayout, IndexSlice, IndexVec, Integer,
13-
LayoutData, Niche, NonZeroUsize, Primitive, ReprOptions, Scalar, Size, StructKind, TagEncoding,
14-
TargetDataLayout, Variants, WrappingRange,
13+
LayoutData, Niche, NonZeroUsize, NumScalableVectors, Primitive, ReprOptions, Scalar, Size,
14+
StructKind, TagEncoding, TargetDataLayout, Variants, WrappingRange,
1515
};
1616

1717
mod coroutine;
@@ -204,13 +204,19 @@ impl<Cx: HasDataLayout> LayoutCalculator<Cx> {
204204
&self,
205205
element: F,
206206
count: u64,
207+
number_of_vectors: NumScalableVectors,
207208
) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
208209
where
209210
FieldIdx: Idx,
210211
VariantIdx: Idx,
211212
F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
212213
{
213-
vector_type_layout(SimdVectorKind::Scalable, self.cx.data_layout(), element, count)
214+
vector_type_layout(
215+
SimdVectorKind::Scalable(number_of_vectors),
216+
self.cx.data_layout(),
217+
element,
218+
count,
219+
)
214220
}
215221

216222
pub fn simd_type<FieldIdx, VariantIdx, F>(
@@ -1526,7 +1532,7 @@ impl<Cx: HasDataLayout> LayoutCalculator<Cx> {
15261532

15271533
enum SimdVectorKind {
15281534
/// `#[rustc_scalable_vector]`
1529-
Scalable,
1535+
Scalable(NumScalableVectors),
15301536
/// `#[repr(simd, packed)]`
15311537
PackedFixed,
15321538
/// `#[repr(simd)]`
@@ -1559,9 +1565,10 @@ where
15591565
let size =
15601566
elt.size.checked_mul(count, dl).ok_or_else(|| LayoutCalculatorError::SizeOverflow)?;
15611567
let (repr, align) = match kind {
1562-
SimdVectorKind::Scalable => {
1563-
(BackendRepr::SimdScalableVector { element, count }, dl.llvmlike_vector_align(size))
1564-
}
1568+
SimdVectorKind::Scalable(number_of_vectors) => (
1569+
BackendRepr::SimdScalableVector { element, count, number_of_vectors },
1570+
dl.llvmlike_vector_align(size),
1571+
),
15651572
// Non-power-of-two vectors have padding up to the next power-of-two.
15661573
// If we're a packed repr, remove the padding while keeping the alignment as close
15671574
// to a vector as possible.

compiler/rustc_abi/src/lib.rs

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1696,6 +1696,28 @@ impl AddressSpace {
16961696
pub const ZERO: Self = AddressSpace(0);
16971697
}
16981698

1699+
/// How many scalable vectors are in a `BackendRepr::ScalableVector`?
1700+
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1701+
#[cfg_attr(feature = "nightly", derive(HashStable_Generic))]
1702+
pub struct NumScalableVectors(pub u8);
1703+
1704+
impl NumScalableVectors {
1705+
/// Returns a `NumScalableVector` for a non-tuple scalable vector (e.g. a single vector).
1706+
pub fn for_non_tuple() -> Self {
1707+
NumScalableVectors(1)
1708+
}
1709+
1710+
// Returns `NumScalableVectors` for values of two through eight, which are a valid number of
1711+
// fields for a tuple of scalable vectors to have. `1` is a valid value of `NumScalableVectors`
1712+
// but not for a tuple which would have a field count.
1713+
pub fn from_field_count(count: usize) -> Option<Self> {
1714+
match count {
1715+
2..8 => Some(NumScalableVectors(count as u8)),
1716+
_ => None,
1717+
}
1718+
}
1719+
}
1720+
16991721
/// The way we represent values to the backend
17001722
///
17011723
/// Previously this was conflated with the "ABI" a type is given, as in the platform-specific ABI.
@@ -1714,6 +1736,7 @@ pub enum BackendRepr {
17141736
SimdScalableVector {
17151737
element: Scalar,
17161738
count: u64,
1739+
number_of_vectors: NumScalableVectors,
17171740
},
17181741
SimdVector {
17191742
element: Scalar,
@@ -1820,8 +1843,12 @@ impl BackendRepr {
18201843
BackendRepr::SimdVector { element: element.to_union(), count }
18211844
}
18221845
BackendRepr::Memory { .. } => BackendRepr::Memory { sized: true },
1823-
BackendRepr::SimdScalableVector { element, count } => {
1824-
BackendRepr::SimdScalableVector { element: element.to_union(), count }
1846+
BackendRepr::SimdScalableVector { element, count, number_of_vectors } => {
1847+
BackendRepr::SimdScalableVector {
1848+
element: element.to_union(),
1849+
count,
1850+
number_of_vectors,
1851+
}
18251852
}
18261853
}
18271854
}
@@ -2161,7 +2188,7 @@ impl<FieldIdx: Idx, VariantIdx: Idx> LayoutData<FieldIdx, VariantIdx> {
21612188
}
21622189

21632190
/// Returns `true` if the size of the type is only known at runtime.
2164-
pub fn is_runtime_sized(&self) -> bool {
2191+
pub fn is_scalable_vector(&self) -> bool {
21652192
matches!(self.backend_repr, BackendRepr::SimdScalableVector { .. })
21662193
}
21672194

compiler/rustc_codegen_gcc/src/builder.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@ use rustc_data_structures::fx::FxHashSet;
2424
use rustc_middle::bug;
2525
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
2626
use rustc_middle::ty::layout::{
27-
FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTyCtxt, HasTypingEnv, LayoutError, LayoutOfHelpers,
27+
FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTyCtxt, HasTypingEnv, LayoutError,
28+
LayoutOfHelpers, TyAndLayout,
2829
};
2930
use rustc_middle::ty::{self, AtomicOrdering, Instance, Ty, TyCtxt};
3031
use rustc_span::Span;
@@ -943,8 +944,8 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> {
943944
.get_address(self.location)
944945
}
945946

946-
fn scalable_alloca(&mut self, _elt: u64, _align: Align, _element_ty: Ty<'_>) -> RValue<'gcc> {
947-
todo!()
947+
fn alloca_with_ty(&mut self, ty: TyAndLayout<'tcx>) -> RValue<'gcc> {
948+
self.alloca(ty.layout.size, ty.layout.align.abi)
948949
}
949950

950951
fn load(&mut self, pointee_ty: Type<'gcc>, ptr: RValue<'gcc>, align: Align) -> RValue<'gcc> {

compiler/rustc_codegen_llvm/src/builder.rs

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@ pub(crate) mod autodiff;
77
pub(crate) mod gpu_offload;
88

99
use libc::{c_char, c_uint};
10-
use rustc_abi as abi;
11-
use rustc_abi::{Align, Size, WrappingRange};
10+
use rustc_abi::{self as abi, Align, Size, WrappingRange};
1211
use rustc_codegen_ssa::MemFlags;
1312
use rustc_codegen_ssa::common::{IntPredicate, RealPredicate, SynchronizationScope, TypeKind};
1413
use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
@@ -616,21 +615,14 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
616615
}
617616
}
618617

619-
fn scalable_alloca(&mut self, elt: u64, align: Align, element_ty: Ty<'_>) -> Self::Value {
618+
fn alloca_with_ty(&mut self, layout: TyAndLayout<'tcx>) -> Self::Value {
620619
let mut bx = Builder::with_cx(self.cx);
621620
bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
622-
let llvm_ty = match element_ty.kind() {
623-
ty::Bool => bx.type_i1(),
624-
ty::Int(int_ty) => self.cx.type_int_from_ty(*int_ty),
625-
ty::Uint(uint_ty) => self.cx.type_uint_from_ty(*uint_ty),
626-
ty::Float(float_ty) => self.cx.type_float_from_ty(*float_ty),
627-
_ => unreachable!("scalable vectors can only contain a bool, int, uint or float"),
628-
};
621+
let scalable_vector_ty = layout.llvm_type(self.cx);
629622

630623
unsafe {
631-
let ty = llvm::LLVMScalableVectorType(llvm_ty, elt.try_into().unwrap());
632-
let alloca = llvm::LLVMBuildAlloca(&bx.llbuilder, ty, UNNAMED);
633-
llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
624+
let alloca = llvm::LLVMBuildAlloca(&bx.llbuilder, scalable_vector_ty, UNNAMED);
625+
llvm::LLVMSetAlignment(alloca, layout.align.abi.bytes() as c_uint);
634626
alloca
635627
}
636628
}

compiler/rustc_codegen_llvm/src/type_of.rs

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,54 @@ fn uncached_llvm_type<'a, 'tcx>(
2424
let element = layout.scalar_llvm_type_at(cx, element);
2525
return cx.type_vector(element, count);
2626
}
27-
BackendRepr::SimdScalableVector { ref element, count } => {
27+
BackendRepr::SimdScalableVector { ref element, count, number_of_vectors } => {
2828
let element = if element.is_bool() {
2929
cx.type_i1()
3030
} else {
3131
layout.scalar_llvm_type_at(cx, *element)
3232
};
3333

34-
return cx.type_scalable_vector(element, count);
34+
let vector_type = cx.type_scalable_vector(element, count);
35+
return match number_of_vectors.0 {
36+
1 => vector_type,
37+
2 => cx.type_struct(&[vector_type, vector_type], false),
38+
3 => cx.type_struct(&[vector_type, vector_type, vector_type], false),
39+
4 => cx.type_struct(&[vector_type, vector_type, vector_type, vector_type], false),
40+
5 => cx.type_struct(
41+
&[vector_type, vector_type, vector_type, vector_type, vector_type],
42+
false,
43+
),
44+
6 => cx.type_struct(
45+
&[vector_type, vector_type, vector_type, vector_type, vector_type, vector_type],
46+
false,
47+
),
48+
7 => cx.type_struct(
49+
&[
50+
vector_type,
51+
vector_type,
52+
vector_type,
53+
vector_type,
54+
vector_type,
55+
vector_type,
56+
vector_type,
57+
],
58+
false,
59+
),
60+
8 => cx.type_struct(
61+
&[
62+
vector_type,
63+
vector_type,
64+
vector_type,
65+
vector_type,
66+
vector_type,
67+
vector_type,
68+
vector_type,
69+
vector_type,
70+
],
71+
false,
72+
),
73+
_ => bug!("`#[rustc_scalable_vector]` tuple struct with too many fields"),
74+
};
3575
}
3676
BackendRepr::Memory { .. } | BackendRepr::ScalarPair(..) => {}
3777
}

compiler/rustc_codegen_ssa/src/mir/debuginfo.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -438,8 +438,8 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
438438
if operand.layout.ty.is_scalable_vector()
439439
&& bx.sess().target.arch == rustc_target::spec::Arch::AArch64
440440
{
441-
let (count, element_ty) =
442-
operand.layout.ty.scalable_vector_element_count_and_type(bx.tcx());
441+
let (count, element_ty, _) =
442+
operand.layout.ty.scalable_vector_parts(bx.tcx()).unwrap();
443443
// i.e. `<vscale x N x i1>` when `N != 16`
444444
if element_ty.is_bool() && count != 16 {
445445
return;

compiler/rustc_codegen_ssa/src/mir/place.rs

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::ops::Deref as _;
2+
13
use rustc_abi::{
24
Align, BackendRepr, FieldIdx, FieldsShape, Size, TagEncoding, VariantIdx, Variants,
35
};
@@ -109,8 +111,8 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> {
109111
bx: &mut Bx,
110112
layout: TyAndLayout<'tcx>,
111113
) -> Self {
112-
if layout.is_runtime_sized() {
113-
Self::alloca_runtime_sized(bx, layout)
114+
if layout.deref().is_scalable_vector() {
115+
Self::alloca_scalable(bx, layout)
114116
} else {
115117
Self::alloca_size(bx, layout.size, layout)
116118
}
@@ -151,16 +153,11 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> {
151153
}
152154
}
153155

154-
fn alloca_runtime_sized<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
156+
fn alloca_scalable<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
155157
bx: &mut Bx,
156158
layout: TyAndLayout<'tcx>,
157159
) -> Self {
158-
let (element_count, ty) = layout.ty.scalable_vector_element_count_and_type(bx.tcx());
159-
PlaceValue::new_sized(
160-
bx.scalable_alloca(element_count as u64, layout.align.abi, ty),
161-
layout.align.abi,
162-
)
163-
.with_type(layout)
160+
PlaceValue::new_sized(bx.alloca_with_ty(layout), layout.align.abi).with_type(layout)
164161
}
165162
}
166163

compiler/rustc_codegen_ssa/src/traits/builder.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ pub trait BuilderMethods<'a, 'tcx>:
235235
fn to_immediate_scalar(&mut self, val: Self::Value, scalar: Scalar) -> Self::Value;
236236

237237
fn alloca(&mut self, size: Size, align: Align) -> Self::Value;
238-
fn scalable_alloca(&mut self, elt: u64, align: Align, element_ty: Ty<'_>) -> Self::Value;
238+
fn alloca_with_ty(&mut self, layout: TyAndLayout<'tcx>) -> Self::Value;
239239

240240
fn load(&mut self, ty: Self::Type, ptr: Self::Value, align: Align) -> Self::Value;
241241
fn volatile_load(&mut self, ty: Self::Type, ptr: Self::Value) -> Self::Value;

compiler/rustc_middle/src/ty/sty.rs

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use std::debug_assert_matches;
77
use std::ops::{ControlFlow, Range};
88

99
use hir::def::{CtorKind, DefKind};
10-
use rustc_abi::{FIRST_VARIANT, FieldIdx, ScalableElt, VariantIdx};
10+
use rustc_abi::{FIRST_VARIANT, FieldIdx, NumScalableVectors, ScalableElt, VariantIdx};
1111
use rustc_errors::{ErrorGuaranteed, MultiSpan};
1212
use rustc_hir as hir;
1313
use rustc_hir::LangItem;
@@ -1261,17 +1261,27 @@ impl<'tcx> Ty<'tcx> {
12611261
}
12621262
}
12631263

1264-
pub fn scalable_vector_element_count_and_type(self, tcx: TyCtxt<'tcx>) -> (u16, Ty<'tcx>) {
1264+
pub fn scalable_vector_parts(
1265+
self,
1266+
tcx: TyCtxt<'tcx>,
1267+
) -> Option<(u16, Ty<'tcx>, NumScalableVectors)> {
12651268
let Adt(def, args) = self.kind() else {
1266-
bug!("`scalable_vector_size_and_type` called on invalid type")
1269+
return None;
12671270
};
1268-
let Some(ScalableElt::ElementCount(element_count)) = def.repr().scalable else {
1269-
bug!("`scalable_vector_size_and_type` called on non-scalable vector type");
1271+
let (num_vectors, vec_def) = match def.repr().scalable? {
1272+
ScalableElt::ElementCount(_) => (NumScalableVectors::for_non_tuple(), *def),
1273+
ScalableElt::Container => (
1274+
NumScalableVectors::from_field_count(def.non_enum_variant().fields.len())?,
1275+
def.non_enum_variant().fields[FieldIdx::ZERO].ty(tcx, args).ty_adt_def()?,
1276+
),
12701277
};
1271-
let variant = def.non_enum_variant();
1278+
let Some(ScalableElt::ElementCount(element_count)) = vec_def.repr().scalable else {
1279+
return None;
1280+
};
1281+
let variant = vec_def.non_enum_variant();
12721282
assert_eq!(variant.fields.len(), 1);
12731283
let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1274-
(element_count, field_ty)
1284+
Some((element_count, field_ty, num_vectors))
12751285
}
12761286

12771287
pub fn simd_size_and_type(self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) {

compiler/rustc_public/src/abi.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,10 @@ pub enum TagEncoding {
232232
},
233233
}
234234

235+
/// How many scalable vectors are in a `ValueAbi::ScalableVector`?
236+
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
237+
pub struct NumScalableVectors(pub(crate) u8);
238+
235239
/// Describes how values of the type are passed by target ABIs,
236240
/// in terms of categories of C types there are ABI rules for.
237241
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
@@ -245,6 +249,7 @@ pub enum ValueAbi {
245249
ScalableVector {
246250
element: Scalar,
247251
count: u64,
252+
number_of_vectors: NumScalableVectors,
248253
},
249254
Aggregate {
250255
/// If true, the size is exact, otherwise it's only a lower bound.

0 commit comments

Comments
 (0)