📜 ⬆️ ⬇️

Optimizing the comparison of this with a null pointer in gcc 6.1



Good news TM are waiting for gcc users when upgrading to version 6.1. A code of this type (taken from here ):

class CWindow {
    HWND handle;
public:
    HWND GetSafeHandle() const
    {
         return this == 0 ? 0 : handle;
    }
};

«» — , . , , , gcc 6.1 .

gcc.godbolt.org -O2

:

struct CWindow {
CWindow() : handle() {}
    int handle;
    int GetSafeHandle() const
    {
      return (this == 0) ? 1 : handle;
    }
};
int main()
{
   CWindow* wnd = 0;
   return wnd->GetSafeHandle();
}

gcc 6.1 …

main:
        movl    0, %eax
        ud2

~ , gcc __builtin_trap(), « », .

gcc 5.3 :

main:
        movl    $1, %eax
        ret

gcc 5. « ».

, , , CWindow::GetSafeHandle() __attribute__ ((noinline)), . :

int GetSafeHandle() const __attribute__ ((noinline))

gcc 5.3 :

CWindow::GetSafeHandle() const:
        testq   %rdi, %rdi
        je      .L1
        movl    (%rdi), %eax
        ret
.L1:
        movl    $1, %eax
        ret
main:
        xorl    %edi, %edi
        jmp     CWindow::GetSafeHandle() const

GetSafeHandle() this ( testq) ( je). gcc 6.1:

CWindow::GetSafeHandle() const:
        movl    (%rdi), %eax
        ret
main:
        xorl    %edi, %edi
        jmp     CWindow::GetSafeHandle() const

– . , , « » .

rdi. edirdi, – rdi. , , ( ), – , .

, O1. -fno-delete-null-pointer-checks – , gcc 5.3

, , – «» ! , . -Wnonnull-comparethis ») , , -Wall. :

int GetSafeHandle() const __attribute__ ((noinline))
{
  if (this == 0) // -Wnonnull-compare
     return 1;
   if((this == 0))
     return 1; //  
  return this == 0 ? 1 : handle; // -Wnonnull-compare
  return (this == 0) ? 1 : handle; //  
}

— gcc.

, GetSafeHandle() main(), – , , , this . , , « » — , .

-Wnonnull-compare , -fno-delete-null-pointer-checks

clang…

3.5 clang -Wtautological-undefined-compare :

if (this == 0);
(this == 0) ? 1 : handle;
if(this != 0);
(this != 0) ? handle : 1;

-Wundefined-bool-conversion :

if(this);
this ? handle : 1;
if(!this);
!this ? 1 : handle;

3.8 (3.8 — ) ( , ).

.

,

')

Source: https://habr.com/ru/post/308346/


All Articles