Issue 161389
Summary [Clang] Missed optimization (flatten array access)
Labels clang
Assignees
Reporter richtw1
    ```
extern int (*fns[8][8])(int);

int dispatch(unsigned int state, int param) {
 return fns[state / 8][state % 8](param);
}

int dispatch2(unsigned int state, int param) {
    // cast to 1d flattened array
    return (*(int (*(*)[64])(int))&fns)[state](param);
}
```
https://godbolt.org/z/oqjP1Pvsc

In `dispatch()`. the optimizer ought to notice that the `state` index can map directly to the flattened array in memory., and emit code like `dispatch2()`. Instead it emits more complicated, redundant code:

```
dispatch:
 mov     eax, edi
        mov     ecx, edi
        shr     ecx, 3
 and     eax, 7
        shl     rcx, 6
        add     rcx, qword ptr [rip + fns@GOTPCREL]
        mov     edi, esi
        jmp     qword ptr [rcx + 8*rax]

dispatch2:
        mov     eax, edi
        mov     rcx, qword ptr [rip + fns@GOTPCREL]
        mov     edi, esi
        jmp     qword ptr [rcx + 8*rax]
```

GCC and MSVC both generate the simpler code in each case.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to