Optimize exact sdiv by a constant power of 2 to ashr.
authorDan Gohman <gohman@apple.com>
Tue, 11 Aug 2009 20:47:47 +0000 (20:47 +0000)
committerDan Gohman <gohman@apple.com>
Tue, 11 Aug 2009 20:47:47 +0000 (20:47 +0000)
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@78714 91177308-0d34-0410-b5e6-96231b3b80d8

lib/Transforms/Scalar/InstructionCombining.cpp
test/Transforms/InstCombine/exact-sdiv.ll [new file with mode: 0644]

index b9b4ccb6cfb82a66fabec4cab970357cac7acc48..798e3d24e9f0b3301c0b31db8d0d791cc99c16aa 100644 (file)
@@ -3064,6 +3064,15 @@ Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
     // sdiv X, -1 == -X
     if (RHS->isAllOnesValue())
       return BinaryOperator::CreateNeg(*Context, Op0);
+
+    // sdiv X, C  --> ashr X, log2(C)
+    if (cast<SDivOperator>(&I)->isExact() &&
+        RHS->getValue().isNonNegative() &&
+        RHS->getValue().isPowerOf2()) {
+      Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
+                                            RHS->getValue().exactLogBase2());
+      return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
+    }
   }
 
   // If the sign bits of both operands are zero (i.e. we can prove they are
diff --git a/test/Transforms/InstCombine/exact-sdiv.ll b/test/Transforms/InstCombine/exact-sdiv.ll
new file mode 100644 (file)
index 0000000..9ed524f
--- /dev/null
@@ -0,0 +1,15 @@
+; RUN: llvm-as < %s | opt -instcombine | llvm-dis | FileCheck %s
+
+; CHECK: define i32 @foo
+; CHECK: sdiv i32 %x, 8
+define i32 @foo(i32 %x) {
+  %y = sdiv i32 %x, 8
+  ret i32 %y
+}
+
+; CHECK: define i32 @bar
+; CHECK: ashr i32 %x, 3
+define i32 @bar(i32 %x) {
+  %y = sdiv exact i32 %x, 8
+  ret i32 %y
+}