[llvm] [RISCV][P-ext] Recognize (select (X >u ((1 << C) - 1), sext(X >s -1), trunc(X)) as usati (PR #190810)

Sam Elliott via llvm-commits llvm-commits at lists.llvm.org
Tue Apr 7 12:01:19 PDT 2026


================
@@ -20280,11 +20280,77 @@ static SDValue performVSELECTCombine(SDNode *N, SelectionDAG &DAG) {
   return DAG.getNode(ISD::ADD, DL, VT, A, NewB);
 }
 
+// Fold (iC (select (src >u ((1 << C) - 1)), sext(src >s -1), trunc(src))) to
+// USATI. This pattern saturates a signed value to an unsigned N-bit range
+// [0, 2^N-1]:
+//   - If src < 0: result = 0
+//       (via the inner comparison src > -1 = false, sext to 0)
+//   - If src > ((1 << C) - 1): result = all 1s
+//       (via sext(true) = -1 = 0xFF...)
+//   - Otherwise: result = src (via trunc(src))
+// The outer comparison is unsigned, so negative values appear as large
+// unsigned values and trigger the saturation to MaxVal path, where the
+// inner signed comparison then produces 0.
+// TODO: Support (select (src <=u ((1 << C) - 1)), trunc(src), sext(src >s -1)).
+static SDValue foldSelectToUSATI(SDNode *N, SelectionDAG &DAG,
+                                 const RISCVSubtarget &Subtarget) {
+  if (!Subtarget.hasStdExtP())
+    return SDValue();
+
+  EVT VT = N->getValueType(0);
+  MVT XLenVT = Subtarget.getXLenVT();
+
+  // Only support scalar integer types smaller than XLenVT
+  if (!VT.isScalarInteger() || VT.bitsGE(XLenVT))
+    return SDValue();
+
+  unsigned SatWidth = VT.getSizeInBits();
+  uint64_t MaxVal = (1ULL << SatWidth) - 1;
+
+  using namespace SDPatternMatch;
+
+  SDValue Src, InnerSetCC, FalseSrc;
+  if (!sd_match(N, m_Select(m_SetCC(m_Value(Src), m_SpecificInt(MaxVal),
+                                    m_SpecificCondCode(ISD::SETUGT)),
+                            m_SExt(m_Value(InnerSetCC)),
+                            m_Trunc(m_Value(FalseSrc)))))
+    return SDValue();
+
+  // Src can't be larger than XLenVT.
+  if (Src.getValueType().bitsGT(XLenVT))
+    return SDValue();
+
+  // Check inner setcc: src > -1 (signed comparison)
+  if (InnerSetCC.getValueType() != MVT::i1 ||
+      !sd_match(InnerSetCC, m_SetCC(m_Specific(Src), m_AllOnes(),
+                                    m_SpecificCondCode(ISD::SETGT))))
+    return SDValue();
+
+  // FalseSrc may have been optimized from a truncate of a truncate. There may
+  // still be a truncate on Src. Look through it so we can compare them.
+  SDValue CmpSrc = Src;
+  if (CmpSrc.getOpcode() == ISD::TRUNCATE)
+    CmpSrc = CmpSrc.getOperand(0);
----------------
lenary wrote:

Is this something we can hit? This is folded away in `getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1, const SDNodeFlags Flags)` - maybe we're creating one a different way?

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


More information about the llvm-commits mailing list