[Mlir-commits] [mlir] [mlir][LLVM] Fix crash when dereferenceable instruction is folded (PR #221682)

Fangrui Song llvmlistbot at llvm.org
Mon Sep 7 01:57:59 PDT 2026


https://github.com/MaskRay created https://github.com/llvm/llvm-project/pull/221682

`inst` is null when the builder folds the cast of a constant. Fix
nullptr dereference by dropping the metadata.


>From e1659be7cf3b532002d4b24e83e342ab2fbe7316 Mon Sep 17 00:00:00 2001
From: Fangrui Song <i at maskray.me>
Date: Mon, 7 Sep 2026 00:57:43 -0700
Subject: [PATCH] [mlir][LLVM] Fix crash when dereferenceable instruction is
 folded

`inst` is null when the builder folds the cast of a constant. Fix
nullptr dereference by dropping the metadata.
---
 mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td            | 4 ++--
 mlir/test/Target/LLVMIR/attribute-dereferenceable.mlir | 9 +++++++++
 2 files changed, 11 insertions(+), 2 deletions(-)

diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
index ab641a5da8c22..3acbfe25ffb91 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
@@ -620,8 +620,8 @@ class LLVM_DereferenceableCastOp<string mnemonic, string instName, Type type,
     auto *val = builder.Create}] # instName # [{($arg, $_resultType);
     $res = val;
     if ($dereferenceable) {
-      llvm::Instruction *inst = dyn_cast<llvm::Instruction>(val);
-      moduleTranslation.setDereferenceableMetadata(op, inst);
+      if (auto *inst = dyn_cast<llvm::Instruction>(val))
+        moduleTranslation.setDereferenceableMetadata(op, inst);
     }
   }];
   string mlirBuilder = [{
diff --git a/mlir/test/Target/LLVMIR/attribute-dereferenceable.mlir b/mlir/test/Target/LLVMIR/attribute-dereferenceable.mlir
index 6e7f03110faa7..d624392d8bf25 100644
--- a/mlir/test/Target/LLVMIR/attribute-dereferenceable.mlir
+++ b/mlir/test/Target/LLVMIR/attribute-dereferenceable.mlir
@@ -20,5 +20,14 @@ llvm.func @deref_or_null(%arg0: i64, %arg1: !llvm.ptr) {
   llvm.return
 }
 
+// Dereferenceable metadata is dropped if the cast is folded.
+llvm.func @deref_folded_away() -> !llvm.ptr {
+  // CHECK: define ptr @deref_folded_away()
+  // CHECK-NEXT: ret ptr inttoptr (i64 64 to ptr)
+  %0 = llvm.mlir.constant(64 : i64) : i64
+  %1 = llvm.inttoptr %0 dereferenceable<bytes = 4> : i64 to !llvm.ptr
+  llvm.return %1 : !llvm.ptr
+}
+
 // CHECK: [[D0]] = !{i64 4}
 // CHECK: [[D1]] = !{i64 8}



More information about the Mlir-commits mailing list