[Interest] How does one use Q_ASSUME?

Thiago Macieira thiago.macieira at intel.com
Sat May 25 19:19:19 CEST 2019


On Saturday, 25 May 2019 02:43:11 PDT Giuseppe D'Angelo via Interest wrote:
> On the other hand, Q_ASSUME(cond) tells the compiler that cond is true,
> always. If cond is actually false at runtime, you have undefined
> behavior. And since undefined behavior cannot happen, the compiler is
> free to optimize the following code assuming that cond is true.

Please be careful with Q_ASSUME and GCC. Unlike the other three major 
compilers, it does not have __assume or __builtin_assume. So Q_ASSUME 
implements by the if {} else __builtin_unreachable() expression that Peppe's 
link shows. That has two important side-effects:

1) sometimes, the compare-and-branch isn't removed. You end up with worse code 
than not assuming at all.

2) unlike the other compilers, the conditional is actually in evaluated 
context. So make sure you only Q_ASSUME on variables, never on function calls. 
GCC will call them, the others won't. This is the same rule as Q_ASSERT, btw.

My idea with Q_ASSUME was to make Q_ASSERT expand to it when asserts are 
disabled. After all, calling a [[noreturn]] function is the same as having a 
__builtin_unreachable() after that function call, right? 

Unfortunately, because of the issues above, it couldn't be done.

PS: Q_UNREACHABLE() is implemented on MSVC with __assume(false).

-- 
Thiago Macieira - thiago.macieira (AT) intel.com
  Software Architect - Intel System Software Products





More information about the Interest mailing list