[llvm] [DAG] SDPatternMatch - add matchers for reassociatable binops (PR #119985)

Simon Pilgrim via llvm-commits llvm-commits at lists.llvm.org
Wed Apr 16 07:56:12 PDT 2025


================
@@ -1134,6 +1136,87 @@ inline BinaryOpc_match<ValTy, AllOnes_match, true> m_Not(const ValTy &V) {
   return m_Xor(V, m_AllOnes());
 }
 
+template <typename... PatternTs> struct ReassociatableOpc_match {
+  unsigned Opcode;
+  std::tuple<PatternTs...> Patterns;
+
+  ReassociatableOpc_match(unsigned Opcode, const PatternTs &...Patterns)
+      : Opcode(Opcode), Patterns(Patterns...) {}
+
+  template <typename MatchContext>
+  bool match(const MatchContext &Ctx, SDValue N) {
+    SmallVector<SDValue> Leaves;
+    collectLeaves(N, Leaves);
+    if (Leaves.size() != std::tuple_size_v<std::tuple<PatternTs...>>)
+      return false;
+
+    // Matches[I][J] == true iff sd_context_match(Leaves[I], Ctx,
+    // std::get<J>(Patterns)) == true
+    std::array<SmallBitVector, std::tuple_size_v<std::tuple<PatternTs...>>>
+        Matches;
+    for (size_t I = 0, N = Leaves.size(); I < N; I++) {
+      SmallVector<bool> MatchResults;
+      std::apply(
+          [&](auto &...P) {
+            (Matches[I].push_back(sd_context_match(Leaves[I], Ctx, P)), ...);
----------------
RKSimon wrote:

I was expecting m_Value(A) to match one of %s0 or %s1 and m_Value(B) to match the other - but instead both are matching to the same one.

I was really hoping to do this, but I doubt the current implementation can manage it:
```cpp
if (sd_match(N, m_ReassociatableAdd(m_Srl(m_Value(A), m_SpecificInt(1)),
                                    m_Srl(m_Value(B), m_SpecificInt(1)),
                                    m_ReassociatableAnd(m_Deferred(A), m_Deferred(B), m_SpecificInt(1)))))
  return DAG.getNode(ISD::AVGFLOORU, DL, VT, A, B);
```

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


More information about the llvm-commits mailing list