[C++20] [Modules] Fix the duplicated static initializer problem (#114193)
authorChuanqi Xu <yedeng.yd@linux.alibaba.com>
Wed, 30 Oct 2024 09:27:04 +0000 (17:27 +0800)
committerTobias Hieta <tobias@hieta.se>
Fri, 15 Nov 2024 08:32:03 +0000 (09:32 +0100)
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.

(cherry picked from commit 259eaa6878ead1e2e7ef572a874dc3d885c1899b)

clang/lib/CodeGen/CodeGenModule.cpp
clang/test/Modules/static-initializer.cppm [new file with mode: 0644]

index 151505baf38db1704dbc89f5cea70516cd2fcb4a..2a5d5f9083ae6526355728f67e50ac7b064aa795 100644 (file)
@@ -7080,8 +7080,8 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) {
     // For C++ standard modules we are done - we will call the module
     // initializer for imported modules, and that will likewise call those for
     // any imports it has.
-    if (CXX20ModuleInits && Import->getImportedOwningModule() &&
-        !Import->getImportedOwningModule()->isModuleMapModule())
+    if (CXX20ModuleInits && Import->getImportedModule() &&
+        Import->getImportedModule()->isNamedModule())
       break;
 
     // For clang C++ module map modules the initializers for sub-modules are
diff --git a/clang/test/Modules/static-initializer.cppm b/clang/test/Modules/static-initializer.cppm
new file mode 100644 (file)
index 0000000..10d4854
--- /dev/null
@@ -0,0 +1,18 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+//
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 %t/a.cppm -emit-module-interface -o %t/a.pcm
+// 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
+
+//--- a.cppm
+export module a;
+int func();
+static int a = func();
+
+//--- a.cpp
+import a;
+
+// CHECK-NOT: internal global
+// CHECK-NOT: __cxx_global_var_init
+