WebAssembly / WebAssembly/binaryen

Global to local optimization idea

Open
#1,371 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

help wanted
Dominant language
WebAssembly
Stars
8.6k
Forks
885
Avg merge
1d 19h
Merged PRs (30d)
69

Description

I have the following scenario

(module
 (type $v (func))
 (global $tests/compiler/whatif/aVar (mut i32) (i32.const 0))
 (memory $0 1)
 (export "memory" (memory $0))
 (start $start)
 (func $start (; 0 ;) (type $v)
  (set_global $tests/compiler/whatif/aVar
   (i32.const 42)
  )
 )
)

as a result of compiling and -O3 optimizing

let aVar: i32 = 0;

aVar = 42;

function aFunc(): void {
  // aVar = 24;
}

Here, aVar is compiled in the context of the implicit start function and thus preemptively compiled as a global because it isn't known beforehand whether it is used within any other top-level function, like aFunc.

When not used in a top-level function, this results in quite a few globals that are only used by one function, that is the start function here, and could be optimized away to become locals instead because, here, the start function is called exactly once. Other such functions could, potentially always reinitialize the global.

Unfortunately I have yet to find another scenario where this makes any sense, but while thinking about it I figured that replacing such globals with locals might as well become a Binaryen pass, that is if there is any performance- or size-win in moving non-exported-globals to locals? Another thing I thought of is that such a variable could take advantage of tee_local.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No files, tests, or entry points are named. Start by locating Binaryen's optimization-pass framework and how non-exported globals and the implicit start function are represented. Compare the generated output before and after any proposed transformation, and establish whether the change provides a size or performance benefit.

Written by the indexing model from the issue text.

Assessment

Tech stack
wasm
Domain
compilers, performance
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.