Showing posts with label while loop. Show all posts
Showing posts with label while loop. Show all posts

2008/02/12

Branches (While Loop - !0)

Consider the code block:

int x = 0;

while(x <= 10) {
  x++;

}
x += 4;

while(x > 10) {
  x--;
}
x -= 4;  

When we have a loop condition that involves a non-zero argument, we need to re-express that condition in terms of a zero argument. The code block above translates to:

int x = 0;

while(x -10 <= 0) {         // or [ 0 <= 10 - x]
  x++;
}
x += 4;

while(x -10 > 0) {          // or [ 0 > 10 - x]
  x--;
}
x -= 4;  

Converting to assembly gives:

0:   ld $0x0000, r0       # x = 0

# first loop, false conditional at top
2:   ld $0xfffffff6, r1   # r1 = -10
8:   mov r0, r2            
     add r1, r2           # r2 = x - 10
     bgt r2, 0x0012       # if x-10 > 0, x > 10, !(x <= 10) goto +3

     inc r0               # x++
     br 0x0008            # goto -4

12:  add $4, r0           # x += 4

# second loop, true conditional at bottom
14:  ld $0xfffffff6, r1   # r1 = -10
1a:  br 0x0022            # goto +4
1c:  dec r0               # x--;

     mov r0, r2
     add r1, r2           # r2 = x - 10;
22:  bgt r2, 0x001c       # if x-10 > 0, x > 10 goto -3

     add $-4, r0          # x -= 4  

Note: the condition being evaluated in each case is identical, it is just treated differently. In one block, it is used as a condition to exit the loop; in the other, it is used as a condition to continue the loop.

2008/02/07

Branches (While Loop - false)

while(x != 0 ) {
  ~~~i
  ~~~i
  ~~~i
}
~~~o
Address Machine Assembly Notes
assume r0 = x
0: 9005 beq r0, 0x10 branch to exit
2: ~~~i true case
~~~i
~~~i
8: 80FC br 0x00 loop
10: ~~~o exited loop

Note 1: 2 branches total, 1 branch taken on critical path.

Note 2: conditional at top.

2008/02/05

Branches (While Loop - true)

while( x == 0 ) {
 ~~i
 ~~i
 ~~i
}
~~ o

Naive / Literal

Address Machine Assembly Notes
assume r0 = x
0: 9002 beq r0, 0x04 conditional
2: 8005 br 0x0c exit
4: ~~~i true case
~~~i
~~~i
a: 80FB br 0x00 loop
c: ~~~o exited loop

Note: 3 branches total, 2 branches in critical path.

Preferred

Address Machine Assembly Notes
assume r0 = x
0: 8004 br 0x08 prime (need to check condition)
2: ~~~i true case
~~~i
~~~i
8: 90FD beq r0, 0x02 loop conditional
~~~o exited loop

Note 1: 2 branches total, 1 branch in critical path.

Note 2: conditional at bottom.