[llvm] [InstCombine] Canonicalize Bit Testing by Shifting to Sign Bit (PR #101822)

Marius Kamp via llvm-commits llvm-commits at lists.llvm.org
Sun Aug 11 00:02:26 PDT 2024


================
@@ -2304,19 +2304,33 @@ Instruction *InstCombinerImpl::foldICmpShlConstant(ICmpInst &Cmp,
     if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
       return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
 
+  unsigned TypeBits = C.getBitWidth();
+  Value *X = Shl->getOperand(0);
+  Type *ShType = Shl->getType();
+
+  // (icmp slt (shl X, (sub bw-1, Y)), 0)  --> (icmp ne (and X, (shl 1, Y)), 0)
+  // (icmp sgt (shl X, (sub bw-1, Y)), -1) --> (icmp eq (and X, (shl 1, Y)), 0)
+  Value *Y;
+  if (Shl->hasOneUse() &&
+      (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT) &&
+      (Pred == ICmpInst::ICMP_SLT ? C.isZero() : C.isAllOnes()) &&
+      match(Shl->getOperand(1),
+            m_OneUse(m_Sub(m_SpecificInt(TypeBits - 1), m_Value(Y)))))
+    return new ICmpInst(
+        Pred == ICmpInst::ICMP_SLT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
+        Builder.CreateAnd(X, Builder.CreateShl(ConstantInt::get(ShType, 1), Y,
----------------
mskamp wrote:

The definition of the variable `X` is just moved upwards in this commit. `X` is used quite a lot by the following code. Therefore, I think, it's better to use `X` here instead of `Shl->getOperand(0)` and then defining `X` as `Shl->getOperand(0)` for the following transformations.

https://github.com/llvm/llvm-project/pull/101822


More information about the llvm-commits mailing list