home comics writing pictures archive about

2016-11-06 - In IL: Switch instruction

In IL

Along with the branching instructions that we have already seen there's a special multi-branching instruction. It is used in situations where there are multiple possible outcomes based the value of a single input.

switch

Instruction Binary Format
switch 0x45 <uint32> <int32> ... <int32>

The switch instruction is unique because its encoding is variable length. The encoded instruction contains a value, the uint32, that indicates the number of subsequent int32 values. These int32 values are the targets of the instruction and are the same as the int32 values that showed up when we looked at branching instructions. In IL assembly the uint32 would be computed based on the number of arguments, usually labels, to the switch instruction.

The switch instruction works by popping a value off of the stack and then using that value as an index into the instruction's target list. The instruction then jumps to the instruction indicated by the target at that index. If the value is 0 then the instruction jumps to the instruction indicated by the first target. If the value is 1 then the instruction jumps to the instruction indicated by the second target. If the value is greater than the number of targets then the instruction does nothing and execution moves on to the next instruction.

Next time we will look at some uses of the switch instruction.

Comments: