rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
99.11k stars 12.8k forks source link

Unoptimized code for big enums (>127 values) #82699

Open mjdr opened 3 years ago

mjdr commented 3 years ago

I tring to write riscv linux emulator in rust. I have enum Instruction with 203 values.

For small enums (< 128 values) rustc generates optimized code. 'Small' enum on compiler explorer

But, the moment I add one more value it defaults to standard behavior with table of offsets 'Big' enum on compiler explorer

I expected to see this happen: Couple of math instructions

Instead, this happened: Giant table

Meta

if I understand correctly, that behavior tie to rust's internal enum type representation i8.

Tried on versions of rustc:

beta nightly 1.50.0

Flags:

-C opt-level=3

mjdr commented 3 years ago

It's dumb, but

I probably outsmart the compiler. With padding value and specific indexing compiler generate roughly what I want.

Hand 'optimized' code on compiler explorer

mjdr commented 3 years ago

Even smaller example Smaller