[Mlir-commits] [mlir] Expand the MemRefToEmitC pass - Lowering `AllocOp` (PR #148257)

Gil Rapaport llvmlistbot at llvm.org
Wed Jul 16 10:01:46 PDT 2025


================
@@ -77,6 +77,43 @@ 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(
+          allocOp.getLoc(), "cannot transform alloc op with dynamic shape");
+
+    // TODO: Is there a better API to determine the number of bits in a byte in
+    // MLIR?
+    int64_t totalSize = memrefType.getNumElements() *
+                        memrefType.getElementTypeBitWidth() / CHAR_BIT;
----------------
aniragil wrote:

The `memref` to `LLVM` lowering implements a version of `sizeof` for finding the element size in bytes (see `ConvertToLLVMPattern::getSizeInBytes`). Since we're emitting C code you could emit the computation as `malloc()`'s parameter, e.g
```mlir
   %c = emitc.literal "int" : !emitc.opaque<"type">
   %e = emitc.call_opaque "sizeof", %c : !emitc.size_t
   %d = emitc.constant 57: !emitc.size_t
   %s = emitc.mul %e, %d : !emitc.size_t
   %m = emitc.call_opaque "malloc", %s : !emitc.ptr<!emitc.opaque<"void">>
```
which should translate to
```C
 size_t v0 = sizeof(int);
 size_t v1 = 57;
 size_t v2 = v0 * v1;
 void* v3 = malloc(v2);
```
The `form-expressions` pass sould fold this code into a single expression, i.e.
```C
 void* v3 = malloc(sizeof(int) * 57);
```
And the C compiler irons out such static calculations anyway.

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


More information about the Mlir-commits mailing list