ternary operator invalidates __builtin_expect

Liu Hao lh_mouse@126.com
Tue Mar 2 08:07:00 GMT 2021


Hi all,

Generally the `__builtin_expect()` functions is used to inform the compiler about whether a branch 
is likely to be taken. But given this example:

```c++
#ifdef USE_TERNARY
#  define EXPECT(...)  __builtin_expect((__VA_ARGS__)?1:0,1)
#else
#  define EXPECT(...)  __builtin_expect(!!(__VA_ARGS__),1)
#endif

struct data
   {
     char* ptr;

     int get_flags_slow() const;
     int get_flags() const
       {
         if(EXPECT(!this->ptr))
           return 0;
         return this->get_flags_slow();
       }

     int use() const;
   };

int gdata(const data* p)
   {
     int flags = p->get_flags();
     return flags & p->use();
   }
```

when `USE_TERNARY` is defined, the ternary operator is used to contextually convert the condition 
expression to type `bool`, which seems to invalidate the hint for GCC (not for clang), as shown in 
<https://gcc.godbolt.org/z/fvqYbh>. The traditional way of forcing such conversion (when 
`USE_TERNARY` is not defined) does not suffer from this issue. What could be the potential cause of 
this differentiation? Thanks in advance.


-- 
Best regards,
Liu Hao

-------------- next part --------------
A non-text attachment was scrubbed...
Name: OpenPGP_signature
Type: application/pgp-signature
Size: 840 bytes
Desc: OpenPGP digital signature
URL: <https://gcc.gnu.org/pipermail/gcc-help/attachments/20210302/5510daaf/attachment.sig>


More information about the Gcc-help mailing list