[clang] [clang][CodeGen] Propagate `volatile` qualifier in derived-to-base conversion (PR #127824)

Antonio Frighetto via cfe-commits cfe-commits at lists.llvm.org
Wed Feb 19 07:57:54 PST 2025


https://github.com/antoniofrighetto created https://github.com/llvm/llvm-project/pull/127824

A miscompilation issue has been addressed with improved handling.

Fixes: https://github.com/llvm/llvm-project/issues/127683.

>From fd06a833ba56f812693d89e19f594ed3f238fea4 Mon Sep 17 00:00:00 2001
From: Antonio Frighetto <me at antoniofrighetto.com>
Date: Wed, 19 Feb 2025 16:47:18 +0100
Subject: [PATCH] [clang][CodeGen] Propagate `volatile` qualifier in
 derived-to-base conversion

A miscompilation issue has been addressed with improved handling.

Fixes: https://github.com/llvm/llvm-project/issues/127683.
---
 clang/lib/CodeGen/CGExpr.cpp              |  8 ++++++--
 clang/test/CodeGenCXX/derived-to-base.cpp | 19 +++++++++++++++++++
 2 files changed, 25 insertions(+), 2 deletions(-)

diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 191912ca7d800..3bba142f2b96e 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -5403,8 +5403,12 @@ LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
     // TODO: Support accesses to members of base classes in TBAA. For now, we
     // conservatively pretend that the complete object is of the base class
     // type.
-    return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
-                          CGM.getTBAAInfoForSubobject(LV, E->getType()));
+    LValue CastedLV =
+        MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
+                       CGM.getTBAAInfoForSubobject(LV, E->getType()));
+    if (LV.isVolatile())
+      CastedLV.getQuals().addVolatile();
+    return CastedLV;
   }
   case CK_ToUnion:
     return EmitAggExprToLValue(E);
diff --git a/clang/test/CodeGenCXX/derived-to-base.cpp b/clang/test/CodeGenCXX/derived-to-base.cpp
index c8dbd5bf5cb05..37a8e6f7ea6b6 100644
--- a/clang/test/CodeGenCXX/derived-to-base.cpp
+++ b/clang/test/CodeGenCXX/derived-to-base.cpp
@@ -46,4 +46,23 @@ namespace test3 {
   }
 }
 
+// Ensure volatile is preserved during derived-to-base conversion. 
+namespace PR127683 {
+
+struct Base {
+  int Val;
+};
+
+struct Derived : Base { };
+
+volatile Derived Obj;
+
+// CHECK-LABEL: define void @_ZN8PR12768319test_volatile_storeEv() #0
+// CHECK:       store volatile i32 0, ptr @_ZN8PR1276833ObjE, align 4
+void test_volatile_store() {
+  Obj.Val = 0;
+}
+
+}
+
 // CHECK: attributes [[NUW]] = { mustprogress noinline nounwind{{.*}} }



More information about the cfe-commits mailing list