From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: by sourceware.org (Postfix, from userid 48) id 7DA903858D28; Thu, 5 Jan 2023 10:51:18 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org 7DA903858D28 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gcc.gnu.org; s=default; t=1672915878; bh=s15JjfVIjYUsZJ+m8EI0FRBmYBGBi7Bu08wVB9UpYx8=; h=From:To:Subject:Date:From; b=hhB5YnaCFa3zEdHu6w4ZwSTgPDnckUE01UjmMy+VjXEAEa0Y+aHyC+cZF1Pc83Gs1 /JEqJM5IvY7A0u1QMulSkja1gJlsUFZxiiUQ4dHMGBvLwHDQhsjzyjZqnqIp41rpJD Pq7d9xBG9iYM/QzEji9LRX79aVzrvYZMLsCsmZMU= From: "agriff at tin dot it" To: gcc-bugs@gcc.gnu.org Subject: [Bug c++/108299] New: toplevel thread_local variables are not initialized if not referenced and initialized at wrong moment when referenced Date: Thu, 05 Jan 2023 10:51:17 +0000 X-Bugzilla-Reason: CC X-Bugzilla-Type: new X-Bugzilla-Watch-Reason: None X-Bugzilla-Product: gcc X-Bugzilla-Component: c++ X-Bugzilla-Version: 12.2.0 X-Bugzilla-Keywords: X-Bugzilla-Severity: normal X-Bugzilla-Who: agriff at tin dot it X-Bugzilla-Status: UNCONFIRMED X-Bugzilla-Resolution: X-Bugzilla-Priority: P3 X-Bugzilla-Assigned-To: unassigned at gcc dot gnu.org X-Bugzilla-Target-Milestone: --- X-Bugzilla-Flags: X-Bugzilla-Changed-Fields: bug_id short_desc product version bug_status bug_severity priority component assigned_to reporter target_milestone Message-ID: Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: quoted-printable X-Bugzilla-URL: http://gcc.gnu.org/bugzilla/ Auto-Submitted: auto-generated MIME-Version: 1.0 List-Id: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=3D108299 Bug ID: 108299 Summary: toplevel thread_local variables are not initialized if not referenced and initialized at wrong moment when referenced Product: gcc Version: 12.2.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: agriff at tin dot it Target Milestone: --- The standard mandates that thread_local variables at top level must be initialized in case anything in the compilation unit is referred to. There = is a specific note on the fact that they must be initialized even if they're not used in the program. Also they must be initialized at thread start or before anything from the compilation unit is accessed by the thread. This code however shows that g++ doesn't follow this rule #include thread_local int flag =3D ([](){ printf("HERE!\n"); return 1; })(); int main() { printf("Hello, world.\n"); return 0; } In this version the thread local initialization is skipped. Mover if after the printf the statement flag; is added then the initialization is performed, but AFTER the "Hello, world" message (another violation of the standard). Trying on godbolt I saw the problem is present even in trunk and in clang (works as expected in MSVC). The problems are present both on the main implicit thread and with threads started explicitly with std::thread.=