Can compilers escape branch instructions?

I read about bit-creaking hacks and thought that compilers could avoid branching in the following code:

constexpr int min(const int lhs, const int rhs) noexcept {
    if (lhs < rhs) {
        return lhs;
    }
    return rhs
}

replacing it ( explanation ):

constexpr int min(const int lhs, const int rhs) noexcept {
    return rhs ^ ((lhs ^ rhs) & -(lhs < rhs));
}
+4
source share
3 answers

clang++(3.5.2-1) seems smart enough -O3(I don't use C ++ 11 or C ++ 14, constexprand noexceptremoved from the source code):

08048760 <_Z3minii>:
 8048760:   8b 44 24 08             mov    0x8(%esp),%eax
 8048764:   8b 4c 24 04             mov    0x4(%esp),%ecx
 8048768:   39 c1                   cmp    %eax,%ecx
 804876a:   0f 4e c1                cmovle %ecx,%eax
 804876d:   c3                      ret    

gcc(4.9.3) ( -O3) instead branch with jle:

08048740 <_Z3minii>:
 8048740:       8b 54 24 08             mov    0x8(%esp),%edx
 8048744:       8b 44 24 04             mov    0x4(%esp),%eax
 8048748:       39 d0                   cmp    %edx,%eax
 804874a:       7e 02                   jle    804874e <_Z3minii+0xe>
 804874c:       89 d0                   mov    %edx,%eax
 804874e:       f3 c3                   repz ret 

(x86 32bit)

This min2(distorted) is an alternative to a bit (from gcc):

08048750 <_Z4min2ii>:
 8048750:       8b 44 24 08             mov    0x8(%esp),%eax
 8048754:       8b 54 24 04             mov    0x4(%esp),%edx
 8048758:       31 c9                   xor    %ecx,%ecx
 804875a:       39 c2                   cmp    %eax,%edx
 804875c:       0f 9c c1                setl   %cl
 804875f:       31 c2                   xor    %eax,%edx
 8048761:       f7 d9                   neg    %ecx
 8048763:       21 ca                   and    %ecx,%edx
 8048765:       31 d0                   xor    %edx,%eax
 8048767:       c3                      ret    
+4
source
  • ...: !
  • ?: , - . - , - . , , , , ( ( ) , ). (1)
  • , : , , ? ! -, ( x86) , , . , , .
  • twiddel?: : - , , - ! , , ( , , ...), , - .

:
, ( , / ). , , , , . , , , .

, , - , - . , - , , , (, ).

(1) , , , , , , . -, , ( , , ). -, ++ , , - .

+7

, .

, clang++, g++ , ., , g++ 5.2.0 .

0

All Articles