http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59863
Bug ID: 59863
Summary: const array in function is placed on stack
Product: gcc
Version: 4.8.2
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c
Assignee: unassigned at gcc dot gnu.org
Reporter: sam at gcc dot gnu.org
Created attachment 31875
--> http://gcc.gnu.org/bugzilla/attachment.cgi?id=31875&action=edit
Source file to reproduce the issue
This source code
int f(int i) {
const int a[] = {1, 2, 3, 4};
return a[i];
}
int g(int i) {
static const int a[] = {1, 2, 3, 4};
return a[i];
}
generates different code with GCC 4.8.2 on x86_64 for f() and g(). In f(), the
const array is really created on the stack, and initialized one element at a
time, instead of being placed in .rodata as it is for g().
With GCC on ARM (4.7), both arrays from f() and g() are placed in .rodata, but
the code to access them is different:
.text
.align2
.globalf
.typef, %function
f:
@ args = 0, pretend = 0, frame = 16
@ frame_needed = 0, uses_anonymous_args = 0
@ link register save eliminated.
strr4, [sp, #-4]!
ldrr3, .L2
subsp, sp, #20
movip, r0
ldmiar3, {r0, r1, r2, r3}
addr4, sp, #16
stmdbr4, {r0, r1, r2, r3}
addip, r4, ip, asl #2
ldrr0, [ip, #-16]
addsp, sp, #20
ldmfdsp!, {r4}
bxlr
.L3:
.align2
.L2:
.word.LANCHOR0
.sizef, .-f
.align2
.globalg
.typeg, %function
g:
@ args = 0, pretend = 0, frame = 0
@ frame_needed = 0, uses_anonymous_args = 0
@ link register save eliminated.
ldrr3, .L5
addr0, r3, r0, asl #2
ldrr0, [r0, #16]
bxlr
.L6:
.align2
.L5:
.word.LANCHOR0
.sizeg, .-g
.section.rodata
.align2
.set.LANCHOR0,. + 0
.LC0:
.word1
.word2
.word3
.word4
.typea.4057, %object
.sizea.4057, 16
a.4057:
.word1
.word2
.word3
.word4
Note that on x86_64, clang generates the same code for f() and g() and even
unifies both const arrays in .rodata.
Is there anything in the C standard preventing a const array declared in a
function from being put in .rodata or are those missed optimizations?