detecting integer overflow

Bruce Karsh karsh at trifolium.esd.sgi.com
Sat Aug 25 07:59:20 AEST 1990


In article <GLOBUS.90Aug21114837 at wk208.nas.nasa.gov> globus at nas.nasa.gov (Al Globus) writes:
>I have a program that can potentially generate an integer overflow.
>I'd like to detect this when it happens and deal with it.  According
>to SGI's Hotline folks, no can do.  The OS catches the interrupt
>and then allows the process to go on its merry way with no mechanism
>to detect the overflow.

Well, our illustrious Hotline crew is usually gives perfectly reliable
information, but I think they may have missed this time.  Here's the
straight scoop:

The MIPS CPU will generate an integer overflow exception for signed 
arithmetic instructions, but not unsigned ones.  So if the MIPS ADD
instruction overflows, a SIGFPE signal is posted, while if an ADDU
instruction overflows, there's no interrupt and hence, no signal is posted.
In fact, this is the only difference between the operation of the ADD and
ADDU instructions.

The MIPS C compiler generates unsigned arithmetic instructions.  This is
the right thing for it to do since most C compilers do not treat 2's
complement overflow as an error and some programs even depend on this.

I think similar considerations would apply to the Fortran compiler, but
I haven't looked.

>Is there really no way?  There's good mechanisms for floating point
>exceptions, why not for integer exceptions?

There is a pretty good way if you know the operation which can potentially
overflow.  If a and b are added, then this test will detect whether c, their
sum, has overflowed.

	c = a + b
	if( (~a^b && a^c) < 0) handle_overflow();

			Bruce Karsh
			karsh at sgi.com



More information about the Comp.sys.sgi mailing list