EECS 112/CSE 132
Solutions Week 4
Problem 1
Consider the following RISC-V loop:
LOOP: beq x6, x0, DONE
addi x6, x6, -1
addi x5, x5, 2
jal x0,
LOOP
DONE:
a. Assume that the register x6 is initialized to the value 10. What is the final
value in register x5 assuming the x5 is initially zero?
x6 = 10 , x5 = 0
LOOP: beq x6, x0, DONE // 𝑥6 = 10 ≠ 0
addi x6, x6, -1 // 𝑥6 = 10 − 1 = 9
addi x5, x5, 2 // 𝑥5 = 0 + 2 = 2
jal x0, LOOP // jump to LOOP
LOOP: beq x6, x0, DONE // 𝑥6 = 9 ≠ 0
addi x6, x6, -1 // 𝑥6 = 9 − 1 = 8
addi x5, x5, 2 // 𝑥5 = 2 + 2 = 4
jal x0, LOOP // jump to LOOP
….
LOOP: beq x6, x0, DONE // 𝑥6 = 1 ≠ 0
addi x6, x6, -1 // 𝑥6 = 1 − 1 = 0
Page 1 of 16
, addi x5, x5, 2 // 𝑥5 = 18 + 2 = 20
jal x0, LOOP // jump to LOOP
LOOP: beq x6, x0, DONE // 𝑥6 = 0 = 0
DONE:
x5 = 20
b. For the loop above, write the equivalent C code. Assume that the registers
x5 and x6 are integers acc and i, respectively.
for (i=10; i>0;
i--) acc =
acc + 2;
Problem 2
Translate the following C code to RISC-V assembly code. Use a minimum number
of instructions. Assume that the values of a, b, i, and j are in registers x5, x6, x7,
and x29, respectively. Also, assume that register x10 holds the base address of the
array D.
for (i=0; i<a; i++)
for (j=0; j<b; j++)
D [ 4 * j ] = i + j;
x5 = a , x6 = b , x7 = i , x29 = j
add x7, x0, x0 // = 0
LOOP1: beq x7, x5, DONE // go to DONE if =
addi x7, x7, 1 // = + 1
add x29, x0, x0 // = 0
Page 2 of 16
, Page 3 of 16