Bug 63164 - unnecessary calls to __dynamic_cast
Summary: unnecessary calls to __dynamic_cast
Status: UNCONFIRMED
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 4.9.1
: P3 enhancement
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: missed-optimization
Depends on:
Blocks:
 
Reported: 2014-09-04 12:02 UTC by Avi Kivity
Modified: 2019-07-27 18:33 UTC (History)
8 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Avi Kivity 2014-09-04 12:02:12 UTC
The code

  struct A {
    virtual ~A() {}
  };

  struct B final : A {
    virtual ~B() {}
  };

  B* dc(A* a) {
    return dynamic_cast<B*>(a);
  }

compiles into the following assembly, which contains a call (jump) to __dynamic_cast:

0000000000000000 <dc(A*)>:
   0:	48 85 ff             	test   %rdi,%rdi
   3:	74 1b                	je     20 <dc(A*)+0x20>
   5:	31 c9                	xor    %ecx,%ecx
   7:	ba 00 00 00 00       	mov    $0x0,%edx
			8: R_X86_64_32	typeinfo for B
   c:	be 00 00 00 00       	mov    $0x0,%esi
			d: R_X86_64_32	typeinfo for A
  11:	e9 00 00 00 00       	jmpq   16 <dc(A*)+0x16>
			12: R_X86_64_PC32	__dynamic_cast-0x4
  16:	66 2e 0f 1f 84 00 00 	nopw   %cs:0x0(%rax,%rax,1)
  1d:	00 00 00 
  20:	31 c0                	xor    %eax,%eax
  22:	c3                   	retq   


However, since B is declared final, a simple compare of a's typeinfo with B's would suffice.  This is a missed optimization opportunity.
Comment 1 Jakub Jelinek 2019-02-28 13:27:19 UTC
I guess when we implement http://wg21.link/p1327r1 we could use the same function to optimize __dynamic_cast in constexpr as well as if during optimization we determine which vtable a particular __dynamic_cast call is called with and optimize that too if possible.