Name: Box: Date:
HW7 solution
-
In the following assembly code fragment, registers $t1 and $t2 are initialized to N and zero respectively.
LOOP: beq $t1, $0, DONE addi $t2, $t2, 1 addi $t1, $t1, -1 j LOOP DONE:
a. (2 points) What is the value in register $t2 for when the code reaches the label DONE:?
\(N\)
b. (2 points) How many MIPS instructions are executed?
$$ 4N+1$$c. (6 points) If the registers $t1 and $t2 correspond to variables i and a respectively, write the equivalent C code for the loop.
Code to initialize
a
andi
is optional.while(i != 0) { a++; i--; }
or
for(i=n; i!=0; i--) a++;
-
Consider the following C code fragment.
for (i=0; i<a; i++) { a = a + b; }
a. (4 points) Assuming that the values of i, a, and b in registers $t0, $t1 and $t2, translate the C code to MIPS assembly. Use a minimum number of instructions.
add $t0, $0, $0 L: slt $t3, $t0, $t1 beq $t3, $0, done add $t1, $t1, $t2 addi $t0, $t0, 1 j L done:
b. (4 points) If the variables a and b are initialized to 10 and 1, what is the total number of MIPS instructions executed?
\(\infty\) since
a
grows as fast asi
.BUT, not really!
a
will overflow after(2^31-1)-10
iterations of the loop because it starts at 10, then overflows when it tries to add 1 to2^31-1
:a
becomes negative. The next time through the loop, the comparison will fail and the loop will end. So the real number is((2^31-1)-10) * 5 + 1 + 2
(the plus two is for the final comparison that fails).