[Interest] How does one use Q_ASSUME?

Giuseppe D'Angelo giuseppe.dangelo at kdab.com
Sat May 25 11:43:11 CEST 2019


Hi,

Il 25/05/19 10:12, René J.V. Bertin ha scritto:
> I can't seem to wrap my head around what one can do with Q_ASSUME, i.e. which will be the code for which the compiler won't emit code (and how the compiler could know not to emit code as a function of a runtime condition?!)
> 
> Squinting at the macros it seems evident that you cannot do something like this, which to me the documentation suggests (and I think) you SHOULD be able to do:
> 
> Q_ASSUME(conditionsMet, {
>    // do something that should be done only when conditions are met
> });

That's wrong; what you just wrote is a plain if. You can tune codegen by 
using Q_LIKELY / Q_UNLIKELY in the predicate, if you know statically 
that a condition is (way) more likely to be true than false (or viceversa).

   if (Q_LIKELY(condition)) { ~~~ }



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.

Look here at a possible example at how it can improve codegen:

https://gcc.godbolt.org/z/KlWBRY


HTH,

-- 
Giuseppe D'Angelo | giuseppe.dangelo at kdab.com | Senior Software Engineer
KDAB (France) S.A.S., a KDAB Group company
Tel. France +33 (0)4 90 84 08 53, http://www.kdab.com
KDAB - The Qt, C++ and OpenGL Experts

-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 4329 bytes
Desc: Firma crittografica S/MIME
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20190525/854b3e80/attachment.bin>


More information about the Interest mailing list