constant folding vs exceptions

henry@zoo.toronto.edu (Henry Spencer)
Wed, 26 Aug 1992 20:34:53 GMT

          From comp.compilers

Related articles
Re: constant folding at parse time twpierce@amhux1.amherst.EDU (Tim Pierce) (1992-08-19)
Re: constant folding at parse time wjw@eb.ele.tue.nl (1992-08-21)
constant folding vs exceptions henry@zoo.toronto.edu (1992-08-26)
Re: constant folding vs exceptions eggert@twinsun.com (1992-08-28)
| List of all articles for this month |

Newsgroups: comp.compilers
From: henry@zoo.toronto.edu (Henry Spencer)
Organization: U of Toronto Zoology
Date: Wed, 26 Aug 1992 20:34:53 GMT
References: 92-08-114 92-08-132
Keywords: parse, optimize

wjw@eb.ele.tue.nl (Willem Jan Withagen) writes:
>Now I don't want to open another tarpit again, but this certainly is going
>to have effects on the semantics of the used program...
>[This was for integer expressions in C, which traditionally haven't paid
>much attention to overflows...


In fact, ANSI C handed down a much stricter line on this: expressions
execute as written, with the only escape clause being the "as if" rule
(which says that the compiler can do anything it pleases if the user can't
legally tell the difference). You can still do the things that old C
compilers do, but only if you are generating code that ignores integer
overflow. Alternatively, you may still be able to do some optimization if
you generate code that catches the cases where overflow would matter --
ANSI C doesn't constrain what *happens* when overflow occurs, so the
program doesn't have to dump core in precisely the same way as the
unoptimized one would. The only restriction is that if overflows are
visible, optimizations can't add or remove overflows. This is for
integers, of course; for floating point, optimizations are a lot more
tightly constrained under "as if".


A subtle point worth mentioning here... A *compiler* that ignores the
possibility of overflow might not generate *code* that ignores overflows.
On many machines, overflow is figured into how some of the conditional
branches work. If the generated code is to truly ignore overflows, the
compiler has to be aware of the issue and be careful about the code it
generates. The original Ritchie C compiler, for example, generated code
that could malfunction in peculiar ways in the presence of overflow.
Consider the following with 16-bit ints:


int foo;


foo = 32767;
if ((foo += 200) < 0)
printf("%d is negative\n", foo);
else
printf("%d is non-negative (!)\n", foo);


Guess which message you got out of code from the Ritchie compiler...
--
Henry Spencer @ U of Toronto Zoology, henry@zoo.toronto.edu utzoo!henry
--


Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.