Skip to content

Fix union field access by representing unions as structs #269

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 16 additions & 15 deletions crates/rustc_codegen_spirv/src/abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -718,21 +718,22 @@ fn trans_aggregate<'tcx>(cx: &CodegenCx<'tcx>, span: Span, ty: TyAndLayout<'tcx>
FieldsShape::Union(_) => {
assert!(!ty.is_unsized(), "{ty:#?}");

// Represent the `union` with its largest case, which should work
// for at least `MaybeUninit<T>` (which is between `T` and `()`),
// but also potentially some other ones as well.
// NOTE(eddyb) even if long-term this may become a byte array, that
// only works for "data types" and not "opaque handles" (images etc.).
let largest_case = (0..ty.fields.count())
.map(|i| ty.field(cx, i))
.max_by_key(|case| case.size);

if let Some(case) = largest_case {
assert_eq!(ty.size, case.size);
case.spirv_type(span, cx)
} else {
assert_eq!(ty.size, Size::ZERO);
create_zst(cx, span, ty)
// NOTE(eddyb) even if long-term this may become a byte array, that only
// works for "data types" and not "opaque handles" (images etc.).
match ty.fields.count() {
// For unions with no fields, represent as a zero-sized type.
0 => {
assert_eq!(ty.size, Size::ZERO);
create_zst(cx, span, ty)
}
// For unions with a single field, represent as the field itself.
1 => {
let field = ty.field(cx, 0);
assert_eq!(ty.size, field.size);
field.spirv_type(span, cx)
}
// For unions with multiple fields, represent as struct with all fields at offset 0
_ => trans_struct(cx, span, ty),
}
}
FieldsShape::Array { stride, count } => {
Expand Down
32 changes: 32 additions & 0 deletions tests/ui/lang/core/union_cast.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// build-pass

use spirv_std::spirv;

#[repr(C)]
#[derive(Clone, Copy)]
struct Data {
a: f32,
b: [f32; 3],
c: f32,
}

#[repr(C)]
union DataOrArray {
arr: [f32; 5],
str: Data,
}

impl DataOrArray {
fn arr(&self) -> [f32; 5] {
unsafe { self.arr }
}
fn new(arr: [f32; 5]) -> Self {
Self { arr }
}
}

#[spirv(fragment)]
pub fn main() {
let dora = DataOrArray::new([0.0, 0.0, 0.0, 0.0, 0.0]);
let _arr = dora.arr();
}