Bug 98337 - Failure to optimize out on-stack array construction when unneeded
Summary: Failure to optimize out on-stack array construction when unneeded
Status: NEW
Alias: None
Product: gcc
Classification: Unclassified
Component: tree-optimization (show other bugs)
Version: 11.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: missed-optimization
Depends on:
Blocks:
 
Reported: 2020-12-16 22:25 UTC by Gabriel Ravier
Modified: 2023-09-21 10:36 UTC (History)
1 user (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed: 2021-01-04 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Gabriel Ravier 2020-12-16 22:25:51 UTC
int f(int x) {
    int a[] = {0, 1};
    return a[x];
}

On AMD64, with -O3, this is generated :

f(int):
  mov rax, QWORD PTR .LC0[rip]
  movsx rdi, edi
  mov QWORD PTR [rsp-8], rax
  mov eax, DWORD PTR [rsp-8+rdi*4]
  ret
.LC0:
  .long 0
  .long 1


LLVM generates this :

f(int): # @f(int)
  movsxd rax, edi
  mov eax, dword ptr [4*rax + .L__const.f(int).a]
  ret
.L__const.f(int).a:
  .long 0 # 0x0
  .long 1 # 0x1

It seems to me like not copying the entire array on the stack makes for faster code.
Comment 1 Richard Biener 2021-01-04 15:44:43 UTC
It could be optimized to return x even ...

Note we're forcing the array to the stack because of the variable array access.
We could optimize this on the GIMPLE level from

  MEM <unsigned long> [(int *)&a] = 3547642986509;
  _5 = a[x_4(D)];

to

  3547642986509ul >> (x_4(D)*32)

for example when using more "interesting" constants like

int f(int x) {
    int a[] = {13, 826};
    return a[x];
}