Name: Date:
HW4 solution
-
In the following assembly code fragment, registers x5 and x6 are initialized to N and zero respectively.
LOOP: beq x5, x0, DONE addi x6, x6, 1 addi x5, x5, -1 jal x0, LOOP DONE:
a. (2 points) What is the value in register x6 for when the code reaches the label DONE:?
\(N\)
b. (2 points) How many RISC-V instructions are executed?
$$ 4N+1$$c. (6 points) If the registers x5 and x6 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 x5, x6 and x7, translate the C code to RISC-V assembly. Use a minimum number of instructions.
add x5, x0, x0 L: bge x5, x6, done add x6, x6, x7 addi x5, x5, 1 jal x0, L done:
b. (4 points) If the variables a and b are initialized to 10 and 1, what is the total number of RISC-V 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. Each iteration through the loop is four instructions, so the real number is((2^31-1)-10) * 4 + 1 + 1
(the plus two is for the final comparison that fails).