I'm currently studying MIPS assembly code, and I'm having trouble understanding the solution for question (b) of a particular problem. I was hoping someone could help me clarify a specific part of the solution.
Here's the problem and the given solution:
(b) Consider the following MIPS assembly code.
addi $t3, $zero, 220 repeat: addi $t3, $t3, -2 add $s3, $s3, $s1 bne $t3, $zero, repeat
Write down the machine code for the bne instruction given in the code above. Answer as a 32-bit hexadecimal number.
Solution:
(b) Short answer: 0x1560fffd
Elaborated answer: The bne instruction is an I-type instruction. The immediate field encodes the relative address that the branch instruction should jump to. According to the MIPS reference sheet, the branch target address is computed as follows:BTA = PC + 4 + signext(imm) * 4
If we assume that the bne instruction is located at address X, then the BTA must be equal to X - 8. Hence, we have the equation:
X - 8 = X + 4 + signext(imm) * 4which is the same as:
signext(imm) = -3Consequently, by computing the two’s complement number of -3 and sign extending it to a 16-bit hexadecimal number, we get 0xfffd.
The part I'm struggling to understand is why we write the equation as "X - 8 = X + 4 + signext(imm) * 4"? I asked ChatGPT and was told "X - 8 = X + 4 + signext(imm) * 4 arises from the relationship between the branch target address (BTA), the program counter (PC), the immediate value (imm), and the assumption of the branch instruction's location at address X" but it's still vague.
Could someone kindly explain why we subtract 8 from X and add 4 to the equation?