[LLVMdev] Integer divide by zero
Joshua Cranmer 🐧
Pidgeot18 at gmail.com
Fri Apr 5 11:40:12 PDT 2013
On 4/5/2013 1:23 PM, Cameron McInally wrote:
> Hey guys,
>
> I'm learning that LLVM does not preserve faults during constant
> folding. I realize that this is an architecture dependent problem, but
> I'm not sure if it's safe to constant fold away a fault on x86-64.
>
> A little testcase:
>
> #include <stdio.h>
>
> int foo(int j, int d) {
> return j / d ;
> }
>
> int bar (int k, int d) {
> return foo(k + 1, d);
> }
>
> int main( void ) {
> int r = bar(5, 0);
> printf( " r = %d\n", r);
> }
>
> At execution, on an x86-64 processor, this optimized code should fault
> with a divide-by-zero. At -O2, LLVM 3.1 folds the divide by zero into
> a constant load. This is, of course, undefined by the C standard, so
> the folding makes sense on that front. But on x86-64, I don't think
> this is okay. On x86-64, an integer divide by zero is non-maskable,
> meaning it will always trap and has no result of any type.
Per C and C++, integer division by 0 is undefined. That means, if it
happens, the compiler is free to do whatever it wants. It is perfectly
legal for LLVM to define r to be, say, 42 in this code; it is not
required to preserve the fact that the idiv instruction on x86 and
x86-64 will trap.
--
Joshua Cranmer
Thunderbird and DXR developer
Source code archæologist
More information about the llvm-dev
mailing list