[llvm] [SelectionDAG] Introduce ISD::PTRADD (PR #140017)
Fabian Ritter via llvm-commits
llvm-commits at lists.llvm.org
Fri May 16 06:27:03 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);
----------------
ritter-x2a wrote:
Having taken a look at the code path in the [CHERIoT](https://github.com/CHERIoT-Platform/llvm-project/blob/ba63f5a2d112f961b921f19656da7ac61fa1fd1c/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp#L2684) repo, I agree that the version there looks problematic. It creates an `ADD` node (or retrieves an equal existing one that has previously been memoized and could be used elsewhere), calls `visit` outside of the worklist algorithm (which might RAUW it) and then potentially does not use the new node, and doesn't add its users to the worklist.
Unless I'm missing something, it doesn't look like "perform this combine if it enables another combine" is a pattern that the DAGCombiner is designed for.
Other than that, the current version misses the "y and z are constant" case present in the CHERIoT version. I was planning to implement that in the subsequent PRs to enable PTRADD for AMDGPU and keep this PR as faithful as possible to @rgwott's, but I can also add it here already if that is preferred.
https://github.com/llvm/llvm-project/pull/140017
More information about the llvm-commits
mailing list