Skip to content

[mlir][GPU] Refactor GPUOps lowering - #188905

Merged
hockyy merged 2 commits into
llvm:mainfrom
hockyy:gpu-ops-lower-refactor
Apr 22, 2026
Merged

hockyy merged 2 commits into
llvm:mainfrom
hockyy:gpu-ops-lower-refactor

Conversation

@hockyy

@hockyy hockyy commented Mar 27, 2026 •

Copy link
Copy Markdown
Member

This change promotes gpu.func / gpu.launch metadata that was previously carried as discardable attributes into proper inherent ODS fields (kernel, workgroup_attributions), renames the block-argument helpers to avoid clashing with generated getters, and routes func.func and gpu.func lowering through a shared helper that maps discardable llvm.* attributes into llvm.func properties.

Downstream producers (Flang CUDA device func transform, kernel outlining, sparse GPU codegen, XeGPU) set kernels via setKernel(true) instead of manually attaching gpu.kernel.

Fixes #185174

Assisted-by: CLion code completion, GPT 5.3 - Codex

@llvmbot

llvmbot commented Mar 27, 2026 •

Copy link
Copy Markdown
Member

@llvm/pr-subscribers-flang-fir-hlfir
@llvm/pr-subscribers-mlir-sparse

@llvm/pr-subscribers-mlir

Author: Hocky Yudhiono (hockyy)

Changes

Refactors gpu.func to llvm.func lowering to reuse the same discardable-attribute path as func.func to llvm.func, moves that shared logic into LLVMCommon, and keeps GPU-specific metadata explicit.


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

6 Files Affected:

  • (added) mlir/include/mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h (+39)
  • (modified) mlir/lib/Conversion/FuncToLLVM/FuncToLLVM.cpp (+3-50)
  • (modified) mlir/lib/Conversion/GPUCommon/GPUOpsLowering.cpp (+73-59)
  • (modified) mlir/lib/Conversion/GPUCommon/GPUOpsLowering.h (+7)
  • (modified) mlir/lib/Conversion/LLVMCommon/CMakeLists.txt (+1)
  • (added) mlir/lib/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.cpp (+56)
diff --git a/mlir/include/mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h b/mlir/include/mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h
new file mode 100644
index 0000000000000..f12f9d2c90e2e
--- /dev/null
+++ b/mlir/include/mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h
@@ -0,0 +1,39 @@
+//===- LowerFunctionAttrsToLLVM.h - Lower func attrs to llvm.func - C++ -*-===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+//
+// Shared helpers for lowering discardable attributes on any FunctionOpInterface
+// (e.g. func.func, gpu.func) into llvm.func properties and discardables.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MLIR_CONVERSION_LLVMCOMMON_LOWERFUNCTIONATTRSTOLLVM_H
+#define MLIR_CONVERSION_LLVMCOMMON_LOWERFUNCTIONATTRSTOLLVM_H
+
+#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
+#include "mlir/IR/OperationSupport.h"
+#include "mlir/Interfaces/FunctionInterfaces.h"
+
+namespace mlir {
+
+/// Result of lowering discardable attributes from a `FunctionOpInterface` to
+/// what `llvm.func` expects: typed inherent properties plus remaining
+/// discardable attributes.
+struct LowerLLVMFuncAttrs {
+  LLVM::LLVMFuncOp::Properties properties;
+  NamedAttrList discardableAttrs;
+};
+
+/// Lower discardable attributes on `func`, splitting `llvm.*` inherent
+/// properties from other attributes to forward to `llvm.func`. Returns
+/// failure if an `llvm.*` property bundle is invalid for `llvm.func`.
+FailureOr<LowerLLVMFuncAttrs>
+lowerDiscardableAttrsForLLVMFunc(FunctionOpInterface func);
+
+} // namespace mlir
+
+#endif // MLIR_CONVERSION_LLVMCOMMON_LOWERFUNCTIONATTRSTOLLVM_H
diff --git a/mlir/lib/Conversion/FuncToLLVM/FuncToLLVM.cpp b/mlir/lib/Conversion/FuncToLLVM/FuncToLLVM.cpp
index 88abc4400c9b7..bd7bc47217bdc 100644
--- a/mlir/lib/Conversion/FuncToLLVM/FuncToLLVM.cpp
+++ b/mlir/lib/Conversion/FuncToLLVM/FuncToLLVM.cpp
@@ -19,6 +19,7 @@
 #include "mlir/Conversion/ConvertToLLVM/ToLLVMInterface.h"
 #include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h"
 #include "mlir/Conversion/LLVMCommon/ConversionTarget.h"
+#include "mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h"
 #include "mlir/Conversion/LLVMCommon/Pattern.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
 #include "mlir/Dialect/LLVMIR/FunctionCallUtils.h"
@@ -77,55 +78,6 @@ static void filterFuncAttributes(FunctionOpInterface func,
   }
 }
 
-/// Add custom lowered funcOp to llvm.func attributes here.
-struct LoweredFuncAttrs {
-  LLVM::LLVMFuncOp::Properties properties;
-  NamedAttrList discardableAttrs;
-};
-
-/// Lower discardable function attributes on `func.func` to attributes expected
-/// by `llvm.func`.
-static FailureOr<LoweredFuncAttrs>
-lowerFuncAttributes(FunctionOpInterface func) {
-  MLIRContext *ctx = func->getContext();
-  LoweredFuncAttrs lowered;
-
-  llvm::SmallDenseSet<StringRef> odsAttrNames(
-      LLVM::LLVMFuncOp::getAttributeNames().begin(),
-      LLVM::LLVMFuncOp::getAttributeNames().end());
-
-  NamedAttrList inherentAttrs;
-
-  for (const NamedAttribute &attr : func->getDiscardableAttrs()) {
-    StringRef attrName = attr.getName().strref();
-
-    if (odsAttrNames.contains(attrName)) {
-      LDBG() << "LLVM specific attributes: " << attrName
-             << "should use llvm.* prefix, discarding it";
-      continue;
-    }
-
-    StringRef inherent = attrName;
-    if (inherent.consume_front("llvm.") && odsAttrNames.contains(inherent))
-      inherentAttrs.set(inherent, attr.getValue()); // collect inherent attrs
-    else
-      lowered.discardableAttrs.push_back(attr);
-  }
-
-  // Convert collected inherent attrs into typed properties.
-  if (!inherentAttrs.empty()) {
-    DictionaryAttr dict = inherentAttrs.getDictionary(ctx);
-    auto emitError = [&] {
-      return func.emitOpError("invalid llvm.func property");
-    };
-    if (failed(LLVM::LLVMFuncOp::setPropertiesFromAttr(lowered.properties, dict,
-                                                       emitError))) {
-      return failure();
-    }
-  }
-  return lowered;
-}
-
 static void buildLLVMFuncProperties(PatternRewriter &rewriter,
                                     FunctionOpInterface srcFunc,
                                     Type llvmFuncType,
@@ -385,7 +337,8 @@ FailureOr<LLVM::LLVMFuncOp> mlir::convertFuncOpToLLVMFuncOp(
         return funcOp.emitError("C interface for variadic functions is not "
                                 "supported yet.");
 
-  FailureOr<LoweredFuncAttrs> loweredAttrs = lowerFuncAttributes(funcOp);
+  FailureOr<LowerLLVMFuncAttrs> loweredAttrs =
+      lowerDiscardableAttrsForLLVMFunc(funcOp);
   if (failed(loweredAttrs))
     return rewriter.notifyMatchFailure(funcOp,
                                        "failed to lower func attributes");
diff --git a/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.cpp b/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.cpp
index 6a705ebab7aa4..771cf0abd3c0e 100644
--- a/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.cpp
+++ b/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.cpp
@@ -14,6 +14,7 @@
 #include "mlir/IR/Attributes.h"
 #include "mlir/IR/Builders.h"
 #include "mlir/IR/BuiltinTypes.h"
+#include "mlir/IR/SymbolTable.h"
 #include "llvm/ADT/SmallVectorExtras.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/FormatVariadic.h"
@@ -74,6 +75,69 @@ LLVM::GlobalOp mlir::getOrCreateStringConstant(OpBuilder &b, Location loc,
                                 name, attr, alignment, addrSpace);
 }
 
+FailureOr<LowerLLVMFuncAttrs> GPUFuncOpLowering::buildLoweredGPULLVMFuncAttrs(
+    gpu::GPUFuncOp gpuFuncOp, Type llvmFuncType, OpBuilder &rewriter) const {
+  FailureOr<LowerLLVMFuncAttrs> loweredAttrs =
+      lowerDiscardableAttrsForLLVMFunc(gpuFuncOp);
+  if (failed(loweredAttrs))
+    return failure();
+
+  // TODO: How do we refactor this to be deny list?
+  NamedAttrList &discardable = loweredAttrs->discardableAttrs;
+  discardable.erase(gpu::GPUFuncOp::getNumWorkgroupAttributionsAttrName());
+  discardable.erase(SymbolTable::getSymbolAttrName());
+  discardable.erase(gpuFuncOp.getFunctionTypeAttrName());
+  discardable.erase(gpuFuncOp.getArgAttrsAttrName());
+  discardable.erase(gpuFuncOp.getResAttrsAttrName());
+  discardable.erase(gpuFuncOp.getWorkgroupAttribAttrsAttrName());
+  discardable.erase(gpuFuncOp.getPrivateAttribAttrsAttrName());
+  discardable.erase(gpuFuncOp.getKnownBlockSizeAttrName());
+  discardable.erase(gpuFuncOp.getKnownGridSizeAttrName());
+  discardable.erase(gpuFuncOp.getKnownClusterSizeAttrName());
+
+  MLIRContext *ctx = rewriter.getContext();
+  LLVM::LLVMFuncOp::Properties &props = loweredAttrs->properties;
+  props.sym_name = rewriter.getStringAttr(gpuFuncOp.getName());
+  props.function_type = TypeAttr::get(llvmFuncType);
+  props.setCConv(LLVM::CConvAttr::get(ctx, gpuFuncOp.isKernel()
+                                               ? kernelCallingConvention
+                                               : nonKernelCallingConvention));
+
+  DenseI32ArrayAttr knownBlockSize = gpuFuncOp.getKnownBlockSizeAttr();
+  DenseI32ArrayAttr knownGridSize = gpuFuncOp.getKnownGridSizeAttr();
+  DenseI32ArrayAttr knownClusterSize = gpuFuncOp.getKnownClusterSizeAttr();
+  // Ensure we don't lose information if the function is lowered before its
+  // surrounding context.
+  auto *gpuDialect = cast<gpu::GPUDialect>(gpuFuncOp->getDialect());
+  if (knownBlockSize)
+    loweredAttrs->discardableAttrs.append(
+        gpuDialect->getKnownBlockSizeAttrHelper().getName(), knownBlockSize);
+  if (knownGridSize)
+    loweredAttrs->discardableAttrs.append(
+        gpuDialect->getKnownGridSizeAttrHelper().getName(), knownGridSize);
+  if (knownClusterSize)
+    loweredAttrs->discardableAttrs.append(
+        gpuDialect->getKnownClusterSizeAttrHelper().getName(),
+        knownClusterSize);
+
+  // Add a dialect specific kernel attribute in addition to GPU kernel
+  // attribute. The former is necessary for further translation while the
+  // latter is expected by gpu.launch_func.
+  if (gpuFuncOp.isKernel()) {
+    if (kernelAttributeName)
+      loweredAttrs->discardableAttrs.append(kernelAttributeName,
+                                            rewriter.getUnitAttr());
+    if (kernelBlockSizeAttributeName && knownBlockSize)
+      loweredAttrs->discardableAttrs.append(kernelBlockSizeAttributeName,
+                                            knownBlockSize);
+    if (kernelClusterSizeAttributeName && knownClusterSize)
+      loweredAttrs->discardableAttrs.append(kernelClusterSizeAttributeName,
+                                            knownClusterSize);
+  }
+
+  return loweredAttrs;
+}
+
 LogicalResult
 GPUFuncOpLowering::matchAndRewrite(gpu::GPUFuncOp gpuFuncOp, OpAdaptor adaptor,
                                    ConversionPatternRewriter &rewriter) const {
@@ -174,67 +238,17 @@ GPUFuncOpLowering::matchAndRewrite(gpu::GPUFuncOp gpuFuncOp, OpAdaptor adaptor,
     });
   }
 
-  // Create the new function operation. Only copy those attributes that are
-  // not specific to function modeling.
-  SmallVector<NamedAttribute, 4> attributes;
-  ArrayAttr argAttrs;
-  for (const auto &attr : gpuFuncOp->getAttrs()) {
-    if (attr.getName() == SymbolTable::getSymbolAttrName() ||
-        attr.getName() == gpuFuncOp.getFunctionTypeAttrName() ||
-        attr.getName() ==
-            gpu::GPUFuncOp::getNumWorkgroupAttributionsAttrName() ||
-        attr.getName() == gpuFuncOp.getWorkgroupAttribAttrsAttrName() ||
-        attr.getName() == gpuFuncOp.getPrivateAttribAttrsAttrName() ||
-        attr.getName() == gpuFuncOp.getKnownBlockSizeAttrName() ||
-        attr.getName() == gpuFuncOp.getKnownGridSizeAttrName() ||
-        attr.getName() == gpuFuncOp.getKnownClusterSizeAttrName())
-      continue;
-    if (attr.getName() == gpuFuncOp.getArgAttrsAttrName()) {
-      argAttrs = gpuFuncOp.getArgAttrsAttr();
-      continue;
-    }
-    attributes.push_back(attr);
-  }
+  ArrayAttr argAttrs = gpuFuncOp.getArgAttrsAttr();
 
-  DenseI32ArrayAttr knownBlockSize = gpuFuncOp.getKnownBlockSizeAttr();
-  DenseI32ArrayAttr knownGridSize = gpuFuncOp.getKnownGridSizeAttr();
-  DenseI32ArrayAttr knownClusterSize = gpuFuncOp.getKnownClusterSizeAttr();
-  // Ensure we don't lose information if the function is lowered before its
-  // surrounding context.
-  auto *gpuDialect = cast<gpu::GPUDialect>(gpuFuncOp->getDialect());
-  if (knownBlockSize)
-    attributes.emplace_back(gpuDialect->getKnownBlockSizeAttrHelper().getName(),
-                            knownBlockSize);
-  if (knownGridSize)
-    attributes.emplace_back(gpuDialect->getKnownGridSizeAttrHelper().getName(),
-                            knownGridSize);
-  if (knownClusterSize)
-    attributes.emplace_back(
-        gpuDialect->getKnownClusterSizeAttrHelper().getName(),
-        knownClusterSize);
+  FailureOr<LowerLLVMFuncAttrs> loweredAttrs =
+      buildLoweredGPULLVMFuncAttrs(gpuFuncOp, funcType, rewriter);
+  if (failed(loweredAttrs))
+    return rewriter.notifyMatchFailure(gpuFuncOp,
+                                       "failed to lower func attributes");
 
-  // Add a dialect specific kernel attribute in addition to GPU kernel
-  // attribute. The former is necessary for further translation while the
-  // latter is expected by gpu.launch_func.
-  if (gpuFuncOp.isKernel()) {
-    if (kernelAttributeName)
-      attributes.emplace_back(kernelAttributeName, rewriter.getUnitAttr());
-    // Set the dialect-specific block size attribute if there is one.
-    if (kernelBlockSizeAttributeName && knownBlockSize) {
-      attributes.emplace_back(kernelBlockSizeAttributeName, knownBlockSize);
-    }
-    // Set the dialect-specific cluster size attribute if there is one.
-    if (kernelClusterSizeAttributeName && knownClusterSize) {
-      attributes.emplace_back(kernelClusterSizeAttributeName, knownClusterSize);
-    }
-  }
-  LLVM::CConv callingConvention = gpuFuncOp.isKernel()
-                                      ? kernelCallingConvention
-                                      : nonKernelCallingConvention;
-  auto llvmFuncOp = LLVM::LLVMFuncOp::create(
-      rewriter, gpuFuncOp.getLoc(), gpuFuncOp.getName(), funcType,
-      LLVM::Linkage::External, /*dsoLocal=*/false, callingConvention,
-      /*comdat=*/nullptr, attributes);
+  auto llvmFuncOp = LLVM::LLVMFuncOp::create(rewriter, gpuFuncOp.getLoc(),
+                                             loweredAttrs->properties,
+                                             loweredAttrs->discardableAttrs);
 
   {
     // Insert operations that correspond to converted workgroup and private
diff --git a/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.h b/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.h
index a3b2e04c35313..7aa1d8da233a4 100644
--- a/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.h
+++ b/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.h
@@ -8,6 +8,7 @@
 #ifndef MLIR_CONVERSION_GPUCOMMON_GPUOPSLOWERING_H_
 #define MLIR_CONVERSION_GPUCOMMON_GPUOPSLOWERING_H_
 
+#include "mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h"
 #include "mlir/Conversion/LLVMCommon/Pattern.h"
 #include "mlir/Dialect/GPU/IR/GPUDialect.h"
 #include "mlir/Dialect/LLVMIR/LLVMAttrs.h"
@@ -106,6 +107,12 @@ struct GPUFuncOpLowering : ConvertOpToLLVMPattern<gpu::GPUFuncOp> {
   matchAndRewrite(gpu::GPUFuncOp gpuFuncOp, OpAdaptor adaptor,
                   ConversionPatternRewriter &rewriter) const override;
 
+  /// Lower discardable attrs like `func` lowering, then set `llvm.func`
+  /// properties and append GPU / target-specific discardable metadata.
+  FailureOr<LowerLLVMFuncAttrs>
+  buildLoweredGPULLVMFuncAttrs(gpu::GPUFuncOp gpuFuncOp, Type llvmFuncType,
+                               OpBuilder &rewriter) const;
+
 private:
   /// The address space to use for `alloca`s in private memory.
   unsigned allocaAddrSpace;
diff --git a/mlir/lib/Conversion/LLVMCommon/CMakeLists.txt b/mlir/lib/Conversion/LLVMCommon/CMakeLists.txt
index 568d9339aaabc..77f5013764d96 100644
--- a/mlir/lib/Conversion/LLVMCommon/CMakeLists.txt
+++ b/mlir/lib/Conversion/LLVMCommon/CMakeLists.txt
@@ -1,5 +1,6 @@
 add_mlir_conversion_library(MLIRLLVMCommonConversion
   ConversionTarget.cpp
+  LowerFunctionAttrsToLLVM.cpp
   LoweringOptions.cpp
   MemRefBuilder.cpp
   Pattern.cpp
diff --git a/mlir/lib/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.cpp b/mlir/lib/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.cpp
new file mode 100644
index 0000000000000..eee7a96b369fd
--- /dev/null
+++ b/mlir/lib/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.cpp
@@ -0,0 +1,56 @@
+//===- LowerFunctionAttrsToLLVM.cpp - Lower func attrs to llvm.func -------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#include "mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/Support/DebugLog.h"
+
+using namespace mlir;
+
+#define DEBUG_TYPE "lower-function-attrs-to-llvm"
+
+FailureOr<LowerLLVMFuncAttrs>
+mlir::lowerDiscardableAttrsForLLVMFunc(FunctionOpInterface func) {
+  MLIRContext *ctx = func->getContext();
+  LowerLLVMFuncAttrs lowered;
+
+  llvm::SmallDenseSet<StringRef> odsAttrNames(
+      LLVM::LLVMFuncOp::getAttributeNames().begin(),
+      LLVM::LLVMFuncOp::getAttributeNames().end());
+
+  NamedAttrList inherentAttrs;
+
+  for (const NamedAttribute &attr : func->getDiscardableAttrs()) {
+    StringRef attrName = attr.getName().strref();
+
+    if (odsAttrNames.contains(attrName)) {
+      LDBG() << "LLVM specific attributes: " << attrName
+             << "should use llvm.* prefix, discarding it";
+      continue;
+    }
+
+    StringRef inherent = attrName;
+    if (inherent.consume_front("llvm.") && odsAttrNames.contains(inherent))
+      inherentAttrs.set(inherent, attr.getValue()); // collect inherent attrs
+    else
+      lowered.discardableAttrs.push_back(attr);
+  }
+
+  // Convert collected inherent attrs into typed properties.
+  if (!inherentAttrs.empty()) {
+    DictionaryAttr dict = inherentAttrs.getDictionary(ctx);
+    auto emitError = [&] {
+      return func.emitOpError("invalid llvm.func property");
+    };
+    if (failed(LLVM::LLVMFuncOp::setPropertiesFromAttr(lowered.properties, dict,
+                                                       emitError))) {
+      return failure();
+    }
+  }
+  return lowered;
+}

@llvmbot

llvmbot commented Mar 27, 2026

Copy link
Copy Markdown
Member

@llvm/pr-subscribers-mlir-llvm

Author: Hocky Yudhiono (hockyy)

Changes

Refactors gpu.func to llvm.func lowering to reuse the same discardable-attribute path as func.func to llvm.func, moves that shared logic into LLVMCommon, and keeps GPU-specific metadata explicit.


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

6 Files Affected:

  • (added) mlir/include/mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h (+39)
  • (modified) mlir/lib/Conversion/FuncToLLVM/FuncToLLVM.cpp (+3-50)
  • (modified) mlir/lib/Conversion/GPUCommon/GPUOpsLowering.cpp (+73-59)
  • (modified) mlir/lib/Conversion/GPUCommon/GPUOpsLowering.h (+7)
  • (modified) mlir/lib/Conversion/LLVMCommon/CMakeLists.txt (+1)
  • (added) mlir/lib/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.cpp (+56)
diff --git a/mlir/include/mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h b/mlir/include/mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h
new file mode 100644
index 0000000000000..f12f9d2c90e2e
--- /dev/null
+++ b/mlir/include/mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h
@@ -0,0 +1,39 @@
+//===- LowerFunctionAttrsToLLVM.h - Lower func attrs to llvm.func - C++ -*-===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+//
+// Shared helpers for lowering discardable attributes on any FunctionOpInterface
+// (e.g. func.func, gpu.func) into llvm.func properties and discardables.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MLIR_CONVERSION_LLVMCOMMON_LOWERFUNCTIONATTRSTOLLVM_H
+#define MLIR_CONVERSION_LLVMCOMMON_LOWERFUNCTIONATTRSTOLLVM_H
+
+#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
+#include "mlir/IR/OperationSupport.h"
+#include "mlir/Interfaces/FunctionInterfaces.h"
+
+namespace mlir {
+
+/// Result of lowering discardable attributes from a `FunctionOpInterface` to
+/// what `llvm.func` expects: typed inherent properties plus remaining
+/// discardable attributes.
+struct LowerLLVMFuncAttrs {
+  LLVM::LLVMFuncOp::Properties properties;
+  NamedAttrList discardableAttrs;
+};
+
+/// Lower discardable attributes on `func`, splitting `llvm.*` inherent
+/// properties from other attributes to forward to `llvm.func`. Returns
+/// failure if an `llvm.*` property bundle is invalid for `llvm.func`.
+FailureOr<LowerLLVMFuncAttrs>
+lowerDiscardableAttrsForLLVMFunc(FunctionOpInterface func);
+
+} // namespace mlir
+
+#endif // MLIR_CONVERSION_LLVMCOMMON_LOWERFUNCTIONATTRSTOLLVM_H
diff --git a/mlir/lib/Conversion/FuncToLLVM/FuncToLLVM.cpp b/mlir/lib/Conversion/FuncToLLVM/FuncToLLVM.cpp
index 88abc4400c9b7..bd7bc47217bdc 100644
--- a/mlir/lib/Conversion/FuncToLLVM/FuncToLLVM.cpp
+++ b/mlir/lib/Conversion/FuncToLLVM/FuncToLLVM.cpp
@@ -19,6 +19,7 @@
 #include "mlir/Conversion/ConvertToLLVM/ToLLVMInterface.h"
 #include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h"
 #include "mlir/Conversion/LLVMCommon/ConversionTarget.h"
+#include "mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h"
 #include "mlir/Conversion/LLVMCommon/Pattern.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
 #include "mlir/Dialect/LLVMIR/FunctionCallUtils.h"
@@ -77,55 +78,6 @@ static void filterFuncAttributes(FunctionOpInterface func,
   }
 }
 
-/// Add custom lowered funcOp to llvm.func attributes here.
-struct LoweredFuncAttrs {
-  LLVM::LLVMFuncOp::Properties properties;
-  NamedAttrList discardableAttrs;
-};
-
-/// Lower discardable function attributes on `func.func` to attributes expected
-/// by `llvm.func`.
-static FailureOr<LoweredFuncAttrs>
-lowerFuncAttributes(FunctionOpInterface func) {
-  MLIRContext *ctx = func->getContext();
-  LoweredFuncAttrs lowered;
-
-  llvm::SmallDenseSet<StringRef> odsAttrNames(
-      LLVM::LLVMFuncOp::getAttributeNames().begin(),
-      LLVM::LLVMFuncOp::getAttributeNames().end());
-
-  NamedAttrList inherentAttrs;
-
-  for (const NamedAttribute &attr : func->getDiscardableAttrs()) {
-    StringRef attrName = attr.getName().strref();
-
-    if (odsAttrNames.contains(attrName)) {
-      LDBG() << "LLVM specific attributes: " << attrName
-             << "should use llvm.* prefix, discarding it";
-      continue;
-    }
-
-    StringRef inherent = attrName;
-    if (inherent.consume_front("llvm.") && odsAttrNames.contains(inherent))
-      inherentAttrs.set(inherent, attr.getValue()); // collect inherent attrs
-    else
-      lowered.discardableAttrs.push_back(attr);
-  }
-
-  // Convert collected inherent attrs into typed properties.
-  if (!inherentAttrs.empty()) {
-    DictionaryAttr dict = inherentAttrs.getDictionary(ctx);
-    auto emitError = [&] {
-      return func.emitOpError("invalid llvm.func property");
-    };
-    if (failed(LLVM::LLVMFuncOp::setPropertiesFromAttr(lowered.properties, dict,
-                                                       emitError))) {
-      return failure();
-    }
-  }
-  return lowered;
-}
-
 static void buildLLVMFuncProperties(PatternRewriter &rewriter,
                                     FunctionOpInterface srcFunc,
                                     Type llvmFuncType,
@@ -385,7 +337,8 @@ FailureOr<LLVM::LLVMFuncOp> mlir::convertFuncOpToLLVMFuncOp(
         return funcOp.emitError("C interface for variadic functions is not "
                                 "supported yet.");
 
-  FailureOr<LoweredFuncAttrs> loweredAttrs = lowerFuncAttributes(funcOp);
+  FailureOr<LowerLLVMFuncAttrs> loweredAttrs =
+      lowerDiscardableAttrsForLLVMFunc(funcOp);
   if (failed(loweredAttrs))
     return rewriter.notifyMatchFailure(funcOp,
                                        "failed to lower func attributes");
diff --git a/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.cpp b/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.cpp
index 6a705ebab7aa4..771cf0abd3c0e 100644
--- a/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.cpp
+++ b/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.cpp
@@ -14,6 +14,7 @@
 #include "mlir/IR/Attributes.h"
 #include "mlir/IR/Builders.h"
 #include "mlir/IR/BuiltinTypes.h"
+#include "mlir/IR/SymbolTable.h"
 #include "llvm/ADT/SmallVectorExtras.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/FormatVariadic.h"
@@ -74,6 +75,69 @@ LLVM::GlobalOp mlir::getOrCreateStringConstant(OpBuilder &b, Location loc,
                                 name, attr, alignment, addrSpace);
 }
 
+FailureOr<LowerLLVMFuncAttrs> GPUFuncOpLowering::buildLoweredGPULLVMFuncAttrs(
+    gpu::GPUFuncOp gpuFuncOp, Type llvmFuncType, OpBuilder &rewriter) const {
+  FailureOr<LowerLLVMFuncAttrs> loweredAttrs =
+      lowerDiscardableAttrsForLLVMFunc(gpuFuncOp);
+  if (failed(loweredAttrs))
+    return failure();
+
+  // TODO: How do we refactor this to be deny list?
+  NamedAttrList &discardable = loweredAttrs->discardableAttrs;
+  discardable.erase(gpu::GPUFuncOp::getNumWorkgroupAttributionsAttrName());
+  discardable.erase(SymbolTable::getSymbolAttrName());
+  discardable.erase(gpuFuncOp.getFunctionTypeAttrName());
+  discardable.erase(gpuFuncOp.getArgAttrsAttrName());
+  discardable.erase(gpuFuncOp.getResAttrsAttrName());
+  discardable.erase(gpuFuncOp.getWorkgroupAttribAttrsAttrName());
+  discardable.erase(gpuFuncOp.getPrivateAttribAttrsAttrName());
+  discardable.erase(gpuFuncOp.getKnownBlockSizeAttrName());
+  discardable.erase(gpuFuncOp.getKnownGridSizeAttrName());
+  discardable.erase(gpuFuncOp.getKnownClusterSizeAttrName());
+
+  MLIRContext *ctx = rewriter.getContext();
+  LLVM::LLVMFuncOp::Properties &props = loweredAttrs->properties;
+  props.sym_name = rewriter.getStringAttr(gpuFuncOp.getName());
+  props.function_type = TypeAttr::get(llvmFuncType);
+  props.setCConv(LLVM::CConvAttr::get(ctx, gpuFuncOp.isKernel()
+                                               ? kernelCallingConvention
+                                               : nonKernelCallingConvention));
+
+  DenseI32ArrayAttr knownBlockSize = gpuFuncOp.getKnownBlockSizeAttr();
+  DenseI32ArrayAttr knownGridSize = gpuFuncOp.getKnownGridSizeAttr();
+  DenseI32ArrayAttr knownClusterSize = gpuFuncOp.getKnownClusterSizeAttr();
+  // Ensure we don't lose information if the function is lowered before its
+  // surrounding context.
+  auto *gpuDialect = cast<gpu::GPUDialect>(gpuFuncOp->getDialect());
+  if (knownBlockSize)
+    loweredAttrs->discardableAttrs.append(
+        gpuDialect->getKnownBlockSizeAttrHelper().getName(), knownBlockSize);
+  if (knownGridSize)
+    loweredAttrs->discardableAttrs.append(
+        gpuDialect->getKnownGridSizeAttrHelper().getName(), knownGridSize);
+  if (knownClusterSize)
+    loweredAttrs->discardableAttrs.append(
+        gpuDialect->getKnownClusterSizeAttrHelper().getName(),
+        knownClusterSize);
+
+  // Add a dialect specific kernel attribute in addition to GPU kernel
+  // attribute. The former is necessary for further translation while the
+  // latter is expected by gpu.launch_func.
+  if (gpuFuncOp.isKernel()) {
+    if (kernelAttributeName)
+      loweredAttrs->discardableAttrs.append(kernelAttributeName,
+                                            rewriter.getUnitAttr());
+    if (kernelBlockSizeAttributeName && knownBlockSize)
+      loweredAttrs->discardableAttrs.append(kernelBlockSizeAttributeName,
+                                            knownBlockSize);
+    if (kernelClusterSizeAttributeName && knownClusterSize)
+      loweredAttrs->discardableAttrs.append(kernelClusterSizeAttributeName,
+                                            knownClusterSize);
+  }
+
+  return loweredAttrs;
+}
+
 LogicalResult
 GPUFuncOpLowering::matchAndRewrite(gpu::GPUFuncOp gpuFuncOp, OpAdaptor adaptor,
                                    ConversionPatternRewriter &rewriter) const {
@@ -174,67 +238,17 @@ GPUFuncOpLowering::matchAndRewrite(gpu::GPUFuncOp gpuFuncOp, OpAdaptor adaptor,
     });
   }
 
-  // Create the new function operation. Only copy those attributes that are
-  // not specific to function modeling.
-  SmallVector<NamedAttribute, 4> attributes;
-  ArrayAttr argAttrs;
-  for (const auto &attr : gpuFuncOp->getAttrs()) {
-    if (attr.getName() == SymbolTable::getSymbolAttrName() ||
-        attr.getName() == gpuFuncOp.getFunctionTypeAttrName() ||
-        attr.getName() ==
-            gpu::GPUFuncOp::getNumWorkgroupAttributionsAttrName() ||
-        attr.getName() == gpuFuncOp.getWorkgroupAttribAttrsAttrName() ||
-        attr.getName() == gpuFuncOp.getPrivateAttribAttrsAttrName() ||
-        attr.getName() == gpuFuncOp.getKnownBlockSizeAttrName() ||
-        attr.getName() == gpuFuncOp.getKnownGridSizeAttrName() ||
-        attr.getName() == gpuFuncOp.getKnownClusterSizeAttrName())
-      continue;
-    if (attr.getName() == gpuFuncOp.getArgAttrsAttrName()) {
-      argAttrs = gpuFuncOp.getArgAttrsAttr();
-      continue;
-    }
-    attributes.push_back(attr);
-  }
+  ArrayAttr argAttrs = gpuFuncOp.getArgAttrsAttr();
 
-  DenseI32ArrayAttr knownBlockSize = gpuFuncOp.getKnownBlockSizeAttr();
-  DenseI32ArrayAttr knownGridSize = gpuFuncOp.getKnownGridSizeAttr();
-  DenseI32ArrayAttr knownClusterSize = gpuFuncOp.getKnownClusterSizeAttr();
-  // Ensure we don't lose information if the function is lowered before its
-  // surrounding context.
-  auto *gpuDialect = cast<gpu::GPUDialect>(gpuFuncOp->getDialect());
-  if (knownBlockSize)
-    attributes.emplace_back(gpuDialect->getKnownBlockSizeAttrHelper().getName(),
-                            knownBlockSize);
-  if (knownGridSize)
-    attributes.emplace_back(gpuDialect->getKnownGridSizeAttrHelper().getName(),
-                            knownGridSize);
-  if (knownClusterSize)
-    attributes.emplace_back(
-        gpuDialect->getKnownClusterSizeAttrHelper().getName(),
-        knownClusterSize);
+  FailureOr<LowerLLVMFuncAttrs> loweredAttrs =
+      buildLoweredGPULLVMFuncAttrs(gpuFuncOp, funcType, rewriter);
+  if (failed(loweredAttrs))
+    return rewriter.notifyMatchFailure(gpuFuncOp,
+                                       "failed to lower func attributes");
 
-  // Add a dialect specific kernel attribute in addition to GPU kernel
-  // attribute. The former is necessary for further translation while the
-  // latter is expected by gpu.launch_func.
-  if (gpuFuncOp.isKernel()) {
-    if (kernelAttributeName)
-      attributes.emplace_back(kernelAttributeName, rewriter.getUnitAttr());
-    // Set the dialect-specific block size attribute if there is one.
-    if (kernelBlockSizeAttributeName && knownBlockSize) {
-      attributes.emplace_back(kernelBlockSizeAttributeName, knownBlockSize);
-    }
-    // Set the dialect-specific cluster size attribute if there is one.
-    if (kernelClusterSizeAttributeName && knownClusterSize) {
-      attributes.emplace_back(kernelClusterSizeAttributeName, knownClusterSize);
-    }
-  }
-  LLVM::CConv callingConvention = gpuFuncOp.isKernel()
-                                      ? kernelCallingConvention
-                                      : nonKernelCallingConvention;
-  auto llvmFuncOp = LLVM::LLVMFuncOp::create(
-      rewriter, gpuFuncOp.getLoc(), gpuFuncOp.getName(), funcType,
-      LLVM::Linkage::External, /*dsoLocal=*/false, callingConvention,
-      /*comdat=*/nullptr, attributes);
+  auto llvmFuncOp = LLVM::LLVMFuncOp::create(rewriter, gpuFuncOp.getLoc(),
+                                             loweredAttrs->properties,
+                                             loweredAttrs->discardableAttrs);
 
   {
     // Insert operations that correspond to converted workgroup and private
diff --git a/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.h b/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.h
index a3b2e04c35313..7aa1d8da233a4 100644
--- a/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.h
+++ b/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.h
@@ -8,6 +8,7 @@
 #ifndef MLIR_CONVERSION_GPUCOMMON_GPUOPSLOWERING_H_
 #define MLIR_CONVERSION_GPUCOMMON_GPUOPSLOWERING_H_
 
+#include "mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h"
 #include "mlir/Conversion/LLVMCommon/Pattern.h"
 #include "mlir/Dialect/GPU/IR/GPUDialect.h"
 #include "mlir/Dialect/LLVMIR/LLVMAttrs.h"
@@ -106,6 +107,12 @@ struct GPUFuncOpLowering : ConvertOpToLLVMPattern<gpu::GPUFuncOp> {
   matchAndRewrite(gpu::GPUFuncOp gpuFuncOp, OpAdaptor adaptor,
                   ConversionPatternRewriter &rewriter) const override;
 
+  /// Lower discardable attrs like `func` lowering, then set `llvm.func`
+  /// properties and append GPU / target-specific discardable metadata.
+  FailureOr<LowerLLVMFuncAttrs>
+  buildLoweredGPULLVMFuncAttrs(gpu::GPUFuncOp gpuFuncOp, Type llvmFuncType,
+                               OpBuilder &rewriter) const;
+
 private:
   /// The address space to use for `alloca`s in private memory.
   unsigned allocaAddrSpace;
diff --git a/mlir/lib/Conversion/LLVMCommon/CMakeLists.txt b/mlir/lib/Conversion/LLVMCommon/CMakeLists.txt
index 568d9339aaabc..77f5013764d96 100644
--- a/mlir/lib/Conversion/LLVMCommon/CMakeLists.txt
+++ b/mlir/lib/Conversion/LLVMCommon/CMakeLists.txt
@@ -1,5 +1,6 @@
 add_mlir_conversion_library(MLIRLLVMCommonConversion
   ConversionTarget.cpp
+  LowerFunctionAttrsToLLVM.cpp
   LoweringOptions.cpp
   MemRefBuilder.cpp
   Pattern.cpp
diff --git a/mlir/lib/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.cpp b/mlir/lib/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.cpp
new file mode 100644
index 0000000000000..eee7a96b369fd
--- /dev/null
+++ b/mlir/lib/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.cpp
@@ -0,0 +1,56 @@
+//===- LowerFunctionAttrsToLLVM.cpp - Lower func attrs to llvm.func -------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#include "mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/Support/DebugLog.h"
+
+using namespace mlir;
+
+#define DEBUG_TYPE "lower-function-attrs-to-llvm"
+
+FailureOr<LowerLLVMFuncAttrs>
+mlir::lowerDiscardableAttrsForLLVMFunc(FunctionOpInterface func) {
+  MLIRContext *ctx = func->getContext();
+  LowerLLVMFuncAttrs lowered;
+
+  llvm::SmallDenseSet<StringRef> odsAttrNames(
+      LLVM::LLVMFuncOp::getAttributeNames().begin(),
+      LLVM::LLVMFuncOp::getAttributeNames().end());
+
+  NamedAttrList inherentAttrs;
+
+  for (const NamedAttribute &attr : func->getDiscardableAttrs()) {
+    StringRef attrName = attr.getName().strref();
+
+    if (odsAttrNames.contains(attrName)) {
+      LDBG() << "LLVM specific attributes: " << attrName
+             << "should use llvm.* prefix, discarding it";
+      continue;
+    }
+
+    StringRef inherent = attrName;
+    if (inherent.consume_front("llvm.") && odsAttrNames.contains(inherent))
+      inherentAttrs.set(inherent, attr.getValue()); // collect inherent attrs
+    else
+      lowered.discardableAttrs.push_back(attr);
+  }
+
+  // Convert collected inherent attrs into typed properties.
+  if (!inherentAttrs.empty()) {
+    DictionaryAttr dict = inherentAttrs.getDictionary(ctx);
+    auto emitError = [&] {
+      return func.emitOpError("invalid llvm.func property");
+    };
+    if (failed(LLVM::LLVMFuncOp::setPropertiesFromAttr(lowered.properties, dict,
+                                                       emitError))) {
+      return failure();
+    }
+  }
+  return lowered;
+}

@llvmbot

llvmbot commented Mar 27, 2026

Copy link
Copy Markdown
Member

@llvm/pr-subscribers-mlir-gpu

Author: Hocky Yudhiono (hockyy)

Changes

Refactors gpu.func to llvm.func lowering to reuse the same discardable-attribute path as func.func to llvm.func, moves that shared logic into LLVMCommon, and keeps GPU-specific metadata explicit.


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

6 Files Affected:

  • (added) mlir/include/mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h (+39)
  • (modified) mlir/lib/Conversion/FuncToLLVM/FuncToLLVM.cpp (+3-50)
  • (modified) mlir/lib/Conversion/GPUCommon/GPUOpsLowering.cpp (+73-59)
  • (modified) mlir/lib/Conversion/GPUCommon/GPUOpsLowering.h (+7)
  • (modified) mlir/lib/Conversion/LLVMCommon/CMakeLists.txt (+1)
  • (added) mlir/lib/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.cpp (+56)
diff --git a/mlir/include/mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h b/mlir/include/mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h
new file mode 100644
index 0000000000000..f12f9d2c90e2e
--- /dev/null
+++ b/mlir/include/mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h
@@ -0,0 +1,39 @@
+//===- LowerFunctionAttrsToLLVM.h - Lower func attrs to llvm.func - C++ -*-===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+//
+// Shared helpers for lowering discardable attributes on any FunctionOpInterface
+// (e.g. func.func, gpu.func) into llvm.func properties and discardables.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MLIR_CONVERSION_LLVMCOMMON_LOWERFUNCTIONATTRSTOLLVM_H
+#define MLIR_CONVERSION_LLVMCOMMON_LOWERFUNCTIONATTRSTOLLVM_H
+
+#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
+#include "mlir/IR/OperationSupport.h"
+#include "mlir/Interfaces/FunctionInterfaces.h"
+
+namespace mlir {
+
+/// Result of lowering discardable attributes from a `FunctionOpInterface` to
+/// what `llvm.func` expects: typed inherent properties plus remaining
+/// discardable attributes.
+struct LowerLLVMFuncAttrs {
+  LLVM::LLVMFuncOp::Properties properties;
+  NamedAttrList discardableAttrs;
+};
+
+/// Lower discardable attributes on `func`, splitting `llvm.*` inherent
+/// properties from other attributes to forward to `llvm.func`. Returns
+/// failure if an `llvm.*` property bundle is invalid for `llvm.func`.
+FailureOr<LowerLLVMFuncAttrs>
+lowerDiscardableAttrsForLLVMFunc(FunctionOpInterface func);
+
+} // namespace mlir
+
+#endif // MLIR_CONVERSION_LLVMCOMMON_LOWERFUNCTIONATTRSTOLLVM_H
diff --git a/mlir/lib/Conversion/FuncToLLVM/FuncToLLVM.cpp b/mlir/lib/Conversion/FuncToLLVM/FuncToLLVM.cpp
index 88abc4400c9b7..bd7bc47217bdc 100644
--- a/mlir/lib/Conversion/FuncToLLVM/FuncToLLVM.cpp
+++ b/mlir/lib/Conversion/FuncToLLVM/FuncToLLVM.cpp
@@ -19,6 +19,7 @@
 #include "mlir/Conversion/ConvertToLLVM/ToLLVMInterface.h"
 #include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h"
 #include "mlir/Conversion/LLVMCommon/ConversionTarget.h"
+#include "mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h"
 #include "mlir/Conversion/LLVMCommon/Pattern.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
 #include "mlir/Dialect/LLVMIR/FunctionCallUtils.h"
@@ -77,55 +78,6 @@ static void filterFuncAttributes(FunctionOpInterface func,
   }
 }
 
-/// Add custom lowered funcOp to llvm.func attributes here.
-struct LoweredFuncAttrs {
-  LLVM::LLVMFuncOp::Properties properties;
-  NamedAttrList discardableAttrs;
-};
-
-/// Lower discardable function attributes on `func.func` to attributes expected
-/// by `llvm.func`.
-static FailureOr<LoweredFuncAttrs>
-lowerFuncAttributes(FunctionOpInterface func) {
-  MLIRContext *ctx = func->getContext();
-  LoweredFuncAttrs lowered;
-
-  llvm::SmallDenseSet<StringRef> odsAttrNames(
-      LLVM::LLVMFuncOp::getAttributeNames().begin(),
-      LLVM::LLVMFuncOp::getAttributeNames().end());
-
-  NamedAttrList inherentAttrs;
-
-  for (const NamedAttribute &attr : func->getDiscardableAttrs()) {
-    StringRef attrName = attr.getName().strref();
-
-    if (odsAttrNames.contains(attrName)) {
-      LDBG() << "LLVM specific attributes: " << attrName
-             << "should use llvm.* prefix, discarding it";
-      continue;
-    }
-
-    StringRef inherent = attrName;
-    if (inherent.consume_front("llvm.") && odsAttrNames.contains(inherent))
-      inherentAttrs.set(inherent, attr.getValue()); // collect inherent attrs
-    else
-      lowered.discardableAttrs.push_back(attr);
-  }
-
-  // Convert collected inherent attrs into typed properties.
-  if (!inherentAttrs.empty()) {
-    DictionaryAttr dict = inherentAttrs.getDictionary(ctx);
-    auto emitError = [&] {
-      return func.emitOpError("invalid llvm.func property");
-    };
-    if (failed(LLVM::LLVMFuncOp::setPropertiesFromAttr(lowered.properties, dict,
-                                                       emitError))) {
-      return failure();
-    }
-  }
-  return lowered;
-}
-
 static void buildLLVMFuncProperties(PatternRewriter &rewriter,
                                     FunctionOpInterface srcFunc,
                                     Type llvmFuncType,
@@ -385,7 +337,8 @@ FailureOr<LLVM::LLVMFuncOp> mlir::convertFuncOpToLLVMFuncOp(
         return funcOp.emitError("C interface for variadic functions is not "
                                 "supported yet.");
 
-  FailureOr<LoweredFuncAttrs> loweredAttrs = lowerFuncAttributes(funcOp);
+  FailureOr<LowerLLVMFuncAttrs> loweredAttrs =
+      lowerDiscardableAttrsForLLVMFunc(funcOp);
   if (failed(loweredAttrs))
     return rewriter.notifyMatchFailure(funcOp,
                                        "failed to lower func attributes");
diff --git a/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.cpp b/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.cpp
index 6a705ebab7aa4..771cf0abd3c0e 100644
--- a/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.cpp
+++ b/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.cpp
@@ -14,6 +14,7 @@
 #include "mlir/IR/Attributes.h"
 #include "mlir/IR/Builders.h"
 #include "mlir/IR/BuiltinTypes.h"
+#include "mlir/IR/SymbolTable.h"
 #include "llvm/ADT/SmallVectorExtras.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/FormatVariadic.h"
@@ -74,6 +75,69 @@ LLVM::GlobalOp mlir::getOrCreateStringConstant(OpBuilder &b, Location loc,
                                 name, attr, alignment, addrSpace);
 }
 
+FailureOr<LowerLLVMFuncAttrs> GPUFuncOpLowering::buildLoweredGPULLVMFuncAttrs(
+    gpu::GPUFuncOp gpuFuncOp, Type llvmFuncType, OpBuilder &rewriter) const {
+  FailureOr<LowerLLVMFuncAttrs> loweredAttrs =
+      lowerDiscardableAttrsForLLVMFunc(gpuFuncOp);
+  if (failed(loweredAttrs))
+    return failure();
+
+  // TODO: How do we refactor this to be deny list?
+  NamedAttrList &discardable = loweredAttrs->discardableAttrs;
+  discardable.erase(gpu::GPUFuncOp::getNumWorkgroupAttributionsAttrName());
+  discardable.erase(SymbolTable::getSymbolAttrName());
+  discardable.erase(gpuFuncOp.getFunctionTypeAttrName());
+  discardable.erase(gpuFuncOp.getArgAttrsAttrName());
+  discardable.erase(gpuFuncOp.getResAttrsAttrName());
+  discardable.erase(gpuFuncOp.getWorkgroupAttribAttrsAttrName());
+  discardable.erase(gpuFuncOp.getPrivateAttribAttrsAttrName());
+  discardable.erase(gpuFuncOp.getKnownBlockSizeAttrName());
+  discardable.erase(gpuFuncOp.getKnownGridSizeAttrName());
+  discardable.erase(gpuFuncOp.getKnownClusterSizeAttrName());
+
+  MLIRContext *ctx = rewriter.getContext();
+  LLVM::LLVMFuncOp::Properties &props = loweredAttrs->properties;
+  props.sym_name = rewriter.getStringAttr(gpuFuncOp.getName());
+  props.function_type = TypeAttr::get(llvmFuncType);
+  props.setCConv(LLVM::CConvAttr::get(ctx, gpuFuncOp.isKernel()
+                                               ? kernelCallingConvention
+                                               : nonKernelCallingConvention));
+
+  DenseI32ArrayAttr knownBlockSize = gpuFuncOp.getKnownBlockSizeAttr();
+  DenseI32ArrayAttr knownGridSize = gpuFuncOp.getKnownGridSizeAttr();
+  DenseI32ArrayAttr knownClusterSize = gpuFuncOp.getKnownClusterSizeAttr();
+  // Ensure we don't lose information if the function is lowered before its
+  // surrounding context.
+  auto *gpuDialect = cast<gpu::GPUDialect>(gpuFuncOp->getDialect());
+  if (knownBlockSize)
+    loweredAttrs->discardableAttrs.append(
+        gpuDialect->getKnownBlockSizeAttrHelper().getName(), knownBlockSize);
+  if (knownGridSize)
+    loweredAttrs->discardableAttrs.append(
+        gpuDialect->getKnownGridSizeAttrHelper().getName(), knownGridSize);
+  if (knownClusterSize)
+    loweredAttrs->discardableAttrs.append(
+        gpuDialect->getKnownClusterSizeAttrHelper().getName(),
+        knownClusterSize);
+
+  // Add a dialect specific kernel attribute in addition to GPU kernel
+  // attribute. The former is necessary for further translation while the
+  // latter is expected by gpu.launch_func.
+  if (gpuFuncOp.isKernel()) {
+    if (kernelAttributeName)
+      loweredAttrs->discardableAttrs.append(kernelAttributeName,
+                                            rewriter.getUnitAttr());
+    if (kernelBlockSizeAttributeName && knownBlockSize)
+      loweredAttrs->discardableAttrs.append(kernelBlockSizeAttributeName,
+                                            knownBlockSize);
+    if (kernelClusterSizeAttributeName && knownClusterSize)
+      loweredAttrs->discardableAttrs.append(kernelClusterSizeAttributeName,
+                                            knownClusterSize);
+  }
+
+  return loweredAttrs;
+}
+
 LogicalResult
 GPUFuncOpLowering::matchAndRewrite(gpu::GPUFuncOp gpuFuncOp, OpAdaptor adaptor,
                                    ConversionPatternRewriter &rewriter) const {
@@ -174,67 +238,17 @@ GPUFuncOpLowering::matchAndRewrite(gpu::GPUFuncOp gpuFuncOp, OpAdaptor adaptor,
     });
   }
 
-  // Create the new function operation. Only copy those attributes that are
-  // not specific to function modeling.
-  SmallVector<NamedAttribute, 4> attributes;
-  ArrayAttr argAttrs;
-  for (const auto &attr : gpuFuncOp->getAttrs()) {
-    if (attr.getName() == SymbolTable::getSymbolAttrName() ||
-        attr.getName() == gpuFuncOp.getFunctionTypeAttrName() ||
-        attr.getName() ==
-            gpu::GPUFuncOp::getNumWorkgroupAttributionsAttrName() ||
-        attr.getName() == gpuFuncOp.getWorkgroupAttribAttrsAttrName() ||
-        attr.getName() == gpuFuncOp.getPrivateAttribAttrsAttrName() ||
-        attr.getName() == gpuFuncOp.getKnownBlockSizeAttrName() ||
-        attr.getName() == gpuFuncOp.getKnownGridSizeAttrName() ||
-        attr.getName() == gpuFuncOp.getKnownClusterSizeAttrName())
-      continue;
-    if (attr.getName() == gpuFuncOp.getArgAttrsAttrName()) {
-      argAttrs = gpuFuncOp.getArgAttrsAttr();
-      continue;
-    }
-    attributes.push_back(attr);
-  }
+  ArrayAttr argAttrs = gpuFuncOp.getArgAttrsAttr();
 
-  DenseI32ArrayAttr knownBlockSize = gpuFuncOp.getKnownBlockSizeAttr();
-  DenseI32ArrayAttr knownGridSize = gpuFuncOp.getKnownGridSizeAttr();
-  DenseI32ArrayAttr knownClusterSize = gpuFuncOp.getKnownClusterSizeAttr();
-  // Ensure we don't lose information if the function is lowered before its
-  // surrounding context.
-  auto *gpuDialect = cast<gpu::GPUDialect>(gpuFuncOp->getDialect());
-  if (knownBlockSize)
-    attributes.emplace_back(gpuDialect->getKnownBlockSizeAttrHelper().getName(),
-                            knownBlockSize);
-  if (knownGridSize)
-    attributes.emplace_back(gpuDialect->getKnownGridSizeAttrHelper().getName(),
-                            knownGridSize);
-  if (knownClusterSize)
-    attributes.emplace_back(
-        gpuDialect->getKnownClusterSizeAttrHelper().getName(),
-        knownClusterSize);
+  FailureOr<LowerLLVMFuncAttrs> loweredAttrs =
+      buildLoweredGPULLVMFuncAttrs(gpuFuncOp, funcType, rewriter);
+  if (failed(loweredAttrs))
+    return rewriter.notifyMatchFailure(gpuFuncOp,
+                                       "failed to lower func attributes");
 
-  // Add a dialect specific kernel attribute in addition to GPU kernel
-  // attribute. The former is necessary for further translation while the
-  // latter is expected by gpu.launch_func.
-  if (gpuFuncOp.isKernel()) {
-    if (kernelAttributeName)
-      attributes.emplace_back(kernelAttributeName, rewriter.getUnitAttr());
-    // Set the dialect-specific block size attribute if there is one.
-    if (kernelBlockSizeAttributeName && knownBlockSize) {
-      attributes.emplace_back(kernelBlockSizeAttributeName, knownBlockSize);
-    }
-    // Set the dialect-specific cluster size attribute if there is one.
-    if (kernelClusterSizeAttributeName && knownClusterSize) {
-      attributes.emplace_back(kernelClusterSizeAttributeName, knownClusterSize);
-    }
-  }
-  LLVM::CConv callingConvention = gpuFuncOp.isKernel()
-                                      ? kernelCallingConvention
-                                      : nonKernelCallingConvention;
-  auto llvmFuncOp = LLVM::LLVMFuncOp::create(
-      rewriter, gpuFuncOp.getLoc(), gpuFuncOp.getName(), funcType,
-      LLVM::Linkage::External, /*dsoLocal=*/false, callingConvention,
-      /*comdat=*/nullptr, attributes);
+  auto llvmFuncOp = LLVM::LLVMFuncOp::create(rewriter, gpuFuncOp.getLoc(),
+                                             loweredAttrs->properties,
+                                             loweredAttrs->discardableAttrs);
 
   {
     // Insert operations that correspond to converted workgroup and private
diff --git a/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.h b/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.h
index a3b2e04c35313..7aa1d8da233a4 100644
--- a/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.h
+++ b/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.h
@@ -8,6 +8,7 @@
 #ifndef MLIR_CONVERSION_GPUCOMMON_GPUOPSLOWERING_H_
 #define MLIR_CONVERSION_GPUCOMMON_GPUOPSLOWERING_H_
 
+#include "mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h"
 #include "mlir/Conversion/LLVMCommon/Pattern.h"
 #include "mlir/Dialect/GPU/IR/GPUDialect.h"
 #include "mlir/Dialect/LLVMIR/LLVMAttrs.h"
@@ -106,6 +107,12 @@ struct GPUFuncOpLowering : ConvertOpToLLVMPattern<gpu::GPUFuncOp> {
   matchAndRewrite(gpu::GPUFuncOp gpuFuncOp, OpAdaptor adaptor,
                   ConversionPatternRewriter &rewriter) const override;
 
+  /// Lower discardable attrs like `func` lowering, then set `llvm.func`
+  /// properties and append GPU / target-specific discardable metadata.
+  FailureOr<LowerLLVMFuncAttrs>
+  buildLoweredGPULLVMFuncAttrs(gpu::GPUFuncOp gpuFuncOp, Type llvmFuncType,
+                               OpBuilder &rewriter) const;
+
 private:
   /// The address space to use for `alloca`s in private memory.
   unsigned allocaAddrSpace;
diff --git a/mlir/lib/Conversion/LLVMCommon/CMakeLists.txt b/mlir/lib/Conversion/LLVMCommon/CMakeLists.txt
index 568d9339aaabc..77f5013764d96 100644
--- a/mlir/lib/Conversion/LLVMCommon/CMakeLists.txt
+++ b/mlir/lib/Conversion/LLVMCommon/CMakeLists.txt
@@ -1,5 +1,6 @@
 add_mlir_conversion_library(MLIRLLVMCommonConversion
   ConversionTarget.cpp
+  LowerFunctionAttrsToLLVM.cpp
   LoweringOptions.cpp
   MemRefBuilder.cpp
   Pattern.cpp
diff --git a/mlir/lib/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.cpp b/mlir/lib/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.cpp
new file mode 100644
index 0000000000000..eee7a96b369fd
--- /dev/null
+++ b/mlir/lib/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.cpp
@@ -0,0 +1,56 @@
+//===- LowerFunctionAttrsToLLVM.cpp - Lower func attrs to llvm.func -------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#include "mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/Support/DebugLog.h"
+
+using namespace mlir;
+
+#define DEBUG_TYPE "lower-function-attrs-to-llvm"
+
+FailureOr<LowerLLVMFuncAttrs>
+mlir::lowerDiscardableAttrsForLLVMFunc(FunctionOpInterface func) {
+  MLIRContext *ctx = func->getContext();
+  LowerLLVMFuncAttrs lowered;
+
+  llvm::SmallDenseSet<StringRef> odsAttrNames(
+      LLVM::LLVMFuncOp::getAttributeNames().begin(),
+      LLVM::LLVMFuncOp::getAttributeNames().end());
+
+  NamedAttrList inherentAttrs;
+
+  for (const NamedAttribute &attr : func->getDiscardableAttrs()) {
+    StringRef attrName = attr.getName().strref();
+
+    if (odsAttrNames.contains(attrName)) {
+      LDBG() << "LLVM specific attributes: " << attrName
+             << "should use llvm.* prefix, discarding it";
+      continue;
+    }
+
+    StringRef inherent = attrName;
+    if (inherent.consume_front("llvm.") && odsAttrNames.contains(inherent))
+      inherentAttrs.set(inherent, attr.getValue()); // collect inherent attrs
+    else
+      lowered.discardableAttrs.push_back(attr);
+  }
+
+  // Convert collected inherent attrs into typed properties.
+  if (!inherentAttrs.empty()) {
+    DictionaryAttr dict = inherentAttrs.getDictionary(ctx);
+    auto emitError = [&] {
+      return func.emitOpError("invalid llvm.func property");
+    };
+    if (failed(LLVM::LLVMFuncOp::setPropertiesFromAttr(lowered.properties, dict,
+                                                       emitError))) {
+      return failure();
+    }
+  }
+  return lowered;
+}

@joker-eph

Copy link
Copy Markdown
Contributor

Can you also check this fixes #185174 ? (and mention Fixes #185174 in the description)

@hockyy

hockyy commented Mar 27, 2026

Copy link
Copy Markdown
Member Author

Can you also check this fixes #185174 ? (and mention Fixes #185174 in the description)

It fixes it. Simply changing the attributes from linkage to llvm.linkage and %shared_counter = gpu.alloc() : memref<4xi16, 3> to %shared_counter = memref.alloca() : memref<4xi16, 3>

@hockyy
hockyy force-pushed the gpu-ops-lower-refactor branch 2 times, most recently from a1a6996 to 3c1188e Compare March 30, 2026 07:41
@llvmbot llvmbot added flang Flang issues not falling into any other category flang:fir-hlfir mlir:sparse labels Mar 30, 2026
@github-actions

github-actions Bot commented Mar 30, 2026 •

Copy link
Copy Markdown

✅ With the latest revision this PR passed the C/C++ code formatter.

@hockyy
hockyy force-pushed the gpu-ops-lower-refactor branch from 3c1188e to 1ea9046 Compare March 30, 2026 07:55
@hockyy

hockyy commented Mar 30, 2026

Copy link
Copy Markdown
Member Author

GPU dialect

  • gpu.func: Add inherent kernel (unit) and workgroup_attributions (optional non-negative i64). isKernel() prefers the inherent flag and still treats legacy discardable gpu.kernel as a kernel for old IR. Workgroup block arguments are accessed via getWorkgroupAttributionBBArgs() (replacing the old name that collided with the new inherent accessor). This removes the hardcode inherent attributes check from the GPU filtering.
  • gpu.launch: Same inherent workgroup_attributions shape; builders/parser only attach the attribute when the count is non-zero.
  • GPUDialect::isKernel: For gpu.func, delegates to GPUFuncOp::isKernel() so both inherent and legacy representations work. gpu.launch_func verification uses this helper when checking the callee. I believe it's natural for kernel annotation to be inherent to the function. Wondering why this is discardable in the first place.
  • Kernel outlining and other sites use setKernel(true) on outlined/generated gpu.func ops.

LLVM lowering

  • New mlir/Conversion/LLVMCommon/LowerFunctionAttrsToLLVM.{h,cpp}: lowerDiscardableAttrsForLLVMFunc splits discardable attributes into LLVMFuncOp properties vs. forwarded discardables, mirroring the previous FuncToLLVM logic but skipping names that resolve as inherent on the source op (important for property-backed ops where the raw dictionary can still reflect inherent fields).
  • FuncToLLVM: Calls the shared helper instead of a local duplicate.
  • GPUFuncOpLowering: Builds llvm.func via buildLoweredGPULLVMFuncAttrs, which runs the same lowering path as func.func, then fills symbol name, type, calling convention, and GPU/target discardable metadata (known block/grid/cluster sizes, kernel markers, etc.).

@hockyy
hockyy requested review from joker-eph and krzysz00 March 30, 2026 08:06
@hockyy
hockyy force-pushed the gpu-ops-lower-refactor branch from 8e00f65 to 66bd92c Compare April 21, 2026 07:24
@hockyy
hockyy force-pushed the gpu-ops-lower-refactor branch from 66bd92c to c2a812c Compare April 21, 2026 07:35
@hockyy

hockyy commented Apr 21, 2026

Copy link
Copy Markdown
Member Author

Hi @Hardcode84 @fabianmcg @kuhar I’d really appreciate it if you could review this PR and share your thoughts whenever you have some time :D

@krzysz00 krzysz00 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm here

@fabianmcg

fabianmcg commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Just in case @hockyy, if an LLVM member approved the PR and didn't say something like wait for other reviewers, and a reasonable amount of review time has elapsed, then you don't need to ask for more reviews, as this creates unnecessary review requests.

If you don't have merge privileges, you can leave a comment asking for someone to merge it.

@hockyy

hockyy commented Apr 22, 2026

Copy link
Copy Markdown
Member Author

Hi, @joker-eph let's merge this one as well

@joker-eph

Copy link
Copy Markdown
Contributor

LG, please do!

@hockyy
hockyy merged commit c1cff89 into llvm:main Apr 22, 2026
8 checks passed
linuxlonelyeagle pushed a commit to linuxlonelyeagle/llvm-project that referenced this pull request Apr 23, 2026
This change promotes `gpu.func` / `gpu.launch` metadata that was
previously carried as discardable attributes into proper inherent ODS
fields (`kernel`, `workgroup_attributions`), renames the block-argument
helpers to avoid clashing with generated getters, and routes `func.func`
and `gpu.func` lowering through a shared helper that maps discardable
`llvm.*` attributes into `llvm.func` properties.

Downstream producers (Flang CUDA device func transform, kernel
outlining, sparse GPU codegen, XeGPU) set kernels via `setKernel(true)`
instead of manually attaching `gpu.kernel`.

Fixes llvm#185174

Assisted-by: CLion code completion, GPT 5.3 - Codex
yingopq pushed a commit to yingopq/llvm-project that referenced this pull request Apr 29, 2026
This change promotes `gpu.func` / `gpu.launch` metadata that was
previously carried as discardable attributes into proper inherent ODS
fields (`kernel`, `workgroup_attributions`), renames the block-argument
helpers to avoid clashing with generated getters, and routes `func.func`
and `gpu.func` lowering through a shared helper that maps discardable
`llvm.*` attributes into `llvm.func` properties.

Downstream producers (Flang CUDA device func transform, kernel
outlining, sparse GPU codegen, XeGPU) set kernels via `setKernel(true)`
instead of manually attaching `gpu.kernel`.

Fixes llvm#185174

Assisted-by: CLion code completion, GPT 5.3 - Codex
KHicketts pushed a commit to KHicketts/llvm-project that referenced this pull request Apr 30, 2026
This change promotes `gpu.func` / `gpu.launch` metadata that was
previously carried as discardable attributes into proper inherent ODS
fields (`kernel`, `workgroup_attributions`), renames the block-argument
helpers to avoid clashing with generated getters, and routes `func.func`
and `gpu.func` lowering through a shared helper that maps discardable
`llvm.*` attributes into `llvm.func` properties.

Downstream producers (Flang CUDA device func transform, kernel
outlining, sparse GPU codegen, XeGPU) set kernels via `setKernel(true)`
instead of manually attaching `gpu.kernel`.

Fixes llvm#185174

Assisted-by: CLion code completion, GPT 5.3 - Codex
trdthg added a commit to buddy-compiler/buddy-mlir that referenced this pull request May 29, 2026
## Version and Build Flow

- fetch branch / apply local patch -> fetch exact submodule commit with
  `git fetch origin "${LLVM_COMMIT}"`
- `LLVM_COMMIT + riscv-jitlink.patch hash` -> `LLVM_COMMIT` cache key
- apply `riscv-jitlink.patch` -> no patch; current LLVM already has the fix
- [#172581](llvm/llvm-project#172581) / 3d7018c70b97: `nanobind` /
  `nanobind==2.4.*` -> `nanobind>=2.9,<3.0` / `nanobind==2.9.*`

## Python Bindings

- [#172581](llvm/llvm-project#172581) / 3d7018c70b97:
  `PybindAdaptors.h` -> `NanobindAdaptors.h`
- [#172581](llvm/llvm-project#172581) / 3d7018c70b97:
  `PYBIND11_MODULE` -> `NB_MODULE`
- [#172581](llvm/llvm-project#172581) / 3d7018c70b97: manual
  pybind/nanobind CMake setup -> `mlir_configure_python_dev_packages()`

## MLIR API

- [#162167](llvm/llvm-project#162167) / ea291d0e8c93:
  `vector::SplatOp` -> `vector::BroadcastOp`
- [#149603](llvm/llvm-project#149603) / 33465bb2bb75:
  `vector::InsertElementOp` -> `vector::InsertOp`
- [#149603](llvm/llvm-project#149603) / 33465bb2bb75:
  `vector::ExtractElementOp` -> `vector::ExtractOp`
- [#145445](llvm/llvm-project#145445) / 63f30d7d820c:
  `ValueRange{std::nullopt}` -> `ValueRange{}`
- [#145445](llvm/llvm-project#145445) / 63f30d7d820c:
  `TypeRange(std::nullopt)` -> `TypeRange{}`
- [#145445](llvm/llvm-project#145445) / 63f30d7d820c: empty
  `scf.yield` with null operands -> empty `scf.yield`
- [#196082](llvm/llvm-project#196082) / dd57b0c9728a:
  `computeConstantBound(..., /*closedUB=*/true)` ->
  `computeConstantBound(..., ValueBoundsOptions{/*closedUB=*/true})`
- [#182715](llvm/llvm-project#182715) / 72f5050ae765:
  `applyPatternsAndFoldGreedily(...)` -> `applyPatternsGreedily(...)`

## GPU and AMX

- [#188905](llvm/llvm-project#188905) / c1cff89bdcea:
  `launchOp.getWorkgroupAttributions()` ->
  `launchOp.getWorkgroupAttributionBBArgs()`
- [#188905](llvm/llvm-project#188905) / c1cff89bdcea: manual
  `gpu.kernel` attr -> `outlinedFunc.setKernel(true)`
- [#188905](llvm/llvm-project#188905) / c1cff89bdcea:
  `setAttr(getKnown*AttrName(), ...)` ->
  `setKnownBlockSizeAttr(...)` / `setKnownGridSizeAttr(...)`
- [#111197](llvm/llvm-project#111197) / 2f743ac52e94:
  `mlir/Dialect/AMX/AMXDialect.h` -> `mlir/Dialect/X86/X86Dialect.h`
- [#111197](llvm/llvm-project#111197) / 2f743ac52e94:
  `mlir::amx::AMXDialect` -> `mlir::x86::X86Dialect`

## LLVM Source Lists

- [#167271](llvm/llvm-project#167271) / 2345b7d98f75:
  `InlineSizeEstimatorAnalysis.cpp` -> removed upstream; no Buddy source-list
  entry needed
- [#172680](llvm/llvm-project#172680) / 71760f324ff9:
  `ExpandLargeDivRem.cpp` -> merged into `ExpandFp.cpp`
- [#172681](llvm/llvm-project#172681) / 5c05824d2bd3:
  `ExpandFp.cpp` / merged `ExpandLargeDivRem.cpp` -> `ExpandIRInsts.cpp`
- [#77370](llvm/llvm-project#77370) / 5e0a06b34d09:
  `ExpandMemCmp.cpp` in CodeGen -> moved to `Transforms/Scalar`
- [#181547](llvm/llvm-project#181547) / 9a0d65cdfd0d:
  `CallBrPrepare.cpp` -> `InlineAsmPrepare.cpp`
- [#160454](llvm/llvm-project#160454) / aa6a33ae6556:
  `EVLIndVarSimplify.cpp` -> removed upstream; no Buddy source-list entry needed
- [#192635](llvm/llvm-project#192635) / 680a9908194e:
  `VPlanSLP.cpp` -> removed upstream; no Buddy source-list entry needed

## RISC-V Backend

- local Buddy `M0`-`M7` definitions -> upstream RISC-V `M0`-`M7` definitions
- Buddy `MatrixReg` using local mask regs -> `MatrixReg` using upstream mask regs
- IME `*N` instructions in disassembler tables -> mark affected instructions
  `isCodeGenOnly = 1`

## Tool API and Link Libraries

- [#156715](llvm/llvm-project#156715) / dfbd76bda01e:
  `Expected<std::unique_ptr<ToolOutputFile>>` from
  `setupLLVMOptimizationRemarks` -> `Expected<LLVMRemarkFileHandle>`
- [#186998](llvm/llvm-project#186998) / 69cd746bd2f1:
  `codegen::setFunctionAttributes(CPUStr, FeaturesStr, F)` ->
  `codegen::setFunctionAttributes(F, CPUStr, FeaturesStr[, TuneCPUStr])`
- [#186998](llvm/llvm-project#186998) / 69cd746bd2f1:
  `codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M)` ->
  `codegen::setFunctionAttributes(*M, CPUStr, FeaturesStr[, TuneCPUStr])`
- [#87226](llvm/llvm-project#87226) / d0e72ccc54df:
  `TargetMachine::buildCodeGenPipeline(MPM, OS, DwoOut, FileType, Opt, PIC)` ->
  pass `MAM` and `MMI.getContext()`
- [#170846](llvm/llvm-project#170846) / cd806d7e7689: `buddy-llc`
  without `Plugins` -> link LLVM `Plugins`
- [#150805](llvm/llvm-project#150805) / ace42cf063a5,
  [#151150](llvm/llvm-project#151150) / e68a20e0b762: implicit MLIR
  register-all symbols -> link `MLIRRegisterAllDialects`,
  `MLIRRegisterAllExtensions`, `MLIRRegisterAllPasses`
trdthg added a commit to buddy-compiler/buddy-mlir that referenced this pull request May 29, 2026
- fetch branch / apply local patch -> fetch exact submodule commit with
  `git fetch origin "${LLVM_COMMIT}"`
- `LLVM_COMMIT + riscv-jitlink.patch hash` -> `LLVM_COMMIT` cache key
- apply `riscv-jitlink.patch` -> no patch; current LLVM already has the fix
- [#172581](llvm/llvm-project#172581) / 3d7018c70b97: `nanobind` /
  `nanobind==2.4.*` -> `nanobind>=2.9,<3.0` / `nanobind==2.9.*`

- [#172581](llvm/llvm-project#172581) / 3d7018c70b97:
  `PybindAdaptors.h` -> `NanobindAdaptors.h`
- [#172581](llvm/llvm-project#172581) / 3d7018c70b97:
  `PYBIND11_MODULE` -> `NB_MODULE`
- [#172581](llvm/llvm-project#172581) / 3d7018c70b97: manual
  pybind/nanobind CMake setup -> `mlir_configure_python_dev_packages()`

- [#162167](llvm/llvm-project#162167) / ea291d0e8c93:
  `vector::SplatOp` -> `vector::BroadcastOp`
- [#149603](llvm/llvm-project#149603) / 33465bb2bb75:
  `vector::InsertElementOp` -> `vector::InsertOp`
- [#149603](llvm/llvm-project#149603) / 33465bb2bb75:
  `vector::ExtractElementOp` -> `vector::ExtractOp`
- [#145445](llvm/llvm-project#145445) / 63f30d7d820c:
  `ValueRange{std::nullopt}` -> `ValueRange{}`
- [#145445](llvm/llvm-project#145445) / 63f30d7d820c:
  `TypeRange(std::nullopt)` -> `TypeRange{}`
- [#145445](llvm/llvm-project#145445) / 63f30d7d820c: empty
  `scf.yield` with null operands -> empty `scf.yield`
- [#196082](llvm/llvm-project#196082) / dd57b0c9728a:
  `computeConstantBound(..., /*closedUB=*/true)` ->
  `computeConstantBound(..., ValueBoundsOptions{/*closedUB=*/true})`
- [#182715](llvm/llvm-project#182715) / 72f5050ae765:
  `applyPatternsAndFoldGreedily(...)` -> `applyPatternsGreedily(...)`

- [#188905](llvm/llvm-project#188905) / c1cff89bdcea:
  `launchOp.getWorkgroupAttributions()` ->
  `launchOp.getWorkgroupAttributionBBArgs()`
- [#188905](llvm/llvm-project#188905) / c1cff89bdcea: manual
  `gpu.kernel` attr -> `outlinedFunc.setKernel(true)`
- [#188905](llvm/llvm-project#188905) / c1cff89bdcea:
  `setAttr(getKnown*AttrName(), ...)` ->
  `setKnownBlockSizeAttr(...)` / `setKnownGridSizeAttr(...)`
- [#111197](llvm/llvm-project#111197) / 2f743ac52e94:
  `mlir/Dialect/AMX/AMXDialect.h` -> `mlir/Dialect/X86/X86Dialect.h`
- [#111197](llvm/llvm-project#111197) / 2f743ac52e94:
  `mlir::amx::AMXDialect` -> `mlir::x86::X86Dialect`

- [#167271](llvm/llvm-project#167271) / 2345b7d98f75:
  `InlineSizeEstimatorAnalysis.cpp` -> removed upstream; no Buddy source-list
  entry needed
- [#172680](llvm/llvm-project#172680) / 71760f324ff9:
  `ExpandLargeDivRem.cpp` -> merged into `ExpandFp.cpp`
- [#172681](llvm/llvm-project#172681) / 5c05824d2bd3:
  `ExpandFp.cpp` / merged `ExpandLargeDivRem.cpp` -> `ExpandIRInsts.cpp`
- [#77370](llvm/llvm-project#77370) / 5e0a06b34d09:
  `ExpandMemCmp.cpp` in CodeGen -> moved to `Transforms/Scalar`
- [#181547](llvm/llvm-project#181547) / 9a0d65cdfd0d:
  `CallBrPrepare.cpp` -> `InlineAsmPrepare.cpp`
- [#160454](llvm/llvm-project#160454) / aa6a33ae6556:
  `EVLIndVarSimplify.cpp` -> removed upstream; no Buddy source-list entry needed
- [#192635](llvm/llvm-project#192635) / 680a9908194e:
  `VPlanSLP.cpp` -> removed upstream; no Buddy source-list entry needed

- local Buddy `M0`-`M7` definitions -> upstream RISC-V `M0`-`M7` definitions
- Buddy `MatrixReg` using local mask regs -> `MatrixReg` using upstream mask regs
- IME `*N` instructions in disassembler tables -> mark affected instructions
  `isCodeGenOnly = 1`

- [#156715](llvm/llvm-project#156715) / dfbd76bda01e:
  `Expected<std::unique_ptr<ToolOutputFile>>` from
  `setupLLVMOptimizationRemarks` -> `Expected<LLVMRemarkFileHandle>`
- [#186998](llvm/llvm-project#186998) / 69cd746bd2f1:
  `codegen::setFunctionAttributes(CPUStr, FeaturesStr, F)` ->
  `codegen::setFunctionAttributes(F, CPUStr, FeaturesStr[, TuneCPUStr])`
- [#186998](llvm/llvm-project#186998) / 69cd746bd2f1:
  `codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M)` ->
  `codegen::setFunctionAttributes(*M, CPUStr, FeaturesStr[, TuneCPUStr])`
- [#87226](llvm/llvm-project#87226) / d0e72ccc54df:
  `TargetMachine::buildCodeGenPipeline(MPM, OS, DwoOut, FileType, Opt, PIC)` ->
  pass `MAM` and `MMI.getContext()`
- [#170846](llvm/llvm-project#170846) / cd806d7e7689: `buddy-llc`
  without `Plugins` -> link LLVM `Plugins`
- [#150805](llvm/llvm-project#150805) / ace42cf063a5,
  [#151150](llvm/llvm-project#151150) / e68a20e0b762: implicit MLIR
  register-all symbols -> link `MLIRRegisterAllDialects`,
  `MLIRRegisterAllExtensions`, `MLIRRegisterAllPasses`
trdthg added a commit to buddy-compiler/buddy-mlir that referenced this pull request May 29, 2026
- fetch branch / apply local patch -> fetch exact submodule commit with
  `git fetch origin "${LLVM_COMMIT}"`
- `LLVM_COMMIT + riscv-jitlink.patch hash` -> `LLVM_COMMIT` cache key
- apply `riscv-jitlink.patch` -> no patch; current LLVM already has the fix
- [#172581](llvm/llvm-project#172581) / 3d7018c70b97: `nanobind` /
  `nanobind==2.4.*` -> `nanobind>=2.9,<3.0` / `nanobind==2.9.*`

- [#172581](llvm/llvm-project#172581) / 3d7018c70b97:
  `PybindAdaptors.h` -> `NanobindAdaptors.h`
- [#172581](llvm/llvm-project#172581) / 3d7018c70b97:
  `PYBIND11_MODULE` -> `NB_MODULE`
- [#172581](llvm/llvm-project#172581) / 3d7018c70b97: manual
  pybind/nanobind CMake setup -> `mlir_configure_python_dev_packages()`

- [#162167](llvm/llvm-project#162167) / ea291d0e8c93:
  `vector::SplatOp` -> `vector::BroadcastOp`
- [#149603](llvm/llvm-project#149603) / 33465bb2bb75:
  `vector::InsertElementOp` -> `vector::InsertOp`
- [#149603](llvm/llvm-project#149603) / 33465bb2bb75:
  `vector::ExtractElementOp` -> `vector::ExtractOp`
- [#145445](llvm/llvm-project#145445) / 63f30d7d820c:
  `ValueRange{std::nullopt}` -> `ValueRange{}`
- [#145445](llvm/llvm-project#145445) / 63f30d7d820c:
  `TypeRange(std::nullopt)` -> `TypeRange{}`
- [#145445](llvm/llvm-project#145445) / 63f30d7d820c: empty
  `scf.yield` with null operands -> empty `scf.yield`
- [#196082](llvm/llvm-project#196082) / dd57b0c9728a:
  `computeConstantBound(..., /*closedUB=*/true)` ->
  `computeConstantBound(..., ValueBoundsOptions{/*closedUB=*/true})`
- [#182715](llvm/llvm-project#182715) / 72f5050ae765:
  `applyPatternsAndFoldGreedily(...)` -> `applyPatternsGreedily(...)`

- [#188905](llvm/llvm-project#188905) / c1cff89bdcea:
  `launchOp.getWorkgroupAttributions()` ->
  `launchOp.getWorkgroupAttributionBBArgs()`
- [#188905](llvm/llvm-project#188905) / c1cff89bdcea: manual
  `gpu.kernel` attr -> `outlinedFunc.setKernel(true)`
- [#188905](llvm/llvm-project#188905) / c1cff89bdcea:
  `setAttr(getKnown*AttrName(), ...)` ->
  `setKnownBlockSizeAttr(...)` / `setKnownGridSizeAttr(...)`
- [#111197](llvm/llvm-project#111197) / 2f743ac52e94:
  `mlir/Dialect/AMX/AMXDialect.h` -> `mlir/Dialect/X86/X86Dialect.h`
- [#111197](llvm/llvm-project#111197) / 2f743ac52e94:
  `mlir::amx::AMXDialect` -> `mlir::x86::X86Dialect`

- [#167271](llvm/llvm-project#167271) / 2345b7d98f75:
  `InlineSizeEstimatorAnalysis.cpp` -> removed upstream; no Buddy source-list
  entry needed
- [#172680](llvm/llvm-project#172680) / 71760f324ff9:
  `ExpandLargeDivRem.cpp` -> merged into `ExpandFp.cpp`
- [#172681](llvm/llvm-project#172681) / 5c05824d2bd3:
  `ExpandFp.cpp` / merged `ExpandLargeDivRem.cpp` -> `ExpandIRInsts.cpp`
- [#77370](llvm/llvm-project#77370) / 5e0a06b34d09:
  `ExpandMemCmp.cpp` in CodeGen -> moved to `Transforms/Scalar`
- [#181547](llvm/llvm-project#181547) / 9a0d65cdfd0d:
  `CallBrPrepare.cpp` -> `InlineAsmPrepare.cpp`
- [#160454](llvm/llvm-project#160454) / aa6a33ae6556:
  `EVLIndVarSimplify.cpp` -> removed upstream; no Buddy source-list entry needed
- [#192635](llvm/llvm-project#192635) / 680a9908194e:
  `VPlanSLP.cpp` -> removed upstream; no Buddy source-list entry needed

- local Buddy `M0`-`M7` definitions -> upstream RISC-V `M0`-`M7` definitions
- Buddy `MatrixReg` using local mask regs -> `MatrixReg` using upstream mask regs
- IME `*N` instructions in disassembler tables -> mark affected instructions
  `isCodeGenOnly = 1`

- [#156715](llvm/llvm-project#156715) / dfbd76bda01e:
  `Expected<std::unique_ptr<ToolOutputFile>>` from
  `setupLLVMOptimizationRemarks` -> `Expected<LLVMRemarkFileHandle>`
- [#186998](llvm/llvm-project#186998) / 69cd746bd2f1:
  `codegen::setFunctionAttributes(CPUStr, FeaturesStr, F)` ->
  `codegen::setFunctionAttributes(F, CPUStr, FeaturesStr[, TuneCPUStr])`
- [#186998](llvm/llvm-project#186998) / 69cd746bd2f1:
  `codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M)` ->
  `codegen::setFunctionAttributes(*M, CPUStr, FeaturesStr[, TuneCPUStr])`
- [#87226](llvm/llvm-project#87226) / d0e72ccc54df:
  `TargetMachine::buildCodeGenPipeline(MPM, OS, DwoOut, FileType, Opt, PIC)` ->
  pass `MAM` and `MMI.getContext()`
- [#170846](llvm/llvm-project#170846) / cd806d7e7689: `buddy-llc`
  without `Plugins` -> link LLVM `Plugins`
- [#150805](llvm/llvm-project#150805) / ace42cf063a5,
  [#151150](llvm/llvm-project#151150) / e68a20e0b762: implicit MLIR
  register-all symbols -> link `MLIRRegisterAllDialects`,
  `MLIRRegisterAllExtensions`, `MLIRRegisterAllPasses`
trdthg added a commit to buddy-compiler/buddy-mlir that referenced this pull request Jun 1, 2026
- fetch branch / apply local patch -> fetch exact submodule commit with
  `git fetch origin "${LLVM_COMMIT}"`
- `LLVM_COMMIT + riscv-jitlink.patch hash` -> `LLVM_COMMIT` cache key
- apply `riscv-jitlink.patch` -> no patch; current LLVM already has the fix
- [#172581](llvm/llvm-project#172581) / 3d7018c70b97: `nanobind` /
  `nanobind==2.4.*` -> `nanobind>=2.9,<3.0` / `nanobind==2.9.*`

- [#172581](llvm/llvm-project#172581) / 3d7018c70b97:
  `PybindAdaptors.h` -> `NanobindAdaptors.h`
- [#172581](llvm/llvm-project#172581) / 3d7018c70b97:
  `PYBIND11_MODULE` -> `NB_MODULE`
- [#172581](llvm/llvm-project#172581) / 3d7018c70b97: manual
  pybind/nanobind CMake setup -> `mlir_configure_python_dev_packages()`

- [#162167](llvm/llvm-project#162167) / ea291d0e8c93:
  `vector::SplatOp` -> `vector::BroadcastOp`
- [#149603](llvm/llvm-project#149603) / 33465bb2bb75:
  `vector::InsertElementOp` -> `vector::InsertOp`
- [#149603](llvm/llvm-project#149603) / 33465bb2bb75:
  `vector::ExtractElementOp` -> `vector::ExtractOp`
- [#145445](llvm/llvm-project#145445) / 63f30d7d820c:
  `ValueRange{std::nullopt}` -> `ValueRange{}`
- [#145445](llvm/llvm-project#145445) / 63f30d7d820c:
  `TypeRange(std::nullopt)` -> `TypeRange{}`
- [#145445](llvm/llvm-project#145445) / 63f30d7d820c: empty
  `scf.yield` with null operands -> empty `scf.yield`
- [#196082](llvm/llvm-project#196082) / dd57b0c9728a:
  `computeConstantBound(..., /*closedUB=*/true)` ->
  `computeConstantBound(..., ValueBoundsOptions{/*closedUB=*/true})`
- [#182715](llvm/llvm-project#182715) / 72f5050ae765:
  `applyPatternsAndFoldGreedily(...)` -> `applyPatternsGreedily(...)`

- [#188905](llvm/llvm-project#188905) / c1cff89bdcea:
  `launchOp.getWorkgroupAttributions()` ->
  `launchOp.getWorkgroupAttributionBBArgs()`
- [#188905](llvm/llvm-project#188905) / c1cff89bdcea: manual
  `gpu.kernel` attr -> `outlinedFunc.setKernel(true)`
- [#188905](llvm/llvm-project#188905) / c1cff89bdcea:
  `setAttr(getKnown*AttrName(), ...)` ->
  `setKnownBlockSizeAttr(...)` / `setKnownGridSizeAttr(...)`
- [#111197](llvm/llvm-project#111197) / 2f743ac52e94:
  `mlir/Dialect/AMX/AMXDialect.h` -> `mlir/Dialect/X86/X86Dialect.h`
- [#111197](llvm/llvm-project#111197) / 2f743ac52e94:
  `mlir::amx::AMXDialect` -> `mlir::x86::X86Dialect`

- [#167271](llvm/llvm-project#167271) / 2345b7d98f75:
  `InlineSizeEstimatorAnalysis.cpp` -> removed upstream; no Buddy source-list
  entry needed
- [#172680](llvm/llvm-project#172680) / 71760f324ff9:
  `ExpandLargeDivRem.cpp` -> merged into `ExpandFp.cpp`
- [#172681](llvm/llvm-project#172681) / 5c05824d2bd3:
  `ExpandFp.cpp` / merged `ExpandLargeDivRem.cpp` -> `ExpandIRInsts.cpp`
- [#77370](llvm/llvm-project#77370) / 5e0a06b34d09:
  `ExpandMemCmp.cpp` in CodeGen -> moved to `Transforms/Scalar`
- [#181547](llvm/llvm-project#181547) / 9a0d65cdfd0d:
  `CallBrPrepare.cpp` -> `InlineAsmPrepare.cpp`
- [#160454](llvm/llvm-project#160454) / aa6a33ae6556:
  `EVLIndVarSimplify.cpp` -> removed upstream; no Buddy source-list entry needed
- [#192635](llvm/llvm-project#192635) / 680a9908194e:
  `VPlanSLP.cpp` -> removed upstream; no Buddy source-list entry needed

- local Buddy `M0`-`M7` definitions -> upstream RISC-V `M0`-`M7` definitions
- Buddy `MatrixReg` using local mask regs -> `MatrixReg` using upstream mask regs
- IME `*N` instructions in disassembler tables -> mark affected instructions
  `isCodeGenOnly = 1`

- [#156715](llvm/llvm-project#156715) / dfbd76bda01e:
  `Expected<std::unique_ptr<ToolOutputFile>>` from
  `setupLLVMOptimizationRemarks` -> `Expected<LLVMRemarkFileHandle>`
- [#186998](llvm/llvm-project#186998) / 69cd746bd2f1:
  `codegen::setFunctionAttributes(CPUStr, FeaturesStr, F)` ->
  `codegen::setFunctionAttributes(F, CPUStr, FeaturesStr[, TuneCPUStr])`
- [#186998](llvm/llvm-project#186998) / 69cd746bd2f1:
  `codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M)` ->
  `codegen::setFunctionAttributes(*M, CPUStr, FeaturesStr[, TuneCPUStr])`
- [#87226](llvm/llvm-project#87226) / d0e72ccc54df:
  `TargetMachine::buildCodeGenPipeline(MPM, OS, DwoOut, FileType, Opt, PIC)` ->
  pass `MAM` and `MMI.getContext()`
- [#170846](llvm/llvm-project#170846) / cd806d7e7689: `buddy-llc`
  without `Plugins` -> link LLVM `Plugins`
- [#150805](llvm/llvm-project#150805) / ace42cf063a5,
  [#151150](llvm/llvm-project#151150) / e68a20e0b762: implicit MLIR
  register-all symbols -> link `MLIRRegisterAllDialects`,
  `MLIRRegisterAllExtensions`, `MLIRRegisterAllPasses`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

flang:fir-hlfir flang Flang issues not falling into any other category mlir:gpu mlir:llvm mlir:sparse mlir

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[MLIR] Crash when lowering gpu function to llvm due to attribute sorting issue

5 participants