for ( expr1; condition; expr2 ) <==> expr1;
statements while ( condition )
{
statements;
expr2;
}
Translate all for statements into a while statement before translating into assembler code.
int A[10];
int sum, i;
sum = 0;
for (i = 0; i < 10; i++);
sum = sum + A[i];
Convert to while loop and then to assembler code:
sum = 0; sethi %hi(sum), %l0
st %g0, [%l0 + %lo(sum)]
i = 0; sethi %hi(i), %l0
st %g0, [%l0 + %lo(i)]
while (i < 10) Loop: sethi %hi(i), %l0
{ ld [%l0 + %lo(i)], %l0
sum = sum + A[i]; cmp %l0, 10
i++; bge LoopExit
} nop
sethi %hi(sum), %l0
ld [%l0 + %lo(sum)], %l0 // l0 = sum
sethi %hi(A), %l1
add %l1, %lo(A), %l1 // l1 = #A
sethi %hi(i), %l2
ld [%l2 + %lo(i)], %l2 // l2 = i
smul %l2, 4, %l2 // offset
ld [%l1 + %l2], %l3 //reg l3 = A[i]
add %l0, %l3, %l0 //reg l0 = sum + A[i]
sethi %hi(sum), %l1
st %l0, [%l1 + %lo(sum)] //sum=sum+A[i]
sethi %hi(i), %l0
ld [%l0 + %lo(i)], %l1 // reg l1 = i
add %l1, 1, %l1 // reg l1 = i+1
st %l1, [%l0 + %lo(i)] // i = reg l1
ba Loop
nop
LoopExit: