0
#switch ( a [ j * 2 + 1 ] ) {
switch01_test:
la $t0 , j               # $t0 <− address of j
lw $t1 , 0( $t0 )        # $t1 <− j
addiu $t2 , $zero , 2    # $t2 <− 2
mul $t3 , $t1 , $t2      # $t3 <− j * 2
addiu $t4 , $t3 , 1      # $t4 <− j * 2 + 1
sll $t5 , $t4 , 2        # $t5 <− 4 *(j*2+1) 
la $t6 , a               # $t6 <− base address of a
addu $t7 , $t6 , $t5     # $t7 <− address of a [j*2+1]
lw $t8 , 0( $t7 )        # $t8 <− a[j*2+1]
#Check if a[j*2+1] = 1
addiu $t9 , $zero , 1    # $t9 <− 1
beq $t9 , $t8 , switch01_code_1#if a[j*2+1]=1 execute case 1:
#Check if a[j*2+1] = 3
addiu $t9 , $zero , 3    # $t9 <− 3
beq $t9 , $t8 , switch01_code_3#if a[j*2+1]=3 execute case 3:
#Check if a[j*2+1] = 5
addiu $t9 , $zero , 5    # $t9 <− 5
beq $t9 , $t8 , switch01_code_5#if a[j*2+1]=5 execute case 5:
#a[j*2+1] not equal 1,3 or 5
j switch01_end # switch01 exit

What does sll do in the code and why is it necessary?

I understood all the code except the "sll" part

Loylis
  • 11
  • 1
  • 1
    `a[]` is an array of 4-byte `int` elements, not bytes, since we can see it's loaded with `lw` not `lb`. In C, array indexing works by elements, not byte offsets. It's very silly that this code used `mul` to multiply by 2, instead of doing that with another shift. Or better, byte_offset = `j*8 + 4` with `slli + addiu`. (That's what a real compiler will do: https://godbolt.org/z/jEenT5nro except that further optimizes by folding the `+4` into the offset of `lw`, like `lw $t8, 4($t7)`) – Peter Cordes Jan 02 '23 at 08:10
  • The sll $t5 , $t4 , 2 shifts the value in $t4 (which is j * 2 + 1) two positions to the left and stores the result in $t5. This operation has the effect of multiplying j * 2 + 1 by 4, since a left shift by two positions is equivalent to multiplying a binary number by 4 (1 shifted two positions to the left is 100 in binary, which is 4 in decimal). The sll is necessary in this code because it is used to calculate the address of the element a[j * 2 + 1] in the array a. – Kozydot Jan 02 '23 at 08:12
  • An integer takes 4 bytes, and that means it also takes 4 addresses. If an integer is at address x, then it is occupying addresses x+0, x+1, x+2, and x+3. To skip past that whole integer and its 4 addresses (to whatever is next after), we need address x+4. An array of integers stores them consecutive, so what is next after one integer is another — each taking 4 bytes and having 4 addresses. Thus, `a[i]` is at address `a+i*4`. The `sll` is doing the `i*4` part. – Erik Eidt Jan 02 '23 at 14:09
  • Just a pro tip, it would be much easier to read if all the comments were aligned. You did this at the start but stopped halfway through. – puppydrum64 Jan 03 '23 at 11:38
  • In short, `SLL` multiplies a number by two. – puppydrum64 Jan 03 '23 at 11:52

0 Answers0