Switch codegen.

claptrap clap at trap.com
Sun Aug 13 18:51:38 UTC 2023


On Sunday, 13 August 2023 at 10:45:11 UTC, Basile B. wrote:
> As I've heard good feedback about that alternative to LLVM 
> `switch` and also because I'm also interested to implement that 
> in another compiler, I've made a comparison of both way here : 
> https://godbolt.org/z/G41P88EY7 (D code at the end as comments)
>
> It seems that this would only work well for `final switch`es 
> (no default block) over enum members. The main problem is that 
> you need to build a constant array made of `blockaddress`, 
> meaning that
>
> 1. if the first member value is not 0 then you'll need to apply 
> an offset for the index used to select the right 
> `blockaddress`. (Source 1, line 13)
> 2. if there are gaps between members, you'll need to use a 
> dummy block, containing `unreachable`, to fill them.
>
> A note about the fact that I think that this would only works 
> for enums: `final switch` over a value of an integral type is 
> currently a lie [(see issue 
> 6060)](https://issues.dlang.org/show_bug.cgi?id=6060), there's 
> still a fallback with a runtime error.
>
> Otherwise, more concretly in LDC, the work would have to be 
> done 
> [here](https://github.com/ldc-developers/ldc/blob/cf32bac668540f3dd022493b3ba89b598a485dfb/gen/statements.cpp#L953). At first glance you'll need to define a flag, similarly to the already existing `useSwitchInst` (used for the infamous case where `case`s are not compile-time constants), let's say `useIndirectBrInst`.
>
> To conclude, that seems faisable even if that would only be 
> beneficial for a few specific cases.

 From what I can tell even "final switch" generates a bounds 
check, it does a compare and then a ja to the topmost case, i 
guess it's "better to at least jump to known code even if its the 
wrong code than it is to jump into the unknown. Im not sure if 
this is the IR generated by LDC, or what LLVM does.

Anyway I'm going to download the source and play around with it 
see what I can figure out.

Thanks.


More information about the digitalmars-d-ldc mailing list