darksky
darksky

Reputation: 21019

MIPS BNE Instruction

I have a set of instructions as follows:

loop:
        sll  $t1, $t0, 2              # t1 = (i * 4)
        add $t2, $a0, $t1             # t2 contains address of array[i]
        sw $t0, 0($t2)                # array[i] = i

        addi $t0, $t0, 1              # i = i+1
        add $t4, $t4, $t0             # sum($t4) = ($t4 + array[i])

        slt $t3, $t0,   $a1             # $t3 = ( i < array_size)
        bne $t3, $zero, loop          # if ( i < array_size ) then loop

The sll instruction has an address (program counter) of 0x18. bne has an address of 0x30. MARS Simulator interprets the bne instruction as: bne $11, $0, 0xfff9. 0xfff9 is -7, meaning the instruction will jump 7 steps back. However, sll is six steps back. Does MIPS take into account the current instruction? Or does this happen because the program counter is incremented in the fetch stage, before the instruction finishes executing?

Upvotes: 2

Views: 17086

Answers (2)

ninjalj
ninjalj

Reputation: 43688

On most architectures, branch targets are calculated from the instruction following the branch instruction (i.e: the PC is already advanced). IIRC ARM is the only common exception (there, the PC has advanced farther still, due to pipelining (of the original ARM implementation)).

Upvotes: 1

ArtemB
ArtemB

Reputation: 3622

On branch mips executes two instructions -- the branch instruction itself and the one following it (so called branch delay slot).

At the time branch takes effect, PC points to the instruction that follows the branch instruction itself, so -7 is appropriate.

Upvotes: 2

Related Questions