capstonene
capstonene

Reputation: 179

Where is the WebAssembly stack-based virtual machine implemented?

Quoting https://webassembly.org/ :

WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable compilation target for programming languages, enabling deployment on the web for client and server applications.

I have read about stack-based virtual machines on Wikipedia. Still, I wonder where the WebAssembly stack-based virtual machine resides. Is it embedded in the javascript engine (for example, on V8)? Does V8 hand the .wasm file to another virtual machine to run it?

Upvotes: 4

Views: 1824

Answers (1)

jmrk
jmrk

Reputation: 40651

This statement describes the concept that Wasm instructions operate on a value stack. For example, i32.add takes two i32 values from this stack, and pushes another (the result) onto that stack. Note that this is an abstract, theoretical model.

Wasm engines, of course, have to accept these instructions, and behave as if there was this stack that the instructions use to exchange input and output values. They may or may not map this conceptual behavior to an actual stack, that's an implementation detail. In fact, it's common for engines to do both: non-optimizing baseline compilers often, but not always, map the conceptual stack onto an actual stack in memory (because that makes the compiler simpler and hence faster), whereas optimizing last-tier compilers typically use an IR ("intermediate representation") in SSA ("static single assignment") form, which is not a conceptual stack machine (and makes the compiler more powerful).

The alternative to a "stack machine" is a "register machine". For example, both x86 and ARM machine code is based on this model: instructions encode which registers they use to take input values and return results. It's also possible to build engines based on a "register machine" model; V8's "Ignition" interpreter (used for JavaScript) is an example of that. It would have been possible to design the Wasm instruction format as a register-based thing -- I'm not sure why it wasn't done that way; probably because modules in binary form would have been bigger if e.g. i32.add had to specify that it takes its two inputs from virtual register x and virtual register y, instead of just implicitly taking the topmost two stack values).

Upvotes: 5

Related Questions