https://gcc.gnu.org/bugzilla/show_bug.cgi?id=84103
Bug ID: 84103
Summary: Dynamic initialization is performed for non-local
variables in case when constant initialization is
permitted
Product: gcc
Version: 8.0.1
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: antoshkka at gmail dot com
Target Milestone: ---
Following code
struct foo {
const char* data_;
unsigned size_;
foo(const char* data, unsigned size) noexcept
: data_(data)
, size_(size)
{}
};
extern const foo v{"Hello", 5};
Produces assembly with dynamic initialization:
.LC0:
.string "Hello"
_GLOBAL__sub_I_v:
mov QWORD PTR v[rip], OFFSET FLAT:.LC0
mov DWORD PTR v[rip+8], 5
ret
v:
.zero 16
However in this case C++ Standard permits constant initialization:
"An implementation is permitted to perform the initialization of a variable
with static or thread storage duration as a static initialization even if such
initialization is not required to be done statically, provided that
— the dynamic version of the initialization does not change the value of any
other object of static or thread storage duration prior to its initialization,
and
— the static version of the initialization produces the same value in the
initialized variable as would be produced by the dynamic initialization if all
variables not required to be initialized statically were initialized
dynamically.
"
Optimal assembly would look like the following
v:
.quad .L.str
.long 5 # 0x5
.zero 4
.L.str:
.asciz "Hello"
(clang produces the code from above)
Bug 84099 may be related to this one. That bug is about local variables
initialization, this bug is about non-local variables.