cfallin labeled issue #1052:
The bitreverse seqences in lib/codegen/meta-python/base/legalize.py all end with two shifts and a bitwise or that effectively swap the low half of the value and the high half:
https://github.com/CraneStation/cranelift/blob/master/lib/codegen/meta-python/base/legalize.py#L445
https://github.com/CraneStation/cranelift/blob/master/lib/codegen/meta-python/base/legalize.py#L475
and others for the other typesIt would be better to replace these trailing sequences with
rotl_imm.That change is the first step, however the catch is that
rotl_immisn't implemented in isel yet so we'll need to implement that too. See the encodings for shifts and non-imm rotates as well as the encodings for imm shifts for some examples.Of course, in the future Cranelift is expected to have a pattern-matching optimization which would automatically optimize shift+bor sequences into rotates, however it doesn't have one right now, and even when it does, it would make the code simpler to just use rotate, and it's more efficient to just use the instruction we want than to emit sequences of instructions that we know will end up getting replaced.
cfallin commented on issue #1052:
Marking this as x64-specific; we use the
bitrevinstruction in the aarch64 backend.
fitzgen commented on issue #1052:
So
legalize.pyis long gone, but we could do this kind of thing in the ISLE rules in our egraphs midend. Currently the only rules we have forbitrevare these two:
- https://github.com/bytecodealliance/wasmtime/blob/9ba5358ad506cb229ba9a23559dd03084e561f4b/cranelift/codegen/src/opts/bitops.isle#L110
- https://github.com/bytecodealliance/wasmtime/blob/9ba5358ad506cb229ba9a23559dd03084e561f4b/cranelift/codegen/src/opts/bitops.isle#L110
Could certainly add more for turning them into rotates!
Also have these x64-specific lowerings, fwiw, but they do not use rotates (assuming rotates are better than what we have?):
Could be good to do this kind of thing as a target-specific legalization in ISLE (none of the infrastructure for this exists at the time of writing, fwiw).
Last updated: Dec 13 2025 at 19:03 UTC