blob: aa1ad84afee352fb890feff58f34321b9eeadfd3 [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
Sean Silva36be1ae2012-10-05 03:32:01 +000068#. In the base class, introduce an enum which discriminates all of the
Sean Silva40573992012-10-11 23:30:52 +000069 different concrete classes in the hierarchy, and stash the enum value
70 somewhere in the base class.
Sean Silva36be1ae2012-10-05 03:32:01 +000071
72 Here is the code after introducing this change:
73
74 .. code-block:: c++
75
76 class Shape {
77 public:
78 + /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
79 + enum ShapeKind {
Sean Silva6df933e2012-10-12 01:55:51 +000080 + SK_Square,
81 + SK_Circle
Sean Silva36be1ae2012-10-05 03:32:01 +000082 + };
83 +private:
84 + const ShapeKind Kind;
85 +public:
86 + ShapeKind getKind() const { return Kind; }
87 +
Dmitri Gribenko07d1c212012-10-05 20:52:13 +000088 Shape() {}
Sean Silva36be1ae2012-10-05 03:32:01 +000089 virtual double computeArea() = 0;
90 };
91
92 You will usually want to keep the ``Kind`` member encapsulated and
93 private, but let the enum ``ShapeKind`` be public along with providing a
94 ``getKind()`` method. This is convenient for clients so that they can do
95 a ``switch`` over the enum.
96
97 A common naming convention is that these enums are "kind"s, to avoid
98 ambiguity with the words "type" or "class" which have overloaded meanings
99 in many contexts within LLVM. Sometimes there will be a natural name for
100 it, like "opcode". Don't bikeshed over this; when in doubt use ``Kind``.
101
102 You might wonder why the ``Kind`` enum doesn't have an entry for
103 ``Shape``. The reason for this is that since ``Shape`` is abstract
104 (``computeArea() = 0;``), you will never actually have non-derived
Sean Silva40573992012-10-11 23:30:52 +0000105 instances of exactly that class (only subclasses). See `Concrete Bases
Sean Silva36be1ae2012-10-05 03:32:01 +0000106 and Deeper Hierarchies`_ for information on how to deal with
107 non-abstract bases. It's worth mentioning here that unlike
108 ``dynamic_cast<>``, LLVM-style RTTI can be used (and is often used) for
109 classes that don't have v-tables.
110
111#. Next, you need to make sure that the ``Kind`` gets initialized to the
112 value corresponding to the dynamic type of the class. Typically, you will
113 want to have it be an argument to the constructor of the base class, and
114 then pass in the respective ``XXXKind`` from subclass constructors.
115
116 Here is the code after that change:
117
118 .. code-block:: c++
119
120 class Shape {
121 public:
122 /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
123 enum ShapeKind {
Sean Silva6df933e2012-10-12 01:55:51 +0000124 SK_Square,
125 SK_Circle
Sean Silva36be1ae2012-10-05 03:32:01 +0000126 };
127 private:
128 const ShapeKind Kind;
129 public:
130 ShapeKind getKind() const { return Kind; }
131
Dmitri Gribenko07d1c212012-10-05 20:52:13 +0000132 - Shape() {}
133 + Shape(ShapeKind K) : Kind(K) {}
Sean Silva36be1ae2012-10-05 03:32:01 +0000134 virtual double computeArea() = 0;
135 };
136
137 class Square : public Shape {
138 double SideLength;
139 public:
140 - Square(double S) : SideLength(S) {}
Sean Silva6df933e2012-10-12 01:55:51 +0000141 + Square(double S) : Shape(SK_Square), SideLength(S) {}
Sean Silva36be1ae2012-10-05 03:32:01 +0000142 double computeArea() /* override */;
143 };
144
145 class Circle : public Shape {
146 double Radius;
147 public:
148 - Circle(double R) : Radius(R) {}
Sean Silva6df933e2012-10-12 01:55:51 +0000149 + Circle(double R) : Shape(SK_Circle), Radius(R) {}
Sean Silva36be1ae2012-10-05 03:32:01 +0000150 double computeArea() /* override */;
151 };
152
153#. Finally, you need to inform LLVM's RTTI templates how to dynamically
154 determine the type of a class (i.e. whether the ``isa<>``/``dyn_cast<>``
155 should succeed). The default "99.9% of use cases" way to accomplish this
156 is through a small static member function ``classof``. In order to have
157 proper context for an explanation, we will display this code first, and
158 then below describe each part:
159
160 .. code-block:: c++
161
162 class Shape {
163 public:
164 /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
165 enum ShapeKind {
Sean Silva6df933e2012-10-12 01:55:51 +0000166 SK_Square,
167 SK_Circle
Sean Silva36be1ae2012-10-05 03:32:01 +0000168 };
169 private:
170 const ShapeKind Kind;
171 public:
172 ShapeKind getKind() const { return Kind; }
173
Dmitri Gribenko07d1c212012-10-05 20:52:13 +0000174 Shape(ShapeKind K) : Kind(K) {}
Sean Silva36be1ae2012-10-05 03:32:01 +0000175 virtual double computeArea() = 0;
Sean Silva36be1ae2012-10-05 03:32:01 +0000176 };
177
178 class Square : public Shape {
179 double SideLength;
180 public:
Sean Silva6df933e2012-10-12 01:55:51 +0000181 Square(double S) : Shape(SK_Square), SideLength(S) {}
Sean Silva36be1ae2012-10-05 03:32:01 +0000182 double computeArea() /* override */;
183 +
Sean Silva36be1ae2012-10-05 03:32:01 +0000184 + static bool classof(const Shape *S) {
Sean Silva6df933e2012-10-12 01:55:51 +0000185 + return S->getKind() == SK_Square;
Sean Silva36be1ae2012-10-05 03:32:01 +0000186 + }
187 };
188
189 class Circle : public Shape {
190 double Radius;
191 public:
Sean Silva6df933e2012-10-12 01:55:51 +0000192 Circle(double R) : Shape(SK_Circle), Radius(R) {}
Sean Silva36be1ae2012-10-05 03:32:01 +0000193 double computeArea() /* override */;
194 +
Sean Silva36be1ae2012-10-05 03:32:01 +0000195 + static bool classof(const Shape *S) {
Sean Silva6df933e2012-10-12 01:55:51 +0000196 + return S->getKind() == SK_Circle;
Sean Silva36be1ae2012-10-05 03:32:01 +0000197 + }
198 };
199
Sean Silva8a6538c2012-10-11 23:30:41 +0000200 The job of ``classof`` is to dynamically determine whether an object of
Sean Silva40573992012-10-11 23:30:52 +0000201 a base class is in fact of a particular derived class. In order to
202 downcast a type ``Base`` to a type ``Derived``, there needs to be a
203 ``classof`` in ``Derived`` which will accept an object of type ``Base``.
Sean Silva36be1ae2012-10-05 03:32:01 +0000204
Sean Silva40573992012-10-11 23:30:52 +0000205 To be concrete, consider the following code:
Sean Silva8a6538c2012-10-11 23:30:41 +0000206
207 .. code-block:: c++
208
209 Shape *S = ...;
210 if (isa<Circle>(S)) {
211 /* do something ... */
212 }
213
Sean Silva40573992012-10-11 23:30:52 +0000214 The code of the ``isa<>`` test in this code will eventually boil
215 down---after template instantiation and some other machinery---to a
216 check roughly like ``Circle::classof(S)``. For more information, see
Sean Silva8a6538c2012-10-11 23:30:41 +0000217 :ref:`classof-contract`.
Sean Silva36be1ae2012-10-05 03:32:01 +0000218
Sean Silva40573992012-10-11 23:30:52 +0000219 The argument to ``classof`` should always be an *ancestor* class because
220 the implementation has logic to allow and optimize away
221 upcasts/up-``isa<>``'s automatically. It is as though every class
222 ``Foo`` automatically has a ``classof`` like:
223
224 .. code-block:: c++
225
226 class Foo {
227 [...]
228 template <class T>
229 static bool classof(const T *,
230 ::llvm::enable_if_c<
231 ::llvm::is_base_of<Foo, T>::value
232 >::type* = 0) { return true; }
233 [...]
234 };
235
236 Note that this is the reason that we did not need to introduce a
237 ``classof`` into ``Shape``: all relevant classes derive from ``Shape``,
238 and ``Shape`` itself is abstract (has no entry in the ``Kind`` enum),
239 so this notional inferred ``classof`` is all we need. See `Concrete
240 Bases and Deeper Hierarchies`_ for more information about how to extend
241 this example to more general hierarchies.
242
Sean Silva36be1ae2012-10-05 03:32:01 +0000243Although for this small example setting up LLVM-style RTTI seems like a lot
244of "boilerplate", if your classes are doing anything interesting then this
245will end up being a tiny fraction of the code.
246
247Concrete Bases and Deeper Hierarchies
248=====================================
249
250For concrete bases (i.e. non-abstract interior nodes of the inheritance
251tree), the ``Kind`` check inside ``classof`` needs to be a bit more
Sean Silva40573992012-10-11 23:30:52 +0000252complicated. The situation differs from the example above in that
253
254* Since the class is concrete, it must itself have an entry in the ``Kind``
255 enum because it is possible to have objects with this class as a dynamic
256 type.
257
258* Since the class has children, the check inside ``classof`` must take them
259 into account.
260
261Say that ``SpecialSquare`` and ``OtherSpecialSquare`` derive
Sean Silva36be1ae2012-10-05 03:32:01 +0000262from ``Square``, and so ``ShapeKind`` becomes:
263
264.. code-block:: c++
265
266 enum ShapeKind {
Sean Silva6df933e2012-10-12 01:55:51 +0000267 SK_Square,
268 + SK_SpecialSquare,
269 + SK_OtherSpecialSquare,
270 SK_Circle
Sean Silva36be1ae2012-10-05 03:32:01 +0000271 }
272
273Then in ``Square``, we would need to modify the ``classof`` like so:
274
275.. code-block:: c++
276
Sean Silva36be1ae2012-10-05 03:32:01 +0000277 - static bool classof(const Shape *S) {
Sean Silva6df933e2012-10-12 01:55:51 +0000278 - return S->getKind() == SK_Square;
Sean Silva36be1ae2012-10-05 03:32:01 +0000279 - }
280 + static bool classof(const Shape *S) {
Sean Silva6df933e2012-10-12 01:55:51 +0000281 + return S->getKind() >= SK_Square &&
282 + S->getKind() <= SK_OtherSpecialSquare;
Sean Silva36be1ae2012-10-05 03:32:01 +0000283 + }
284
285The reason that we need to test a range like this instead of just equality
286is that both ``SpecialSquare`` and ``OtherSpecialSquare`` "is-a"
287``Square``, and so ``classof`` needs to return ``true`` for them.
288
289This approach can be made to scale to arbitrarily deep hierarchies. The
290trick is that you arrange the enum values so that they correspond to a
291preorder traversal of the class hierarchy tree. With that arrangement, all
292subclass tests can be done with two comparisons as shown above. If you just
293list the class hierarchy like a list of bullet points, you'll get the
294ordering right::
295
296 | Shape
297 | Square
298 | SpecialSquare
299 | OtherSpecialSquare
300 | Circle
301
Sean Silva8a6538c2012-10-11 23:30:41 +0000302.. _classof-contract:
303
304The Contract of ``classof``
305---------------------------
306
307To be more precise, let ``classof`` be inside a class ``C``. Then the
308contract for ``classof`` is "return ``true`` if the dynamic type of the
309argument is-a ``C``". As long as your implementation fulfills this
310contract, you can tweak and optimize it as much as you want.
311
Sean Silva36be1ae2012-10-05 03:32:01 +0000312.. TODO::
313
314 Touch on some of the more advanced features, like ``isa_impl`` and
315 ``simplify_type``. However, those two need reference documentation in
316 the form of doxygen comments as well. We need the doxygen so that we can
317 say "for full details, see http://llvm.org/doxygen/..."
Sean Silva40573992012-10-11 23:30:52 +0000318
319Rules of Thumb
320==============
321
322#. The ``Kind`` enum should have one entry per concrete class, ordered
323 according to a preorder traversal of the inheritance tree.
324#. The argument to ``classof`` should be a ``const Base *``, where ``Base``
325 is some ancestor in the inheritance hierarchy. The argument should
326 *never* be a derived class or the class itself: the template machinery
327 for ``isa<>`` already handles this case and optimizes it.
328#. For each class in the hierarchy that has no children, implement a
329 ``classof`` that checks only against its ``Kind``.
330#. For each class in the hierarchy that has children, implement a
331 ``classof`` that checks a range of the first child's ``Kind`` and the
332 last child's ``Kind``.