ECAD and Architecture Practical Classes
Tick 3 - Division in assembler
Write a RISC-V assembly program to perform integer division.
Division is slow and expensive in hardware, and we use it relatively rarely. Division by powers of two can be more common, but the compiler will generate a shift operation instead. For these two reasons, simpler processors sometimes do not implement an integer division instruction, which is reflected in the RISC-V based "I" integer-only ISA not contaning division, instead providing division as part of the "M" extension.
We can support integer division in software as an assembler function, which is the focus of this tick.
Wikipedia gives the long division algorithm as follows (in Pascal like pseudo-code):
Q := 0 -- initialize quotient and remainder to zero
R := 0
for i = n-1...0 do -- where n is number of bits in N
R := R << 1 -- left-shift R by 1 bit
R(0) := N(i) -- set the least-significant bit of R equal to bit i of the numerator
if R >= D then
R := R - D
Q(i) := 1
end
end
Task: in assembly, write a function div that for two numbers passed in argument in registers a0 and a1, calculates (a0/a1) and returns the quotient in a0 and remainder in a1. In the ecad-distribution2025/riscv/assembly/ directory you will find div.s provided as a starting point. The main.s file needs to be modified to call your div() function. You might want to think about how your function should behave when given 0 as a denominator: the above pseudo-code would lead to a quotient with n 1's as the least significant bits, and a remainder equal to the numerator. You should return 0 when the denominator is zero.).
Verify that the program you just wrote behaves as expected. For example, invoke your code from main.s by replacing the code between # *** with this):
li a0, 32 # a0 = 32 li a1, 3 # a1 = 3 call div DEBUG_PRINT a0 # display the quotient DEBUG_PRINT a1 # display the remainder
Add more tests to cover key points in the design space. Follow the steps in the previous tutorial to compile/assemble your code and run it on the Spike ISA simulator.
Submit your div.s code on Moodle to be automatically tested and ticked.