Overflow trap

Several instruction set architectures include arithmetic operations that can trap on overflow, or support this feature with a separate trap-on-overflow-flag instruction (such as the x86 INTO instruction).

I am adding a back-end to the Open Dylan compiler to generate LLVM IR. The original back-end, which generates x86 machine code, makes use of the INTO instruction, and the runtime turns the resulting INT 4 into a language-level exception. In order to support this not-uncommon requirement using LLVM, I see three alternatives:

  1. Add llvm.sadd.with.overflow.trap., … intrinsics corresponding to the current llvm.sadd.with.overflow., … intrinsics to LLVM and the current code generators.

  2. Add a single llvm.trap.overflow intrinsic to LLVM and the current code generators, and ensure that the code generators can generate the proper arithmetic-with-overflow-trap or trap-on-overflow-flag instruction when it is executed conditionally based on the output of one of the llvm.sadd.with.overflow.* etc. intrinsics.

  3. Don’t try to solve this problem for LLVM in general but use inline assembly for these few operations in my back-end.

Which alternative should I pursue? The third is obviously the easiest for me, but other LLVM users would benefit from the other two.

-Peter-

I don’t understand… why can’t you use a branch on a llvm.sadd.with.overflow that goes to an llvm.trap? This is what clang does with -ftrapv.

-Chris

After chatting on IRC, Peter wants a very specific interrupt (int4 on x86). I suggested he add a new llvm.x86.int(i32) intrinsic, and use the existing branch on llvm.sadd.with.overflow intrinsic. The x86 backend can then turn jo+int4 into into when reasonable.

-Chris

The enclosed patch adds a llvm.x86.int(i8) intrinsic expanding to the INT or INT3 instruction as appropriate. I haven’t yet figured out the best way to select for the INTO instruction across basic blocks (hints would be welcome), but that can be added later with no changes in semantics.

-Peter-

int.diff (2.13 KB)

The enclosed patch adds a llvm.x86.int(i8) intrinsic expanding to the INT or INT3 instruction as appropriate.

Looks great! Applied in r111831.

I haven't yet figured out the best way to select for the INTO instruction across basic blocks (hints would be welcome), but that can be added later with no changes in semantics.

I'd suggest handling this late in the pipeline, probably in the branch folding phase. I'm not sure if branch folding allows target-specific xforms to be implemented in it yet though.

-Chris