CMPUT 229 - Computer Organization and Architecture I

Do-While Loops

229 RISC-V Examples - Do-While Loops

This page covers the basic structure of do-while loops in RISC-V. The main idea is to use a label as an anchor point so we can utilize branches to loop.

Consider the following do-while loop:

do {
    value = value >> 1;
    count = count + 1;
} while (value > 0);

The control flow for this loop is shown in the figure below.

In order to implement the above control flow, we will have a label at the begining of the body of the do-while loop and a branch at the end, checking the looping condition.

The assembly code for the above example:

# Register Usage:
# t0: value
# t1: count
# t2: 1 constant for comparisons

    # Before the do-while loop, lets set count = 0 and t2 = 1.
    # We assume t0 already contains our value.
    add     t1, zero, zero
    addi    t2, zero, 1

    # Label starting the do-while loop.
_doWhileLoop:
    srli    t0, t0, 1   # value = value >> 1
    addi    t1, t1, 1   # count = count + 1

    # Check condition to see if we should continue looping.
    bge     t0, t2, _doWhileLoop

_doWhileLoopDone:
    # We are done the do-while loop.

While the _doWhileLoopDone label in this example is extraneous, it can be included to allow for the use of break statements in the do-while loop. When you want to break, use the instruction jal zero, _doWhileLoopDone.

Link to a file containing the above code snippets