NCL 508: Jump Tables
In the previous lesson, we gave useful operations their own handlers.
Now we're going to step away from subroutines for a moment and look at a simpler problem.
Suppose a program has four modes, numbered 0 through 3.
Depending on the current selection, execution needs to continue at one of four different places.
Choosing a Destination
If #selection contains a number from 0 to 3, we can use branches:
BEQ :mode_0 #selection 0
BEQ :mode_1 #selection 1
BEQ :mode_2 #selection 2
BEQ :mode_3 #selection 3
Each branch compares the selection against a number and transfers execution to the corresponding destination.
This is a perfectly reasonable solution.
But notice what we're doing.
We have four numbers, each corresponding to a particular destination:
| Selection | Destination |
|---|---|
0 |
:mode_0 |
1 |
:mode_1 |
2 |
:mode_2 |
3 |
:mode_3 |
We've encountered this sort of relationship before.
It looks rather like an array.
Destinations Are Values
A label names a location in the program.
We've already used labels directly as execution destinations:
JUMP :mode_0
But the destination represented by :mode_0 is also an integer value.
And integer values can be stored in memory.
For example:
MOVE $120 :mode_0
Here, two different kinds of location are involved:
$120is an ordinary memory address.:mode_0is a label naming a program location.
The integer stored at $120 represents the execution destination named by :mode_0.
We can store all four destinations:
MOVE $120 :mode_0
MOVE $121 :mode_1
MOVE $122 :mode_2
MOVE $123 :mode_3
Now we have four consecutive memory locations containing execution destinations.
| Index | Memory address | Destination |
|---|---|---|
0 |
$120 |
:mode_0 |
1 |
$121 |
:mode_1 |
2 |
$122 |
:mode_2 |
3 |
$123 |
:mode_3 |
That's an array.
Back in the 400 level, we established that a data structure is an agreement about what some memory means.
This array is no different.
Its entries contain integers.
We agree that these integers are execution destinations.
Selecting a Destination
Our array begins at $120.
We already know how to calculate the memory address of an array entry using an index:
ADD $100 0x120 #selection
Suppose #selection contains 2.
The calculation produces:
0x120 + 2 = 0x122
So $100 now contains 0x122.
That's the memory address of our third table entry.
And that entry contains the destination represented by :mode_2.
We can retrieve a value through an address stored in memory using indirect addressing:
[$100]
What happens if we use that as the destination of a JUMP?
JUMP [$100]
The processor reads the selected entry and continues execution at the destination stored there.
Put the two instructions together:
ADD $100 0x120 #selection
JUMP [$100]
That's it.
We've built a jump table.
A jump table stores execution destinations so a program can select where to go using an index.
Instead of comparing the selection against four different numbers:
BEQ :mode_0 #selection 0
BEQ :mode_1 #selection 1
BEQ :mode_2 #selection 2
BEQ :mode_3 #selection 3
we use the number directly to select a destination:
ADD $100 0x120 #selection
JUMP [$100]
The relationship between selections and destinations now lives in data rather than in a series of branch instructions.
Check the Index
There's one important detail.
A jump table is still an array.
Our table contains four entries, indexed 0 through 3.
What happens if #selection contains 73?
ADD $100 0x120 #selection
JUMP [$100]
We would select a memory location outside our table and attempt to use its contents as an execution destination.
That's not what we intended.
The solution is the same one we've used with ordinary arrays: validate the index.
BLT :invalid #selection 0
BGT :invalid #selection 3
ADD $100 0x120 #selection
JUMP [$100]
Only valid selections reach the jump.
Validate the index
A jump table does not automatically know how many entries it contains.
Validate an index before indexing the table.
Otherwise, your program may interpret unrelated memory as an execution destination.
What About Handlers?
So far, our jump table has selected places where execution should simply continue.
But in NCL 507, we built handlers.
Suppose we have four operations:
:action_0
-- Perform operation 0.
RET
:action_1
-- Perform operation 1.
RET
:action_2
-- Perform operation 2.
RET
:action_3
-- Perform operation 3.
RET
These aren't merely places where execution continues.
They're subroutines.
We want to select one, run it, and then return to the code that made the selection.
We already know how to choose between four destinations using branches.
Could we do this?
BEQ :action_0 #selection 0
BEQ :action_1 #selection 1
BEQ :action_2 #selection 2
BEQ :action_3 #selection 3
Not safely.
Each branch transfers execution directly into a handler.
But none of those branches performs a CALL.
Remember NCL 501:
CALL creates a return obligation. RET fulfills it.
A branch creates no such obligation.
When the selected handler reaches RET, there isn't a new return destination waiting for it on the call stack.
We need to perform an actual CALL.
Calling the Selected Handler
With direct branches and calls, we could write:
BLT :invalid #selection 0
BGT :invalid #selection 3
BEQ :call_0 #selection 0
BEQ :call_1 #selection 1
BEQ :call_2 #selection 2
BEQ :call_3 #selection 3
:call_0
CALL :action_0
JUMP :done
:call_1
CALL :action_1
JUMP :done
:call_2
CALL :action_2
JUMP :done
:call_3
CALL :action_3
JUMP :done
:invalid
-- Handle an invalid selection.
:done
-- Continue execution.
This works.
Each branch lands at a small piece of code that performs the corresponding CALL.
After the handler returns, that code jumps to the common continuation point.
These little intermediate paths are sometimes called trampolines.
But look at how much code we've written.
Four comparisons.
Four calls.
Four jumps back to the common path.
All to choose one handler.
And adding another handler means adding another comparison, another call, and another jump.
Surely there's a better way.
Calling Through the Table
Our jump table solved almost exactly this problem a moment ago.
We selected a destination at runtime and gave it to JUMP:
ADD $100 0x120 #selection
JUMP [$100]
Does CALL accept an indirect destination too?
CALL [$100]
Yes.
We can put our handler destinations in a table:
MOVE $120 :action_0
MOVE $121 :action_1
MOVE $122 :action_2
MOVE $123 :action_3
Select an entry:
ADD $100 0x120 #selection
And call the destination stored there:
CALL [$100]
Together:
ADD $100 0x120 #selection
CALL [$100]
The entire collection of trampoline branches disappears.
The only difference from an ordinary call is where the destination comes from.
Compare:
CALL :action_2
with:
CALL [$100]
In the first case, the destination is written directly into the instruction.
In the second, the processor obtains it from memory.
Either way, CALL creates the usual return obligation on the internal call stack.
The selected handler runs, executes RET, and returns to the instruction following CALL.
Nothing about the handler needs to change.
Dispatch
We now have three pieces:
- A collection of handlers representing useful operations.
- A jump table containing their execution destinations.
- An index selecting which handler to use.
Selecting an operation and transferring execution to its handler is called dispatch.
For example:
BLT :invalid #selection 0
BGT :invalid #selection 3
ADD $100 0x120 #selection
CALL [$100]
The value of #selection determines which handler receives the call.
We don't need a separate CALL instruction for every operation.
The table separates how we choose an operation from the operation itself.
A handler doesn't need to know whether it was called directly or selected through a table.
It simply receives a call, performs its work, and returns.
Compatible Interfaces
There's another useful consequence.
Suppose our jump table contains two mathematical operations:
:double_value
POP $000
MUL $000 $000 2
PUSH $000
FREE $000
RET
:square_value
POP $000
MUL $000 $000 $000
PUSH $000
FREE $000
RET
Both handlers have the same interface.
| Takes | Type |
|---|---|
value |
Integer |
| Returns | Type |
|---|---|
result |
Integer |
We can place them in a table:
MOVE $120 :double_value
MOVE $121 :square_value
Now the caller can prepare its argument without knowing which operation will run:
PUSH #value
ADD $100 0x120 #selection
CALL [$100]
POP #result
The selected handler receives one integer and returns one integer.
Whether it doubles or squares the value is determined by the table entry.
The caller doesn't need different argument-handling code for each operation.
This is where the interfaces we established earlier in the 500 level become particularly useful.
A jump table is easiest to use when every entry points to a handler with the interface the caller expects.
The table doesn't enforce interfaces
A jump table only stores destinations.
It doesn't know how many arguments a handler expects, what types they should have, or what results it returns.
If one handler expects two arguments while the caller supplies one, the table won't fix that mismatch.
Compatible interfaces are another agreement between the pieces of our program.
It gets weirder
JUMP and CALL aren't the only instructions that can use an indirect destination.
Branch verbs can too.
BEQ [$100] #lhs #rhs
If the values are equal, execution continues at the destination stored in the selected table entry.
The same works with the other integer branches:
BNEQ [$100] #lhs #rhs
BGT [$100] #lhs #rhs
BLT [$100] #lhs #rhs
BGE [$100] #lhs #rhs
BLE [$100] #lhs #rhs
And the string branches:
S.BEQ [$100] #lhs #rhs
S.BNEQ [$100] #lhs #rhs
Yes, you can make a table of conditional branch destinations.
Whether you should is between you and whoever has to read your program later.
Try It
Suppose we're building a calculator.
It already provides four handlers:
:calculate_add
-- ...
RET
:calculate_subtract
-- ...
RET
:calculate_multiply
-- ...
RET
:calculate_divide
-- ...
RET
Each handler has the same interface.
| Takes | Type |
|---|---|
lhs |
Integer |
rhs |
Integer |
| Returns | Type |
|---|---|
result |
Integer |
The calculator identifies its operations using numbers:
| Selection | Operation | Handler |
|---|---|---|
0 |
Addition | :calculate_add |
1 |
Subtraction | :calculate_subtract |
2 |
Multiplication | :calculate_multiply |
3 |
Division | :calculate_divide |
Build a jump table beginning at $200.
Then write code that uses #selection to choose and call the appropriate calculator handler.
Your code should:
- Store the four handler destinations in the table.
- Reject selections outside
0–3. - Calculate the memory address of the selected entry.
- Push
#lhsand#rhsin the correct order. - Call the selected handler indirectly.
- Pop the returned value into
#result.
The arithmetic handlers are already written.
Your job is to dispatch to the correct one.
Build the table
Each entry should contain one handler destination.
The first entry belongs at $200, followed by three more consecutive memory locations.
Still stuck?
Start with:
MOVE $200 :calculate_add
MOVE $201 :calculate_subtract
Continue with the remaining two handlers.
Find the selected entry
#selection is an array index.
The table begins at $200.
Calculate the memory address of the entry before trying to use its contents.
Don't forget to check that the index is valid.
Still stuck?
The bounds check and address calculation can look like this:
BLT :invalid #selection 0
BGT :invalid #selection 3
ADD $100 0x200 #selection
Make the call
$100 now contains the memory address of the selected table entry.
That entry contains the execution destination.
The handler still expects its two arguments on the value stack.
Still stuck?
Prepare the arguments and call indirectly:
PUSH #lhs
PUSH #rhs
CALL [$100]
POP #result
Show me one solution
One possible solution is:
-- Build the jump table.
MOVE $200 :calculate_add
MOVE $201 :calculate_subtract
MOVE $202 :calculate_multiply
MOVE $203 :calculate_divide
-- Validate the selection.
BLT :invalid #selection 0
BGT :invalid #selection 3
-- Select the handler.
ADD $100 0x200 #selection
-- Call it using the shared interface.
PUSH #lhs
PUSH #rhs
CALL [$100]
POP #result
JUMP :done
:invalid
-- Handle the invalid selection.
:done
-- Continue with the result, if valid.
Notice that there are no branches for the individual arithmetic operations.
The selection determines which table entry to read, and that entry determines which handler receives the call.
Adding another operation would require another table entry and an updated bounds check, but the indirect call itself would remain unchanged.
We've seen how execution destinations can be stored as data.
An array of those destinations gives us a jump table, and an indirect CALL lets us dispatch to a selected handler without writing separate calling code for every operation.
But there's a limitation to our current approach.
Numeric selections are convenient for the computer, but not especially friendly to the person using it.
If we want to call :command_open, we'd rather write "OPEN" than remember that it happens to be operation 2.
In the next lesson, NCL 509: Command Dispatch, we'll combine handlers with the associative arrays we learned in the 400 level to select operations by name.