MIPS Assembly & C β†’ MIPS

The instruction and register reference, plus the C-translation questions (if/else with bne, and array code). This is the material behind Q3(b).

Core instructions

CategoryInstructionExampleMeaning
Arithmeticaddadd $s1,$s2,$s3$s1 = $s2 + $s3
subtractsub $s1,$s2,$s3$s1 = $s2 βˆ’ $s3
add immediateaddi $s1,$s2,20$s1 = $s2 + 20
Data transferload wordlw $s1,100($s2)$s1 = Memory[$s2+100]
store wordsw $s1,100($s2)Memory[$s2+100] = $s1
load upper imm.lui $s1,100$s1 = 100Γ—216100 \times 2^{16}
Logicaland / or / norand $s1,$s2,$s3bit-wise AND/OR/NOR
and/or immediateandi $s1,$s2,20$s1 = $s2 & 20
shift left/rightsll $s1,$s2,10$s1 = $s2 Β« 10
Branchbranch on equalbeq $s1,$s2,Lif ($s1==$s2) go to L
branch not equalbne $s1,$s2,Lif ($s1!=$s2) go to L
set on less thanslt $s1,$s2,$s3$s1 = ($s2<$s3) ? 1 : 0
Jumpjumpj 2500go to target
jump & link / regjal 2500 Β· jr $racall / return

Register conventions

NameNumberUsage
$zero0constant 0
$v0–$v12–3results / expression evaluation
$a0–$a34–7arguments
$t0–$t78–15temporaries
$s0–$s716–23saved
$t8–$t924–25more temporaries
$gp / $sp / $fp / $ra28 / 29 / 30 / 31global, stack, frame ptr, return addr
Quick math you’ll reuse: $s0=16, $s1=17, $s2=18, $s3=19, $s4=20… and $t0=8, $t1=9… Register number β†’ 5-bit binary by writing the number in binary (e.g. $s2 = 18 = 10010).

Load / arithmetic rule

Arithmetic works on registers only. To use a value from memory you must lw it into a register first, compute, then sw back.

Translating an if/else (Autumn-24 Q3a)

With f–j = $s0–$s4 (so h=$s2, i=$s3, j=$s4):
if (i != j)
    h = i + j;
else
    h = i - j;
Using the decision instruction bne:
      bne $s3, $s4, Else    # if i != j, skip the "then"
      add $s2, $s3, $s4    # h = i + j
      j   Exit
Else: sub $s2, $s3, $s4    # h = i - j
Exit: ...

Machine code (bne op=000101, add/sub R-type op=000000, add funct=100000, sub funct=100010):

bne $s3,$s4,Else : 000101 10011 10100 0000000000000010
add $s2,$s3,$s4  : 000000 10011 10100 10010 00000 100000
j   Exit         : 000010 <26-bit word address of Exit>
sub $s2,$s3,$s4  : 000000 10011 10100 10010 00000 100010

The bne offset is 2 because, counting from the instruction after bne, Else is 2 instructions ahead (add, then j).

Array code (Spring-26 Q3b)

Each int is a word (4 bytes), so p[k] lives at byte address $base+4Γ—k\text{\$base} + 4 \times k. temp = p[k+1] uses offset 4Γ—(k+1)4 \times (k+1), etc. Steps: compute the byte offset with sll/addi, lw the element, operate, sw it back. Pattern: index β†’ Γ—4 β†’ base+offset β†’ lw/sw.