Subroutines in MIPS — practice with QtSpim: the fight banner, the turn order and a recursive spell (and the level 4 spell that did 0 damage)

For the last program of the session I wanted a fire spell that got stronger with each level: level 0 is the basic spark and each level multiplies by 3. Textbook recursion, like the factorial in the notes. I wrote the subroutine, added a trace to see how it went in and out of each level, and in the base case I put what seemed obvious to me: “level 0, damage 0”.

lw $a1, 0($sp)
bnez $a1, po_next
li $v0, 0               # base case: level 0, damage 0 (so I thought)
j po_trace

And this is what came out on the console:

entering level 4
  entering level 3
    entering level 2
      entering level 1
        entering level 0
        level 0 returns 0
      level 1 returns 0
    level 2 returns 0
  level 3 returns 0
level 4 returns 0
Level 4 spell damage: 0

The way in and out of each level was perfect: the stack was doing its job. But every level returned 0. Of course: 3 · 0 = 0, 3 · 0 = 0… If the base case returns 0, any multiplication on top of it is still 0. The base case of a power isn’t 0, it’s 1 (like the factorial’s), because 1 is the identity of multiplication. I changed a 0 to a 1 and the level 4 spell went on to deal 81 damage.

The lesson holds for today’s three programs: the stack and the jal can be perfect and the subroutine can still fail. You have to check each subroutine’s “contract” (what it gets, what it returns and what it leaves as it was) with real numbers.

This is the practice for the theory of subroutines in MIPS. There are three medium-level programs about Kira’s fight: a banner put together with four leaf subroutines and one that isn’t, the turn order with a subroutine that returns the address of the fastest (like the manual’s r_maximo) and gets called with a shorter and shorter array, and the recursive spell with its trace. They use data close to a real game: names of different lengths, speeds in no particular order and levels you have to go down and back up.

Before you start

It helps to be clear on:

  • That jal saves in $ra the address of the next instruction and jr $ra goes back to it.
  • The convention: arguments in $a0–$a3, results in $v0/$v1, the subroutine may change the $t and $a, and it has to hand back the $s intact.
  • How to save and restore on the stack: addi $sp, $sp, -N, sw with offsets, lw and addi $sp, $sp, N.
  • read_string and its \n (topic 5) and the index with sll (topic 4).

If any of them sounds shaky, go over the theory before carrying on.

In QtSpim, put a breakpoint on the first line of a subroutine (right-click on it in the text panel, Set Breakpoint) and press F5: it stops every time it’s called. That way you see $ra, $sp and the arguments of each call without going through everything else with F10.

Program 1: the fight banner

Before each fight, the game asks for the names of the hero and the enemy and announces them on a banner in capitals, with a line of = above and below as long as the text. What makes it tricky is that the names have different lengths (Kira has 4 letters; Rey Slime, 9 with a space), that they arrive with their \n, and that every letter has to be turned into a capital without touching the spaces.

The idea

Instead of a long main, five small subroutines with one job each:

  1. strip_nl(string): the one from the theory, for read_string‘s \n.
  2. len(string) → $v0: how many characters it has, to work out the width of the rule.
  3. rule(n): prints n = signs and a newline.
  4. upper(c) → $v0: a character in capitals if it was a lower-case letter. It is the “per-character routine” of exercises 7.6 to 7.8 in the manual: it is called once per letter inside a loop.
  5. shout(string): walks through the string and, for each letter, calls upper and prints it.

The first four are leaves: they call nobody and only use $t, so they don’t touch the stack. shout is not a leaf, because it calls upper, so it saves its $ra (and the $s1 it uses as a pointer).

Before you code, think about which of main‘s values have to survive a jal. Only one here: the width of the rule, which is worked out with two calls to len and used in two calls to rule. It goes in $s0.

The code

# banner.s: the fight banner: four leaf subroutines and one that is not
        .data
hero:   .space 16
rival:  .space 16
ph:     .asciiz "Hero: "
pr:     .asciiz "Enemy: "
vs:     .asciiz " VS "
        .text
        .globl main
main:   la $a0, ph              # --- 1. ask for the names ---
        li $v0, 4
        syscall
        la $a0, hero
        li $a1, 16
        li $v0, 8
        syscall
        la $a0, hero
        jal strip_nl
        la $a0, pr
        li $v0, 4
        syscall
        la $a0, rival
        li $a1, 16
        li $v0, 8
        syscall
        la $a0, rival
        jal strip_nl
        la $a0, hero            # --- 2. width = len(hero) + 4 + len(rival) + 2 ---
        jal len
        move $s0, $v0           # in an $s: len uses $t
        la $a0, rival
        jal len
        add $s0, $s0, $v0
        addi $s0, $s0, 6        # " VS " is 4 and one space on each side, 2
        move $a0, $s0           # --- 3. the banner ---
        jal rule
        li $a0, ' '
        li $v0, 11
        syscall
        la $a0, hero
        jal shout
        la $a0, vs
        li $v0, 4
        syscall
        la $a0, rival
        jal shout
        li $a0, 10              # '\n'
        li $v0, 11
        syscall
        move $a0, $s0
        jal rule
        li $v0, 10
        syscall

# shout: prints a string in capitals, letter by letter, calling upper
# Input: $a0 = string. As it calls upper, it saves $ra; and $s1, its pointer.
shout:  addi $sp, $sp, -8
        sw $ra, 4($sp)
        sw $s1, 0($sp)
        move $s1, $a0           # $s1 walks through the string
sh_next:
        lbu $a0, 0($s1)
        beqz $a0, sh_end
        jal upper               # $v0 = the letter in capitals
        move $a0, $v0
        li $v0, 11              # print_char
        syscall
        addi $s1, $s1, 1
        j sh_next
sh_end: lw $s1, 0($sp)
        lw $ra, 4($sp)
        addi $sp, $sp, 8
        jr $ra

# upper: $a0 = character -> $v0 = the same in capitals if it was 'a'..'z'
upper:  move $v0, $a0
        blt $a0, 'a', up_end
        bgt $a0, 'z', up_end
        addi $v0, $a0, -32      # 'a' (97) - 32 = 'A' (65)
up_end: jr $ra

# len: $a0 = string -> $v0 = how many characters it has (without the '\0')
len:    li $v0, 0
le_next:
        add $t0, $a0, $v0       # address of character $v0
        lbu $t0, 0($t0)
        beqz $t0, le_end
        addi $v0, $v0, 1
        j le_next
le_end: jr $ra

# rule: prints $a0 '=' signs and a newline. Uses $t0.
rule:   move $t0, $a0
ru_next:
        blez $t0, ru_end
        li $a0, '='
        li $v0, 11
        syscall
        addi $t0, $t0, -1
        j ru_next
ru_end: li $a0, 10
        li $v0, 11
        syscall
        jr $ra

# strip_nl: $a0 = string; changes its final '\n' to '\0'. Uses $t0 and $t1.
strip_nl:
        move $t0, $a0
qn_look:
        lbu $t1, 0($t0)
        beq $t1, 10, qn_strip
        beqz $t1, qn_end
        addi $t0, $t0, 1
        j qn_look
qn_strip:
        sb $zero, 0($t0)
qn_end: jr $ra

Output

With the inputs Kira and Rey Slime:

Hero:  Kira
Enemy:   Rey Slime
===================
 KIRA VS REY SLIME
===================

Let’s check the width: len returns 4 for “Kira” and 9 for “Rey Slime” (the space counts). The middle line is a space, KIRA, ” VS “, REY SLIME and, if you counted the matching space at the end, one more: 1 + 4 + 4 + 9 + 1 = 19. And the rule has 4 + 9 + 6 = 19 = signs. The sums add up.

Zoom in on len

# len: $a0 = string -> $v0 = how many characters it has (without the '\0')
len:    li $v0, 0
le_next:
        add $t0, $a0, $v0       # address of character $v0
        lbu $t0, 0($t0)
        beqz $t0, le_end
        addi $v0, $v0, 1
        j le_next
le_end: jr $ra

len uses $v0 both as counter and as result: it starts at 0 and, while the character at address $a0 + $v0 isn’t '\0', it adds 1. For “Kira”:

Round$v0 beforeAddress looked atCharacterCarry on?
10hero + 0KYes
21hero + 1iYes
32hero + 2rYes
43hero + 3aYes
54hero + 4'\0'No: returns 4

The '\0' is at hero + 4 because strip_nl changed the \n there. If you called len before strip_nl, it would count 5.

Zoom in on shout and upper

# shout: prints a string in capitals, letter by letter, calling upper
# Input: $a0 = string. As it calls upper, it saves $ra; and $s1, its pointer.
shout:  addi $sp, $sp, -8
        sw $ra, 4($sp)
        sw $s1, 0($sp)
        move $s1, $a0           # $s1 walks through the string
sh_next:
        lbu $a0, 0($s1)
        beqz $a0, sh_end
        jal upper               # $v0 = the letter in capitals
        move $a0, $v0
        li $v0, 11              # print_char
        syscall
        addi $s1, $s1, 1
        j sh_next
sh_end: lw $s1, 0($sp)
        lw $ra, 4($sp)
        addi $sp, $sp, 8
        jr $ra

# upper: $a0 = character -> $v0 = the same in capitals if it was 'a'..'z'
upper:  move $v0, $a0
        blt $a0, 'a', up_end
        bgt $a0, 'z', up_end
        addi $v0, $a0, -32      # 'a' (97) - 32 = 'A' (65)
up_end: jr $ra

shout is the only one that needs the stack. It reserves 8 bytes, saves $ra (because the jal upper is going to overwrite it) and $s1 (because it uses it as a pointer and the convention says the $s are handed back intact). In each round it leaves the letter in $a0, calls upper and collects the result from $v0 before the syscall’s li $v0, 11.

Put numbers on it. If $sp was 0x7ffffff0 at the start, on the first call shout lowers it to 0x7fffffe8: 0x7fffffec holds $ra, which is the address of la $a0, vs, the instruction after jal shout; 0x7fffffe8 holds main’s $s1. On the way out it goes back to 0x7ffffff0, and the call for the rival reuses the same boxes.

upper does the sum from topic 4: if the character is between 'a' (97) and 'z' (122), it subtracts 32. For the i in Kira: 105 − 32 = 73, which is I. The space in “Rey Slime” (32) isn’t in the range and comes out as it is.

This is how “Rey Slime” goes through upper:

CharacterCodeBetween 97 and 122?$v0Why
R82No82 (R)It’s already a capital: it leaves through the blt unchanged
e101Yes69 (E)101 − 32
y121Yes89 (Y)It’s just below z (122), inside the range
space32No32Less than 97: the blt leaves it as it is
S83No83 (S)Same as the R
l108Yes76 (L)108 − 32

The last three (i, m, e) go like the l: 73, 77 and 69. That’s why upper starts with move $v0, $a0: in the two cases where nothing has to change, the result is already in place before jumping to up_end.

Four leaves and one that is notCall tree of banner.s: main calls strip_nl, len, rule and shout twice each. shout calls upper once per letter: 4 for KIRA plus 9 for REY SLIME, 13 times. The leaves, in green, call nobody; shout, in coral, does, and that is why it saves $ra.The calls in banner.smainstrip_nlx2lenx2rulex2shoutx2upperonce per letter (13)leaf: calls nobody; $t is enoughnon-leaf: saves $ra and the $s it uses
Look below each box: if an arrow comes out, that subroutine needs to save its $ra.

Questions you might ask

Why doesn’t main save its $ra if it does loads of jal? Because main never goes back with jr $ra: it ends with syscall 10. Its original $ra (the way back to the start-up code) is lost at the first jal and nothing happens. If main ended with jr $ra, it would have to save it.

Why is the width in $s0 and not in $t0? Because between working it out and using it there are several jal, and len and rule use $t0. With the width in $t0, the second call to len would trample it before the addition, and rule would leave it at 0 when it finished the first line.

Could shout save its $ra in a $t instead of on the stack? It would work here, because upper only touches $v0. But the convention doesn’t guarantee it: if one day upper used that $t, shout‘s way back would be lost. The stack is the only safe place.

Why does rule copy $a0 into $t0 first thing? Because it needs $a0 for the syscall that prints each =. It’s the usual thing: an argument that arrives in $a0 and is going to be used while you make syscalls gets copied to another register on the first line.

What happens if the name has 15 letters or more? read_string keeps 15 and the '\0'; there is no \n to remove and strip_nl leaves through its beqz. The banner comes out with the name cut short, but well formed.

Calling len before strip_nl. The \n counts as a character, so the rule comes out two = too long (one per name) even though the text looks fine.

Try it yourself

  • Add a subroutine center(string, width) that prints the spaces needed for the title to be centred in a fixed rule of 30 =.
  • Write a lower (from capitals to lower case, +32) and a second banner in lower case with a subroutine whisper that is like shout but calls lower. What else has to change, apart from the label’s name? (Hint: the inner labels, sh_next and sh_end, can’t be repeated.)

Program 2: the turn order

In each round five characters act, from fastest to slowest. Their speeds are in an array and their names in a table of addresses in the same order. The program has to sort both at once and show the list. What makes it tricky: when two speeds are swapped, their names have to be swapped too, and the subroutine that looks for the fastest is called several times with a shorter and shorter array (like exercise 7.1 in the manual).

The idea

Selection sort, split into two subroutines:

  1. biggest(addr, n) → $v1: the address of the largest of the n words starting at addr. It returns an address and not a value because the caller needs it to swap in memory. It’s a leaf.
  2. sort(speed, names, n): for box 0, it calls biggest with the 5 boxes and swaps the fastest with the first; for box 1, with the 4 that are left; and so on. It’s not a leaf: it saves $ra and the $s it uses.

The trick for the names: the table names comes right after speed and has the same element size (4 bytes). If $v1 is the address of speed[k], that of names[k] is $v1 + (names − speed). That distance is worked out once and kept in $s1.

With the program’s data: speed starts at 0x10010000 and takes 5 words, 20 bytes, so names starts at 0x10010014 and $s1 = 0x10010014 − 0x10010000 = 20. In the first round, biggest returns 0x10010008 (box 2 of speed); adding 20 gives 0x1001001C, box 2 of names, where the address of “Archer” is. It works because both tables have 4-byte elements: box k of each one is 4 · k bytes from its start.

Before you code, write down what has to survive each jal biggest: the box I’m on ($s0), the distance to the names ($s1) and how many are left ($s2). All three in $s, because biggest moves $a0 and $a1.

The code

# order.s: the turn order: sort calls biggest with an array that shrinks
        .data
speed:  .word 14, 6, 17, 3, 11  # each character's speed
names:.word n0, n1, n2, n3, n4 # address of the name of each one
n0:     .asciiz "Kira"
n1:     .asciiz "Slime"
n2:     .asciiz "Archer"
n3:     .asciiz "Golem"
n4:     .asciiz "Mage"
ttl:    .asciiz "Turn order:\n"
pdot:   .asciiz ". "
open:   .asciiz " ("
close:  .asciiz ")\n"
        .text
        .globl main
main:   la $a0, speed           # --- 1. sort ---
        la $a1, names
        li $a2, 5
        jal sort
        la $a0, ttl             # --- 2. print the list ---
        li $v0, 4
        syscall
        li $s0, 0               # i
mlist:  bge $s0, 5, mdone
        addi $a0, $s0, 1        # the position: i + 1
        li $v0, 1
        syscall
        la $a0, pdot
        li $v0, 4
        syscall
        sll $t0, $s0, 2         # i * 4
        lw $a0, names($t0)      # address of name i
        syscall
        la $a0, open
        syscall
        lw $a0, speed($t0)
        li $v0, 1
        syscall
        la $a0, close
        li $v0, 4
        syscall
        addi $s0, $s0, 1
        j mlist
mdone:  li $v0, 10
        syscall

# sort: from highest to lowest speed, moving the names as well
# Input: $a0 = speed, $a1 = names, $a2 = n. Returns nothing.
sort:   addi $sp, $sp, -16      # $ra and three $s: 4 words
        sw $ra, 12($sp)
        sw $s0, 8($sp)
        sw $s1, 4($sp)
        sw $s2, 0($sp)
so_inside:
        move $s0, $a0           # $s0 = &speed[i] (starts at i = 0)
        sub $s1, $a1, $a0       # $s1 = names - speed: the same distance for all
        move $s2, $a2           # $s2 = how many are left to place
so_loop:
        ble $s2, 1, so_end      # with just one, it is already in place
        move $a0, $s0           # biggest(&speed[i], left)
        move $a1, $s2
        jal biggest             # $v1 = address of the fastest
        lw $t0, 0($s0)          # swap the speeds
        lw $t1, 0($v1)
        sw $t1, 0($s0)
        sw $t0, 0($v1)
        add $t2, $s0, $s1       # &names[i]
        add $t3, $v1, $s1       # &names[of the biggest]
        lw $t0, 0($t2)          # swap the names
        lw $t1, 0($t3)
        sw $t1, 0($t2)
        sw $t0, 0($t3)
        addi $s0, $s0, 4        # the array starts one box later...
        addi $s2, $s2, -1       # ...and has one box fewer
        j so_loop
so_end: lw $s2, 0($sp)
        lw $s1, 4($sp)
        lw $s0, 8($sp)
        lw $ra, 12($sp)
        addi $sp, $sp, 16
        jr $ra

# biggest: returns the ADDRESS of the largest element, not its value
# Input: $a0 = address of the array, $a1 = n (>= 1). Output: $v1. Uses $t0, $t1 and moves $a0, $a1.
biggest: lw $t0, 0($a0)         # $t0 = the largest so far
        move $v1, $a0           # $v1 = where it is
bi_next: addi $a0, $a0, 4
        addi $a1, $a1, -1
        blez $a1, bi_end
        lw $t1, 0($a0)
        ble $t1, $t0, bi_next   # not bigger: next
        move $t0, $t1
        move $v1, $a0
        j bi_next
bi_end: jr $ra

Output

Turn order:
1. Archer (17)
2. Kira (14)
3. Mage (11)
4. Slime (6)
5. Golem (3)

The list is sorted from 17 to 3 and each name still goes with its speed. Check it against the data: Kira 14, Slime 6, Archer 17, Golem 3 and Mage 11. The fastest is Archer and the slowest, Golem.

Zoom in on biggest

# biggest: returns the ADDRESS of the largest element, not its value
# Input: $a0 = address of the array, $a1 = n (>= 1). Output: $v1. Uses $t0, $t1 and moves $a0, $a1.
biggest: lw $t0, 0($a0)          # $t0 = the largest so far
        move $v1, $a0            # $v1 = where it is
bi_next: addi $a0, $a0, 4
        addi $a1, $a1, -1
        blez $a1, bi_end
        lw $t1, 0($a0)
        ble $t1, $t0, bi_next    # not bigger: next
        move $t0, $t1
        move $v1, $a0
        j bi_next
bi_end: jr $ra

It starts by assuming the largest is the first one ($t0 = its value, $v1 = its address) and moves on. Notice that it moves $a0 and $a1: it uses them as pointer and counter. The convention allows it (the $a aren’t kept), and that is why sort doesn’t count on them after the call. In the first call, with the 5 boxes:

Round$a0 points toValue$t0 (largest)$v1 (address of the largest)
Startspeed[0]1414speed + 0
1speed[1]614speed + 0
2speed[2]1717speed + 8
3speed[3]317speed + 8
4speed[4]1117speed + 8

It returns speed + 8, box 2. sort swaps the 17 with the 14 in box 0, and the address of “Archer” with that of “Kira”.

The four rounds of sort, one after another:

Round$s0 (box)$s2Piece biggest looks at$v1speed afterwardsWhy
10x10010000 (0)514, 6, 17, 3, 110x10010008 (17)17, 6, 14, 3, 11Archer moves to the front; Kira, to box 2
20x10010004 (1)46, 14, 3, 110x10010008 (14)17, 14, 6, 3, 11Kira’s 14 is now in box 2
30x10010008 (2)36, 3, 110x10010010 (11)17, 14, 11, 3, 6Mage goes up; Slime goes down to box 4
40x1001000C (3)23, 60x10010010 (6)17, 14, 11, 6, 3Slime and Golem swap
—0x10010010 (4)1———With just one, so_end

The names follow the same path: after round 4 they are Archer, Kira, Mage, Slime and Golem, exactly the order in the output.

The turn order, call by callFive rows with the speed array 14, 6, 17, 3, 11. In each call, biggest gets the part that is left (5, 4, 3 and 2 boxes) and returns in $v1 the address of the largest, in coral, which is swapped with the first box of that part. The grey boxes are already in place. At the end it is 17, 14, 11, 6, 3.Each call to biggest looks at an array one box shortercall 114Kira6Slime17Archer3Golem11Mage$a1 = 5$v1 → box 2call 217Archer6Slime14Kira3Golem11Mage$a1 = 4$v1 → box 2call 317Archer14Kira6Slime3Golem11Mage$a1 = 3$v1 → box 4call 417Archer14Kira11Mage3Golem6Slime$a1 = 2$v1 → box 4end17Archer14Kira11Mage6Slime3Golem
Grey: in place. Violet: what biggest looks at. Coral: the address it returns in $v1.

Zoom in on sort

# sort: from highest to lowest speed, moving the names as well
# Input: $a0 = speed, $a1 = names, $a2 = n. Returns nothing.
sort:   addi $sp, $sp, -16      # $ra and three $s: 4 words
        sw $ra, 12($sp)
        sw $s0, 8($sp)
        sw $s1, 4($sp)
        sw $s2, 0($sp)
so_inside:
        move $s0, $a0           # $s0 = &speed[i] (starts at i = 0)
        sub $s1, $a1, $a0       # $s1 = names - speed: the same distance for all
        move $s2, $a2           # $s2 = how many are left to place
so_loop:
        ble $s2, 1, so_end      # with just one, it is already in place
        move $a0, $s0           # biggest(&speed[i], left)
        move $a1, $s2
        jal biggest             # $v1 = address of the fastest
        lw $t0, 0($s0)          # swap the speeds
        lw $t1, 0($v1)
        sw $t1, 0($s0)
        sw $t0, 0($v1)
        add $t2, $s0, $s1       # &names[i]
        add $t3, $v1, $s1       # &names[of the biggest]
        lw $t0, 0($t2)          # swap the names
        lw $t1, 0($t3)
        sw $t1, 0($t2)
        sw $t0, 0($t3)
        addi $s0, $s0, 4        # the array starts one box later...
        addi $s2, $s2, -1       # ...and has one box fewer
        j so_loop
so_end: lw $s2, 0($sp)
        lw $s1, 4($sp)
        lw $s0, 8($sp)
        lw $ra, 12($sp)
        addi $sp, $sp, 16
        jr $ra

It saves four words: $ra (because it does jal biggest) and $s0, $s1 and $s2, the three $s it uses. Notice that the epilogue reads each one from the same offset where the prologue saved it: $ra at 12, $s0 at 8, $s1 at 4 and $s2 at 0. In each round, the array “starts” one box later ($s0 + 4) and has one box fewer ($s2 − 1). When one is left, it’s already in place. It’s the same idea as exercise 7.1 in the manual: calling the same subroutine with a shorter and shorter array.

Questions you might ask

Why return the address of the largest and not its value? With the value you’d know the fastest has 17, but not where it is to swap it. With the address you can read it (lw $t1, 0($v1)), write over it (sw $t0, 0($v1)) and work out where its name is. It’s what the manual’s r_maximo does.

Why in $v1 and not in $v0? To mirror the manual, which returns it in $v1. The convention says results go in $v0 and $v1; with just one, $v0 is the usual. In the exam, what matters is that the subroutine’s comment says so and that the caller reads it from the same place.

What would happen if sort kept using $a0 after the jal biggest? $a0 would no longer point to the box it’s on, but to the one after the end of the part, because biggest moved it forward. The swap would write outside the array, over the table of names. That’s why $s0.

Does it work with two equally fast characters? Yes: biggest only changes candidate with a strictly larger one (ble $t1, $t0, bi_next), so it keeps the first of the tied ones.

And if n is 0? sort doesn’t call biggest (it leaves through ble $s2, 1), which with n = 0 would read a box that isn’t part of the array. That’s why biggest‘s comment says “n ≥ 1”.

What would happen if you subtracted the other way round, sub $s1, $a0, $a1?

$s1 would be speed − names = −20. The speeds would be sorted correctly, because they don’t use $s1. The names wouldn’t: each “&names[i]” would be speed + 4 · i − 20, from 0x1000FFEC onwards, 20 bytes below speed.

That area is still inside the data segment (which starts at 0x10000000) and is all zeros, so no error message comes up: the program swaps zeros for zeros. I checked it in spim:

Turn order:
1. Kira (17)
2. Slime (14)
3. Archer (11)
4. Golem (6)
5. Mage (3)

It’s the symptom of the typical error below, and it’s silent only because speed is the first thing in .data: if there were another variable in front, those swaps would ruin it.

Swapping the speeds and forgetting the names (or the other way round). The list comes out sorted by speed, but with the names in the original order: “1. Kira (17)”. If two arrays go “in parallel”, every swap is done in both.

Try it yourself

  • Sort from slowest to fastest by writing a subroutine smallest and changing only the call.
  • Add a sixth character (Bard, 11) and check who goes first in the tie with Mage.

Program 3: the fire spell

The level 0 fire spell deals 1 damage and each level multiplies by 3: the level 4 one deals 3⁴. The subroutine power(base, n) works it out recursively and leaves a trace on the console with an indent of two spaces per level, so you can see the levels going down and back up. What makes it tricky: the arguments arrive in $a0 and $a1, but the trace’s syscalls use $a0, and each level’s result has to be printed while more calls are being made.

The idea

power(base, 0) = 1 and power(base, n) = base · power(base, n − 1). Each call reserves a 12-byte frame:

  • 8($sp): its $ra, because it calls itself and indent.
  • 4($sp): the base, which it needs after the call to multiply. On the way back, that slot is no longer needed and is reused to keep the result while it is printed.
  • 0($sp): its n, which is printed on the way in and on the way out.

Before you code, write down by hand the calls for power(3, 2): enter 2, enter 1, enter 0, return 1, return 3, return 9. If your trace doesn’t come out like that, the bug is in the frame.

The code

# spell.s: the power of a fire spell: each level multiplies by 3
# power(base, 0) = 1;  power(base, n) = base * power(base, n - 1)
        .data
tin:    .asciiz "entering level "
tout:   .asciiz "level "
tret:   .asciiz " returns "
ttot:   .asciiz "Level 4 spell damage: "
        .text
        .globl main
main:   li $a0, 3               # base: each level x3
        li $a1, 4               # the spell's level
        jal power
        move $s0, $v0
        la $a0, ttot
        li $v0, 4
        syscall
        move $a0, $s0
        li $v0, 1
        syscall
        li $v0, 10
        syscall

# power: $a0 = base, $a1 = n -> $v0 = base to the power n (and a trace on the console)
# On return, $a0 is no longer the base: $a registers are not kept (convention).
power:  addi $sp, $sp, -12      # my frame: $ra, base and n
        sw $ra, 8($sp)
        sw $a0, 4($sp)          # the syscalls use $a0: I save it now
        sw $a1, 0($sp)
po_frame:
        li $a0, 4               # indent: 2 spaces for each level down
        sub $a0, $a0, $a1
        jal indent
        la $a0, tin
        li $v0, 4
        syscall
        lw $a0, 0($sp)          # n, from my frame
        li $v0, 1
        syscall
        li $a0, 10
        li $v0, 11
        syscall
        lw $a1, 0($sp)
        bnez $a1, po_next
        li $v0, 1               # base case: base^0 = 1
        j po_trace
po_next:
        lw $a0, 4($sp)          # power(base, n - 1)
        addi $a1, $a1, -1
        jal power
        lw $t0, 4($sp)          # my base
        mul $v0, $v0, $t0       # base * power(base, n - 1)
po_trace:
        sw $v0, 4($sp)          # the result, to my frame (the base is no longer needed)
        li $a0, 4
        lw $a1, 0($sp)
        sub $a0, $a0, $a1
        jal indent
        la $a0, tout
        li $v0, 4
        syscall
        lw $a0, 0($sp)
        li $v0, 1
        syscall
        la $a0, tret
        li $v0, 4
        syscall
        lw $a0, 4($sp)          # the result, from my frame
        li $v0, 1
        syscall
        li $a0, 10
        li $v0, 11
        syscall
        lw $v0, 4($sp)          # I return it in $v0
        lw $a1, 0($sp)          # n, as it was
        lw $ra, 8($sp)
        addi $sp, $sp, 12
        jr $ra

# indent: prints 2 * $a0 spaces. Uses $t0.
indent:
        sll $t0, $a0, 1
in_next:
        blez $t0, in_end
        li $a0, ' '
        li $v0, 11
        syscall
        addi $t0, $t0, -1
        j in_next
in_end: jr $ra

Output

entering level 4
  entering level 3
    entering level 2
      entering level 1
        entering level 0
        level 0 returns 1
      level 1 returns 3
    level 2 returns 9
  level 3 returns 27
level 4 returns 81
Level 4 spell damage: 81

The way down goes from 4 to 0, with the indent growing, and the way up returns 1, 3, 9, 27 and 81: each level is the previous one times 3. 3 · 27 = 81 = 3⁴.

Zoom in on power‘s frame

# power: $a0 = base, $a1 = n -> $v0 = base to the power n (and a trace on the console)
# On return, $a0 is no longer the base: $a registers are not kept (convention).
power:  addi $sp, $sp, -12      # my frame: $ra, base and n
        sw $ra, 8($sp)
        sw $a0, 4($sp)          # the syscalls use $a0: I save it now
        sw $a1, 0($sp)
po_frame:

The three words are saved before the first syscall, because that syscall needs $a0 and the base was in it. From then on, power always reads its data from the frame (lw $a0, 0($sp) to print n, lw $a0, 4($sp) for the base of the next call) and not from the registers, which change with every jal.

The 4($sp) slot changes use on the way backFive frames of pot, from power(3, 4) down to power(3, 0), with three words each: $ra at 8($sp), the base at 4($sp) and n at 0($sp). On the right, the same frames on the way back: 4($sp) no longer holds the base but that level's result, 1, 3, 9, 27 and 81, kept there while the trace is printed.The frames of power(3, 4): 12 bytes eachgoing downcoming uppower(3, 4)$ra8($sp)base 34($sp)n = 40($sp)$rares. 814power(3, 3)$ra8($sp)base 34($sp)n = 30($sp)$rares. 273power(3, 2)$ra8($sp)base 34($sp)n = 20($sp)$rares. 92power(3, 1)$ra8($sp)base 34($sp)n = 10($sp)$rares. 31power(3, 0)$ra8($sp)base 34($sp)n = 00($sp)$rares. 10At the bottom $sp = 7fffffb4: 5 frames × 12 = 60 bytes below where it started.
A frame is yours while the call lasts: you can reuse a slot you no longer need.

The stack at each level, with the values from the run:

Call$sp0($sp): n4($sp) going down4($sp) coming up
power(3, 4)0x7fffffe443 (base)81
power(3, 3)0x7fffffd83327
power(3, 2)0x7fffffcc239
power(3, 1)0x7fffffc0133
power(3, 0)0x7fffffb4031

At the bottom there are five 12-byte frames: 60 bytes below 0x7ffffff0, where $sp was before the first call.

Zoom in on the way back

po_next:
        lw $a0, 4($sp)          # power(base, n - 1)
        addi $a1, $a1, -1
        jal power
        lw $t0, 4($sp)          # my base
        mul $v0, $v0, $t0       # base * power(base, n - 1)
po_trace:
        sw $v0, 4($sp)          # the result, to my frame (the base is no longer needed)
        li $a0, 4
        lw $a1, 0($sp)
        sub $a0, $a0, $a1
        jal indent
        la $a0, tout
        li $v0, 4
        syscall
        lw $a0, 0($sp)
        li $v0, 1
        syscall
        la $a0, tret
        li $v0, 4
        syscall
        lw $a0, 4($sp)          # the result, from my frame
        li $v0, 1
        syscall
        li $a0, 10
        li $v0, 11
        syscall
        lw $v0, 4($sp)          # I return it in $v0
        lw $a1, 0($sp)          # n, as it was
        lw $ra, 8($sp)
        addi $sp, $sp, 12
        jr $ra

In po_next the base is fetched from the frame for the call and, on return, again for the mul: $a0 no longer has it, because the inner call used it for its syscalls. Then sw $v0, 4($sp) leaves the result in the frame, because the trace’s syscalls are going to overwrite $v0. At the end, lw $v0, 4($sp) returns it where the caller expects it.

The way back up, level by level:

Level$v0 on return from jal powerBase read from 4($sp)$v0 after the mulWhy
0—(not read)1Base case: li $v0, 1 and jump to po_trace without calling
1133What level 0 returned, times the base
2339Each level receives the result of the one below
39327The base has been in the frame since the way down
427381This is main’s call: the 81 goes back to main in $v0

Multiplying by $a0 instead of reading the base from the frame (mul $v0, $v0, $a0). On return from jal power, $a0 holds the last thing the inner call printed, the 10 of the newline, so the levels return 10, 100, 1000 and 10000, and the level 4 spell does 10000 damage.

Questions you might ask

Why does the base case return 1 and not 0? Because of the story at the start: with 0, every product above it is 0. 3⁰ = 1, just like 0! = 1 in the factorial.

Why isn’t $a1 saved at the end, like $a0? n is restored from the frame (lw $a1, 0($sp)) to leave it as it was, but $a0 isn’t: power‘s comment warns that on return it is no longer the base. The convention doesn’t require the $a to be kept; what matters is saying so.

What would happen if you removed the lw $a1, 0($sp) at the end of power?

Nothing: the trace comes out identical, line by line (I checked it in spim). And not only because nobody looks at $a1 afterwards: when that line is reached, $a1 is already n. po_trace loaded it from the frame (lw $a1, 0($sp)) to work out the indent, and since then there is only indent and syscalls 4, 1 and 11, which don’t touch it.

So what is it for? So that the contract doesn’t depend on that. If tomorrow you change the trace and use $a1 for something else, power will still hand n back as it was, which is what its comment implies by only warning about $a0.

Can indent use $t0 even though power is halfway through? Yes: power doesn’t keep anything in $t between calls. Everything it needs is in its frame.

What happens with power(3, 20)? 3²⁰ = 3,486,784,401 doesn’t fit in 32 signed bits. mul keeps the low 32 bits and the result comes out negative or absurd, without warning. The recursion, on the other hand, holds up: 21 frames of 12 bytes are 252 bytes of stack.

Saving the base in the frame after the first syscall. By then $a0 is no longer the base but the address of tin (268500992), and that is what gets saved. The entry trace looks fine, but level 1 returns 268500992, from level 2 on everything is 0 (the product overflows and its low 32 bits are 0) and the spell does 0 damage. With the sw somewhere else in that stretch you would save something else (the indent’s 4 − n or a 32 from its spaces), but level 4 would still end at 0.

Try it yourself

  • Change the base to 2 and the level to 10: you should get 1024, with eleven levels in the trace.
  • Write power without recursion, with a loop that multiplies n times. Does it need the stack? And $ra?

Common mistakes in this practice

  • Keeping in a $t what crosses a jal. The banner’s width or the order’s box vanish at the next call.
  • Forgetting $ra in a subroutine that calls another. shout, sort and power save it; if you remove the sw $ra, none of them comes back.
  • Different offsets when saving and restoring. Each register comes back from the slot where it was saved; with four words in sort, it’s easy to get one wrong.
  • Using $a0 after a jal. The subroutine may have moved it (biggest) or used it for its syscalls (power).
  • Reading $v0 late. There can’t be any syscall between the jal and the move.
  • A base case that isn’t the identity. 1 for products, 0 for sums.

Try it in QtSpim (or right here)

This is the turn order. Open it in QtSpim or in the environment below:

Loading the MIPS environment… If it doesn’t appear, copy order.s into your QtSpim.

Things to look at:

  1. Run it and check the list. Then open the Data tab: at 0x10010000, where speed is, you’ll see 00000011, 0000000e, 0000000b, 00000006 and 00000003 (17, 14, 11, 6 and 3 in hexadecimal).
  2. Put a breakpoint on bi_end and run it: at each stop, $v1 holds the address of the fastest in the part and $a1 has reached 0.
  3. Stop at so_inside and look at $sp: it has gone down 16 bytes from its starting value. When sort ends it is back to the same.
  4. Change ble $t1, $t0, bi_next to blt $t1, $t0, bi_next and add a tie (give Slime 11). Who goes first, Slime or Mage?
  5. Change move $s0, $a0 to move $s0, $zero: biggest will try to read at address 0 and Messages will show “Bad address in data/stack read: 0x00000000”.

Summary

  • One subroutine per job, with a comment that says what it gets, what it returns and which registers it uses.
  • Leaves that only use $t don’t touch the stack; those that do jal save $ra, and those that use $s save them too.
  • A subroutine can return an address (biggest) when the caller needs to change the value in memory.
  • Calling the same subroutine with a shrinking array ($s0 + 4, $s2 − 1) is a clean way to go through “what’s left”.
  • In recursion, each call keeps in its frame what it needs afterwards; a slot that’s no longer needed can be reused.
  • The base case has to be the identity of the operation: 1 for products, 0 for sums.

Checklist: have you practised it?

  • Have you run the three programs and checked the outputs?
  • Could you say why my level 4 spell did 0 damage?
  • Why does shout save $ra and upper doesn’t?
  • What would $sp be inside sort if it was 0x7ffffff0 at the start? (Answer: 0x7fffffe0.)
  • Which three things does each power frame keep, and what is one of them reused for?
  • Have you tried the “Try it yourself” without looking at the theory?

If you answered yes to almost everything, you’re ready for the subroutine exercises, where I don’t hand you the code. See you there!

Next step: exercisesSubroutines in MIPS — exercises with the average of a round, a poison you have to turn into subroutines and the combos that fit in your energy (and the counter that only saw 4 combos with 6 energy)

Did this article help you? Here is how you can support SergioLearns →