EtchedPixels / Fuzix-Compiler-Kit

Fuzix C Compiler Project
Other
49 stars 13 forks source link

bug? be-code-6800.c cmp_direct() cmpb not generated. #145

Closed zu2 closed 1 week ago

zu2 commented 3 weeks ago

cmp_direct tries to generate a cmpb for a 1-byte comparison, but the number is promoted to a 2-byte type by T_CAST, cmpb not generated.

This is not a big problem on the 6809 because 6809 has the cmpd instruction, but on the 6800 it would increase the number of instructions.

And if we could know in advance whether the result of the comparison will be used for a branch or to get 0/1, we could generate even better code.

unsigned cmp_direct(struct node *n, const char *uop, const char *op)
{               
    register struct node *r = n->right;
    register unsigned v = r->value;
    register unsigned s = get_size(r->type);

    if (r->op != T_CONSTANT)
        return 0;
    if (r->type & UNSIGNED)
        op = uop;
    if (s == 1) {
        printf("\tcmpb #%u\n\t%s %s\n", v & 0xFF, jsr_op, op);
        n->flags |= ISBOOL;
        invalidate_b();
        return 1;
    }       
    if (s == 2 && cpu_has_d) {
        printf("\tsubd #%u\n\t%s %s\n", v & 0xFFFF, jsr_op, op);
        n->flags |= ISBOOL; 
        invalidate_work();
        return 1;
    }       
    return 0;   
}           
EtchedPixels commented 3 weeks ago

This is the general item on the TODO list about byte sized operations. 6502 needs it as well, and 8080 would benefit somewhat.

The right approach I think though is to have an optional new function in backend.c (or its own file) that walks the expression tree and works out what can be done byte sized without breaking the C type rules. For example an assignment of 8bits can do many operations on the right hand side in 8bit form, same for below a cast to char or bool and some comparisons.

The branches are similar and 65C816 and Z80 do some of this but it's not very tidy as they do it in the code generation rather than doing most of the work in the expression tree.

EtchedPixels commented 3 weeks ago

Pushed some initial experiments using the 6502 tree (at it's a lot less complicated). Need to think a bit more about comparisons as they are more complex than the initial simple byte operations it tries to do

EtchedPixels commented 3 weeks ago

Added a tweak so that if the upper byte is known and matches the constant we compare only the lower byte. Done for unsigned, need to double check for signed but I think it just needs doing as an unsigned byte bool instead as the signs match

56b79643473f5fcde86196e14aa872904d189f13