[llvm] [InstCombine] Try optimizing with knownbits which determined from Cond (PR #91762)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Mon May 13 18:30:41 PDT 2024


================
@@ -1790,6 +1790,159 @@ static Instruction *foldSelectICmpEq(SelectInst &SI, ICmpInst *ICI,
   return nullptr;
 }
 
+// ICmpInst of SelectInst is not included in the calculation of KnownBits
+// so we are missing the opportunity to optimize the Value of the True or
+// False Condition via ICmpInst with KnownBits.
+//
+// Consider:
+//   %or = or i32 %x, %y
+//   %or0 = icmp eq i32 %or, 0
+//   %and = and i32 %x, %y
+//   %cond = select i1 %or0, i32 %and, i32 %or
+//   ret i32 %cond
+//
+// Expect:
+//   %or = or i32 %x, %y
+//   ret i32 %or
+//
+// We could know what bit was enabled for %x, %y by ICmpInst in SelectInst.
+static Instruction *foldSelectICmpBinOp(SelectInst &SI, ICmpInst *ICI,
+                                        Value *CmpLHS, Value *CmpRHS,
+                                        Value *TVal, Value *FVal,
+                                        InstCombinerImpl &IC) {
+  Value *X, *Y;
+  const APInt *C;
+
+  if (!((match(CmpLHS, m_BinOp(m_Value(X), m_Value(Y))) &&
+         match(CmpRHS, m_APInt(C))) &&
+        (match(TVal, m_c_BinOp(m_Specific(X), m_Value())) ||
+         match(TVal, m_c_BinOp(m_Specific(Y), m_Value())))))
----------------
dtcxzyw wrote:

Consider the following example: https://alive2.llvm.org/ce/z/f579pe
```
define i32 @src(i32 %x, i32 %y) {
    %or = or i32 %x, %y
    %or0 = icmp ne i32 %or, 0
    %and = and i32 %x, %y
    %cond = select i1 %or0, i32 %or, i32 %and
    ret i32 %cond
}

define i32 @tgt(i32 %x, i32 %y) {
    %or = or i32 %x, %y
    ret i32 %or
}
```


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


More information about the llvm-commits mailing list