SDCC Compiler Z80 - Strange use of registers

Thread Starter

Robin Mitchell

Joined Oct 25, 2009
819
Hi all,

I am using the SDCC for my ZBM project and have begun writing a library so the C program can interface with system calls (RST). I am having some trouble with this and the manual is not very helpful at all. When I generate the output assembly and go through it the first variation of C code produces a sensible output. The second variation does not.

Here is the first C program:
Code:
    printChar('a');
    userinput = getline();
    printString(userinput);
And this is the assembler it produces:
Code:
;Source\main.c:11: printChar('a');
    ld    a,#0x61
    push    af
    inc    sp
    call    _printChar
    inc    sp
;Source\main.c:12: userinput = getline();
    call    _getline
    ld    (_userinput),hl
;Source\main.c:13: printString(userinput);
    ld    hl,(_userinput)
    push    hl
    call    _printString
    pop    af
This makes sense and I like it. Register A holds the character (not sure why it is pushing af then increment the sp though).

Here is the second variation that DOES NOT make sense.
Code:
    userinput = getline();
    printString(userinput);
    printChar('a');
This is the generated output
Code:
;Source\main.c:12: userinput = getline();
    call    _getline
    ld    (_userinput),hl
;Source\main.c:13: printString(userinput);
    ld    hl,(_userinput)
    push    hl
    call    _printString
;Source\main.c:14: printChar('a');
    ld    h,#0x61
    ex    (sp),hl
    inc    sp
    call    _printChar
    inc    sp
Why is it exchanging the variable found in the stack pointer with hl? And why is it now using register l instead of a like before? My printChar function relies on the same register being used every time. I dont care if it is a or l but I cant have SDCC keep changing its mind :S

Any help?
 

JohnInTX

Joined Jun 26, 2012
4,787
It is pushing the parameters onto the stack for passing to the functions. In the second one, HL is loaded to the address of userinput and pushed so it is on the top of the stack. _printString expects the address of the string in the stack.
ld h,#0x61 ex (sp),hl loads H with 'a' and swaps top stack with HL to get that parameter onto the stack. In this case inc sp is used instead of push/pop ops - don't know why. But that's what its doing, passing params on the stack and adjusting the SP to keep things aligned.
 
Last edited:
Top