[llvm] [InstCombie] Add folds for (icmp eq/ne (and (add/sub/xor A, P2), P2), 0/P2) (PR #67836)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Fri Sep 29 11:51:00 PDT 2023


================
@@ -5453,6 +5453,45 @@ Instruction *InstCombinerImpl::foldICmpEquality(ICmpInst &I) {
                          m_CombineAnd(m_Value(B), m_Unless(m_ImmConstant())))))
     return new ICmpInst(Pred, Builder.CreateXor(A, B), Cst);
 
+  {
+    auto MatchAndP2OfAddSubXor = [&](unsigned Opc) -> std::optional<bool> {
+      // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
+      std::optional<bool> Matched = std::nullopt;
+      if (match(&I, m_c_ICmp(
+                        PredUnused,
+                        m_OneUse(m_c_And(m_Value(A), m_c_BinOp(Opc, m_Value(B),
+                                                               m_Deferred(A)))),
+                        m_Deferred(A))))
+        Matched = false;
+      // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
+      else if (match(&I, m_ICmp(PredUnused,
+                                m_OneUse(m_c_And(
+                                    m_Value(A),
+                                    m_c_BinOp(Opc, m_Value(B), m_Deferred(A)))),
+                                m_Zero())))
+        Matched = true;
+
+      if (Matched && isKnownToBeAPowerOfTwo(A, /* OrZero */ true, 0, &I))
+        return Matched;
+      return std::nullopt;
+    };
+    std::optional<bool> IsZero = MatchAndP2OfAddSubXor(Instruction::Add);
+    if (!IsZero)
+      IsZero = MatchAndP2OfAddSubXor(Instruction::Sub);
+    if (!IsZero)
+      IsZero = MatchAndP2OfAddSubXor(Instruction::Xor);
+
+    if (IsZero) {
+      // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
+      //    -> (icmp eq/ne (and X, P2), 0)
+      // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
+      //    -> (icmp eq/ne (and X, P2), P2)
+      return new ICmpInst(Pred, Builder.CreateAnd(A, B),
----------------
dtcxzyw wrote:

```suggestion
      return new ICmpInst(Pred, Builder.CreateAnd(B, A),
```
A is likely to be a constant.


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


More information about the llvm-commits mailing list