HowToSetUpLLVMStyleRTTI.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. ======================================================
  2. How to set up LLVM-style RTTI for your class hierarchy
  3. ======================================================
  4. .. contents::
  5. Background
  6. ==========
  7. LLVM avoids using C++'s built in RTTI. Instead, it pervasively uses its
  8. own hand-rolled form of RTTI which is much more efficient and flexible,
  9. although it requires a bit more work from you as a class author.
  10. A description of how to use LLVM-style RTTI from a client's perspective is
  11. given in the `Programmer's Manual <ProgrammersManual.html#isa>`_. This
  12. document, in contrast, discusses the steps you need to take as a class
  13. hierarchy author to make LLVM-style RTTI available to your clients.
  14. Before diving in, make sure that you are familiar with the Object Oriented
  15. Programming concept of "`is-a`_".
  16. .. _is-a: http://en.wikipedia.org/wiki/Is-a
  17. Basic Setup
  18. ===========
  19. This section describes how to set up the most basic form of LLVM-style RTTI
  20. (which is sufficient for 99.9% of the cases). We will set up LLVM-style
  21. RTTI for this class hierarchy:
  22. .. code-block:: c++
  23. class Shape {
  24. public:
  25. Shape() {}
  26. virtual double computeArea() = 0;
  27. };
  28. class Square : public Shape {
  29. double SideLength;
  30. public:
  31. Square(double S) : SideLength(S) {}
  32. double computeArea() override;
  33. };
  34. class Circle : public Shape {
  35. double Radius;
  36. public:
  37. Circle(double R) : Radius(R) {}
  38. double computeArea() override;
  39. };
  40. The most basic working setup for LLVM-style RTTI requires the following
  41. steps:
  42. #. In the header where you declare ``Shape``, you will want to ``#include
  43. "llvm/Support/Casting.h"``, which declares LLVM's RTTI templates. That
  44. way your clients don't even have to think about it.
  45. .. code-block:: c++
  46. #include "llvm/Support/Casting.h"
  47. #. In the base class, introduce an enum which discriminates all of the
  48. different concrete classes in the hierarchy, and stash the enum value
  49. somewhere in the base class.
  50. Here is the code after introducing this change:
  51. .. code-block:: c++
  52. class Shape {
  53. public:
  54. + /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
  55. + enum ShapeKind {
  56. + SK_Square,
  57. + SK_Circle
  58. + };
  59. +private:
  60. + const ShapeKind Kind;
  61. +public:
  62. + ShapeKind getKind() const { return Kind; }
  63. +
  64. Shape() {}
  65. virtual double computeArea() = 0;
  66. };
  67. You will usually want to keep the ``Kind`` member encapsulated and
  68. private, but let the enum ``ShapeKind`` be public along with providing a
  69. ``getKind()`` method. This is convenient for clients so that they can do
  70. a ``switch`` over the enum.
  71. A common naming convention is that these enums are "kind"s, to avoid
  72. ambiguity with the words "type" or "class" which have overloaded meanings
  73. in many contexts within LLVM. Sometimes there will be a natural name for
  74. it, like "opcode". Don't bikeshed over this; when in doubt use ``Kind``.
  75. You might wonder why the ``Kind`` enum doesn't have an entry for
  76. ``Shape``. The reason for this is that since ``Shape`` is abstract
  77. (``computeArea() = 0;``), you will never actually have non-derived
  78. instances of exactly that class (only subclasses). See `Concrete Bases
  79. and Deeper Hierarchies`_ for information on how to deal with
  80. non-abstract bases. It's worth mentioning here that unlike
  81. ``dynamic_cast<>``, LLVM-style RTTI can be used (and is often used) for
  82. classes that don't have v-tables.
  83. #. Next, you need to make sure that the ``Kind`` gets initialized to the
  84. value corresponding to the dynamic type of the class. Typically, you will
  85. want to have it be an argument to the constructor of the base class, and
  86. then pass in the respective ``XXXKind`` from subclass constructors.
  87. Here is the code after that change:
  88. .. code-block:: c++
  89. class Shape {
  90. public:
  91. /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
  92. enum ShapeKind {
  93. SK_Square,
  94. SK_Circle
  95. };
  96. private:
  97. const ShapeKind Kind;
  98. public:
  99. ShapeKind getKind() const { return Kind; }
  100. - Shape() {}
  101. + Shape(ShapeKind K) : Kind(K) {}
  102. virtual double computeArea() = 0;
  103. };
  104. class Square : public Shape {
  105. double SideLength;
  106. public:
  107. - Square(double S) : SideLength(S) {}
  108. + Square(double S) : Shape(SK_Square), SideLength(S) {}
  109. double computeArea() override;
  110. };
  111. class Circle : public Shape {
  112. double Radius;
  113. public:
  114. - Circle(double R) : Radius(R) {}
  115. + Circle(double R) : Shape(SK_Circle), Radius(R) {}
  116. double computeArea() override;
  117. };
  118. #. Finally, you need to inform LLVM's RTTI templates how to dynamically
  119. determine the type of a class (i.e. whether the ``isa<>``/``dyn_cast<>``
  120. should succeed). The default "99.9% of use cases" way to accomplish this
  121. is through a small static member function ``classof``. In order to have
  122. proper context for an explanation, we will display this code first, and
  123. then below describe each part:
  124. .. code-block:: c++
  125. class Shape {
  126. public:
  127. /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
  128. enum ShapeKind {
  129. SK_Square,
  130. SK_Circle
  131. };
  132. private:
  133. const ShapeKind Kind;
  134. public:
  135. ShapeKind getKind() const { return Kind; }
  136. Shape(ShapeKind K) : Kind(K) {}
  137. virtual double computeArea() = 0;
  138. };
  139. class Square : public Shape {
  140. double SideLength;
  141. public:
  142. Square(double S) : Shape(SK_Square), SideLength(S) {}
  143. double computeArea() override;
  144. +
  145. + static bool classof(const Shape *S) {
  146. + return S->getKind() == SK_Square;
  147. + }
  148. };
  149. class Circle : public Shape {
  150. double Radius;
  151. public:
  152. Circle(double R) : Shape(SK_Circle), Radius(R) {}
  153. double computeArea() override;
  154. +
  155. + static bool classof(const Shape *S) {
  156. + return S->getKind() == SK_Circle;
  157. + }
  158. };
  159. The job of ``classof`` is to dynamically determine whether an object of
  160. a base class is in fact of a particular derived class. In order to
  161. downcast a type ``Base`` to a type ``Derived``, there needs to be a
  162. ``classof`` in ``Derived`` which will accept an object of type ``Base``.
  163. To be concrete, consider the following code:
  164. .. code-block:: c++
  165. Shape *S = ...;
  166. if (isa<Circle>(S)) {
  167. /* do something ... */
  168. }
  169. The code of the ``isa<>`` test in this code will eventually boil
  170. down---after template instantiation and some other machinery---to a
  171. check roughly like ``Circle::classof(S)``. For more information, see
  172. :ref:`classof-contract`.
  173. The argument to ``classof`` should always be an *ancestor* class because
  174. the implementation has logic to allow and optimize away
  175. upcasts/up-``isa<>``'s automatically. It is as though every class
  176. ``Foo`` automatically has a ``classof`` like:
  177. .. code-block:: c++
  178. class Foo {
  179. [...]
  180. template <class T>
  181. static bool classof(const T *,
  182. ::std::enable_if<
  183. ::std::is_base_of<Foo, T>::value
  184. >::type* = 0) { return true; }
  185. [...]
  186. };
  187. Note that this is the reason that we did not need to introduce a
  188. ``classof`` into ``Shape``: all relevant classes derive from ``Shape``,
  189. and ``Shape`` itself is abstract (has no entry in the ``Kind`` enum),
  190. so this notional inferred ``classof`` is all we need. See `Concrete
  191. Bases and Deeper Hierarchies`_ for more information about how to extend
  192. this example to more general hierarchies.
  193. Although for this small example setting up LLVM-style RTTI seems like a lot
  194. of "boilerplate", if your classes are doing anything interesting then this
  195. will end up being a tiny fraction of the code.
  196. Concrete Bases and Deeper Hierarchies
  197. =====================================
  198. For concrete bases (i.e. non-abstract interior nodes of the inheritance
  199. tree), the ``Kind`` check inside ``classof`` needs to be a bit more
  200. complicated. The situation differs from the example above in that
  201. * Since the class is concrete, it must itself have an entry in the ``Kind``
  202. enum because it is possible to have objects with this class as a dynamic
  203. type.
  204. * Since the class has children, the check inside ``classof`` must take them
  205. into account.
  206. Say that ``SpecialSquare`` and ``OtherSpecialSquare`` derive
  207. from ``Square``, and so ``ShapeKind`` becomes:
  208. .. code-block:: c++
  209. enum ShapeKind {
  210. SK_Square,
  211. + SK_SpecialSquare,
  212. + SK_OtherSpecialSquare,
  213. SK_Circle
  214. }
  215. Then in ``Square``, we would need to modify the ``classof`` like so:
  216. .. code-block:: c++
  217. - static bool classof(const Shape *S) {
  218. - return S->getKind() == SK_Square;
  219. - }
  220. + static bool classof(const Shape *S) {
  221. + return S->getKind() >= SK_Square &&
  222. + S->getKind() <= SK_OtherSpecialSquare;
  223. + }
  224. The reason that we need to test a range like this instead of just equality
  225. is that both ``SpecialSquare`` and ``OtherSpecialSquare`` "is-a"
  226. ``Square``, and so ``classof`` needs to return ``true`` for them.
  227. This approach can be made to scale to arbitrarily deep hierarchies. The
  228. trick is that you arrange the enum values so that they correspond to a
  229. preorder traversal of the class hierarchy tree. With that arrangement, all
  230. subclass tests can be done with two comparisons as shown above. If you just
  231. list the class hierarchy like a list of bullet points, you'll get the
  232. ordering right::
  233. | Shape
  234. | Square
  235. | SpecialSquare
  236. | OtherSpecialSquare
  237. | Circle
  238. A Bug to be Aware Of
  239. --------------------
  240. The example just given opens the door to bugs where the ``classof``\s are
  241. not updated to match the ``Kind`` enum when adding (or removing) classes to
  242. (from) the hierarchy.
  243. Continuing the example above, suppose we add a ``SomewhatSpecialSquare`` as
  244. a subclass of ``Square``, and update the ``ShapeKind`` enum like so:
  245. .. code-block:: c++
  246. enum ShapeKind {
  247. SK_Square,
  248. SK_SpecialSquare,
  249. SK_OtherSpecialSquare,
  250. + SK_SomewhatSpecialSquare,
  251. SK_Circle
  252. }
  253. Now, suppose that we forget to update ``Square::classof()``, so it still
  254. looks like:
  255. .. code-block:: c++
  256. static bool classof(const Shape *S) {
  257. // BUG: Returns false when S->getKind() == SK_SomewhatSpecialSquare,
  258. // even though SomewhatSpecialSquare "is a" Square.
  259. return S->getKind() >= SK_Square &&
  260. S->getKind() <= SK_OtherSpecialSquare;
  261. }
  262. As the comment indicates, this code contains a bug. A straightforward and
  263. non-clever way to avoid this is to introduce an explicit ``SK_LastSquare``
  264. entry in the enum when adding the first subclass(es). For example, we could
  265. rewrite the example at the beginning of `Concrete Bases and Deeper
  266. Hierarchies`_ as:
  267. .. code-block:: c++
  268. enum ShapeKind {
  269. SK_Square,
  270. + SK_SpecialSquare,
  271. + SK_OtherSpecialSquare,
  272. + SK_LastSquare,
  273. SK_Circle
  274. }
  275. ...
  276. // Square::classof()
  277. - static bool classof(const Shape *S) {
  278. - return S->getKind() == SK_Square;
  279. - }
  280. + static bool classof(const Shape *S) {
  281. + return S->getKind() >= SK_Square &&
  282. + S->getKind() <= SK_LastSquare;
  283. + }
  284. Then, adding new subclasses is easy:
  285. .. code-block:: c++
  286. enum ShapeKind {
  287. SK_Square,
  288. SK_SpecialSquare,
  289. SK_OtherSpecialSquare,
  290. + SK_SomewhatSpecialSquare,
  291. SK_LastSquare,
  292. SK_Circle
  293. }
  294. Notice that ``Square::classof`` does not need to be changed.
  295. .. _classof-contract:
  296. The Contract of ``classof``
  297. ---------------------------
  298. To be more precise, let ``classof`` be inside a class ``C``. Then the
  299. contract for ``classof`` is "return ``true`` if the dynamic type of the
  300. argument is-a ``C``". As long as your implementation fulfills this
  301. contract, you can tweak and optimize it as much as you want.
  302. For example, LLVM-style RTTI can work fine in the presence of
  303. multiple-inheritance by defining an appropriate ``classof``.
  304. An example of this in practice is
  305. `Decl <http://clang.llvm.org/doxygen/classclang_1_1Decl.html>`_ vs.
  306. `DeclContext <http://clang.llvm.org/doxygen/classclang_1_1DeclContext.html>`_
  307. inside Clang.
  308. The ``Decl`` hierarchy is done very similarly to the example setup
  309. demonstrated in this tutorial.
  310. The key part is how to then incorporate ``DeclContext``: all that is needed
  311. is in ``bool DeclContext::classof(const Decl *)``, which asks the question
  312. "Given a ``Decl``, how can I determine if it is-a ``DeclContext``?".
  313. It answers this with a simple switch over the set of ``Decl`` "kinds", and
  314. returning true for ones that are known to be ``DeclContext``'s.
  315. .. TODO::
  316. Touch on some of the more advanced features, like ``isa_impl`` and
  317. ``simplify_type``. However, those two need reference documentation in
  318. the form of doxygen comments as well. We need the doxygen so that we can
  319. say "for full details, see http://llvm.org/doxygen/..."
  320. Rules of Thumb
  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``.