[llvm] [AMDGPU][GISel] Fold 'min(min(x,y),z)' and 'max(max(x,y),z)' into min3 and max3 (PR #200410)

Petar Avramovic via llvm-commits llvm-commits at lists.llvm.org
Thu Jun 4 04:49:59 PDT 2026


================
@@ -481,6 +491,75 @@ bool AMDGPURegBankCombinerImpl::combineD16Load(MachineInstr &MI) const {
   return false;
 }
 
+void AMDGPURegBankCombinerImpl::applyMinMaxToMinMax3(
+    MachineInstr &MI, MinMaxToMinMax3MatchInfo &MatchInfo) const {
+  B.buildInstr(MatchInfo.Opc, {MI.getOperand(0)},
+               {MatchInfo.Val0, MatchInfo.Val1, MatchInfo.Val2}, MI.getFlags());
+  MI.eraseFromParent();
+  return;
+}
+
+bool AMDGPURegBankCombinerImpl::matchMinMaxToMinMax3(
+    MachineInstr &MI, MinMaxToMinMax3MatchInfo &MatchInfo) const {
+  Register dst = MI.getOperand(0).getReg();
+  Register src1 = MI.getOperand(1).getReg();
+  Register src2 = MI.getOperand(2).getReg();
+  // if the register is SGPR, don't optimize it.
+  if (!(isVgprRegBank(dst) && isVgprRegBank(src1) && isVgprRegBank(src2))) {
+    return false;
+  }
+
+  LLT t = MRI.getType(dst);
+  bool IsSupportedTy = t == LLT::scalar(32) ||
+                       (t == LLT::scalar(16) && STI.hasMin3Max3_16()) ||
+                       (t.isVector() && t.getScalarSizeInBits() == 32);
+
+  if (!IsSupportedTy)
+    return false;
+
+  Register R0, R1, R2;
+  unsigned opc = MI.getOpcode();
+  auto matchMinOrMax3 = [&](MachineInstr &MI, MachineRegisterInfo &MRI,
+                            unsigned op, Register &r0, Register &r1,
+                            Register &r2) {
+    auto p1 = m_BinOp(op, m_OneNonDBGUse(m_BinOp(op, m_Reg(r0), m_Reg(r1))),
+                      m_Reg(r2));
+    auto p2 = m_BinOp(op, m_Reg(r0),
+                      m_OneNonDBGUse(m_BinOp(op, m_Reg(r1), m_Reg(r2))));
+
+    return mi_match(MI, MRI, m_any_of(p1, p2));
+  };
+  if (!matchMinOrMax3(MI, MRI, opc, R0, R1, R2)) {
----------------
petar-avramovic wrote:

just inline matchMinOrMax3?

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


More information about the llvm-commits mailing list