############################################################################################### # MIPS example: Using Subroutines # Function: This code tests the use of subroutines in the MIPS architecture # The main program just calls a subroutine that does the # job # Routine sum_tst add two numbers (that are not on the stack) # and then calls another routine that verifies if the # is an even number. sum_tst is a non-leaf routine ############################################################################################### .text # Add what follows to the text segment of the program .globl main # Declare the label main to be a global one main: addiu $sp,$sp,-4 # allocate space in the stack, 4 bytes sw $ra,0($sp) # save current return adddress in the stack jal sum_tst # jump to subroutine sum_tst lw $ra,0($sp) # upon return, retrieve return address from stack addiu $sp,$sp,4 # deallocate space from the stack # The program is finished. Exit. end: li $v0,10 # system call for exit syscall # Exit! # Start of first subroutine: sum_tst - sum two values and verify if result is even sum_tst:la $t0,var_a # get address of first variable lw $t0,0($t0) # get var_a value la $t1,var_b # get address of second variable lw $t1,0($t1) # get var_b value addu $t2,$t1,$t0 # add var_a with var_b addiu $sp,$sp,-8 # allocate space in the stack sw $t2,0($sp) # on top of stack goes the result of the sum sw $ra,4($sp) # below the top, save current return adddress jal ver_ev # go verify if it is an even number lw $ra,4($sp) # upon return, retrieve return address from stack addiu $sp,$sp,8 # update stack, removing data from there jr $ra # return to caller # Start of second subroutine: ver_ev. This is a leaf subroutine, that need not modify the stack ver_ev: lw $t3,0($sp) # take data from top of stack (subroutine argument) andi $t3,1 # set $t3 to 1 if number on top of stack is odd, set it to 0 otherwise jr $ra # and return .data # add what follows to the data segment of the program var_a: .word 0xff # a variable var_b: .word 0x100 # another variable ###############################################################################################