Question: In class, we compiled a program with functions. A slightly different program is below (modifications in bold): main() { x = 2*foo(4*y+4); x = x+(4*y+4);
In class, we compiled a program with functions. A slightly different program is below (modifications in bold):
main() { x = 2*foo(4*y+4); x = x+(4*y+4);
} int foo (int n) {
int magic[16]; // Mod 1 - assume magic is stored above (i.e., lower address) junk on stack int junk[10] = {0,1,2,3,4,5,6,7,8,9}; junk[4] += 2 - magic[9]; // Mod 2 if (n<1) return 1;
else return 2*bar(n,magic[9],n+1,magic[9]) + junk[4] + foo(n-1); // Mod 3 }
Modify the assembly language we wrote in class for this revised program (bar is of course a function that has already been written properly). Obviously, you need to use the procedure convention described in class and posted on bb. In cases where the convention was left unspecified, use the convention of the example. Also note that we need to call bar before foo as in the HLL code, since the compiler has no way of knowing whether bar has side effects such as writing some fixed memory location that is read by foo.
Make sure to use a different ink color (or boldface font) to make your modifications clear, and label your program to indicate which changes support which mod. Do not change the original code, except as needed for these modifications. As usual in this course, the compiler does not do any optimization.
The assembly code I gave in class (or a slight variation) is below:
# Allocate Registers: x$s0, y$s1 # Assume optimizing compiler avoids computing 4*y+4 twice
Main: add $t0,$s1,$s1 add $t0,$t0,$t0
addi $t0,$t0,4 addi $sp,$sp,-4 sw $t0,0($sp) add $a0,$t0,$zero jal Foo
# $t02y # $t04y # $t0 4y+4 # Push $t0
# arg0 4y+4 # Call foo # Pop $t0
lw $t0,0($sp ) addi $sp,$sp,4 #
add $s0,$v0,$v0 add $s0,$t0,$s0 ...
Foo: addi $sp,$sp,-48 sw $ra,44($sp) sw $fp,40($sp)
addi $fp,$sp,44 addi $t1,$zero,0 sw $t1,-44($fp) addi $t1,$zero,1 sw $t1,-40($fp) ...
addi $t1,$zero,9 sw $t1,-8($fp) lw $t1,-28($fp) addi $t1,$t1,2 sw $t1,-28($fp) slti $t0,$a0,1 bne $t0,$zero,RetOne
# Call foo(n-1) addi $sp,$sp,-4
sw $a0,0($sp) addi $a0,$a0,-1 jal Foo lw $a0,0($sp) addi $sp,$sp,4 lw $t1,-28($fp) add $v0,$v0,$t1 j Ret
RetOne: addi $v0,$zero,1 Ret: lw $fp,40($sp) lw $ra,44($sp)
addi $sp,$sp,48 jr $ra
# x 2*foo(4*y+4) # x x+4*y+4 # End of Main # Push:
# $ra # $fp # Establish frame # $t10 # junk[0] 0 # $t11 # junk[1] 1
# $t19 # junk[9] 9 # $t1 junk[4] # $t1 junk[4]+2 # junk[4] junk[4]+2 # $t01ifn<1;else0 # Return 1 if n<1
# Push # ... $a0 # arg0 n-1 # Call foo(n-1) # Pop $a0
# $t1 junk[4] # $v0 foo(n-1)+junk[4] # Return # $v01 # pop $fp # pop $ra # reclaim stack space # return to caller
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
