TExcelTAD
Home › WebAssembly › Blocks & Branches

Blocks & Branches

Most machine languages have goto: jump to any address. WebAssembly deliberately doesn't. Its control flow is structured: code is organised into nested block, loop and if constructs, and branches can only jump to the boundary of a construct that encloses them. This makes validation simple and makes it impossible to jump into the middle of an instruction or another function.

block and br

A block … end groups instructions. A branch br to a block jumps to the end of that block (it "breaks out" of it), skipping everything in between:

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (func (export "main")
    (block $skip
      (call $log (i32.const 1))
      (br $skip)                    ;; jump to the end of $skip
      (call $log (i32.const 2)))    ;; never runs
    (call $log (i32.const 3))))
1
3

Labels such as $skip are just names. Like everything else they become numbers in the binary: a relative depth, where 0 is the innermost enclosing block, 1 the one around it, and so on.

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (func (export "main")
    block           ;; outer (depth 1 from inside the inner block)
      block         ;; inner (depth 0)
        i32.const 10
        call $log
        br 1        ;; leave BOTH blocks
      end
      i32.const 20  ;; skipped
      call $log
    end
    i32.const 30
    call $log))
10
30

Conditional branch: br_if

br_if $label pops an i32 and branches only if it is non-zero. Combined with blocks, it gives you early exits. Here is a function that classifies a number using a chain of checks:

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  ;; returns 0 for negative, 1 for zero, 2 for small (1..9), 3 for big
  (func $classify (param $n i32) (result i32)
    (block $big
      (block $small
        (block $zero
          (block $negative
            (br_if $negative (i32.lt_s (local.get $n) (i32.const 0)))
            (br_if $zero (i32.eqz (local.get $n)))
            (br_if $small (i32.lt_s (local.get $n) (i32.const 10)))
            (br $big))
          ;; end of $negative lands here
          (return (i32.const 0)))
        (return (i32.const 1)))
      (return (i32.const 2)))
    (i32.const 3))
  (func (export "main")
    (call $log (call $classify (i32.const -5)))
    (call $log (call $classify (i32.const 0)))
    (call $log (call $classify (i32.const 7)))
    (call $log (call $classify (i32.const 300)))))
0
1
2
3

Read the nesting carefully: a branch to $negative exits the innermost block, which lands on (return (i32.const 0)). This "ladder of blocks" pattern is exactly what compilers generate for switch statements.

Blocks with results

A block can have a result type, like a function. Its body must leave that value on the stack when it falls off the end, and a branch out of the block must carry the value with it. A br_if that targets such a block therefore takes two operands: the value to carry and the condition (on top).

There is one subtlety: when br_if is not taken, it leaves the carried value on the stack. Its type is [i32 i32] → [i32], not [i32 i32] → []. Watch that value survive here:

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (func (export "main")
    (block $b (result i32)
      i32.const 99         ;; value to carry
      i32.const 0          ;; condition: false, so the branch is not taken
      br_if $b             ;; 99 stays on the stack...
      call $log            ;; ...so we can log it
      i32.const 5)         ;; the block's result when it falls through
    call $log))
99
5

So when you use br_if for "return early with a value", drop the leftover value on the path where it isn't taken. Here is a sign function written that way:

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (func $sign (param $x i32) (result i32)
    (block $done (result i32)
      (drop (br_if $done (i32.const -1) (i32.lt_s (local.get $x) (i32.const 0))))
      (drop (br_if $done (i32.const 0) (i32.eqz (local.get $x))))
      (i32.const 1)))
  (func (export "main")
    (call $log (call $sign (i32.const -42)))
    (call $log (call $sign (i32.const 0)))
    (call $log (call $sign (i32.const 42)))))
-1
0
1

Forget a drop and the validator catches it: the block ends with one value too many.

wat · try it yourself
(module
  (func (export "main") (result i32)
    (block $done (result i32)
      (br_if $done (i32.const -1) (i32.const 0))
      (i32.const 1))))
main.wat:5:20: error: type mismatch at end of block, expected [] but got [i32]
      (i32.const 1))))
                   ^

br_table: a jump table

br_table takes a list of labels and a default label, pops an i32 index, and jumps to the label at that index (or the default if it is out of range). It's how a dense switch compiles:

wat · try it yourself
(module
  (import "console" "str" (func $print (param i32 i32)))
  (memory (export "memory") 1)
  (data (i32.const 0) "zero one  two  many")
  ;; print a word for 0, 1, 2, and "many" for anything else
  (func $say (param $n i32)
    (block $many
      (block $two
        (block $one
          (block $zero
            (br_table $zero $one $two $many (local.get $n)))
          (call $print (i32.const 0) (i32.const 4))
          (return))
        (call $print (i32.const 5) (i32.const 3))
        (return))
      (call $print (i32.const 10) (i32.const 3))
      (return))
    (call $print (i32.const 15) (i32.const 4)))
  (func (export "main")
    (call $say (i32.const 0))
    (call $say (i32.const 1))
    (call $say (i32.const 2))
    (call $say (i32.const 9))))
zero
one
two
many

Unreachable code

After an unconditional branch (br, br_table, return, unreachable) the stack is "polymorphic": the validator lets the following instructions type-check against anything, because they can never run. You will mostly see this in compiler output; just don't be surprised by code after a return.

Test yourself

Where does br $b jump to when $b is a block?

  1. The start of the block
  2. The end of the block
  3. The start of the function
  4. Any instruction you choose

Inside two nested blocks, what does br 1 target?

  1. The inner block
  2. The outer block
  3. The function's first instruction
  4. Instruction number 1

What does br_table do with an index that is larger than its label list?

  1. Traps
  2. Wraps around
  3. Jumps to the default (last) label
  4. Does nothing