Page 153 - ARM 64 Bit Assembly Language
P. 153

Structured programming 139

                     Listing 5.31 shows how the reverse function can be implemented using recursion in AArch64
                     assembly. Line 8 saves the link register to the stack and decrements the stack pointer. Lines
                     10 and 11 test for the base case. If the current case is the base case, then the function simply
                     returns (restoring the stack as it goes). Otherwise, the first and last characters are swapped in
                     lines 12 through 15 and a recursive call is made in lines 17 through 19.

                              Listing 5.31 AArch64 assembly implementation of the reverse function.
                    1         .data  // Declare static data
                    2  str:   .string "\nThis is the string to reverse\n"
                    3
                    4         .text
                    5         .type  reverse, %function
                    6         .global reverse
                    7  reverse:
                    8         stp    x29, x30, [sp, #-16]!  // push FP and LR
                    9         // if( left >= right) goto endif
                   10         cmp    x1, x2
                   11         bge    endif
                   12         ldrb   w3, [x0, x1]           // w3 = a[left]
                   13         ldrb   w4, [x0, x2]           // w4 = a[right]
                   14         strb   w4, [x0, x1]           // a[left] = w4
                   15         strb   w3, [x0, x2]           // a[right] = w3
                   16         // reverse(a, left+1, right-1)
                   17         add    w1, w1, #1             // left += 1
                   18         sub    w2, w2, #1             // right -= 1
                   19         bl    reverse
                   20  endif:  ldp   x29, x30, [sp], #16    // pop FP and LR
                   21         ret
                   22         .size  reverse, (. - reverse)
                   23
                   24         .type  main, %function
                   25         .global main
                   26  main:  stp    x29, x30, [sp, #-16]!
                   27         // printf(str)
                   28         adr    x0, str
                   29         bl     printf
                   30         // reverse(str, 0, strlen(str)-1)
                   31         adr    x0, str
                   32         bl     strlen
                   33         add    w0, w0, #-1
                   34         mov    w2, w0
                   35         mov    w1, wzr
                   36         adr    x0, str
                   37         bl     reverse
                   38         // printf(str)
                   39         adr    x0, str
                   40         bl     printf
   148   149   150   151   152   153   154   155   156   157   158