Skip to content

Commit 6236188

Browse files
zhassan-awstedinski
authored andcommitted
Fix for computing the minimum offset for an enum variant (rust-lang#468)
1 parent 145aa97 commit 6236188

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

compiler/rustc_codegen_llvm/src/gotoc/mir_to_goto/codegen/typ.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -990,7 +990,20 @@ impl<'tcx> GotocCtx<'tcx> {
990990
variants
991991
.iter()
992992
.filter_map(|lo| {
993-
if lo.fields.count() == 0 { None } else { Some(lo.fields.offset(0).bits_usize()) }
993+
if lo.fields.count() == 0 {
994+
None
995+
} else {
996+
// get the offset of the leftmost field, which is the one
997+
// with the least offset since we codegen fields in a struct
998+
// in the order of increasing offsets. Note that this is not
999+
// necessarily the 0th field since the compiler may reorder
1000+
// fields.
1001+
Some(
1002+
lo.fields
1003+
.offset(lo.fields.index_by_increasing_offset().nth(0).unwrap())
1004+
.bits_usize(),
1005+
)
1006+
}
9941007
})
9951008
.min()
9961009
}

src/test/cbmc/Enum/min_offset.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0 OR MIT
3+
4+
// Check that we properly handle structs for which the compiler reorders the
5+
// fields to optimize the layout. In such cases, the field with minimum offset
6+
// need not be the first field in the original struct (e.g. in "Foo" below, "b"
7+
// is the field with minimum offset even though "a" is the leftmost field in the
8+
// original struct).
9+
10+
enum E {
11+
Foo { a: u64, b: u16 },
12+
Bar,
13+
}
14+
15+
fn main() {
16+
let e = E::Foo { a: 32, b: 100 };
17+
match e {
18+
E::Foo { a, b } => {
19+
assert!(a == 32);
20+
assert!(b == 100);
21+
}
22+
E::Bar => assert!(false),
23+
}
24+
}

0 commit comments

Comments
 (0)