Page 135 - ARM 64 Bit Assembly Language
P. 135

Structured programming 121


                                        Listing 5.12 Post-test loop in AArch64 assembly.
                               .
                    1          . .
                    2  do:
                               .
                    3          . .                  // body of loop
                    4         cmp    x0, x1          // perform loop test
                    5         bge    do              // repeat loop if x0 >= x1
                               .
                    6          . .



                                        Listing 5.13 Guarded loop in AArch64 assembly.
                               .
                    1          . .
                    2         cmp    x0, x1
                    3         blt    loopEnd         // if (x0 < x1) goto loopEnd
                    4  loop:
                               .
                    5          . .                  // body of loop
                    6         cmp    x0, x1
                    7         bge    do              // if (x0 >= x1) goto loop
                    8  loopEnd:
                               .
                    9          . .



                     do-while loop in C, and Listing 5.12 shows a post-test loop in AArch64 assembly. The body
                     of a post-test loop will always be executed at least once.
                     A post-test loop is more efficient than a pre-test loop because it will always perform the loop
                     test one time less than a pre-test loop, and has one fewer branch instruction. When the test
                     fails, the post-test loop can exit immediately. A pre-test loop must first branch up to the begin-
                     ning and then branch back down to the end. When the programmer can guarantee that the loop
                     body must always execute at least once, a post-test loop is obviously the better choice.
                     Even if the loop body is not guaranteed to execute at least once in all cases, the post-test loop
                     can provide slightly better performance. In order to take advantage of this efficiency, pre-test
                     loops can be turned into post-test loops by adding one check before the pre-test loop begins.
                     This is commonly referred to as a guarded loop. The guarded loop is shown in Listing 5.13.


                     5.3.3 For loop


                     Many structured programming languages have a for loop construct, which is a type of count-
                     ing loop. The for loop is not essential, and is only included as a matter of syntactical conve-
                     nience. In some cases, a for loop is easier to write and understand than an equivalent pre-test
   130   131   132   133   134   135   136   137   138   139   140