mipsmachine-instruction

How does the following I-Type instruction change the program counter?


Consider this I-type instruction (BNE, branch on not equal): 0001 0100 1010 1001 1111 1111 1110 1111. When the NE condition is satisfied, what is the change of the PC value, i.e., PC = PC + _____?

The answer to the question is -68, but I'm not entirely sure why. I know that for an I-Type instruction the last 16 bits if the offset, the signed difference between the source destination and the place where you are branching too. So all the 1's are indicating a negative value? But, I still don't get how the value 68 was derived.


Solution

  • The immediate part of the instruction is

    1111 1111 1110 1111

    that is equal to -17. This is due to two's complement encoding and one can easily verify that by adding 17 to this number, we get 2^16 (that is zero if we only keep the 16 first bits).

    MIPS instruction are 32 bits (4 bytes) and they are aligned, ie their address is always a multiple of 4. MIPS architecture uses this characteristic to increase branch range and, as PC is always a multiple of 4, branch offset will be multiplied by 4 before been added to PC. This allows to store 4 times larger offsets.

    So, a value 0 4*(-17) will be added to PC, that is -68.

    To be precise, official MIPS documentation states that

    An 18-bit signed offset (the 16-bit offset field shifted left 2 bits) is added to the address of the instruction following the branch (not the branch itself), in the branch delay slot, to form a PC-relative effective target address.

    An equivalent formulation is that this value of -68 will be added to PC, after it has been increment by 4 in the fetch instruction stage.