[Mlir-commits] [mlir] [mlir][EmitC]Expand the MemRefToEmitC pass - Lowering `AllocOp` (PR #148257)
Jaden Angella
llvmlistbot at llvm.org
Mon Jul 21 15:51:15 PDT 2025
================
@@ -77,6 +78,78 @@ struct ConvertAlloca final : public OpConversionPattern<memref::AllocaOp> {
}
};
+struct ConvertAlloc final : public OpConversionPattern<memref::AllocOp> {
+ using OpConversionPattern::OpConversionPattern;
+ LogicalResult
+ matchAndRewrite(memref::AllocOp allocOp, OpAdaptor operands,
+ ConversionPatternRewriter &rewriter) const override {
+ mlir::Location loc = allocOp.getLoc();
+ auto memrefType = allocOp.getType();
+ if (!memrefType.hasStaticShape()) {
+ // TODO: Handle Dynamic shapes in the future. If the size
+ // of the allocation is the result of some function, we could
+ // potentially evaluate the function and use the result in the call to
+ // allocate.
+ return rewriter.notifyMatchFailure(
+ loc, "cannot transform alloc with dynamic shape");
+ }
+
+ Type elementType = memrefType.getElementType();
+ mlir::Value elementTypeLiteral = rewriter.create<emitc::LiteralOp>(
+ loc, mlir::emitc::OpaqueType::get(rewriter.getContext(), "type"),
+ rewriter.getStringAttr(getCTypeName(elementType)));
+ emitc::CallOpaqueOp sizeofElementOp = rewriter.create<emitc::CallOpaqueOp>(
+ loc, mlir::emitc::SizeTType::get(rewriter.getContext()),
+ rewriter.getStringAttr("sizeof"), mlir::ValueRange{elementTypeLiteral});
+ mlir::Value sizeofElement = sizeofElementOp.getResult(0);
+
+ unsigned int elementWidth = elementType.getIntOrFloatBitWidth();
+ mlir::Value numElements;
+ if (elementType.isF32())
+ numElements = rewriter.create<emitc::ConstantOp>(
+ loc, elementType, rewriter.getFloatAttr(elementType, elementWidth));
+ else
+ numElements = rewriter.create<emitc::ConstantOp>(
+ loc, elementType, rewriter.getIntegerAttr(elementType, elementWidth));
+ mlir::Value totalSizeBytes = rewriter.create<emitc::MulOp>(
+ loc, mlir::emitc::SizeTType::get(rewriter.getContext()), sizeofElement,
+ numElements);
+
+ auto mallocCall = rewriter.create<emitc::CallOpaqueOp>(
+ loc,
+ emitc::PointerType::get(
+ rewriter.getContext(),
+ mlir::emitc::OpaqueType::get(rewriter.getContext(), "void")),
+ rewriter.getStringAttr("malloc"), mlir::ValueRange{totalSizeBytes});
+ auto targetPointerType =
+ emitc::PointerType::get(rewriter.getContext(), elementType);
----------------
Jaddyen wrote:
ack, thanks for the pointer!
https://github.com/llvm/llvm-project/pull/148257
More information about the Mlir-commits
mailing list