Signed overflow optimization hazards in the kernel
Signed overflow optimization hazards in the kernel
Posted Aug 16, 2012 14:04 UTC (Thu) by baldrick (subscriber, #4123)Parent article: Signed overflow optimization hazards in the kernel
> which is using a variation on this theme to determine whether the
> requested event time really is in the future. Here the actual subtraction
> is unsigned, but the result is cast to an signed integer. Because unsigned
> longs are always positive, the only way that the result can be negative
> (when interpreted as a signed value) is overflow, which the compiler is
> permitted to assume never happens. The compiler is therefore within its
> rights to unconditionally evaluate the test as false and return zero,
> which might fatally disappoint the caller.
As far as I know this is wrong: there is no problem in the second example. The misunderstanding is in "Because unsigned longs are always positive, the only way that the result can be negative (when interpreted as a signed value) is overflow, which the compiler is permitted to assume never happens". Since the numbers have unsigned type, subtracting them always has a well defined result. The fact that when you think of these numbers as being signed you see in your head that a signed overflow must have occurred is of no relevance. The cast to a signed type is also always well defined. In fact I would say the right way to avoid this issue is to copy this example and do something like
(signed) ((unsigned)x - (unsigned)y) < 0
rather than do the baroque comparison recommended by the article.
For more on this kind of thing I recommend http://blog.regehr.org/archives/213
