[clang] [clang][bytecode] Fix definining extern variables (PR #108940)

Timm Baeder via cfe-commits cfe-commits at lists.llvm.org
Tue Sep 17 01:04:25 PDT 2024


https://github.com/tbaederr created https://github.com/llvm/llvm-project/pull/108940

At the point of defintion of the variable, a function might already refert to the variable by its index. Replace the index with the new one.

>From db26626c766426d6d848f459d4a243319f9badbe Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= <tbaeder at redhat.com>
Date: Tue, 17 Sep 2024 08:49:55 +0200
Subject: [PATCH] [clang][bytecode] Fix definining extern variables

At the point of defintion of the variable, a function might already
refert to the variable by its index. Replace the index with the new one.
---
 clang/lib/AST/ByteCode/Program.cpp | 11 ++++++++++-
 clang/test/AST/ByteCode/extern.cpp | 13 +++++++++++++
 2 files changed, 23 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/AST/ByteCode/extern.cpp

diff --git a/clang/lib/AST/ByteCode/Program.cpp b/clang/lib/AST/ByteCode/Program.cpp
index bd5860beabaecd..79c645257306e0 100644
--- a/clang/lib/AST/ByteCode/Program.cpp
+++ b/clang/lib/AST/ByteCode/Program.cpp
@@ -204,9 +204,18 @@ std::optional<unsigned> Program::createGlobal(const ValueDecl *VD,
     IsStatic = false;
     IsExtern = true;
   }
+
+  // Register all previous declarations as well. For extern blocks, just replace
+  // the index with the new variable.
   if (auto Idx = createGlobal(VD, VD->getType(), IsStatic, IsExtern, Init)) {
-    for (const Decl *P = VD; P; P = P->getPreviousDecl())
+    for (const Decl *P = VD; P; P = P->getPreviousDecl()) {
+      if (P != VD) {
+        unsigned PIdx = GlobalIndices[P];
+        if (Globals[PIdx]->block()->isExtern())
+          Globals[PIdx] = Globals[*Idx];
+      }
       GlobalIndices[P] = *Idx;
+    }
     return *Idx;
   }
   return std::nullopt;
diff --git a/clang/test/AST/ByteCode/extern.cpp b/clang/test/AST/ByteCode/extern.cpp
new file mode 100644
index 00000000000000..a616269911a7ec
--- /dev/null
+++ b/clang/test/AST/ByteCode/extern.cpp
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify=both,expected %s
+// RUN: %clang_cc1 -verify=both,ref %s
+
+
+// both-no-diagnostics
+
+extern const int E;
+constexpr int getE() {
+  return E;
+}
+const int E = 10;
+static_assert(getE() == 10);
+



More information about the cfe-commits mailing list