https://github.com/Prajwal-kp-18 updated 
https://github.com/llvm/llvm-project/pull/241126

>From ac2f4296ea31cfa4d9129da8b48ee01673f545fc Mon Sep 17 00:00:00 2001
From: Prajwal <[email protected]>
Date: Tue, 10 Nov 2026 13:03:05 +0530
Subject: [PATCH] [clang] Don't fold reads of modifiable file-scope compound
 literals

A compound literal at file scope is an unnamed object with static storage
duration. Unless its type is const-qualified it can be modified at
runtime, but the constant evaluator returned its initial value for any
read, for example through a const pointer:

  static struct S *const p = &(struct S){255};
  int f(void) { p->x = 252; return p->x; } // returned 255

Reject reads of such compound literals, except for the GNU extension
where the compound literal is immediately read by an lvalue-to-rvalue
conversion, possibly through '.' member access or __real/__imag, as in
'int x = (int){1};' or 'int y = (struct S){1}.a;'. That is not a read of
the object, so its value is used directly.

The bytecode interpreter still folds these reads, so the new checks only
run against the current evaluator for now.

Fixes #54014
---
 clang/lib/AST/ExprConstant.cpp        | 66 +++++++++++++++++++++------
 clang/test/CodeGen/compound-literal.c | 28 +++++++++++-
 clang/test/Sema/compound-literal.c    | 11 ++++-
 clang/test/Sema/constexpr.c           |  4 ++
 4 files changed, 94 insertions(+), 15 deletions(-)

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 647bb9c45f871a..2a67cc96118c4b 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -4712,10 +4712,12 @@ static bool AreElementsOfSameArray(QualType ObjType,
   return CommonLength >= A.Entries.size() - IsArray;
 }
 
-/// Find the complete object to which an LValue refers.
-static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
-                                         AccessKinds AK, const LValue &LVal,
-                                         QualType LValType) {
+/// Find the complete object to which an LValue refers. \p DirectlyReadCLE is a
+/// compound literal that may be read; see getDirectlyReadCompoundLiteral.
+static CompleteObject
+findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
+                   const LValue &LVal, QualType LValType,
+                   const CompoundLiteralExpr *DirectlyReadCLE = nullptr) {
   if (LVal.InvalidBase) {
     Info.FFDiag(E);
     return CompleteObject();
@@ -4995,6 +4997,18 @@ static CompleteObject findCompleteObject(EvalInfo &Info, 
const Expr *E,
           return CompleteObject();
         }
 
+        // A compound literal with static storage duration is an unnamed object
+        // (C11 6.5.2.5) that can be modified unless it is const-qualified, so
+        // its value is not known, except in the GNU extension
+        // 'int x = (int){1};'; see getDirectlyReadCompoundLiteral.
+        if (!CLE->getType().isConstant(Info.Ctx) && CLE != DirectlyReadCLE) {
+          if (!IsAccess)
+            return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
+          Info.FFDiag(E);
+          Info.Note(CLE->getExprLoc(), diag::note_declared_at);
+          return CompleteObject();
+        }
+
         BaseVal = &CLE->getStaticValue();
       } else {
         if (!IsAccess)
@@ -5047,10 +5061,12 @@ static CompleteObject findCompleteObject(EvalInfo 
&Info, const Expr *E,
 /// \param WantObjectRepresentation - If true, we're looking for the object
 ///               representation rather than the value, and in particular,
 ///               there is no requirement that the result be fully initialized.
-static bool
-handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
-                               const LValue &LVal, APValue &RVal,
-                               bool WantObjectRepresentation = false) {
+/// \param DirectlyReadCLE - The compound literal read directly by this
+///               conversion, if any; see getDirectlyReadCompoundLiteral.
+static bool handleLValueToRValueConversion(
+    EvalInfo &Info, const Expr *Conv, QualType Type, const LValue &LVal,
+    APValue &RVal, bool WantObjectRepresentation = false,
+    const CompoundLiteralExpr *DirectlyReadCLE = nullptr) {
   if (LVal.Designator.Invalid)
     return false;
 
@@ -5086,7 +5102,8 @@ handleLValueToRValueConversion(EvalInfo &Info, const Expr 
*Conv, QualType Type,
     }
   }
 
-  CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
+  CompleteObject Obj =
+      findCompleteObject(Info, Conv, AK, LVal, Type, DirectlyReadCLE);
   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
 }
 
@@ -8751,6 +8768,25 @@ static bool diagnoseBPFPreserveAIEnumerator(EvalInfo 
&Info,
   return true;
 }
 
+/// GNU extension: a compound literal that is immediately read by an
+/// lvalue-to-rvalue conversion, possibly through '.' member access or
+/// __real/__imag, as in 'int x = (int){1};' or 'int y = (struct S){1}.a;', is
+/// not a read of the compound literal object; the value of its initializer is
+/// used directly. Returns that compound literal, if E is such an operand.
+static const CompoundLiteralExpr *
+getDirectlyReadCompoundLiteral(const Expr *E) {
+  while (true) {
+    E = E->IgnoreParens();
+    if (const auto *ME = dyn_cast<MemberExpr>(E); ME && !ME->isArrow())
+      E = ME->getBase();
+    else if (const auto *UO = dyn_cast<UnaryOperator>(E);
+             UO && (UO->getOpcode() == UO_Real || UO->getOpcode() == UO_Imag))
+      E = UO->getSubExpr();
+    else
+      return dyn_cast<CompoundLiteralExpr>(E);
+  }
+}
+
 template <class Derived>
 class ExprEvaluatorBase
   : public ConstStmtVisitor<Derived, bool> {
@@ -9376,8 +9412,10 @@ class ExprEvaluatorBase
         return false;
       APValue RVal;
       // Note, we use the subexpression's type in order to retain 
cv-qualifiers.
-      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
-                                          LVal, RVal))
+      if (!handleLValueToRValueConversion(
+              Info, E, E->getSubExpr()->getType(), LVal, RVal,
+              /*WantObjectRepresentation=*/false,
+              getDirectlyReadCompoundLiteral(E->getSubExpr())))
         return false;
       return DerivedSuccess(RVal, E);
     }
@@ -10610,8 +10648,10 @@ bool PointerExprEvaluator::VisitCastExpr(const 
CastExpr *E) {
 
     APValue RVal;
     // Note, we use the subexpression's type in order to retain cv-qualifiers.
-    if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
-                                        LVal, RVal))
+    if (!handleLValueToRValueConversion(
+            Info, E, E->getSubExpr()->getType(), LVal, RVal,
+            /*WantObjectRepresentation=*/false,
+            getDirectlyReadCompoundLiteral(SubExpr)))
       return InvalidBaseOK &&
              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
     return Success(RVal, E);
diff --git a/clang/test/CodeGen/compound-literal.c 
b/clang/test/CodeGen/compound-literal.c
index 5fe9594c0f954f..785ce8beae235e 100644
--- a/clang/test/CodeGen/compound-literal.c
+++ b/clang/test/CodeGen/compound-literal.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm %s -o - | FileCheck 
%s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm %s -o - | FileCheck 
%s --check-prefixes=CHECK,REF
 // RUN: %clang_cc1 -triple x86_64-apple-darwin 
-fexperimental-new-constant-interpreter -emit-llvm %s -o - | FileCheck %s
 
 // Capture the type and name so matching later is cleaner.
@@ -94,3 +94,29 @@ int compound_array_fn(void) {
   int compound_array[] = (int[]){1,2,3,4,5,6,7,8};
   return compound_array[0];
 }
+
+// GH54014: a file-scope compound literal is a modifiable object even when it
+// is only reachable through a const pointer, so reads of it must load from
+// memory instead of being folded to its initial value.
+// FIXME: The bytecode interpreter still folds these reads.
+struct GH54014 { int counter; };
+static struct GH54014 *const GH54014_ptr = &(struct GH54014){255};
+void GH54014_g(void);
+
+// REF-LABEL: define{{.*}} i32 @GH54014_write_then_read()
+// REF:      store i32 252, ptr [[CL:@.compoundliteral[.0-9]*]]
+// REF-NEXT: [[V:%.*]] = load i32, ptr [[CL]]
+// REF-NEXT: ret i32 [[V]]
+int GH54014_write_then_read(void) {
+  GH54014_ptr->counter = 252;
+  return GH54014_ptr->counter;
+}
+
+// REF-LABEL: define{{.*}} i32 @GH54014_read_after_call()
+// REF:      call void @GH54014_g()
+// REF-NEXT: [[V:%.*]] = load i32, ptr @.compoundliteral{{[.0-9]*}}
+// REF-NEXT: ret i32 [[V]]
+int GH54014_read_after_call(void) {
+  GH54014_g();
+  return GH54014_ptr->counter;
+}
diff --git a/clang/test/Sema/compound-literal.c 
b/clang/test/Sema/compound-literal.c
index 1026e5ece11b49..ecb3c985623fb1 100644
--- a/clang/test/Sema/compound-literal.c
+++ b/clang/test/Sema/compound-literal.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -fblocks -pedantic %s
+// RUN: %clang_cc1 -fsyntax-only -verify=expected,ref -fblocks -pedantic %s
 // RUN: %clang_cc1 -fsyntax-only -verify -fblocks -pedantic %s 
-fexperimental-new-constant-interpreter
 // REQUIRES: LP64
 
@@ -54,3 +54,12 @@ void vla(int n) {
   (void)(int[size]){1,2,3}; // expected-error {{compound literal cannot be of 
variable-length array type}}
   (void)(int[size]){1,2,3,4,5}; // expected-error {{compound literal cannot be 
of variable-length array type}}
 }
+
+// GH54014: a non-const file-scope compound literal may be modified at runtime,
+// so its value can't be read through a pointer in a constant initializer.
+// FIXME: The bytecode interpreter still folds this read.
+static int *const GH54014_p = &(int){255};
+static int GH54014_x = *GH54014_p; // ref-error {{initializer element is not a 
compile-time constant}}
+// A const-qualified compound literal can't change, so this is still folded.
+static const int *const GH54014_q = &(const int){3};
+static int GH54014_y = *GH54014_q;
diff --git a/clang/test/Sema/constexpr.c b/clang/test/Sema/constexpr.c
index aedaba2cb921a7..5654ade47ac5b9 100644
--- a/clang/test/Sema/constexpr.c
+++ b/clang/test/Sema/constexpr.c
@@ -43,6 +43,10 @@ constexpr signed auto Long = 1L; // expected-error {{illegal 
storage class on fi
 // expected-error@-1 {{cannot combine with previous 'constexpr' declaration 
specifier}}
 _Static_assert(_Generic(Ulong, long : 1));
 _Static_assert(_Generic(CompoundLiteral, int : 1));
+// GH54014: a compound literal that is directly converted to an rvalue isn't a
+// read of the (modifiable) compound literal object, unless it is volatile.
+constexpr int *CompoundLiteralPtr = (int *){nullptr};
+constexpr int CompoundLiteralVolatile = (volatile int){1}; // expected-error 
{{constexpr variable 'CompoundLiteralVolatile' must be initialized by a 
constant expression}}
 _Static_assert(_Generic(DoubleCast, double : 1));
 _Static_assert(_Generic(String, char* : 1));
 

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to