docs: Update HowToSetUpLLVMStyleRTTI.
[oota-llvm.git] / docs / HowToSetUpLLVMStyleRTTI.rst
1 .. _how-to-set-up-llvm-style-rtti:
2
3 ======================================================
4 How to set up LLVM-style RTTI for your class hierarchy
5 ======================================================
6
7 .. sectionauthor:: Sean Silva <silvas@purdue.edu>
8
9 .. contents::
10
11 Background
12 ==========
13
14 LLVM avoids using C++'s built in RTTI. Instead, it  pervasively uses its
15 own hand-rolled form of RTTI which is much more efficient and flexible,
16 although it requires a bit more work from you as a class author.
17
18 A description of how to use LLVM-style RTTI from a client's perspective is
19 given in the `Programmer's Manual <ProgrammersManual.html#isa>`_. This
20 document, in contrast, discusses the steps you need to take as a class
21 hierarchy author to make LLVM-style RTTI available to your clients.
22
23 Before diving in, make sure that you are familiar with the Object Oriented
24 Programming concept of "`is-a`_".
25
26 .. _is-a: http://en.wikipedia.org/wiki/Is-a
27
28 Basic Setup
29 ===========
30
31 This 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
33 RTTI for this class hierarchy:
34
35 .. code-block:: c++
36
37    class Shape {
38    public:
39      Shape() {}
40      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
57 The most basic working setup for LLVM-style RTTI requires the following
58 steps:
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       +
89          Shape() {}
90          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
133       -  Shape() {}
134       +  Shape(ShapeKind K) : Kind(K) {}
135          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
175          Shape(ShapeKind K) : Kind(K) {}
176          virtual double computeArea() = 0;
177        };
178
179        class Square : public Shape {
180          double SideLength;
181        public:
182          Square(double S) : Shape(SquareKind), SideLength(S) {}
183          double computeArea() /* override */;
184       +
185       +  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       +
196       +  static bool classof(const Shape *S) {
197       +    return S->getKind() == CircleKind;
198       +  }
199        };
200
201    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:
207
208    .. code-block:: c++
209
210       class Foo {
211         [...]
212         static bool classof(const Foo *) { return true; }
213         [...]
214       };
215
216    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`.
233
234 Although for this small example setting up LLVM-style RTTI seems like a lot
235 of "boilerplate", if your classes are doing anything interesting then this
236 will end up being a tiny fraction of the code.
237
238 Concrete Bases and Deeper Hierarchies
239 =====================================
240
241 For concrete bases (i.e. non-abstract interior nodes of the inheritance
242 tree), the ``Kind`` check inside ``classof`` needs to be a bit more
243 complicated. Say that ``SpecialSquare`` and ``OtherSpecialSquare`` derive
244 from ``Square``, and so ``ShapeKind`` becomes:
245
246 .. code-block:: c++
247
248     enum ShapeKind {
249       SquareKind,
250    +  SpecialSquareKind,
251    +  OtherSpecialSquareKind,
252       CircleKind
253     }
254
255 Then in ``Square``, we would need to modify the ``classof`` like so:
256
257 .. code-block:: c++
258
259    -  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
267 The reason that we need to test a range like this instead of just equality
268 is that both ``SpecialSquare`` and ``OtherSpecialSquare`` "is-a"
269 ``Square``, and so ``classof`` needs to return ``true`` for them.
270
271 This approach can be made to scale to arbitrarily deep hierarchies. The
272 trick is that you arrange the enum values so that they correspond to a
273 preorder traversal of the class hierarchy tree. With that arrangement, all
274 subclass tests can be done with two comparisons as shown above. If you just
275 list the class hierarchy like a list of bullet points, you'll get the
276 ordering right::
277
278    | Shape
279      | Square
280        | SpecialSquare
281        | OtherSpecialSquare
282      | Circle
283
284 .. _classof-contract:
285
286 The Contract of ``classof``
287 ---------------------------
288
289 To be more precise, let ``classof`` be inside a class ``C``.  Then the
290 contract for ``classof`` is "return ``true`` if the dynamic type of the
291 argument is-a ``C``".  As long as your implementation fulfills this
292 contract, you can tweak and optimize it as much as you want.
293
294 .. 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/..."