Standard way to supply hints to branches

Quirin Schroll qs.il.paperinik at gmail.com
Fri Sep 6 10:26:02 UTC 2024


On Friday, 23 August 2024 at 17:43:33 UTC, Richard (Rikki) Andrew 
Cattermole wrote:
>
> On 24/08/2024 5:39 AM, Manu wrote:
>> On Fri, 23 Aug 2024, 19:02 Iain Buclaw via Digitalmars-d, 
>> <digitalmars-d at puremagic.com 
>> <mailto:digitalmars-d at puremagic.com>> wrote:
>> 
>>     On Friday, 23 August 2024 at 02:23:37 UTC, Nicholas Wilson 
>> wrote:
>>      >
>>      > GDC probably has something similar too.
>> 
>>     
>> https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-_005f_005fbuiltin_005fexpect <https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-_005f_005fbuiltin_005fexpect>
>> 
>> 
>>     Regarding DMD, I recall it being said that its code 
>> generator
>>     always treats the true branch as the "likely" code path 
>> taken. So
>>     if you have `if (cond) cold; else hot;`, invert the 
>> condition for
>>     the benefit of DMD.
>> 
>> 
>> Yes, I understand, and this is part of my point here; that 
>> leads to really ugly code and deep nested scopes. That's what 
>> I've been doing, and I don't want my program to look like 
>> that. It's just bad software.
>> 
>> For instance, an extraordinarily common function pattern is to 
>> receive some inputs, validate a few things, and then do the 
>> thing at the end with valid inputs.
>> Validations are usually a series of exclusionary checks framed 
>> as `if(fails_validity_check) return;`
>> That flow keeps code in a nice linear flow, it doesn't 
>> introduce any scopes at all... but it's the opposite of what 
>> the assume(true) prediction rule wants. This is what lead me 
>> to this; almost every if statement I write is predicted 
>> wrong... and I definitely don't want to solve that by writing 
>> functions with 10 level deep nested scopes.
>
> If you want to propose something like an attribute on if 
> statement, I'd be keen to see it (in ideas forum).
>
> ```d
> void func() {
> 	@unlikely
> 	if (random() > 0.5)
> 		return;
> 	@likely
> 	else {
>
> 	}
> }
> ```

It should be a pragma. In general, a pragma is something a 
conforming compiler can ignore without changing semantics. Inline 
is a pragma for exactly this reason. An attribute makes no sense.
```d
if (cond()) { pragma(unlikely); return; }
```


More information about the Digitalmars-d mailing list