Fix optimizer bug affecting casts to char types.

When an expression that the intermediate code peephole optimizer could reduce to a constant was cast to a char type, the resulting value could be outside the range of that type.

The following program illustrates the problem:

#pragma optimize 1
#include <stdio.h>
int main(void) {
        int i = 0;
        i = (unsigned char)(i | -1);
        printf("%i\n", i);
}
This commit is contained in:
Stephen Heumann 2021-02-18 20:31:22 -06:00
parent 28888cf824
commit 0f45e1d0ff

View File

@ -1166,6 +1166,12 @@ case op^.opcode of {check for optimizations of this node}
[cgByte,cgUByte,cgWord,cgUWord,cgLong,cgULong,cgReal,cgDouble,
cgComp,cgExtended] then begin
op^.left^.optype := totype.optype;
if totype.optype in [cgByte,cgUByte] then begin
op^.left^.q := op^.left^.q & $00FF;
if totype.optype = cgByte then
if (op^.left^.q & $0080) <> 0 then
op^.left^.q := op^.left^.q | $FF00;
end; {if}
opv := op^.left;
end; {if}
end {if}