How to set up LLVM-style RTTI for your class hierarchy

Background

LLVM avoids using C++’s built in RTTI. Instead, it pervasively uses itsown hand-rolled form of RTTI which is much more efficient and flexible,although it requires a bit more work from you as a class author.

A description of how to use LLVM-style RTTI from a client’s perspective isgiven in the Programmer’s Manual. Thisdocument, in contrast, discusses the steps you need to take as a classhierarchy author to make LLVM-style RTTI available to your clients.

Before diving in, make sure that you are familiar with the Object OrientedProgramming concept of “is-a”.

Basic Setup

This section describes how to set up the most basic form of LLVM-style RTTI(which is sufficient for 99.9% of the cases). We will set up LLVM-styleRTTI for this class hierarchy:

  1. class Shape {
  2. public:
  3. Shape() {}
  4. virtual double computeArea() = 0;
  5. };
  6.  
  7. class Square : public Shape {
  8. double SideLength;
  9. public:
  10. Square(double S) : SideLength(S) {}
  11. double computeArea() override;
  12. };
  13.  
  14. class Circle : public Shape {
  15. double Radius;
  16. public:
  17. Circle(double R) : Radius(R) {}
  18. double computeArea() override;
  19. };

The most basic working setup for LLVM-style RTTI requires the followingsteps:

  • In the header where you declare Shape, you will want to #include"llvm/Support/Casting.h", which declares LLVM’s RTTI templates. Thatway your clients don’t even have to think about it.
  1. #include "llvm/Support/Casting.h"
  • In the base class, introduce an enum which discriminates all of thedifferent concrete classes in the hierarchy, and stash the enum valuesomewhere in the base class.

Here is the code after introducing this change:

  1. class Shape {
  2. public:
  3. + /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
  4. + enum ShapeKind {
  5. + SK_Square,
  6. + SK_Circle
  7. + };
  8. +private:
  9. + const ShapeKind Kind;
  10. +public:
  11. + ShapeKind getKind() const { return Kind; }
  12. +
  13. Shape() {}
  14. virtual double computeArea() = 0;
  15. };

You will usually want to keep the Kind member encapsulated andprivate, but let the enum ShapeKind be public along with providing agetKind() method. This is convenient for clients so that they can doa switch over the enum.

A common naming convention is that these enums are “kind”s, to avoidambiguity with the words “type” or “class” which have overloaded meaningsin many contexts within LLVM. Sometimes there will be a natural name forit, like “opcode”. Don’t bikeshed over this; when in doubt use Kind.

You might wonder why the Kind enum doesn’t have an entry forShape. The reason for this is that since Shape is abstract(computeArea() = 0;), you will never actually have non-derivedinstances of exactly that class (only subclasses). See Concrete Basesand Deeper Hierarchies for information on how to deal withnon-abstract bases. It’s worth mentioning here that unlikedynamic_cast<>, LLVM-style RTTI can be used (and is often used) forclasses that don’t have v-tables.

  • Next, you need to make sure that the Kind gets initialized to thevalue corresponding to the dynamic type of the class. Typically, you willwant to have it be an argument to the constructor of the base class, andthen pass in the respective XXXKind from subclass constructors.

Here is the code after that change:

  1. class Shape {
  2. public:
  3. /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
  4. enum ShapeKind {
  5. SK_Square,
  6. SK_Circle
  7. };
  8. private:
  9. const ShapeKind Kind;
  10. public:
  11. ShapeKind getKind() const { return Kind; }
  12.  
  13. - Shape() {}
  14. + Shape(ShapeKind K) : Kind(K) {}
  15. virtual double computeArea() = 0;
  16. };
  17.  
  18. class Square : public Shape {
  19. double SideLength;
  20. public:
  21. - Square(double S) : SideLength(S) {}
  22. + Square(double S) : Shape(SK_Square), SideLength(S) {}
  23. double computeArea() override;
  24. };
  25.  
  26. class Circle : public Shape {
  27. double Radius;
  28. public:
  29. - Circle(double R) : Radius(R) {}
  30. + Circle(double R) : Shape(SK_Circle), Radius(R) {}
  31. double computeArea() override;
  32. };
  • Finally, you need to inform LLVM’s RTTI templates how to dynamicallydetermine the type of a class (i.e. whether the isa<>/dyn_cast<>should succeed). The default “99.9% of use cases” way to accomplish thisis through a small static member function classof. In order to haveproper context for an explanation, we will display this code first, andthen below describe each part:
  1. class Shape {
  2. public:
  3. /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
  4. enum ShapeKind {
  5. SK_Square,
  6. SK_Circle
  7. };
  8. private:
  9. const ShapeKind Kind;
  10. public:
  11. ShapeKind getKind() const { return Kind; }
  12.  
  13. Shape(ShapeKind K) : Kind(K) {}
  14. virtual double computeArea() = 0;
  15. };
  16.  
  17. class Square : public Shape {
  18. double SideLength;
  19. public:
  20. Square(double S) : Shape(SK_Square), SideLength(S) {}
  21. double computeArea() override;
  22. +
  23. + static bool classof(const Shape *S) {
  24. + return S->getKind() == SK_Square;
  25. + }
  26. };
  27.  
  28. class Circle : public Shape {
  29. double Radius;
  30. public:
  31. Circle(double R) : Shape(SK_Circle), Radius(R) {}
  32. double computeArea() override;
  33. +
  34. + static bool classof(const Shape *S) {
  35. + return S->getKind() == SK_Circle;
  36. + }
  37. };

The job of classof is to dynamically determine whether an object ofa base class is in fact of a particular derived class. In order todowncast a type Base to a type Derived, there needs to be aclassof in Derived which will accept an object of type Base.

To be concrete, consider the following code:

  1. Shape *S = ...;
  2. if (isa<Circle>(S)) {
  3. /* do something ... */
  4. }

The code of the isa<> test in this code will eventually boildown—after template instantiation and some other machinery—to acheck roughly like Circle::classof(S). For more information, seeThe Contract of classof.

The argument to classof should always be an ancestor class becausethe implementation has logic to allow and optimize awayupcasts/up-isa<>’s automatically. It is as though every classFoo automatically has a classof like:

  1. class Foo {
  2. [...]
  3. template <class T>
  4. static bool classof(const T *,
  5. ::std::enable_if<
  6. ::std::is_base_of<Foo, T>::value
  7. >::type* = 0) { return true; }
  8. [...]
  9. };

Note that this is the reason that we did not need to introduce aclassof into Shape: all relevant classes derive from Shape,and Shape itself is abstract (has no entry in the Kind enum),so this notional inferred classof is all we need. See ConcreteBases and Deeper Hierarchies for more information about how to extendthis example to more general hierarchies.

Although for this small example setting up LLVM-style RTTI seems like a lotof “boilerplate”, if your classes are doing anything interesting then thiswill end up being a tiny fraction of the code.

Concrete Bases and Deeper Hierarchies

For concrete bases (i.e. non-abstract interior nodes of the inheritancetree), the Kind check inside classof needs to be a bit morecomplicated. The situation differs from the example above in that

  • Since the class is concrete, it must itself have an entry in the Kindenum because it is possible to have objects with this class as a dynamictype.
  • Since the class has children, the check inside classof must take theminto account.

Say that SpecialSquare and OtherSpecialSquare derivefrom Square, and so ShapeKind becomes:

  1. enum ShapeKind {
  2. SK_Square,
  3. + SK_SpecialSquare,
  4. + SK_OtherSpecialSquare,
  5. SK_Circle
  6. }

Then in Square, we would need to modify the classof like so:

  1. - static bool classof(const Shape *S) {
  2. - return S->getKind() == SK_Square;
  3. - }
  4. + static bool classof(const Shape *S) {
  5. + return S->getKind() >= SK_Square &&
  6. + S->getKind() <= SK_OtherSpecialSquare;
  7. + }

The reason that we need to test a range like this instead of just equalityis that both SpecialSquare and OtherSpecialSquare “is-a”Square, and so classof needs to return true for them.

This approach can be made to scale to arbitrarily deep hierarchies. Thetrick is that you arrange the enum values so that they correspond to apreorder traversal of the class hierarchy tree. With that arrangement, allsubclass tests can be done with two comparisons as shown above. If you justlist the class hierarchy like a list of bullet points, you’ll get theordering right:

  1. | Shape
  2. | Square
  3. | SpecialSquare
  4. | OtherSpecialSquare
  5. | Circle

A Bug to be Aware Of

The example just given opens the door to bugs where the classofs arenot updated to match the Kind enum when adding (or removing) classes to(from) the hierarchy.

Continuing the example above, suppose we add a SomewhatSpecialSquare asa subclass of Square, and update the ShapeKind enum like so:

  1. enum ShapeKind {
  2. SK_Square,
  3. SK_SpecialSquare,
  4. SK_OtherSpecialSquare,
  5. + SK_SomewhatSpecialSquare,
  6. SK_Circle
  7. }

Now, suppose that we forget to update Square::classof(), so it stilllooks like:

  1. static bool classof(const Shape *S) {
  2. // BUG: Returns false when S->getKind() == SK_SomewhatSpecialSquare,
  3. // even though SomewhatSpecialSquare "is a" Square.
  4. return S->getKind() >= SK_Square &&
  5. S->getKind() <= SK_OtherSpecialSquare;
  6. }

As the comment indicates, this code contains a bug. A straightforward andnon-clever way to avoid this is to introduce an explicit SK_LastSquareentry in the enum when adding the first subclass(es). For example, we couldrewrite the example at the beginning of Concrete Bases and DeeperHierarchies as:

  1. enum ShapeKind {
  2. SK_Square,
  3. + SK_SpecialSquare,
  4. + SK_OtherSpecialSquare,
  5. + SK_LastSquare,
  6. SK_Circle
  7. }
  8. ...
  9. // Square::classof()
  10. - static bool classof(const Shape *S) {
  11. - return S->getKind() == SK_Square;
  12. - }
  13. + static bool classof(const Shape *S) {
  14. + return S->getKind() >= SK_Square &&
  15. + S->getKind() <= SK_LastSquare;
  16. + }

Then, adding new subclasses is easy:

  1. enum ShapeKind {
  2. SK_Square,
  3. SK_SpecialSquare,
  4. SK_OtherSpecialSquare,
  5. + SK_SomewhatSpecialSquare,
  6. SK_LastSquare,
  7. SK_Circle
  8. }

Notice that Square::classof does not need to be changed.

The Contract of classof

To be more precise, let classof be inside a class C. Then thecontract for classof is “return true if the dynamic type of theargument is-a C”. As long as your implementation fulfills thiscontract, you can tweak and optimize it as much as you want.

For example, LLVM-style RTTI can work fine in the presence ofmultiple-inheritance by defining an appropriate classof.An example of this in practice isDecl vs.DeclContextinside Clang.The Decl hierarchy is done very similarly to the example setupdemonstrated in this tutorial.The key part is how to then incorporate DeclContext: all that is neededis in bool DeclContext::classof(const Decl *), which asks the question“Given a Decl, how can I determine if it is-a DeclContext?”.It answers this with a simple switch over the set of Decl “kinds”, andreturning true for ones that are known to be DeclContext’s.

Rules of Thumb

  • The Kind enum should have one entry per concrete class, orderedaccording to a preorder traversal of the inheritance tree.
  • The argument to classof should be a const Base *, where Baseis some ancestor in the inheritance hierarchy. The argument shouldnever be a derived class or the class itself: the template machineryfor isa<> already handles this case and optimizes it.
  • For each class in the hierarchy that has no children, implement aclassof that checks only against its Kind.
  • For each class in the hierarchy that has children, implement aclassof that checks a range of the first child’s Kind and thelast child’s Kind.