Transform -X/C to X/-C, implementing a README.txt entry.
authorDan Gohman <gohman@apple.com>
Wed, 12 Aug 2009 16:37:02 +0000 (16:37 +0000)
committerDan Gohman <gohman@apple.com>
Wed, 12 Aug 2009 16:37:02 +0000 (16:37 +0000)
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@78812 91177308-0d34-0410-b5e6-96231b3b80d8

lib/Target/README.txt
lib/Transforms/Scalar/InstructionCombining.cpp
test/Transforms/InstCombine/nsw.ll [new file with mode: 0644]

index 559835e8b54c09dfd206a38e54f72b3a333e8c0d..97546c4db595db64db3b9a49bec8058a860a2a26 100644 (file)
@@ -1111,16 +1111,6 @@ optimized with "clang -emit-llvm-bc | opt -std-compile-opts".
 
 //===---------------------------------------------------------------------===//
 
-We would like to do the following transform in the instcombiner:
-
-  -X/C -> X/-C
-
-However, this isn't valid if (-X) overflows. We can implement this when we
-have the concept of a "C signed subtraction" operator that which is undefined
-on overflow.
-
-//===---------------------------------------------------------------------===//
-
 This was noticed in the entryblock for grokdeclarator in 403.gcc:
 
         %tmp = icmp eq i32 %decl_context, 4          
index 669ef2d5165f36ed8dc307b4d8bfe1dd74120f92..b875420e5beb521ef015ecfc51f3fa07f7db0552 100644 (file)
@@ -3077,6 +3077,14 @@ Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
                                             RHS->getValue().exactLogBase2());
       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
     }
+
+    // -X/C  -->  X/-C  provided the negation doesn't overflow.
+    if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
+      if (isa<Constant>(Sub->getOperand(0)) &&
+          cast<Constant>(Sub->getOperand(0))->isNullValue() &&
+          Sub->hasNoSignedOverflow())
+        return BinaryOperator::CreateSDiv(Sub->getOperand(1),
+                                          ConstantExpr::getNeg(RHS));
   }
 
   // If the sign bits of both operands are zero (i.e. we can prove they are
diff --git a/test/Transforms/InstCombine/nsw.ll b/test/Transforms/InstCombine/nsw.ll
new file mode 100644 (file)
index 0000000..3218371
--- /dev/null
@@ -0,0 +1,20 @@
+; RUN: llvm-as < %s | opt -instcombine | llvm-dis | FileCheck %s
+
+; CHECK: define i32 @foo
+; %y = sub i32 0, %x
+; %z = sdiv i32 %y, 337
+; ret i32 %y
+define i32 @foo(i32 %x) {
+  %y = sub i32 0, %x
+  %z = sdiv i32 %y, 337
+  ret i32 %y
+}
+
+; CHECK: define i32 @bar
+; %y = sdiv i32 %x, -337
+; ret i32 %y
+define i32 @bar(i32 %x) {
+  %y = sub nsw i32 0, %x
+  %z = sdiv i32 %y, 337
+  ret i32 %y
+}