https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82504

            Bug ID: 82504
           Summary: Optimize away exception allocation and throws handled
                    by catch(...){}
           Product: gcc
           Version: 8.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: middle-end
          Assignee: unassigned at gcc dot gnu.org
          Reporter: antoshkka at gmail dot com
  Target Milestone: ---

Following function

void foo() {
    try {
        throw 1;
    } catch(...) {}
}

produces the following assembly at -O2:

foo():
        mov     edi, 4
        sub     rsp, 8
        call    __cxa_allocate_exception <=== This could be avoided
        xor     edx, edx
        mov     DWORD PTR [rax], 1
        mov     esi, OFFSET FLAT:typeinfo for int
        mov     rdi, rax
        call    __cxa_throw <=== This could be avoided
        jmp     .L2
foo() [clone .cold.0]:
.L2:
        mov     rdi, rax
        call    __cxa_begin_catch <=== This could be avoided
        pop     rax
        jmp     __cxa_end_catch <=== This could be avoided


This is suboptimal as the exception is catched and ignored. Optimal assembly
would be:

foo():
        rep ret

For exception classes with user provided constructors and destructors that have
side effect, leave the calls to constructor and destructor but do no actually
throw the exception:

foo():
        call user_exception()
        call ~user_exception()
        rep ret


The `catch(...){}` expression used widely in C++ code, optimizing it would
improve binary size and performance a lot.

Reply via email to