1
votes

I was wondering how to find the branch location of an instruction such as bne $s1, $s0, label_name. From what I understand the 16-bit immediate value is a relative offset that should be added to the PC to branch.

What I want to know is how the branch address is calculated as I am finding multiple, contradicting answers for the same thing.

What I have found so far:

  1. Increment current PC by four.
  2. Shift immediate value (16-bit) left by two (multiply by four).
  3. Sign extend immediate value to 32-bits.
  4. Add the PC and immediate value.

Is this correct? And if so, how would I sign extend this value in C?

1
The branch offset is typically a signed displacement from the address of the next instruction after the branch instruction, so branch 0 would do nothing.Weather Vane
What I don't understand is how the branch target address is calculated. If I am executing an instruction at 0x400020 and need to jump to 0x400004, how is the new address for the PC calculated? If I add the 16-bit immediate value to the PC, I get an address far larger than what I require.Jack Morgan
It is a signed displacement. But my comments are general, perhaps MIPS isn't like a typical processor.Weather Vane

1 Answers

1
votes

This equation clarify everything.

PC'= the next PC.

SignImm= sign extended immidiate

  PC' = PC + 4 + SignImm*4 

You can get the next PC (PC') as following.

  1. Add four to the current PC.

  2. Sign extend the 16 bit immediate.

  3. shift left it by 2 and add it to PC+4.

How would I sign extend it in C

     int16_t s = -890;
     int32_t i = s;