www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 24332] New: Improve downcast to final classes

https://issues.dlang.org/show_bug.cgi?id=24332

          Issue ID: 24332
           Summary: Improve downcast to final classes
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: bugzilla digitalmars.com

deadalnix writes:

class A {}
final class B : A {}

auto foo(A a) {
    return cast(B) a;
}

This generates a call into the runtime, making things completely opaque to the
optimizer. The algorithm used by the runtime is linear. But there is a dumb
constant time solution. because B is final, a is either an instance of B, or it
is not (as in, it cannot be an instance of a subclass of B). Therefore, we
expect the codegen to look like the following instead:

auto foo(A a) {
    return typeid(a) is typeid(B) ? a : null;
}

This obviously won't compile but you get the idea. Not only this is constant
time, but very simple too, and visible to the optimizer, which means the check
can be folded by the opitimizer after other transforms, for instance inlining.

https://forum.dlang.org/post/hteuczyclxajakrisxjd forum.dlang.org

Here we go: https://github.com/snazzy-d/sdc/blob/master/test/llvm/downcast.d

Except the interface part.

--
Jan 11