[PATCH] Add NSW/NUW flags in InstCombine

Nick Lewycky nicholas at mxc.ca
Tue Apr 1 20:40:52 PDT 2014


David Tweed wrote:
>
>    My understanding was that the meaning of nsw/nuw flags was "there's no need to care about the semantics of the code that would execute in the event that there's a wraparound of that type" (so that in particular there's no need to add extra code to deal with those cases, or forbid optimizing away code that will only execute in the overflowing case). In the case of where an overflow is undefined behaviour according to the higher level languages semantics, the compiler needn't care because it's entitled to do whatever it wants if that occurs. In the case where it's known that overflow can't happen (due to the way the operands on the instruction have been produced) the compiler needn't care because that code can't ever be executed. Or is this understanding not quite right?

Yes, nsw/nuw means that the operands contain values such that overflow 
does not occur in this operation.

Unfortunately, it's not as simple as not adding extra code to deal with 
those cases. There are optimizations that are correct to perform on add 
without nsw/nuw that are invalid given an add with nsw/nuw. Consider:

   %X = xor i32 %A, 2147483648
   %Y = add i32 %X, 1
   %Z = trunc i32 Y to i31
   ret i31 %Z  ;; or otherwise use %Z for something

Because of the truncate, the sign bit change in %X is irrelevant, so we 
can eliminate that xor, producing:

   %Y = add i32 %A, 1
   %Z = trunc i32 Y to i31
   ret i31 %Z  ;; or otherwise use %Z for something

But if you used 'add nsw', then removing a change of the sign bit could 
transform code that did not produce a trap value to code which does. Whoops!

Nick

>
>    (Obviously I do work at ARM, but I've had no involvement in this patch.)
>
> http://llvm-reviews.chandlerc.com/D2426
> _______________________________________________
> llvm-commits mailing list
> llvm-commits at cs.uiuc.edu
> http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits
>




More information about the llvm-commits mailing list