Skip to content

Commit 0a85061

Browse files
committed
Document #[repr(u8)] enum to enable LLVM optimizations
See rust-lang/rust#27303 and rust-lang/libc#48 for discussion of the optimization, or just try compiling `unsafe {free(malloc(16))}` with various Rust definitions of `void *` in the FFI binding.
1 parent 616b984 commit 0a85061

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed

src/other-reprs.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,15 @@ same discriminant.
5050
On non-C-like enums, this will inhibit certain optimizations like the null-
5151
pointer optimization.
5252

53+
For C-like enums, these may also be useful to enable certain LLVM optimizations.
54+
For instance, LLVM will recognize extern functions named `malloc` and `free` and
55+
optimize away unnecessary calls, as long as the functions are of the right type:
56+
`malloc` needs to return a C `void *`, which LLVM interprets as a pointer to
57+
`u8`, and `free` needs to accept one. The libc crate uses `#[repr(u8)]` on its
58+
`c_void` type to enable this optimization. However, note that this optimization
59+
stops working if the enum is non-C-like, even if the only data is `()` or a
60+
`PhantomData`!
61+
5362
These reprs have no effect on a struct.
5463

5564

0 commit comments

Comments
 (0)