4

I'm tring to do a menu for my work by using a jump table. Everyting looks fine for me but below code does not works. after the "jr $s0" instruction mars gives me an error like:

Error in : invalid program counter value: 268501840

I know the decimal address 268501840 is the actual address of the L1 label and the code supposed to go that label but at that point I take this error.Why?

main:   
.data
jTable: .word L0,L1,L2,L3,L4,L5,L6,default      #jump table definition  
msg:    .asciiz "\nEnter Your Choice;\n [1] for build,\n [2] for insert,\n [3] for       find,\n [4] for findMinMax,\n [5] for delete,\n [6] for print\n [0] for Exit\nYour    choice:#"
.text
userInteraction:
li  $v0,4           #print string
la  $a0,msg         #get string address
syscall

li  $v0,5           #get a menu option from user(0 to 6)
syscall
move    $s0,$v0         #get index in $s0

sll $s0,$s0,2       #$s0=index*4
la  $t0,jTable      #$t0=base address of the jump table
add $s0,$s0,$t0     #$s0+$t0 = actual address of jump label

**jr    $s0**           #jump to label

L0:   Todo
j   finish
L1:   Todo
j   userInteraction
L2:   Todo
j   userInteraction
L3:   Todo
j   userInteraction
L4:   Todo
j   userInteraction 
L5:   Todo
j   userInteraction
L6:   Todo
j   userInteraction
default:   Todo
j   userInteraction
finish:
li  $v0,10      #Exit
syscall         #Exit
kotiloli
  • 45
  • 1
  • 4

2 Answers2

5

You're trying to jump to the array where the addresses are stored, which doesn't make sense. You need to load the target address from the table before the jr instruction:

sll $s0,$s0,2       #$s0=index*4
la  $t0,jTable      #$t0=base address of the jump table
add $s0,$s0,$t0     #$s0+$t0 = actual address of jump label
lw  $s0,($s0)       # <-- load target address 
jr  $s0             #jump to label
Michael
  • 57,169
  • 9
  • 80
  • 125
2

You can accomplish the same thing as Michael suggested with less code by using jTable as an immediate offset for your load word call.

sll $s0,$s0,2       # $s0=index*4
lw  jTable($s0)     # load the target address
jr $s0              # jump to the lable
mattwise
  • 1,464
  • 1
  • 10
  • 20
  • There is no `lw` instruction where you can directly pass a label (address). It wouldn't be possible anyways if `jTable` is at an address larger than `0x7fff` as the offset is a signed 16 bit integer. – Demindiro Nov 23 '21 at 14:20
  • As it turns out, I am wrong. It is possible to pass an address directly to `lw`. My apologies. – Demindiro Nov 25 '21 at 16:21