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

llvmlistbot at llvm.org llvmlistbot at llvm.org
Mon Sep 7 01:58:35 PDT 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-mlir

Author: Fangrui Song (MaskRay)

<details>
<summary>Changes</summary>

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


---
Full diff: https://github.com/llvm/llvm-project/pull/221682.diff


2 Files Affected:

- (modified) mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td (+2-2) 
- (modified) mlir/test/Target/LLVMIR/attribute-dereferenceable.mlir (+9) 


``````````diff
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}

``````````

</details>


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


More information about the Mlir-commits mailing list