5 ms·
Does anyone know what kind of assembly is generated when using std::option in Rust when make a similar function call?
by typon 10y ago
Does anyone know what kind of assembly is generated when using std::option in Rust when make a similar function call?
- steveklabnik 10y agovoid f(std::variant<int, char>) would be f(x: IntOrChar) roughly in Rust, I'm too lazy to make the types _exactly_ the same, but https://godbolt.org/g/pZde2A https://godbolt.org/g/pZde2A is roughly it. Actually, https://godbolt.org/g/1vcMeG https://godbolt.org/g/1vcMeG might be even better to compare; I'm not an expert, but looks like the only difference is in the size. last one, adding inline(never) so you can see the calls in main: https://godbolt.org/g/cVDjQH https://godbolt.org/g/cVDjQH movabs rdi, 21474836480 call example::f1@PLT vs mov edi, 5 pop rbp jmp example::f2@PLT so, yup.
- typon 10y agoThank you! This is really cool.
- cfallin 10y agoAnother cool feature, on top of steveklabnik's comment: rustc is actually smart enough to collapse `Option<T>` where `T` is a borrowed reference (pointer) to a single word. Basically, the compiler knows that the pointer can never be null (borrows are always valid when in scope), so it can use the non-null values for `Some(...)` and the null value for `None`. In other words, the compiler can turn an Option into a null-pointer convention by reasoning from first principles. (I think this optimization works for enums in general, and is somehow related to the `nonzero::NonZero` type, but I could be wrong about that.) Example (look at the calls to f1 and f2 in example::main): https://godbolt.org/g/SSs6X2 https://godbolt.org/g/SSs6X2
- steveklabnik 10y agoYes. It's when the type is NonZero.