[llvm] [GlobalIsel] Combine G_PTR_ADD. (PR #95647)

Pierre van Houtryve via llvm-commits llvm-commits at lists.llvm.org
Mon Jun 17 01:36:59 PDT 2024


Thorsten =?utf-8?q?Schütt?= <schuett at gmail.com>,
Thorsten =?utf-8?q?Schütt?= <schuett at gmail.com>
Message-ID:
In-Reply-To: <llvm.org/llvm/llvm-project/pull/95647 at github.com>


================
@@ -7437,3 +7437,212 @@ bool CombinerHelper::matchNonNegZext(const MachineOperand &MO,
 
   return false;
 }
+
+bool CombinerHelper::matchPtrAddWithSub(const MachineOperand &MO,
+                                        BuildFnTy &MatchInfo) {
+  GPtrAdd *Inner = cast<GPtrAdd>(MRI.getVRegDef(MO.getReg()));
+  GSub *Sub = cast<GSub>(MRI.getVRegDef(Inner->getOffsetReg()));
+
+  // sub(x, c) -> add(x, -c)
+
+  // one-use check
+  if (!MRI.hasOneNonDBGUse(Sub->getReg(0)))
+    return false;
+
+  // Cannot fail due to pattern.
+  std::optional<APInt> MaybeImm = getIConstantVRegVal(Sub->getRHSReg(), MRI);
+  if (!MaybeImm)
+    return false;
+
+  LLT ConstTy = MRI.getType(Inner->getOffsetReg());
+
+  if (!isConstantLegalOrBeforeLegalizer(ConstTy))
+    return false;
+
+  Register Dst = MO.getReg();
+  LLT DstTy = MRI.getType(Dst);
+
+  MatchInfo = [=](MachineIRBuilder &B) {
----------------
Pierre-vh wrote:

`G_SUB $sub, 0, $x` will create a `G_CONSTANT` implicitly, it should realize that `G_SUB` does not allow direct immediates and act accordingly. The type of the constant will also be inferred from `$x`.

But even if you had to create a `G_CONSTANT` manually, it's not really a valid reason to not do the change IMO. It's just more verbose.

I don't understand why you can't do the change, can you just post a example of what MIR pattern you have tried and what behavior/errors you observed?

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


More information about the llvm-commits mailing list