Issue 150844
Summary Optimization when 'while' loop can be converted to 'do-while'
Labels new issue
Assignees
Reporter Explorer09
    This missed optimization issue is more like a feature request than a bug.

When the body of a loop contains only counter increments and the loop condition is determined externally, a `while` loop construct can sometimes be converted to a `do`-`while`.

Clang can do the optimization when the loop counter change is addition or subtraction. Now I wish the optimization can also be performed when the counter change is multiplication (by a constant) or bit shift (shift left or shift right by a constant).

(I'm not requesting for general division cases except for division by a power of two.)

Example code:

```c
#include <stdbool.h>
#include <stdint.h>

extern bool cond(uint32_t x);

uint32_t func2_a(uint32_t x) {
    uint32_t i = 10;
    while (cond(i)) {
        i *= 2;
    }
    return i;
}

uint32_t func2_b(uint32_t x) {
 uint32_t i = 5;
    do {
        i *= 2;
    } while (cond(i));
 return i;
}
```

`func2_a` and `func2_b` should be equivalent. By turning `func2_a` to `func2_b` it can usually save a `jmp` instruction.

[Related GCC bug report](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=121258)

The example code can be tested in Compiler Explorer ([link](https://godbolt.org/z/Kqnr1o8zh)). 

_______________________________________________
llvm-bugs mailing list
llvm-bugs@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to