Case Study: Implementing a Leaf Procedure in MIPS

Introduction

A leaf procedure (or function, or subroutine) is a procedure that does not make any subroutine calls. That is, there's no jal call.

Leaf procedures run more efficiently on a RISC machine, because there's less need to use the stack in a leaf procedure. Sometimes you don't even have to use the stack at all. Arguments are passed to you through registers $a0-$a3 and return values are return using registers $v0-$v1.

findMin3

Here's a simple C function that finds the minimum value of three values passed in, and returns it.
int findMin3( int x, int y, int z ) {
  int min = x ;
  if ( y < min )
     min = y ;
  if ( z < min )
     min = z ;
  return min ;
}

Implementation

Here's the implementation in MIPS. We assume x is stored in $a0, y is stored in $a1, and z is stored in $a2. We use $t0 to represent min.

findMin3:  move $t0, $a0        # min = x
           bge  $a1, $t0, IF2   # branch if !( y < min )
           move $t0, $a1        # min = y
IF2:       bge  $a1, $t0, END   # branch if !( z < min )
           move $t0, $a2        # min = z
END:       move $v0, $t0        # retval = min
           jr $ra               # return 
Notice our reliance on the pseudoinstruction, move.

Making the Call

How do we call findMin3? Let's call findMin( 3, 4, 5 ). Then, place the return value in, say, $t0.
   li $a0, 3     # set arg 0
   li $a1, 4     # set arg 1
   li $a2, 5     # set arg 2
   jal findMin3 
   move $t0, $v0 # save return value to $t0

Summary

In the leaf procedure above, there was no need to use the stack. No values were saved at all. Thus, it's easy to code up.

Web Accessibility