Skip to content

Conversation

@jsgf
Copy link
Contributor

@jsgf jsgf commented Dec 9, 2025

The current bit-at-a-time implementations of bitfield insertion and extraction can generate very bad code, at least for riscv. This PR does two things:

  • change those implementations to use byte at a time operations, which improves the generated code quality, and
  • introduce consts versions which take the bitfield offset and size as const params

Since in general bitfields have constant offset and size, having a function with const params allows the code to be even more specialized at compile time.

Replace bit-at-a-time loops in get(), set(), raw_get(), and raw_set()
with byte-wise shift/mask operations. This significantly improves
performance for multi-bit field access.

The new implementation reads/writes bytes in chunks and uses shifts
and masks to extract/insert values, rather than iterating over each
bit individually.

For big-endian targets, the algorithm reverses bits within bytes and
the final value to maintain the same semantics as the original
implementation.
@jsgf jsgf force-pushed the fix-bitfield-get branch 2 times, most recently from 9f5c6c5 to 00e5503 Compare December 10, 2025 19:21
Add a specialized impl block for `__BindgenBitfieldUnit<[u8; N]>` with
const-generic methods: `get_const`, `set_const`, `raw_get_const`, and
`raw_set_const`. These methods take bit offset and width as const generic
parameters, allowing the compiler to fully optimize bitfield access at
compile time.

Update codegen to use the new const-generic methods for generated
bitfield accessors. Since all bitfield offsets and widths are known at
code generation time, this enables better optimization.

The original runtime-parameter methods are preserved for backwards
compatibility with users who provide custom implementations via the
blocklist mechanism.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant