Consider the C code below which reverses the elements in the array A in place. Both array indexing and pointer versions are given. Assume that A holds doubleword integers and that size is the number of elements in the array. Translate to RISC-V using as few instructions as possible. For your RISC-V code, assume the base address of A is initially in x10 and that the number of elements in the array (i.e., size) is initially in x11.
long long int temp;
for (i = 0; i < size/2; i++) {
temp = A[i];
A[i] = A[size - i - 1];
A[size - i - 1] = temp;
}
Pointer version:
long long int *p = A;
long long int *q = A + size - 1;
while (p < q) {
temp = *p;
*p = *q;
*q = temp;
p++;
q--;
}
Greetings!!
Code:
#DATA SEGMENT
.data
array: .dword 0x1111111111111111,0x2222222222222222,0x3333333333333333,0x4444444444444444,0x5555555555555555,0x6666666666666666,0x7777777777777777,0x8888888888888888
#CODE SEGMENT
.text
main:
la a0,array #loading address of the array
li a1,7 #load length-1
li t0,8 #word size
li t3,1 #constant
mul t1,a1,t0 #calculating the offset of the last element
add t1,a0,t1 #calculating the address of the last element
srl a1,a1,t3 #(length-1)/2 for number of iterations
addi a1,a1,1 #adjusting the number of iterations
loop:
beq a1,zero,end #whether the iteration count is 0?
lw a3,0(a0) #else load the word from the dword from the starting
lw t2,0(t1)q #load the word from the dword from the end of array
sw t2,0(a0) #store word from the end as word to start
sw a3,0(t1) #store word from the start as word to end
addi a0,a0,4 #increment for start index for next word
addi t1,t1,4 #increment for end index for next word
lw a3,0(a0) #load the 2nd word from dword from start
lw t2,0(t1) # load the 2nd word from dword from end
sw t2,0(a0) #store
sw a3,0(t1) #store
addi a1,a1,-1 #reduce loop count
addi a0,a0,4 #increment start index
addi t1,t1,-12 #decrement end index
j loop #repeat
end:
li a7,10 #parameter for termination ecal
ecall
Output screenshot:even length array
Before reversing:
After reversing:
Odd length array:
Before:
After:
Hope this helps
Get Answers For Free
Most questions answered within 1 hours.