|
|
while ( condition ) +---------->|
statement(s) | |
| +--------------+ FALSE
| | condition |--------+
| +--------------+ |
| | |
| | TRUE |
| | |
| V |
| statement(s) |
| | |
(repeat loop) +-----------+ | (exit loop)
|
+<---------------+
|
V
|
while ( condition )
statement(s)
+--> WhileStart:
| Evaluate "condition" (use cmp)
| |
| V FALSE
| Branch on FALSE outcome of "condition" to WhileEnd: ---->+
| | |
| | TRUE |
| | |
| V |
| Assembler codes to exec "statement(s)" |
| | |
| V |
+<-------- b WhileStart |
|
WhileEnd: +<----------------------------------------------+
|
V
|
While loop used to compute the quotient and the remainder of the integer division A ÷ B:
int A, B;
int Q, R;
// Computes: Q = A/B and R = A%B
Q = 0;
R = A;
while ( R >= B )
{
Q = Q + 1;
R = R - B;
}
|
Sample execution: A = 19, B = 4 (quotient A/B = 4, remainder A/B = 3)
Initial values Iter 1 Iter 2 Iter 3 Iter 4
--------------- ------ ------ ------ ------
Q 0 1 2 3 4
R 19 (A) 15 11 7 3
|
Q = 0;
R = A;
while ( R >= B )
{
Q = Q + 1;
R = R - B;
}
|
main:
// Q = 0;
movw r0, #:lower16:Q
movt r0, #:upper16:Q // r0 = addr(Q)
mov r1, #0
str r1, [r0] // Q = 0;
// R = A;
movw r0, #:lower16:A
movt r0, #:upper16:A // r0 = addr(A)
ldr r1, [r0] // r1 = A;
movw r0, #:lower16:R
movt r0, #:upper16:R // r0 = addr(R)
str r1, [r0] // R = A;
while:
// test R >= B
movw r0, #:lower16:R
movt r0, #:upper16:R // r0 = addr(R)
ldr r1, [r0] // r1 = R;
movw r0, #:lower16:B
movt r0, #:upper16:B // r0 = addr(B)
ldr r2, [r0] // r2 = B;
cmp r1, r2 // Check: R >= B
blt whileEnd // If R < B: exit while loop
/* ***********************************
While body
*********************************** */
// Q = Q + 1
movw r0, #:lower16:Q
movt r0, #:upper16:Q // r0 = addr(Q)
ldr r1, [r0] // r1 = Q;
add r1, r1, #1 // r1 = Q+1
str r1, [r0] // Q = Q+1;
// R = R - B
movw r0, #:lower16:R
movt r0, #:upper16:R // r0 = addr(R)
ldr r1, [r0] // r1 = R;
movw r0, #:lower16:B
movt r0, #:upper16:B // r0 = addr(B)
ldr r2, [r0] // r2 = B;
sub r1, r1, r2 // r1 = R - B
movw r0, #:lower16:R
movt r0, #:upper16:R // r0 = addr(R)
str r1, [r0] // R = R - B;
// End of while body --- branch back to test !!
b while
whileEnd:
Stop:
nop
/* --------------------------------------------------
Begin of the permanent program variables
-------------------------------------------------- */
.data
A: .4byte 37 // Sample input
B: .4byte 7
Q: .skip 4 // Quotient
R: .skip 4 // Remainder
.end
|
DEMO: /home/cs255001/demo/asm/7-while/while1.s