Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 38 ยท The Text Format

The Stack Machine and Instructions

Learn how WebAssembly executes code on a stack machine. Trace instructions, use locals and local.tee, arithmetic, bitwise and comparison operators, select, and drop.

WebAssembly code does not use named registers or expressions. Every function runs on an implicit operand stack. An instruction pops the values it needs from the top of the stack and pushes its result. i32.add pops two integers and pushes their sum; i32.const 5 pops nothing and pushes 5; local.get 0 pushes a copy of a local.

This looks odd for a few minutes and then becomes natural. It also explains why the binary is so small (no register names in instructions) and why validation is fast: the engine can check the types on the stack at every step with a single pass.

Tracing a computation

Take the expression (a + b) * c - d as a flat instruction list. Here is the stack after each step, with a=2, b=3, c=4, d=5:

Instruction Stack after (top on the right)
local.get $a 2
local.get $b 2 3
i32.add 5
local.get $c 5 4
i32.mul 20
local.get $d 20 5
i32.sub 15

The order of operands matters for non-commutative instructions: i32.sub computes second from top minus top. That is why you push a before b to get a - b.

flowchart LR
    A["local.get a"] --> B["local.get b"] --> C["i32.add"] --> D["local.get c"] --> E["i32.mul"] --> F["local.get d"] --> G["i32.sub"]

At the end of a function, the stack must hold exactly the function's results, no more and no fewer. If you forget a value or leave an extra one, validation fails before the module can run.

A stack simulator

This runnable block is a tiny model of the machine for the instructions in the table. It is not WebAssembly itself, but it prints the stack after every step so you can follow along and try your own sequences.

Node.js Watch the stack change

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Locals

A function can keep values in locals: numbered variables, each with a type, that exist for one call. Parameters are the first locals. Extra locals are declared with (local $t i32) before the instructions and start at zero.

Instruction Effect
local.get $x Push the value of $x
local.set $x Pop a value and store it in $x
local.tee $x Store the top value in $x and leave it on the stack
drop Pop and discard the top value

local.tee is a time saver. Without it, using a result twice needs a local.set followed by two local.gets. The square function below computes (a - b) * (a - b) using it:

WAT
(func (export "square") (param $a i32) (param $b i32) (result i32)
  (local $t i32)
  (local.tee $t (i32.sub (local.get $a) (local.get $b)))   ;; store a - b, keep a copy on the stack
  (local.get $t)
  i32.mul)

The families of instructions

Every numeric type has a similar set of instructions, named type.operation:

Group Examples
Arithmetic i32.add, sub, mul, div_s, div_u, rem_s, rem_u; f64.add, sub, mul, div, sqrt, neg, abs, floor, ceil, trunc, nearest, min, max
Bitwise i32.and, or, xor, shl, shr_s, shr_u, rotl, rotr, clz, ctz, popcnt
Comparison i32.eq, ne, lt_s, lt_u, gt_s, gt_u, le_*, ge_*, eqz; f64.eq, ne, lt, gt, le, ge
Conversion i32.wrap_i64, i64.extend_i32_s, f64.convert_i32_s, i32.trunc_f64_s, f32.demote_f64, f64.promote_f32, i32.reinterpret_f32
Constants i32.const 5, i64.const -1, f32.const 1.5, f64.const 3.14
Parametric drop, select

Comparisons produce an i32 that is 1 for true and 0 for false. There is no boolean type. i32.eqz tests "equals zero" and doubles as logical not.

select is a branch-free conditional: it pops a condition, then two values, and pushes the first value if the condition is non-zero, otherwise the second. In folded form the order is (select value_if_true value_if_false condition).

The module below shows these in action. Its hex is what wat2wasm produced from the source in this lesson: an expression, a local.tee use, a hypotenuse in f64, clamp built from two selects, bit counting, a power-of-two test and an RGB colour packer.

Node.js Arithmetic, selects and bit tricks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The power-of-two trick is a classic bit hack: a positive number is a power of two exactly when x & (x - 1) is zero. The extra x != 0 check stops zero from being reported as a power of two.

Typing rules

Validation tracks the type of every stack slot. i32.add only accepts two i32 values; giving it an f64 is a validation error, not a run-time surprise. There are no implicit conversions. To add an integer to a float you write the conversion yourself:

WAT
(f64.add (local.get $x) (f64.convert_i32_s (local.get $n)))

Instructions also have a polymorphic case: after an unconditional jump such as return or unreachable, the stack is treated as holding "anything", so the code that follows (which never runs) still type-checks. The next lesson meets it again.

Common mistakes

  • Operand order. Remember that the first value pushed is the left operand. For a / b, push a, then b.
  • Leaving extra values. local.tee and calls that return values leave results behind. Use drop when you do not need one.
  • Mixing types. i32.add on an i64 fails validation. Convert with i64.extend_i32_s or i32.wrap_i64.
  • Assuming booleans. A comparison gives 0 or 1, not true/false. Compare results with i32.eqz rather than i32.const 1.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After local.get $a (5), local.get $b (3), i32.sub, what is on the stack?

    i32.sub pops 3 then 5 and pushes 5 - 3 = 2. The value pushed first is the left operand.
  2. 2. What is the difference between local.set and local.tee?

    local.tee behaves like local.set followed by local.get of the same local.
  3. 3. What type does i32.lt_s produce?

    All comparisons push an i32 that is 1 for true and 0 for false.
  4. 4. What does select pick when its condition is 0?

    select returns the first value if the condition is non-zero, and the second otherwise.
  5. 5. Why does i32.add(f64, f64) fail?

    Every instruction has fixed operand types and the validator rejects a mismatch.

Summary

  • Instructions pop operands from an implicit stack and push results; the stack must match the function's result type at the end.
  • Locals (parameters first) are read with local.get, written with local.set, and local.tee writes while keeping the value.
  • Numeric instructions are named type.operation, with _s and _u variants for signed and unsigned.
  • Comparisons produce 0 or 1; select is a branch-free conditional; drop discards a value.
  • There are no implicit conversions between types.

Next: Control Flow