CS 2734
Computer Organization II
if (condition)
statement;
d = a;
if (a + b > c) {
a += b;
c ++;
}
a = c + d;
!a -> %l0, b -> %l1
!c -> %l2, d -> %l3
add %l0, 0, %l3 !d = a;
add %l0, %l1, %l4 !a + b -> %l4
subcc %l4, %l2, %g0 !set flags for a + b - c
ble go_on !if a + b -c <= 0 to go_on
nop ! (branches need two slots)
add %l0, %l1, %l0 ! a += b;
add %l2, 1, %l2 ! c ++;
go_on:
add %l2, %l3, %l0 ! a = c + d;
Note: Paul spends a lot of time rewriting code to get rid of the nop (filling the delay slot). We aren't going to worry about that at this time.
if (condition)
statement A;
else
statement B;
d = a;
if (a + b > c) {
a += b;
c ++;
} else
a = c + d;
!a -> %l0, b -> %l1
!c -> %l2, d -> %l3
add %l0, 0, %l3 !d = a;
add %l0, %l1, %l4 !a + b -> %l4
subcc %l4, %l2, %g0 !set flags for a + b - c
ble do_else !if a + b -c <= 0 to do_else
nop ! (branches need two slots)
add %l0, %l1, %l0 ! a += b;
add %l2, 1, %l2 ! c ++;
ba go_on ! done with then clause
nop
do_else:
add %l2, %l3, %l0 ! a = c + d;
go_on:
do
statement;
while (condition);
int calsumdo(int x)
{
int sum;
int i;
sum = 0;
i = 1;
do {
sum += i;
i++;
} while (i <= x);
return sum;
}
begin_fun(calsumdo)
!int calsumdo(int x)
!x -> %i0, sum -> %l0, i ->%l1
add %g0, 0, %l0 !sum = 0;
add %g0, 1, %l1 !i = 1;
top_loop: !do {
add %l0, %l1, %l0 ! sum += i;
add %l1, 1, %l1 ! i++;
subcc %i0, %l1, %g0 ![if (x - i >= 0)
bge top_loop ! goto top_loop]
nop !} while (i <= x);
add %l0, 0, %i0 !return sum;
end_fn(calsumdo)
while (condition)
statement;
int calsumwhile(int x)
{
int sum;
int i;
sum = 0;
i = 1;
while (i <= x) {
sum += i;
i++;
}
return sum;
}
begin_fun(calsumwhile)
!int calsumwhile(int x)
!x -> %i0, sum -> %l0, i ->%l1
add %g0, 0, %l0 !sum = 0;
add %g0, 1, %l1 !i = 1;
top_loop: !
subcc %i0, %l1, %g0 ![if (x - i < 0)
bl after_loop ! goto after_loop]
nop !while (i <= x){
add %l0, %l1, %l0 ! sum += i;
add %l1, 1, %l1 ! i++;
ba top_loop !{
nop !
after_loop:
add %l0, 0, %i0 !return sum;
end_fn(calsumwhile)
for (initialization; test; update)
statement;
int calsumfor(int x)
{
int sum;
int i;
sum = 0;
for (i = 1; i <= x; i++)
sum += i;
return sum;
}
begin_fun(calsumfor)
!int calsumfor(int x)
!x -> %i0, sum -> %l0, i ->%l1
add %g0, 0, %l0 !sum = 0;
add %g0, 1, %l1 !i = 1;
top_loop: !
subcc %i0, %l1, %g0 ![if (x - i < 0)
bl after_loop ! goto after_loop]
nop !for (i = 1; i <= x; i++) {
add %l0, %l1, %l0 ! sum += i;
add %l1, 1, %l1 ![ i++;]
ba top_loop !{
nop !
after_loop:
add %l0, 0, %i0 !return sum;
end_fn(calsumfor)