Optimizing away empty loop with step

Iain Buclaw ibuclaw at gdcproject.org
Fri Jul 30 10:21:37 UTC 2021


On Friday, 30 July 2021 at 09:58:01 UTC, Vladimir Panteleev wrote:
> DMD [fails](https://issues.dlang.org/show_bug.cgi?id=22158) to 
> optimize away an empty for loop with an increment of 1. GDC and 
> LDC both succeed.
>
> However, the results are more interesting if you make the step 
> variable:
>
> ```d
> void fun(int a, int b, int step)
> {
>     for (int i = a; i < b; i += step) {
>     }
> }
> ```
>
> The above code (valid C and D) compiles to an empty function 
> with clang and gcc:
>
> https://godbolt.org/z/PnffvhecM
>
> However, all three D compilers fail to optimize away the loop:
>
> https://d.godbolt.org/z/r3MEGzoh1
>
> Is the frontend doing something to prevent the loop from being 
> optimized away as in C?
>

You can look at C-style IR dump using the GDC Tree/RTL output 
option.

https://d.godbolt.org/z/eM8Pv91eT

As you can see, the loop construct that GDC uses is treated as a 
`while (1) { }` statement.

You can reproduce this in Clang by rewriting the for loop into a 
while loop.

https://godbolt.org/z/hWePhqesq

GCC is still unaffected, but looking at the generated code, they 
opt to instead implement both loops with labels and goto 
expressions.



More information about the digitalmars-d-ldc mailing list