[LLVMdev] Closed virtual dispatch (was: Introduce a section to the programmers manual about type hierarchies, polymorphism, and virtual dispatch.)

David Chisnall
Wed, 28 Jan 2015 09:05:29 -0000

On 27 Jan 2015, at 17:13, Philip Reames <listmail at philipreames.com>
wrote:
>
> Given we have a large number of compiler authors and contributors to the
C++ language spec, it seems really odd to me that we can't solve this
problem in a more elegant way. The tagged-dispatch as a sealed world replacement
for virtual dispatch is one that comes up on a pretty regular basis.  Might it
be time to figure out how to generalize this and propose either a clang
extension or a language mechanism for some future version of C++?

One of the motivations for being able to mark a class as final in Java was to
allow compilers to perform optimisations on the assumption that there would
never be any subclasses (I don't believe any modern JVMs take advantage of
this as it's mostly only useful to AoT compilers, but maybe ART does).  For
this idiom, the guarantee that you want is something slightly broader than
final, it's that, at some known point, all subclasses will be visible to the
optimiser.  This is a bit difficult to do in the
files-are-approximately-compilation-units model, but a bit easier with LTO
(though re-inferring enough information to do devirtualisation at this level is
a bit tricky).

C++, at the language level, unfortunately has no notion of a shared library.
This is very problematic in some places in C++11 (the semantics for when
constructors and destructors are run for thread_local objects in the presence of
multiple threads and library loading and unloading are very poorly defined) and
also makes it difficult to have a package-final or similar to indicate that no
subclasses outside of this library are permitted.

Or, if the goal is to put a little bit more burden on the programmer but give
greater flexibility in implementations, I believe that one of the people in this
thread is the head of the reflection subcommittee in WG21, so may already be
reviewing proposals that would make it easier to implement generically...

David