[PATCH] Implement intrinsics for safe division

Nadav Rotem nrotem at apple.com
Sun Apr 20 21:47:44 PDT 2014


LGTM. 

On Apr 17, 2014, at 1:47 AM, Michael Zolotukhin <mzolotukhin at apple.com> wrote:

> Hi,
> 
> This patch implements LLVM intrinsics for safe division: llvm.safe.sdiv.iN, llvm.safe.udiv.iN, llvm.safe.srem.iN, and llvm.safe.urem.iN (iN is i8, i16, i32, or i64). In some extent, they are similar to intrinsics for arithmetic with overflow checks (e.g. llvm.sadd.with.overflow).
> 
> <safe-div-intrinsics.patch>
> 
> The intrinsics give the results following the next rules:
> If the RHS is 0, the return value is a pair {0, 1}.
> If the intrinsic is for signed operation, the RHS is -1 and the LHS is SignedMinValue, the intrinsic returns {SignedMinValue, 1}.
> In other cases, the result value is {LHS op RHS, 0}, where op is sdiv, udiv, srem, and urem, depending on the intrinsic.
> 
> Examples:
> 
> llvm.safe.sdiv.i32(i32 8, i32 3) returns {i32 2, i1 0}.
> llvm.safe.urem.i8(i8 18, i8 5) returns {i8 3, i1 0}.
> llvm.safe.srem.i8(i8 -128, i8 -1) returns {i8 -128, i1 1}.
> llvm.safe.urem.i8(i8 128, i8 0) returns {i8 0, i1 1}.
> llvm.safe.udiv.i8(i8 128, i8 255) returns {i8 0, i1 0}.
> 
> Example of actual use:
> 
>   %divresult32 = type { i32, i1 }
> ...
>   %divr = call %divresult32 @llvm.safe.sdiv.i32(i32 %x, i32 %y)
>   %div = extractvalue %divresult32 %divr, 0
>   %bit = extractvalue %divresult32 %divr, 1
>   br i1 %bit, label %trap.bb, label %ok.bb
> trap.bb:
>   call void @abort()
> ok.bb:
>   ret i32 %div
> 
> The implementation also tries to propagate the computed results to the users. It expects that the users are extractvalue instructions, otherwise it conservatively generates alloca+stores+load. If the propagation succeeds the resultant code becomes much cleaner and more efficient, especially on ARM64 where DIV instructions behave exactly the same way the intrinsic designed. To check whether DIV instruction behave this way or not, a new target hook was introduced.
> 
> The added tests are separated into two parts: the first one checks whether the full set of intrinsics is implemented, and the second one tests if the results propagation works correctly. The tests were added only for X86 and ARM64.
> 
> Is it ok to commit?
> 
> Thanks,
> Michael

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20140420/68cd9a36/attachment.html>


More information about the llvm-commits mailing list