[llvm] [CVP]: Fold `icmp eq X, C` to `trunc X to i1` if C=2k+1 and X in [2k, 2k+1] (PR #83829)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Mon Mar 4 03:57:30 PST 2024


================
@@ -332,6 +332,39 @@ static bool constantFoldCmp(CmpInst *Cmp, LazyValueInfo *LVI) {
   return true;
 }
 
+/// Given an icmp `icmp eq X, C`,
+/// if we already know that C is 2k+1 and X is in [2k, 2k+1],
+/// then we can fold it to `trunc X to i1`.
+static bool processEqualityICmp(CmpInst *Cmp, LazyValueInfo *LVI) {
+  if (Cmp->getType()->isVectorTy() ||
+      !Cmp->getOperand(0)->getType()->isIntegerTy() || !Cmp->isEquality())
+    return false;
+
+  Value *Op0 = Cmp->getOperand(0);
+  Value *Op1 = Cmp->getOperand(1);
+  ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
+  if (!CI)
+    return false;
+
+  ConstantRange Range =
+      LVI->getConstantRangeAtUse(Cmp->getOperandUse(0), /*UndefAllowed*/ true);
+  APInt RangeSize = Range.getUpper() - Range.getLower();
+  APInt Value = CI->getValue();
+  if (RangeSize != 2 || !Range.contains(Value))
+    return false;
+
+  bool ShouldBeOdd = Cmp->getPredicate() == ICmpInst::Predicate::ICMP_EQ;
+  if ((CI->getValue() & 1) == ShouldBeOdd) {
----------------
dtcxzyw wrote:

```suggestion
  if (CI->getValue()[0] == ShouldBeOdd) {
```

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


More information about the llvm-commits mailing list