Skip to content

Commit 2f65993

Browse files
ChuanqiXu9NoumanAmir657
authored andcommitted
[C++20] [Modules] Fix the duplicated static initializer problem (llvm#114193)
Reproducer: ``` //--- a.cppm export module a; int func(); static int a = func(); //--- a.cpp import a; ``` The `func()` should only execute once. However, before this patch we will somehow import `static int a` from a.cppm incorrectly and initialize that again. This is super bad and can introduce serious runtime behaviors. And also surprisingly, it looks like the root cause of the problem is simply some oversight choosing APIs.
1 parent 1cad8b1 commit 2f65993

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

clang/lib/CodeGen/CodeGenModule.cpp

+2-2
Original file line numberDiff line numberDiff line change
@@ -7146,8 +7146,8 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) {
71467146
// For C++ standard modules we are done - we will call the module
71477147
// initializer for imported modules, and that will likewise call those for
71487148
// any imports it has.
7149-
if (CXX20ModuleInits && Import->getImportedOwningModule() &&
7150-
!Import->getImportedOwningModule()->isModuleMapModule())
7149+
if (CXX20ModuleInits && Import->getImportedModule() &&
7150+
Import->getImportedModule()->isNamedModule())
71517151
break;
71527152

71537153
// For clang C++ module map modules the initializers for sub-modules are
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// RUN: rm -rf %t
2+
// RUN: mkdir -p %t
3+
// RUN: split-file %s %t
4+
//
5+
// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 %t/a.cppm -emit-module-interface -o %t/a.pcm
6+
// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 %t/a.cpp -fmodule-file=a=%t/a.pcm -emit-llvm -o - | FileCheck %t/a.cpp
7+
8+
//--- a.cppm
9+
export module a;
10+
int func();
11+
static int a = func();
12+
13+
//--- a.cpp
14+
import a;
15+
16+
// CHECK-NOT: internal global
17+
// CHECK-NOT: __cxx_global_var_init
18+

0 commit comments

Comments
 (0)