[llvm] [InstCombine] Generalize `(A + 1) + ~B` fold to any constant (PR #188271)

Piotr Fusik via llvm-commits llvm-commits at lists.llvm.org
Thu Apr 9 23:49:53 PDT 2026


================
@@ -1604,13 +1604,27 @@ Instruction *InstCombinerImpl::visitAdd(BinaryOperator &I) {
   if (Value *V = checkForNegativeOperand(I, Builder))
     return replaceInstUsesWith(I, V);
 
-  // (A + 1) + ~B --> A - B
-  // ~B + (A + 1) --> A - B
-  // (~B + A) + 1 --> A - B
-  // (A + ~B) + 1 --> A - B
-  if (match(&I, m_c_BinOp(m_Add(m_Value(A), m_One()), m_Not(m_Value(B)))) ||
-      match(&I, m_BinOp(m_c_Add(m_Not(m_Value(B)), m_Value(A)), m_One())))
-    return BinaryOperator::CreateSub(A, B);
+  {
+    // (A + C) + ~B --> A - B + (C-1)
+    // ~B + (A + C) --> A - B + (C-1)
+    // (~B + A) + C --> A - B + (C-1)
+    // (A + ~B) + C --> A - B + (C-1)
+    // This relies on the ~B == -1-B identity.
+    // With constant C, subtraction of one is free, so we replace three ops
+    // (two adds and a bitwise-not) with two (sub and add)
+    // or even one (just sub for the C==1 special case).
+    const APInt *C;
+    if (match(&I, m_c_BinOp(m_OneUse(m_Add(m_Value(A), m_APIntAllowPoison(C))),
+                            m_Not(m_Value(B)))) ||
+        (match(&I, m_c_BinOp(m_Add(m_Value(A), m_APIntAllowPoison(C)),
+                             m_OneUse(m_Not(m_Value(B))))) &&
----------------
pfusik wrote:

This only matches if `A + C` is multi-use, otherwise the previous match would apply. With both `A + C` and  `~B` being multi-use, in `t15` it's a final `add` without the transform vs `sub` with it. The former can use x86 `lea`, the latter has fewer data dependencies.

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


More information about the llvm-commits mailing list