Tim
Tim

Reputation: 5681

C++ LLVM class functionality

I'm playing around with LLVM, but now I got stuck at generating code for classes.

How would one create class functionality using LLVM?

Upvotes: 10

Views: 2374

Answers (1)

Oak
Oak

Reputation: 26868

Long Version

General class behavior

A straightforward approach is to create structs, then model methods as regular functions that receive a pointer to a struct representing the containing class - in essence, a this pointer - as the first parameter. Allocation could be modeled by allocating the struct and then calling a special initializing function - the constructor, really - on the allocated data.

Inheritance could be done by building a struct which contains a special "parent" field (or fields, for multiple inheritance), that has a type identical to the type of the struct for the base class.

Polymorphism

Read about virtual tables; I think they're the best starting point. You could find that the compiler basically:

  1. Creates a static table in memory, mapping from a function "name" to its implementation,
  2. Adds a pointer to the class struct that points to such a table,
  3. Whenever a virtual method is called, compiles it into an indirect call which dereferences the address from the appropriate virtual table entry.

Short Version

Write some code which uses classes in C++, then compile it to LLVM IR with Clang and look at the generated code.

Upvotes: 16

Related Questions