blob: 4c96c95a76f8123b2b314cbb9ea9a07820de57e8 [file] [log] [blame]
Sean Silva36be1ae2012-10-05 03:32:01 +00001.. _how-to-set-up-llvm-style-rtti:
2
3======================================================
4How to set up LLVM-style RTTI for your class hierarchy
5======================================================
6
7.. sectionauthor:: Sean Silva <silvas@purdue.edu>
8
9.. contents::
10
11Background
12==========
13
14LLVM avoids using C++'s built in RTTI. Instead, it pervasively uses its
15own hand-rolled form of RTTI which is much more efficient and flexible,
16although it requires a bit more work from you as a class author.
17
18A description of how to use LLVM-style RTTI from a client's perspective is
19given in the `Programmer's Manual <ProgrammersManual.html#isa>`_. This
20document, in contrast, discusses the steps you need to take as a class
21hierarchy author to make LLVM-style RTTI available to your clients.
22
23Before diving in, make sure that you are familiar with the Object Oriented
24Programming concept of "`is-a`_".
25
26.. _is-a: http://en.wikipedia.org/wiki/Is-a
27
28Basic Setup
29===========
30
31This section describes how to set up the most basic form of LLVM-style RTTI
32(which is sufficient for 99.9% of the cases). We will set up LLVM-style
33RTTI for this class hierarchy:
34
35.. code-block:: c++
36
37 class Shape {
38 public:
Dmitri Gribenko07d1c212012-10-05 20:52:13 +000039 Shape() {}
Sean Silva36be1ae2012-10-05 03:32:01 +000040 virtual double computeArea() = 0;
41 };
42
43 class Square : public Shape {
44 double SideLength;
45 public:
46 Square(double S) : SideLength(S) {}
47 double computeArea() /* override */;
48 };
49
50 class Circle : public Shape {
51 double Radius;
52 public:
53 Circle(double R) : Radius(R) {}
54 double computeArea() /* override */;
55 };
56
57The most basic working setup for LLVM-style RTTI requires the following
58steps:
59
60#. In the header where you declare ``Shape``, you will want to ``#include
61 "llvm/Support/Casting.h"``, which declares LLVM's RTTI templates. That
62 way your clients don't even have to think about it.
63
64 .. code-block:: c++
65
66 #include "llvm/Support/Casting.h"
67
68
69#. In the base class, introduce an enum which discriminates all of the
70 different classes in the hierarchy, and stash the enum value somewhere in
71 the base class.
72
73 Here is the code after introducing this change:
74
75 .. code-block:: c++
76
77 class Shape {
78 public:
79 + /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
80 + enum ShapeKind {
81 + SquareKind,
82 + CircleKind
83 + };
84 +private:
85 + const ShapeKind Kind;
86 +public:
87 + ShapeKind getKind() const { return Kind; }
88 +
Dmitri Gribenko07d1c212012-10-05 20:52:13 +000089 Shape() {}
Sean Silva36be1ae2012-10-05 03:32:01 +000090 virtual double computeArea() = 0;
91 };
92
93 You will usually want to keep the ``Kind`` member encapsulated and
94 private, but let the enum ``ShapeKind`` be public along with providing a
95 ``getKind()`` method. This is convenient for clients so that they can do
96 a ``switch`` over the enum.
97
98 A common naming convention is that these enums are "kind"s, to avoid
99 ambiguity with the words "type" or "class" which have overloaded meanings
100 in many contexts within LLVM. Sometimes there will be a natural name for
101 it, like "opcode". Don't bikeshed over this; when in doubt use ``Kind``.
102
103 You might wonder why the ``Kind`` enum doesn't have an entry for
104 ``Shape``. The reason for this is that since ``Shape`` is abstract
105 (``computeArea() = 0;``), you will never actually have non-derived
106 instances of exactly that class (only subclasses). See `Concrete Bases
107 and Deeper Hierarchies`_ for information on how to deal with
108 non-abstract bases. It's worth mentioning here that unlike
109 ``dynamic_cast<>``, LLVM-style RTTI can be used (and is often used) for
110 classes that don't have v-tables.
111
112#. Next, you need to make sure that the ``Kind`` gets initialized to the
113 value corresponding to the dynamic type of the class. Typically, you will
114 want to have it be an argument to the constructor of the base class, and
115 then pass in the respective ``XXXKind`` from subclass constructors.
116
117 Here is the code after that change:
118
119 .. code-block:: c++
120
121 class Shape {
122 public:
123 /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
124 enum ShapeKind {
125 SquareKind,
126 CircleKind
127 };
128 private:
129 const ShapeKind Kind;
130 public:
131 ShapeKind getKind() const { return Kind; }
132
Dmitri Gribenko07d1c212012-10-05 20:52:13 +0000133 - Shape() {}
134 + Shape(ShapeKind K) : Kind(K) {}
Sean Silva36be1ae2012-10-05 03:32:01 +0000135 virtual double computeArea() = 0;
136 };
137
138 class Square : public Shape {
139 double SideLength;
140 public:
141 - Square(double S) : SideLength(S) {}
142 + Square(double S) : Shape(SquareKind), SideLength(S) {}
143 double computeArea() /* override */;
144 };
145
146 class Circle : public Shape {
147 double Radius;
148 public:
149 - Circle(double R) : Radius(R) {}
150 + Circle(double R) : Shape(CircleKind), Radius(R) {}
151 double computeArea() /* override */;
152 };
153
154#. Finally, you need to inform LLVM's RTTI templates how to dynamically
155 determine the type of a class (i.e. whether the ``isa<>``/``dyn_cast<>``
156 should succeed). The default "99.9% of use cases" way to accomplish this
157 is through a small static member function ``classof``. In order to have
158 proper context for an explanation, we will display this code first, and
159 then below describe each part:
160
161 .. code-block:: c++
162
163 class Shape {
164 public:
165 /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
166 enum ShapeKind {
167 SquareKind,
168 CircleKind
169 };
170 private:
171 const ShapeKind Kind;
172 public:
173 ShapeKind getKind() const { return Kind; }
174
Dmitri Gribenko07d1c212012-10-05 20:52:13 +0000175 Shape(ShapeKind K) : Kind(K) {}
Sean Silva36be1ae2012-10-05 03:32:01 +0000176 virtual double computeArea() = 0;
Sean Silva36be1ae2012-10-05 03:32:01 +0000177 };
178
179 class Square : public Shape {
180 double SideLength;
181 public:
182 Square(double S) : Shape(SquareKind), SideLength(S) {}
183 double computeArea() /* override */;
184 +
Sean Silva36be1ae2012-10-05 03:32:01 +0000185 + static bool classof(const Shape *S) {
186 + return S->getKind() == SquareKind;
187 + }
188 };
189
190 class Circle : public Shape {
191 double Radius;
192 public:
193 Circle(double R) : Shape(CircleKind), Radius(R) {}
194 double computeArea() /* override */;
195 +
Sean Silva36be1ae2012-10-05 03:32:01 +0000196 + static bool classof(const Shape *S) {
197 + return S->getKind() == CircleKind;
198 + }
199 };
200
Sean Silva8a6538c2012-10-11 23:30:41 +0000201 The job of ``classof`` is to dynamically determine whether an object of
202 a base class is in fact of a particular derived class. The argument to
203 ``classof`` should always be an *ancestor* class because the
204 implementation has logic to allow and optimize away
205 upcasts/up-``isa<>``'s automatically. It is as though every class
206 ``Foo`` automatically has a ``classof`` like:
Sean Silva36be1ae2012-10-05 03:32:01 +0000207
Sean Silva8a6538c2012-10-11 23:30:41 +0000208 .. code-block:: c++
Sean Silva36be1ae2012-10-05 03:32:01 +0000209
Sean Silva8a6538c2012-10-11 23:30:41 +0000210 class Foo {
211 [...]
212 static bool classof(const Foo *) { return true; }
213 [...]
214 };
Sean Silva36be1ae2012-10-05 03:32:01 +0000215
Sean Silva8a6538c2012-10-11 23:30:41 +0000216 In order to downcast a type ``Base`` to a type ``Derived``, there needs
217 to be a ``classof`` in ``Derived`` which will accept an object of type
218 ``Base``.
219
220 To be concrete, in the following code:
221
222 .. code-block:: c++
223
224 Shape *S = ...;
225 if (isa<Circle>(S)) {
226 /* do something ... */
227 }
228
229 The code of ``isa<>`` will eventually boil down---after template
230 instantiation and some other machinery---to a check roughly like
231 ``Circle::classof(S)``. For more information, see
232 :ref:`classof-contract`.
Sean Silva36be1ae2012-10-05 03:32:01 +0000233
234Although for this small example setting up LLVM-style RTTI seems like a lot
235of "boilerplate", if your classes are doing anything interesting then this
236will end up being a tiny fraction of the code.
237
238Concrete Bases and Deeper Hierarchies
239=====================================
240
241For concrete bases (i.e. non-abstract interior nodes of the inheritance
242tree), the ``Kind`` check inside ``classof`` needs to be a bit more
243complicated. Say that ``SpecialSquare`` and ``OtherSpecialSquare`` derive
244from ``Square``, and so ``ShapeKind`` becomes:
245
246.. code-block:: c++
247
248 enum ShapeKind {
249 SquareKind,
250 + SpecialSquareKind,
251 + OtherSpecialSquareKind,
252 CircleKind
253 }
254
255Then in ``Square``, we would need to modify the ``classof`` like so:
256
257.. code-block:: c++
258
Sean Silva36be1ae2012-10-05 03:32:01 +0000259 - static bool classof(const Shape *S) {
260 - return S->getKind() == SquareKind;
261 - }
262 + static bool classof(const Shape *S) {
263 + return S->getKind() >= SquareKind &&
264 + S->getKind() <= OtherSpecialSquareKind;
265 + }
266
267The reason that we need to test a range like this instead of just equality
268is that both ``SpecialSquare`` and ``OtherSpecialSquare`` "is-a"
269``Square``, and so ``classof`` needs to return ``true`` for them.
270
271This approach can be made to scale to arbitrarily deep hierarchies. The
272trick is that you arrange the enum values so that they correspond to a
273preorder traversal of the class hierarchy tree. With that arrangement, all
274subclass tests can be done with two comparisons as shown above. If you just
275list the class hierarchy like a list of bullet points, you'll get the
276ordering right::
277
278 | Shape
279 | Square
280 | SpecialSquare
281 | OtherSpecialSquare
282 | Circle
283
Sean Silva8a6538c2012-10-11 23:30:41 +0000284.. _classof-contract:
285
286The Contract of ``classof``
287---------------------------
288
289To be more precise, let ``classof`` be inside a class ``C``. Then the
290contract for ``classof`` is "return ``true`` if the dynamic type of the
291argument is-a ``C``". As long as your implementation fulfills this
292contract, you can tweak and optimize it as much as you want.
293
Sean Silva36be1ae2012-10-05 03:32:01 +0000294.. TODO::
295
296 Touch on some of the more advanced features, like ``isa_impl`` and
297 ``simplify_type``. However, those two need reference documentation in
298 the form of doxygen comments as well. We need the doxygen so that we can
299 say "for full details, see http://llvm.org/doxygen/..."