Description
This is about enums like the following:
enum E1 { A, B(!) }
enum E2 { A, B(!), C(i32, !) }
The first interesting point is that E1
actually will not get any space assigned for storing a discriminant, it has size 0. The algorithm that assigns discriminants entirely skips B
. In Miri we had to make SetDiscriminant throw UB early if the requested variant to set is uninhabited, since otherwise we get ICEs later.
However, E2
has size 8, even though there is only a single valid variant and that variant has size 0. I think we currently always provide storage for all fields of all variants, even if they are uninhabited. This is useful because in theory it lets us compile E2::C(f(), panic!())
into something that does in-place initialization:
let val: E2;
val.C.0 = f();
panic!();
SetDiscriminant(val, C); // this would be UB but we don't get here
(AFAIK we currently don't actually do that, we introduce temporaries instead.)
For structs we have decided that we will always have storage for all fields, and this is unavoidable since safe code can partially initialize a struct. However, safe code cannot partially initialize an enum, so we could soundly decide that E2
has size 0. We have to decide between smaller enums and in-place initialization for arbitrary enums. (We can of course have small enums and then have an analysis that uses in-place initialization where possible -- but in generic MIR, it might not be possible to tell whether the variant we are about to initialize is inhabited.)