Question: Exercise 2.40 The fi rst three problems in this exercise refer to the following function, given in MIPS assembly. Unfortunately, the programmer of this function
Exercise 2.40 The fi rst three problems in this exercise refer to the following function, given in MIPS assembly. Unfortunately, the programmer of this function has fallen prey to the pitfall of assuming that MIPS is a word-addressed machine, but in fact MIPS is byte addressed.
a. ; int f(int a[], int n, int x);
f: move $v0,$zero ; ret=0 move $t0,$zero ; i=0 L: add $t1,$t0,$a0 ; &(a[i])
lw $t1,0($t1) ; read a[i]
bne $t1,$a2,S ; if(a[i]==x)
addi $v0,$v0,1 ; ret++;
S: addi $t0,$t0,1 ; i++
bne $t0,$a1,L ; repeat if i!=n jr $ra ; return ret The my_alloc function is defi ned as follows (given as both C and MIPS code).
Note that the programmer of this function has fallen prey to the pitfall of using a pointer to an automatic variable arr outside the function in which it is defi ned.
my_alloc in C MIPS code for my_alloc int *my_alloc(int n){
int arr[n];
return arr;
}
my_alloc:
addu $sp,$sp,–4 ; Push sw $fp,0($sp) ; $fp to stack move $fp,$sp ; Save $sp in $fp sll $t0,$a0,2 ; We need 4*n bytes sub $sp,$sp,$t0 ; Make room for arr move $v0,$sp ; Return address of arr move $sp,$fp ; Restore $sp from $fp lw $fp,0(sp) ; Pop $fp addiu $sp,$sp,4 ; from stack jr ra The my_init function is defi ned as follows (MIPS code):
a. my_init:
move $t0,$zero ; i=0 move $t1,$a0 L: sw $zero,0($t1) ; v[i]=0 addiu $t1,$t1,4 addiu $t0,$t0,1 ; i=i+1 bne $t0,$a1,L ; until i==n jr $ra
b. my_init:
move $t0,$zero ; i=0 move $t1,$a0 L: sub $t2,$a1,$t0 sw $t2,0($t1) ; a[i]=n-i addiu $t1,$t1,4 addiu $t0,$t0,1 ; i=i+1;
bne $t0,$a1,L ; until i==n jr $ra 2.40.4 [5] <2.18> What are the contents (values of all fi ve elements) of array v right before the “jal sort” instruction in the main code is executed?
2.40.5 [15] <2.18, 2.13> What are the contents of array v right before the sort function enters its outer loop for the fi rst time? Assume that registers $sp, $s0, $s1, $s2, and $s3 have values of 0x1000, 20, 40, 7, and 1, respectively, at the beginning of the main code (right before “li $s0, 5” is executed).
2.40.6 [10] <2.18, 2.13> What are the contents of the 5-element array pointed by v right after “jal sort” returns to the main code?
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
