toy-virtual-machine

Explanation

In many instruction set architectures (ISAs), specific bits within an instruction are designated to represent different components such as registers, immediate values, or operation codes (opcodes). The placement of these bits is determined by the architecture’s design. Let’s break down why the last 3 bits of an instruction might be used to represent a register, such as the second source register (SR2).

Instruction Format

An instruction in a typical ISA might be structured as follows:

| Opcode | DR | SR1 | Mode | SR2/Imm5 |

Each field within the instruction has a specific purpose:

Bit Allocation

In a 16-bit instruction, the bits might be allocated as follows:

| 15-12 | 11-9 | 8-6 | 5 | 4-0 |
| Opcode | DR | SR1 | Mode | SR2/Imm5 |

Extracting SR2

When the mode bit indicates that the instruction uses a second source register (SR2), the last 3 bits (bits 2-0) of the instruction are used to specify SR2. This is because:

Example

Consider an instruction instr with the following binary representation:

1101 001 010 1 01100

If the mode bit were 0 (indicating register mode), the last 3 bits would represent SR2:

1101 001 010 0 00011

Bitwise Operation

To extract SR2 from the instruction:

uint16_t sr2 = instr & 0x7;

Important points