SDCC sucks (?)

ugly SDCC bug:

I try to measure the difference between two counter values at different times. The following code should work – but doesn't because sdcc 'optimizes' away some assignments:

while(1) {
                oldx = x;
                x = TMR0L + 256 * TMR0H;
                diff = x - oldx;
                printf("Count: %ld (%ld, %ld) n", x, diff, oldx);
                delay_ms(10);
}

In the asm file 'oldx' is never assigned any value. The loop starts with

;       .line   113; hellotimer2.c      x = TMR0L + 256 * TMR0H;

An ugly workaround is the following code snippet.

while(1) {
                oldx = x + 1;
                oldx = oldx -1;
                x = TMR0L + 256 * TMR0H;
                diff = x - oldx;
                printf("Count: %ld (%ld, %ld) n", x, diff, oldx);
                delay_ms(10);
}

which results in

line   112; hellotimer2.c      oldx = x + 1;
        INCF    r0x00, F
        BTFSC   STATUS, 0
        INCF    r0x01, F
        BTFSC   STATUS, 0
        INCF    r0x02, F
        BTFSC   STATUS, 0
        INCF    r0x03, F
;       .line   113; hellotimer2.c      oldx = oldx -1;
        MOVLW   0xff
        ADDWF   r0x00, F
        MOVLW   0xff
        ADDWFC  r0x01, F
        MOVLW   0xff
        ADDWFC  r0x02, F
        MOVLW   0xff
        ADDWFC  r0x03, F
;       .line   114; hellotimer2.c      x = TMR0L + 256 * TMR

When you just try to use

oldx = x + 1
oldx = x;

both statements are 'optimized' away (the first line should, the second line not).

And when you try

oldx = x + 1;

this appears correctly in the asm file.

Strange.

And why does the TMR0 counter start at a quasi-random value?

My source code (not stripped down to the bug) is here: hellotimer2.c

UPDATE:declaring every variable as 'volatile' helps. Not very elegant.

Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: