3

I was wondering how I would calculate the machine encoding of a jump instruction.

Let's say I have
j foo
at address 0x00400000
Now, what if foo is at adress 0x0040002c. How would I then find the machine encoding of the jump instruction?

[0x00400000] j foo
...
[0x0040002c] foo:
Found some guide on Youtube saying it would be something like

((400000+4) - 40002c)/4
But jump has the op-code 2, which I don't get with that calculation.

Thank you

Name55555555
  • 35
  • 1
  • 6

1 Answers1

3

J has opcode 2, and is encoded as:

---------------------------
| opcode |     target     |
---------------------------
 6 bits       26 bits

Hence, the instruction word should be (2 << 26) | target.
Now, J and JAL are not PC-relative, but PC-region-relative. That is, target is the distance in words to the target address from the beginning of the 256MB region that you're currently executing in. The 256MB region in which 0x00400000 is located begins at 0x00000000. So target would be encoded as (0x0040002c - 0x00000000) >> 2 == 0x0010000B. That gives you the instruction word (2 << 26) | 0x0010000B == 0x0810000B

Michael
  • 57,169
  • 9
  • 80
  • 125
  • Thank you for your reply @Michael. I read somewhere about shifting left 2 bits, so that does make sense. However, are we really allowed to just add the Opcode as we choose? It seems a bit too good to be true, if you know what I mean. – Name55555555 Sep 15 '16 at 17:25
  • Well, I'm not sure what you mean by _"just [adding] the Opcode as we choose"_. The opcode for `J` is 2 and it needs to be placed in bits 31:26 of the instruction word. That's pretty specific. – Michael Sep 15 '16 at 18:18