https://gcc.gnu.org/bugzilla/show_bug.cgi?id=114391
Bug ID: 114391
Summary: catch() and immediate throw; could be optimized to
noop
Product: gcc
Version: 14.0
Status: UNCONFIRMED
Keywords: missed-optimization
Severity: normal
Priority: P3
Component: middle-end
Assignee: unassigned at gcc dot gnu.org
Reporter: antoshkka at gmail dot com
Target Milestone: ---
Consider the example:
void foo();
void test() {
try {
foo();
} catch (...) {
throw;
}
}
At the moment, the compiler at -O2 generates the assembly:
test():
sub rsp, 24
call foo()
add rsp, 24
ret
mov rdi, rax
jmp .L2
test() [clone .cold]:
.L2:
call __cxa_begin_catch
call __cxa_rethrow
mov QWORD PTR [rsp+8], rax
call __cxa_end_catch
mov rdi, QWORD PTR [rsp+8]
call _Unwind_Resume
However, an optimal assembly is:
test():
jmp foo()
Please, add an optimization that removes catch() + immediate throw.
The sample code could be often met in release builds, due to some invariants
checks or debug logging are removed depending on NDEBUG:
void test() {
try {
foo();
} catch (...) {
#ifdef NDEBUG
std::cerr << "Unhandled exception!" << std::endl <<
boost::current_exception_diagnostic_information();
#endif
throw;
}
}
Godbolt playground: https://godbolt.org/z/qdG91cMe1