How to implement member function in MLIR?

Hi, I have a question about member function in MLIR.

Suppose I have a snip of code like python

class MyClass:
    def foo(self, a: Int):
        return a

x = MyClass()
b = x.foo(1)

After I parse the code into an AST, how to I implement the member function in MLIR ?

I know that common function can be lowered to llvm.func with function name and parameters, but how can I call a member function of an object of MyClass in MLIR?

I checked the builtin and llvm dialect, and DataLayout documents, and I can think of an idea as below:

  1. define a struct type in MLIR to represent MyClass.
  2. convert struct MyClass to MemrefType in MLIR.
  3. for every member function in MyClass, convert it into a llvm.func with name prefixed with class name, for example, foo would be MyClass.foo. And for first parameter self, replace it with MemrefType value which is a mlir::Value that represent an actual object.
  4. for every call of foo, it would use the object as first parameter.

So is this idea correct ? Or are there any other idea to solve this problem ?

I think this is a reasonable starting point. I would say that it’s probably not necessary to use memref though. Do you intend to lower your language to the LLVM dialect? If so, you can probably lower your structs to llvm.struct directly (or perhaps use llvm.struct directly if you do not need higher level features).

Once you have this basic approach going, you can always introduce at a later point constructs to do higher level analysis if you feel like it.

@Moxinilian
Hi, thanks for the reply.

Yes, I intended to lower my language to llvm Dialect. Lowering to llvm.struct directly seems like a good solution. I’ll try this idea.