There's a page on Pipit's site where you can play Doom. The engine is Gore, a Go port of Doom, and it plays Freedoom's levels.
It reaches the page as Go source. Pipit is my Go interpreter, and it compiles that source to its own bytecode inside the tab, then runs those instructions. Pipit itself is a Go program compiled to WebAssembly, which the browser runs.
So that's a game inside an interpreter inside a virtual machine inside a browser. I'm still a bit surprised whenever the title screen turns up.
It's slow, though. Trying to make it faster has led to four changes in Go's WebAssembly compiler.
A census instead of a switch
Each bytecode instruction goes through Pipit's dispatch loop. The loop reads the instruction and picks the function that carries it out (its handler), then comes round for the next one. Choosing a handler happens often enough that even a small cost gets plenty of opportunities.
In the native Go build, that choice uses a switch with more than four hundred cases. Go compiles it to a jump table, an array of code addresses indexed by the operation number, so after checking the range it can look up the handler and jump straight to it.
For WebAssembly, Go compiles the switch as a binary search. It compares the number with the middle case, then searches whichever half remains. A tree for four hundred cases runs about nine comparisons deep, and the interpreter keeps paying for that search.
So the browser build has a workaround I've been calling ranked dispatch. A census build counts how often each operation runs. A generator gives common operations low ranks and produces this code, with the larger groups abbreviated:
rank := flatHotRank[flatDispatchIndex(instr)&(isa.FlatDispatchSlots-1)] - 1
if rank < 4 {
if rank < 2 {
if rank < 1 {
rc = handleJump(vm, frame, registers, instr)
} else {
rc = handleSetSliceByteElement(vm, frame, registers, instr)
}
} else {
if rank < 3 {
rc = handleAddInt64(vm, frame, registers, instr)
} else {
rc = handleAddInt64Constant(vm, frame, registers, instr)
}
}
} else if rank < 16 {
// Next twelve handlers omitted.
} else if rank < 64 {
// Next forty-eight handlers omitted.
} else {
rc = flatDispatchSwitch(vm, frame, registers, instr)
}
The first line looks up the instruction's rank. flatDispatchIndex finds the operation's slot in the table. The table stores ranks plus one, reserving zero for an unlisted operation. Subtracting one from that unsigned byte makes an unlisted rank wrap to 255, which falls through to the switch.
For rank 2, rank < 4 succeeds, rank < 2 fails and rank < 3 selects integer addition. Three comparisons, then the handler can get on with it. The generator gives each larger group its own tree, so the less common instructions remain reachable without making every common instruction search through them.
In the saved census, four handlers account for about 19% of dispatched instructions, sixteen cover a bit over half and sixty-four reach 90%.
It's a hack.
I now own a census, a generator and a text file of hot operations. Their job is to stand in for the word switch.
Four rows with no Pipit in them
While profiling Doom I timed some very small pieces of ordinary Go twice. One build was native and the other was WebAssembly running under Node. Here are four rows, with average time per operation or loop iteration:
| One operation | Native | WebAssembly under Node |
|---|---|---|
| Compare a string with a 13-byte constant | 0.71 ns | 6.5 ns |
| Call a small function | 0.66 ns | 2.8 ns |
| Go round a tight loop once | 0.27 ns | 0.82 ns |
| Follow a pointer | 0.87 ns | 1.25 ns |
A loop that does almost nothing costs three times as much. That's before my interpreter has added an instruction of its own. The string comparison costs nine times as much.
Those fractions of a nanosecond are averages over repeated operations, rather than a stopwatch reading for one call. They're useful here because dispatch repeats its small jobs so often. The pointer row also keeps the comparison interesting. Its gap is much smaller, so I need to look at how particular operations are compiled rather than apply one slowdown factor to everything in the game.
These timings include both the compiler's output and the runtime executing it. They gave me a reason to inspect that output. I'd been treating Doom's speed as a problem to solve inside Pipit, but the Go underneath it was doing work I could remove too.
I've now sent four focused changes to the Go project. Three concern where execution goes next, so they share a little background.
How Go gets back into a function
WebAssembly arranges code inside blocks. A branch can leave a block that surrounds it, continuing after that block's end. Or it can branch to the beginning of a loop that surrounds it. It can't name an arbitrary instruction somewhere else and jump there as a goto would.
Go needs more freedom than that. A goroutine is a piece of Go execution that can stop while waiting on a channel and let the runtime schedule another goroutine before continuing where it left off. Consider a function that receives a value from a channel and adds it to a running total. While the channel is empty, the goroutine waits. When a value arrives, it needs to finish the receive and carry on with the addition, keeping the total it already had. Starting the function again would repeat its earlier work, and returning to its caller would miss the addition entirely. The runtime keeps the execution state, but the compiled function still needs an entrance that can reach the saved position.
The compiler divides the function into basic blocks, straight runs of instructions between branches. It gives the destinations numbers and builds an entry route that can select one of them. The function can enter through that route when it's first called or when a goroutine resumes.
Figure 1 shows the arrangement, leaving the nested WebAssembly blocks for the forward-jump example:
The outer loop has a br_table at the top, WebAssembly's instruction for choosing a branch target by number. A variable called PC_B holds the number to select. For our jump from block 1 to block 3, the generated code sets PC_B to 3 and branches to the loop's beginning. The table then sends execution down to block 3.
A resuming goroutine uses the same entrance, with its saved destination. I like it as a piece of design because one route handles ordinary jumps and resumption, but sending nearby blocks through that entrance makes each generated jump do extra work.
Code can also fall straight into the next block without a jump. The extra route belongs to the branches that need another destination, and those are the ones these changes tackle.
1. Give the switch its jump table
Back at Pipit's switch, a dense run of operation numbers ought to make selection cheap. Dense means the case numbers sit close together, so the table doesn't need a great expanse of empty entries.
Consider eight cases numbered 0 to 7, with the case bodies placed after the selection code. To reach case 5, the search can ask whether the number is below 4, below 6, then below 5. Each comparison narrows the range. When a generated branch is taken, it uses the outer route we've followed.
The slightly maddening part is that WebAssembly already has br_table for numbered selection. Go uses it at the top of the function, while searching through the switch inside it. My jump-table change lets the switch use one too:
The native table holds code addresses, while this instruction selects enclosing WebAssembly branch targets. The compiler still handles values outside the case range, so an input of 12 reaches the default case. For an in-range value, selecting a later case block takes the direct route. A target earlier in the function still needs the outer entry loop, but the binary search is gone.
In the patch's WebAssembly benchmarks, integer switches take about 30% to 40% less time and string switches about 20% less. V8 and SpiderMonkey limit these tables to 65,520 entries, so larger tables keep the search. Mine has a little over four hundred cases. I'm not losing sleep over the limit.
2. Jump forwards without going up
Our block 1 to block 3 jump still takes the long way round. To shorten it, I need the nesting that lets the existing br_table reach block 3.
The compiler puts a WebAssembly block around the code preceding that destination. I'll call it a wrapper to distinguish it from a numbered basic block. Its closing boundary sits immediately before block 3. Leaving the wrapper therefore lands execution at block 3, which is how the table at the top reaches it. This is useful for a conditional that needs to skip some work. If block 1 falls through normally, block 2 runs next, but taking the branch skips block 2 and reaches block 3. Both destinations exist in the same function. The nesting supplies a way to choose between continuing through the intervening code and leaving it behind.
Now look at block 1. It sits inside that same wrapper, and the wrapper is still open while block 1 runs. The destination is already available as a way out. A br instruction can leave it directly:
The new route leaves PC_B alone and never visits the outer table. The patch changes sixteen lines in Go's WebAssembly assembler, reusing the nesting it already produces.
Reversing the journey exposes the limit. By the time block 3 runs, the wrapper ending before block 1 has already closed. Block 3 can't branch out of something it has left behind, so backward jumps still use the outer loop.
In the patch's benchmarks, scanning Go source takes about 27% less time and the tested regular-expression operations take about 25% less overall. Binaries come out about 2% smaller because the direct branches replace the destination-setting sequence.
This is the one I'm fondest of. Once the nesting is drawn, the change is all there in the picture. The compiler has already done the fiddly work of making those destinations reachable, and sixteen lines let ordinary jumps take advantage of it.
3. Let a loop be a loop
A backward jump finishes each iteration of a loop. Imagine a test followed by a body that returns to the test. In the current layout, that return sets PC_B, goes up to the outer table and comes down again. The mostly empty loop in my timing table pays for that route repeatedly.
WebAssembly has a loop construct whose branch target is its beginning, so it can express this return directly. The difficulty is still resumption. If a goroutine stops inside that loop, the function's entry route needs to get back to the saved point, and a branch can't enter the loop halfway through.
In Go's WebAssembly implementation, a goroutine suspends at a function call. A loop with no calls therefore has no suspension point to resume at. My loop change puts eligible loops inside a WebAssembly loop, letting the body branch straight back to the test:
One call anywhere inside keeps the loop on the existing route. The compiler uses the presence of a call as its rule, even if that particular function usually returns immediately. The blocks must also form a loop entered at its first block. An inner loop without calls can qualify even when the outer loop contains a call elsewhere.
The call check happens on compiled code. A helper that's been inlined has its instructions copied into the caller, so writing a function call in Go doesn't automatically exclude the loop. A call instruction that survives compilation does. The small loops that can stay entirely inside a WebAssembly loop are the ones I'm looking for.
Keeping the loop's entry in place
Getting those blocks into the right order took another change. Go normally rotates some loops, arranging entry through the test and moving the backward branch towards the body. That can save a jump in native code. For this WebAssembly transformation, the first block must be the loop's entry, with its body following it, so rotation can prevent the arrangement I need.
The simplest version switched rotation off for every WebAssembly loop. That was too blunt.
Two string-replacing benchmarks got 7% to 9% slower. Both have calls in their loops, so they were losing the benefit of rotation without gaining a WebAssembly loop. The revised change preserves rotation for loops with calls, except where their layout has to accommodate an eligible loop nested inside.
About a third of the loops counted in Go's standard library and tools contain no calls, and 94% of those become WebAssembly loops. In the patch's benchmarks, validating a long, mostly-ASCII string as UTF-8 takes about 60% less time, and the JSON decoding benchmark takes about a fifth less.
My own dispatch loop gets nothing from this. Well, nothing directly.
It calls a handler on every trip, so it has to stay resumable, so none of it can become a WebAssembly loop, and the loop I came here to speed up is the one my own change won't touch. The winners are the small loops inside the handlers and the standard library, the ones doing the copying and the scanning and the comparing and.... everything except dispatch.
4. Read eight bytes at once
The string row in my table points to another opportunity. For s == "hello, gopher", the compiler first checks that s has thirteen bytes. It can then compare their contents, stopping as soon as a comparison fails.
A memory load reads bytes into a value the processor can use. Reading eight adjacent bytes as one integer lets the compiler compare them with one integer constant. For our string, eight bytes, then four, then one cover all thirteen. The constants are calculated during compilation.
The first group covers hello, g, the next covers ophe, and the last is r. Integer equality checks the bits of each group together. It doesn't need to understand letters, punctuation or UTF-8. A mismatch in any group makes the strings unequal, and a shorter input fails the length check before any of those reads. I can still count those bytes on the page, which is rather more pleasant than reading their packed integer constants.
Go can already generate those comparisons, and its WebAssembly backend already knows how to combine adjacent loads. But a target setting called CanMergeLoads still says false. The earlier compiler step deciding whether to expand the string comparison therefore assumes it can't use wide loads. For constants longer than six bytes, it calls the runtime's memequal routine instead.
My merged-loads change sets that flag to true. The implementation change is one word long.
Small arrays benefit from the same permission. The patch's separate ArrayEqual benchmark drops from about 6 ns to under 1 ns. That result belongs to the array benchmark, while the thirteen-byte string shows how the compiler can replace a runtime call with a few comparisons.
Four pull requests and one hack
All four changes are open pull requests against Go. They tackle different costs, and the switch and loop patches need a follow-up to work together. I haven't measured Doom with all four combined, so the demo page still runs the existing compiler output.
Go's release cycle has a feature freeze from late November into January, so these changes are arriving near the cutoff. I'm not expecting a review before the new year. I'd be surprised if all four came back unchanged. The merged-loads issue also asks why that flag was false to begin with. Nobody's answered yet.
When I can build Pipit with a compiler that has all four, I'll try deleting the ranked dispatch.
The census, the generator, the text file of hot operations.... all of it, with the browser build getting its plain switch back. I'd love that generator to have been a waste of my time.