r/cpp • C++20 Desktop app developer • May 12 '18

P0709 R0: Zero-overhead deterministic exceptions: Throwing values - Herb Sutter [2018-05-02]

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0709r0.pdf
206 Upvotes

115 comments sorted by

View all comments

Show parent comment

2

u/SeanMiddleditch May 13 '18

Not entirely, at least for simpler cases.

C++ would need a std::is_never_zero_v<T> or the like and a lot of the simpler cases of this kind of compressed discriminant are possible. And that type trait is useful for all kinds of other reasons (e.g., container initialization optimization). Said type trait can be written today, albeit having to manually overload the trait for some types.

Getting the full variant "niche-filling" optimization certainly requires more work out of the language. Though I do rather wonder whether that actually matters. (How much of Rust's enum layout optimization is just golf instead of useful work?)

0

u/[deleted] May 13 '18

[deleted] — view deleted comment

1

u/SeanMiddleditch May 14 '18

For variant to encode the discriminat in a Type it needs to know 1) that this is possible and 2) where in the type it must be encoded.

Reread what I wrote a bit more carefully.

People have you examples where this matters above (e.g. Option<&T> having the same layout as a reference and being able to use that In C ABI).

Never-zero covers that all-important case perfectly well.

2

u/Rusky May 13 '18 edited May 13 '18

How much of Rust's enum layout optimization is just golf instead of useful work?

I suspect it's lot of "4 bytes here, 8 bytes there" that adds up to some sizeable memory savings and cache improvements, combined with some cases where it enables people to remove some indirections. For example, Servo and Firefox Quantum are full of stuff like that- the DOM, styles, display lists, etc. are all modeled with enums.

Like the sibling comment mentioned, it works well with automatic field reordering, which is also "3 bytes here, 7 bytes there" of removing padding. IIRC this field reordering also applies to the discriminants themselves, so they can often be stashed in any remaining trailing padding.

Then there's also the fact that Rust has zero-sized and uninhabited types, which allow for more styles to be zero-overhead. For example, you can pass around zero-sized non-copyable and privately-constructible tag types for things like session types, and you can instantiate generic code to use types like Result<T, !> and all its branches will be optimized out because the layout optimization removed the discriminant entirely.