[Mlir-commits] [mlir] [mlir][LLVMIR] Add folder pass for `llvm.inttoptr` and `llvm.ptrtoint` (PR #143066)

Christian Ulmann llvmlistbot at llvm.org
Thu Jun 5 22:58:45 PDT 2025


================
@@ -0,0 +1,133 @@
+//===- IntToPtrPtrToIntFolding.cpp - IntToPtr/PtrToInt folding ------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements a pass that folds inttoptr/ptrtoint operation sequences.
+//
+//===----------------------------------------------------------------------===//
+
+#include "mlir/Dialect/LLVMIR/Transforms/IntToPtrPtrToIntFolding.h"
+
+#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
+#include "mlir/IR/PatternMatch.h"
+#include "mlir/Support/LogicalResult.h"
+#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
+
+#define DEBUG_TYPE "fold-llvm-inttoptr-ptrtoint"
+
+namespace mlir {
+namespace LLVM {
+
+#define GEN_PASS_DEF_FOLDINTTOPTRPTRTOINTPASS
+#include "mlir/Dialect/LLVMIR/Transforms/Passes.h.inc"
+
+} // namespace LLVM
+} // namespace mlir
+
+using namespace mlir;
+
+namespace {
+
+/// Return the bitwidth of a pointer or integer type. If the type is a pointer,
+/// return the bitwidth of the address space from `addrSpaceBWs`, if available.
+/// Return failure if the address space bitwidth is not available.
+static FailureOr<unsigned> getIntOrPtrBW(Type type,
+                                         ArrayRef<unsigned> addrSpaceBWs) {
+  if (auto ptrType = dyn_cast<LLVM::LLVMPointerType>(type)) {
+    unsigned addrSpace = ptrType.getAddressSpace();
+    if (addrSpace < addrSpaceBWs.size() && addrSpaceBWs[addrSpace] != 0)
+      return addrSpaceBWs[addrSpace];
+    return failure();
+  }
+
+  auto integerType = cast<IntegerType>(type);
+  return integerType.getWidth();
+}
+
+/// Check if folding inttoptr/ptrtoint is valid. Check that the original type
+/// matches the result type of the end-to-end conversion and that the input
+/// value is not truncated along the conversion chain.
+static LogicalResult canFoldIntToPtrPtrToInt(Type originalType,
+                                             Type intermediateType,
+                                             Type resultType,
+                                             ArrayRef<unsigned> addrSpaceBWs) {
+  // Check if the original type matches the result type.
+  // TODO: Support address space conversions?
+  // TODO: Support int trunc/ext?
----------------
Dinistro wrote:

Note: Maybe using a slicing utility like `walkSlice` would be beneficial for this?

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


More information about the Mlir-commits mailing list