Optimizing away empty loop with step

Iain Buclaw ibuclaw at gdcproject.org
Fri Jul 30 22:23:08 UTC 2021


On Friday, 30 July 2021 at 10:21:37 UTC, Iain Buclaw wrote:
> 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?
>>
>
> GCC is still unaffected, but looking at the generated code, 
> they opt to instead implement both loops with labels and goto 
> expressions.

On digging around further, C *doesn't* optimize away this kind of 
loop.

The actual compiler option that controls this is `-ffinite-loops`.
```
Assume that a loop with an exit will eventually take the exit and 
not loop indefinitely. This allows the compiler to remove loops 
that otherwise have no side-effects, not considering eventual 
endless looping as such.

This option is enabled by default at -O2 for C++ with -std=c++11 
or higher.
```

You can add this to the GDC compiler window to observe the 
optimization, or add `-fno-finite-loops` to the G++ compiler 
window for the inverse.


More information about the digitalmars-d-ldc mailing list