[Mlir-commits] [mlir] [mlir][LLVMIR] Add folders for `llvm.inttoptr` and `llvm.ptrtoint` (PR #141891)

Diego Caballero llvmlistbot at llvm.org
Thu May 29 10:52:05 PDT 2025


================
@@ -134,6 +134,32 @@ llvm.func @fold_extract_splat() -> f64 {
 
 // -----
 
+// CHECK-LABEL: fold_inttoptr_ptrtoint
+//  CHECK-SAME: %[[ARG:.+]]: i32) -> i32
+//   CHECK-NOT: inttoptr
+//   CHECK-NOT: ptrtoint
+//  CHECK-NEXT: llvm.return %[[ARG]]
+llvm.func @fold_inttoptr_ptrtoint(%x : i32) -> i32 {
+  %c = llvm.inttoptr %x : i32 to !llvm.ptr
+  %d = llvm.ptrtoint %c : !llvm.ptr to i32
+  llvm.return %d : i32
+}
+
+// -----
+
+// CHECK-LABEL: fold_ptrtoint_inttoptr
+//  CHECK-SAME: %[[ARG:.+]]: !llvm.ptr<3>) -> !llvm.ptr<3>
+//   CHECK-NOT: inttoptr
+//   CHECK-NOT: ptrtoint
+//  CHECK-NEXT: llvm.return %[[ARG]]
+llvm.func @fold_ptrtoint_inttoptr(%x : !llvm.ptr<3>) -> !llvm.ptr<3> {
+  %c = llvm.ptrtoint %x : !llvm.ptr<3> to i32
+  %d = llvm.inttoptr %c : i32 to !llvm.ptr<3>
+  llvm.return %d : !llvm.ptr<3>
----------------
dcaballe wrote:

Sorry, that's me sending PRs late at night :)

Thanks for pointing that out. Yes, that folding is not correct unless the size of the pointer is 32 bits.
This is what InstCombine does:

```
define ptr @test_i32(ptr %p1) {
  %i = ptrtoint ptr %p1 to i32
  %p2 = inttoptr i32 %i to ptr
  ret ptr %p2
}

define ptr @test_i64(ptr %p1) {
  %i = ptrtoint ptr %p1 to i64
  %p2 = inttoptr i64 %i to ptr
  ret ptr %p2
}

```
-->
```
define ptr @test_i32(ptr %p1) {
  %1 = ptrtoint ptr %p1 to i64
  %2 = and i64 %1, 4294967295
  %p2 = inttoptr i64 %2 to ptr
  ret ptr %p2
}

define ptr @test_i64(ptr %p1) {
  ret ptr %p1
}
```
That makes sense as LLVM defaults to 64-bit pointers. If we add 32-bit pointer info:

```
target datalayout = "e-p:32:32"
```
-->
```
define ptr @test_i32(ptr %p1) {
  ret ptr %p1
}

define ptr @test_i64(ptr %p1) {
  ret ptr %p1
}
```

So I think we should only apply these folders if we are able to retrieve the pointer size from the DL info and we can prove that no actual data truncation happens. Questions:
1. Is retrieving DL info allowed withing a folder? 
2. Have we agreed upon how to represent pointer information in the DL for the LLVM dialect already (@rengolin)?

Thanks!

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


More information about the Mlir-commits mailing list