binaryen icon indicating copy to clipboard operation
binaryen copied to clipboard

SimplifyLocals causes ineffective code

Open xuruiyang2002 opened this issue 7 months ago • 0 comments

Given the following code:

(module
  (type (;0;) (func))
  (import "External" "external_function" (func $external_function (type 0)))
  (func $_start (type 0)
    i32.const 9576
    i32.load
    i32.load
    i32.load
    drop
    i32.const 9576
    i32.load
    i32.load
    i32.load
    i32.const 9576
    i32.load
    i32.load
    i32.load
    i32.gt_s
    if (result i32)  ;; label = @1
      call $external_function
      i32.const 1
    else
      i32.const 0
    end
    drop
    unreachable)
  (memory $0 258 258)
  (export "_start" (func $_start)))

For wasm-opt (c91c0520a61), -O3 -sp=simplify-locals can eliminate the unreachable code, while -O3 cannot:

 (func $_start
  (local $0 i32)
  (if
   (i32.gt_s
    (local.tee $0
     (i32.load
      (i32.load
       (i32.load
        (i32.const 9576)
       )
      )
     )
    )
    (local.get $0)
   )
   (then
    (call $external_function)
   )
  )
  (unreachable)
 )

After investigating, it is the Wasm-specific optimization simplify-locals causes the counter-intuitive code. Below is the change made by simplify-locals:

Image

As you can see, the currently wasm-opt cannot optimize the if condition on the right---it can only do that on the left, which I think it is missed optimization (It is not the simplify-locals fault...).

xuruiyang2002 avatar Jun 21 '25 09:06 xuruiyang2002