[llvm] [InstCombine] Fold `(select C, (x bin_op a), x) bin_op b` into `x bin_op select C, (a bin_op b), b` (PR #173511)

Gábor Spaits via llvm-commits llvm-commits at lists.llvm.org
Thu Dec 25 08:35:15 PST 2025


================
@@ -1876,6 +1876,45 @@ static Value *simplifyInstructionWithPHI(Instruction &I, PHINode *PN,
   return nullptr;
 }
 
+// In some cases it is beneficial to fold a select into a binary operator.
+// For example:
+//   %1 = or %in, 4
+//   %2 = select %cond, %1, %in
+//   %3 = or %2, 1
+// =>
+//   %1 = select i1 %cond, 5, 1
+//   %2 = or %1, %in
+Instruction *InstCombinerImpl::foldSelectIntoBinOp(BinaryOperator &Op) {
+  SelectInst *SI = dyn_cast<SelectInst>(Op.getOperand(0));
+  ConstantInt *Const = dyn_cast<ConstantInt>(Op.getOperand(1));
+  if (!SI || !Const || !Op.hasOneUse() || !SI->hasOneUse())
+    return nullptr;
+
+  // TODO: Maybe hasOneUse the other bin op too?
+
+  Value *Input, *NewTV, *NewFV, *Cond;
+  ConstantInt *Const2;
+  if (match(SI, m_Select(m_Value(Cond),
+                         m_c_BinOp(Op.getOpcode(), m_Value(Input),
----------------
spaits wrote:

After some experimentation I don't think we could make this work for `div`: https://alive2.llvm.org/ce/z/bXNQ9k
The optimization result will be less defined.

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


More information about the llvm-commits mailing list