Encode in machine code an Assembly MIPS instruction

1.4k views Asked by At

I need to encode the following beq instruction:

...
start: addu $8, $9, $10
       addiu $8, $8, 0x00FF7A01
       beq $8, $0, start
...

I know that it is a J format instruction so the division will be 6 bits to opcode and 6 to target address. beq opcode is 000100, so I already have 0001000100000000, but I don't know how to find the 16 remaining bits, any help?

2

There are 2 answers

0
Avi Dubey On BEST ANSWER

When beq $8, $0, start is getting executed, the PC contains the address of next instruction. If the contents of $8 and $0 are not equal, there will be no jump, which means there will be no change in the value of PC.

But if the contents of $8 and $0 are same, you want to jump to the label start. In other words, what you want is this - you want the PC to contain the address of the instruction addu $8, $9, $10.

Therefore, the difference between current value of PC and the value of PC in case of jump needs to be calculated.

Number of instructions to jump = 3 (but in negative direction since we want the PC to jump to a previous instruction).

Binary Equivalent of -3 = 2's complement of (0000 0000 0000 0011) which turns out to be 1111 1111 1111 1101

Therefore, the 32-bit representation of this beq instruction will be:

0001 0010 0000 0000 1111 1111 1111 1101

[6-bits opcode of beq][5-bits register $8][5-bits register $0][16-bits of relative-address]

0
Rakholiya Jenish On

In MIPS, during beq the offset to add to program counter is calculated as:

signextend immediate value

offset = (immediate value) << 2 

New PC is calculated as:

pc += offset

Here, in your code, you want to move pc back 12 bytes or 3 instruction if $8 == $0. Hence to add FFFFFFF4 as offset to pc, the immediate value that you will be requiring will be last 2 bytes of:

FFFFFFF4 >> 2 = FFFFFFFD

You can also understand this as:

Address
00000000 start: addu $8, $09, $10
00000004        addiu $8, $8, 0x00FF7A01
00000008        beq $8, $0, start
0000000C ...

while executing beq pc will be at 0000000C. Suppose $8 == $0 then pc should again become 00000000. Hence offset = final_pc - initial_pc = 00000000-0000000C. So,

offset = FFFFFFF4

and immediatevalue = last 2 byte of ((FFFFFFF4) >> 4). Therefore,

immediate_value = FFFD

Shortcut: Also instead of calculating this long, you can directly calculate number of words you want to shift your program counter. Over here you want to go 3 words backward, hence immediate_value = -3 = FFFD. This also holds true if you want to go forward instead of backward.