From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: by sourceware.org (Postfix, from userid 48) id C161F385800F; Sat, 2 Jan 2021 22:56:36 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org C161F385800F From: "vanyacpp at gmail dot com" To: gcc-bugs@gcc.gnu.org Subject: [Bug c++/98501] New: potential optimization for base<->derived pointer casts Date: Sat, 02 Jan 2021 22:56:36 +0000 X-Bugzilla-Reason: CC X-Bugzilla-Type: new X-Bugzilla-Watch-Reason: None X-Bugzilla-Product: gcc X-Bugzilla-Component: c++ X-Bugzilla-Version: 10.2.1 X-Bugzilla-Keywords: X-Bugzilla-Severity: normal X-Bugzilla-Who: vanyacpp at gmail dot com X-Bugzilla-Status: UNCONFIRMED X-Bugzilla-Resolution: X-Bugzilla-Priority: P3 X-Bugzilla-Assigned-To: unassigned at gcc dot gnu.org X-Bugzilla-Target-Milestone: --- X-Bugzilla-Flags: X-Bugzilla-Changed-Fields: bug_id short_desc product version bug_status bug_severity priority component assigned_to reporter target_milestone Message-ID: Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: quoted-printable X-Bugzilla-URL: http://gcc.gnu.org/bugzilla/ Auto-Submitted: auto-generated MIME-Version: 1.0 X-BeenThere: gcc-bugs@gcc.gnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Gcc-bugs mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Sat, 02 Jan 2021 22:56:36 -0000 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=3D98501 Bug ID: 98501 Summary: potential optimization for base<->derived pointer casts Product: gcc Version: 10.2.1 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: vanyacpp at gmail dot com Target Milestone: --- Consider this code: struct base1 { int a; }; struct base2 { int b; }; struct derived : base1, base2 {}; derived& to_derived_bad(base2* b) { return *static_cast(b); } derived& to_derived_good(base2* b) { return static_cast(*b); } I believe both of these functions are functionally equivalent and should generate the same code. Both functions cast pointer from base to derived if= it is not nullptr and both cause undefined behavior if it is nullptr. GCC optimizes to_derived_good() to a single subtraction, but it inserts nullptr-check into to_derived_bad(): to_derived_good(base2*): lea rax, [rdi-4] ret to_derived_bad(base2*): lea rax, [rdi-4] test rdi, rdi mov edx, 0 cmove rax, rdx ret Could GCC omit the nullptr-check in to_derived_bad?=