SDCC output samples

From GbdevWiki
Revision as of 11:58, 16 January 2022 by PinoBatch (Talk | contribs) (memcpy turns into this?)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

SDCC is a C compiler targeting, among other instruction sets, the Sharp SM83 CPU in the Game Boy. It is commonly used with the GBDK-2020 library to develop Game Boy games. Here are some samples of its output.

memcpy

C source code:

void memcpy(char* dest, char* src, unsigned len) {
    while (len--) {
        *dest = *src;
        dest++;
        src++;
    }
}

SDCC 4.1.0 compiles it to the following: (View in Compiler Explorer)

_memcpy::
        add     sp, #-4
        ldhl    sp,     #6
        ld      a, (hl+)
        ld      e, (hl)
        ldhl    sp,     #0
        ld      (hl+), a
        ld      (hl), e
        ldhl    sp,     #8
        ld      a, (hl+)
        ld      e, (hl)
        ldhl    sp,     #2
        ld      (hl+), a
        ld      (hl), e
        ldhl    sp,#10
        ld      a, (hl+)
        ld      c, a
        ld      b, (hl)
00101$:
        ld      e, c
        ld      d, b
        dec     bc
        ld      a, d
        or      a, e
        jr      Z, 00104$
        ldhl    sp,#2
        ld      a, (hl+)
        ld      e, a
        ld      d, (hl)
        ld      a, (de)
        pop     hl
        push    hl
        ld      (hl), a
        ldhl    sp,     #0
        inc     (hl)
        jr      NZ, 00117$
        inc     hl
        inc     (hl)
00117$:
        ldhl    sp,     #2
        inc     (hl)
        jr      NZ, 00101$
        inc     hl
        inc     (hl)
        jr      00101$
00104$:
        add     sp, #4
        ret

Compare a handwritten implementation in assembly language that takes dest in DE, src in HL, and len in BC. (This is the same register allocation used for Zilog Z80's ldir instruction.)

memcpy_loop:
        ld      a, (hl+)
        ld      (de), a
        dec     bc
_memcpy__de_hl_bc::
        ld      a, b
        or      a, c
        jr      nz, memcpy_loop
        ret