Hi, this is perhaps more a design question than an LLVM question (let me know if I should post it elsewhere):
I’m implementing interfaces in my toy language, and are wondering how to design my vtable layout.
The way I envision it is like this:
Every interface defines a set of functions, and a vtable containing those function signatures as a type. Each class then defines its implementation of the vtable type (function pointers) and hold a pointer to the vtable within each instance. I should then at runtime be able to look up the implementation of a function given an instance and its implemented vtable.
My question concerns the situation where multiple interfaces are implemented, and a function which accepts an interface as argument: How do I know which vtable to look in?
If classA implements IFoo and IBar, and classB only implements IBar, and I’m compiling a function which takes an IBar instance, then classA and classB will (probably) hold their IBar vtable pointer at different indices in their structs.
Here’s my toy language scenario:
interface IFoo {
fooFunction(Int a, Int b): Int
}
interface IBar {
barFunction(Int a): None
}
class ClassA implements IFoo, IBar {
fooFunction(Int a, Int b): Int {
...
}
barFunction(Int a): None {
...
}
}
class ClassB implements IBar {
barFunction(Int a): None {
...
}
}
functionTakesInterface(IBar x): None {
x.barFunction(2)
// How can I ask x where to find its IBar vtable pointer?
}
One idea I had: All types have a unique “index”, e.g. stored in a global array. For every interface, make a list of pointers where the index corresponds to the type and the value is the vtable pointer for that type (to that interface). Then I only have to ask the instance for its type-index at runtime, but it might not scale well if only 3 of 10000 types implement the interface.
Thank you in advance!