/* the C code for the example */ int main () { int a, b; a = 3; b = 4; between(&a, &b); return (0); } void between(int *e, int *f) { *e = *e + 2; *f = *f - 2; swap(e, f); *e = *e + 5; *f = *f - 5; } void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; } # MAL code to implement 2 of these functions # swap # Using pointers to integers, swap the 2 integers # function swap receieves 2 parameters (via the stack) # the first parameter is a pointer to one of the integers # the second parameter is a pointer to the other of the integers # AR is 5 words, 4 for registers $8-$11, and one for $ra swap: # prologue sub $sp, $sp, 20 # allocate AR sw $ra, 20($sp) # save $ra sw $8, 4($sp) # save $8 - $11 as callee saved registers sw $9, 8($sp) sw $10, 12($sp) sw $11, 16($sp) lw $8, 24($sp) # $8 is pointer to first int, incoming P1 lw $9, 28($sp) # $9 is pointer to second int, incoming P2 lw $10, ($8) # follow pointer to load $10, first int lw $11, ($9) # follow pointer to load $11, second int sw $11, ($8) # store second int at first int's address sw $10, ($9) # store first int at second int's address # epilogue lw $8, 4($sp) # restore $8 - $11 lw $9, 8($sp) lw $10, 12($sp) lw $11, 16($sp) lw $ra, 20($sp) # restore $ra add $sp, $sp, 20 # deallocate AR jr $ra # between # function between receieves 2 parameters (via the stack) # the first parameter is a pointer to one of the integers # the second parameter is a pointer to the other of the integers # AR is 7 words, 2 for outgoing parameters to swap, 4 for registers $8-$11, # and one for $ra # between: # prologue sub $sp, $sp, 28 # allocate AR sw $ra, 28($sp) # save $ra sw $8, 12($sp) # save $8 - $11 as callee saved registers sw $9, 16($sp) sw $10, 20($sp) sw $11, 24($sp) # *e = *e + 2; lw $8, 32($sp) # $8 is *e, pointer to first int, incoming P1 lw $9, ($8) # follow pointer to load $9, the first int add $9, $9, 2 sw $9, ($8) # save modified value # *f = *f - 2; lw $10, 36($sp) # $10 is *f, pointer to second int, incoming P2 lw $11, ($10) # follow pointer to load $11, the second int sub $11, $11, 2 sw $11, ($10) # save modified value # set up parameters for call to swap(e, f) sw $8, 4($sp) # first parameter is pointer to e sw $10, 8($sp) # second parameter is pointer to f jal swap # Because we have callee saved registers, $8 and $10 have not changed. # They still contain pointers to e and f (although perhaps the integers # pointed to have changed!) # *e = *e + 5; lw $9, ($8) # again, get *e, so follow pointer to load $9 add $9, $9, 5 sw $9, ($8) # save modified value # *f = *f - 5; lw $11, ($10) # again, get *f, so follow pointer to load $11 sub $11, $11, 5 sw $11, ($10) # save modified value # epilogue lw $8, 12($sp) # restore $8 - $11 lw $9, 16($sp) lw $10, 20($sp) lw $11, 24($sp) lw $ra, 28($sp) # restore $ra add $sp, $sp, 28 # deallocate AR jr $ra