[llvm] [SelectionDAG] Introduce ISD::PTRADD (PR #140017)
Jessica Clarke via llvm-commits
llvm-commits at lists.llvm.org
Fri May 16 16:35:30 PDT 2025
================
@@ -2617,6 +2620,100 @@ SDValue DAGCombiner::foldSubToAvg(SDNode *N, const SDLoc &DL) {
return SDValue();
}
+/// Try to fold a pointer arithmetic node.
+/// This needs to be done separately from normal addition, because pointer
+/// addition is not commutative.
+/// This function was adapted from DAGCombiner::visitPTRADD() from the Morello
+/// project, which is based on CHERI.
+SDValue DAGCombiner::visitPTRADD(SDNode *N) {
+ SDValue N0 = N->getOperand(0);
+ SDValue N1 = N->getOperand(1);
+ EVT PtrVT = N0.getValueType();
+ EVT IntVT = N1.getValueType();
+ SDLoc DL(N);
+
+ // fold (ptradd undef, y) -> undef
+ if (N0.isUndef())
+ return N0;
+
+ // fold (ptradd x, undef) -> undef
+ if (N1.isUndef())
+ return DAG.getUNDEF(PtrVT);
+
+ // fold (ptradd x, 0) -> x
+ if (isNullConstant(N1))
+ return N0;
+
+ if (N0.getOpcode() == ISD::PTRADD &&
+ !reassociationCanBreakAddressingModePattern(ISD::PTRADD, DL, N, N0, N1)) {
+ SDValue X = N0.getOperand(0);
----------------
jrtc27 wrote:
Yeah the "y + z can be constant folded" is the one I'm concerned about losing. Part of the problem here is this is a one-way transformation (going backwards can mean taking a pointer out of bounds that wasn't previously, which is a problem for both CPA and, much more extensively, CHERI), and we don't want to hide a constant operand behind an ADD node because then that can't be selected to an immediate offset by the backend, instead it has to compute the full offset into a register first. The idea behind the CHERI code is that it can peek into what the result would look like if it did the transformation and commit to doing it only after having more information. Yes, "y and z are both constants" will catch some cases, but that won't catch more complex arithmetic expressions that can be simplified (as a trivial example, `(ptradd (ptradd x, c), (sub 0, c))`, but that could be rather more obfuscated and require more peeking, which visitADD already knows how to do). Maybe the only way to do that correctly though is repeat a bunch of visitADD(Like) for visitPTRADD.
https://github.com/llvm/llvm-project/pull/140017
More information about the llvm-commits
mailing list