WebAssembly / WebAssembly/binaryen
Code motion with the same side effects in branches does not always work
Open
Nobody has claimed this yet.
- Dominant language
- WebAssembly
- Stars
- 8.6k
- Forks
- 885
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 69
Description
It seems CodeFolding can't handle such case with side effects (division):
export function not_branchless_ceil_div(x: i32, y: i32): i32 {
return x >= 0 ? x / y : (x + y - 1) / y;
}
export function branchless_ceil_div(x: i32, y: i32): i32 {
return (x >= 0 ? x : x + y - 1) / y;
}
Which output:
(module
(func (export "not_branchless_ceil_div") $a (param $0 i32) (param $1 i32) (result i32)
local.get $0
i32.const 0
i32.ge_s
if (result i32)
local.get $0
local.get $1
i32.div_s
else
local.get $0
local.get $1
i32.add
i32.const 1
i32.sub
local.get $1
i32.div_s
end
)
(func (export "branchless_ceil_div") $b (param $0 i32) (param $1 i32) (result i32)
local.get $0
local.get $0
local.get $1
i32.add
i32.const 1
i32.sub
local.get $0
i32.const 0
i32.ge_s
select
local.get $1
i32.div_s
)
)
But with CodeFolding both code should be identically branchless.
Thought?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the CodeFolding optimization and reproduce the issue using the two TypeScript functions and generated WAT shown here. Compare the folding behavior when division is inside each branch versus after the select, and determine whether the transformation can preserve the division side effects. Done means both functions produce equivalent branchless output without changing semantics.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- wasm
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100